package link import ( "context" "fmt" "time" "git.novox.be/novox/mesh-sdk/go/process" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" ) // The node-engine takes an ask once by its id (design 47 H2 §775, §820; H-A-364 (a)): the ids it took are kept in its own // state taken, under `.`, each for the ask's bound, bound over the link it serves its seat on. // TakenBucket is the node-engine's state `taken`, named by its holder as every state is. const TakenBucket = "mesh-host_" + process.TakenState // TakenBus is a link that binds the node-engine's state taken. type TakenBus interface { TakenKV(ctx context.Context) (jetstream.KeyValue, error) } func takenKV(ctx context.Context, conn *nats.Conn) (jetstream.KeyValue, error) { js, err := jetstream.New(conn) if err != nil { return nil, err } kv, err := js.KeyValue(ctx, TakenBucket) if err != nil { return nil, fmt.Errorf("the state %s cannot be bound: %w", TakenBucket, err) } return kv, nil } func (l *natsLink) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { return takenKV(ctx, l.conn) } func (b OverNATS) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { return takenKV(ctx, b.Conn) } var ( _ TakenBus = (*natsLink)(nil) _ TakenBus = OverNATS{} ) // takenWithin bounds binding the state taken. const takenWithin = 5 * time.Second // TakeOnce takes the ask ask of seat once, in the state taken for bound (process.State.TakeOnce): true the first time it // is given, false when it was taken within its bound. ErrNoLink when no link is held. func (q *Session) TakeOnce(seat, ask string, bound time.Duration) (bool, error) { q.init() q.mu.Lock() bus := q.bus q.mu.Unlock() t, ok := bus.(TakenBus) if bus == nil || !ok { return false, ErrNoLink } ctx, cancel := context.WithTimeout(context.Background(), takenWithin) defer cancel() kv, err := t.TakenKV(ctx) if err != nil { return false, err } return process.StateOver("mesh-host", process.TakenState, kv).TakeOnce(seat, ask, bound) }