package main import ( "context" "encoding/json" "errors" "time" "github.com/nats-io/nats.go/jetstream" "mesh-delivery-builder/internal/build" ) // queueReader is the part of the builder a queues value reads through: heldOnTheBus. type queueReader interface { Queue(ctx context.Context, language string, limit int) (build.SeatQueue, error) } // queueRead answers one value of the queues state (the tool builder_seat_queue, issue 1945 note 62): a value not yet // answered is read now, from the stream the builder's account may read, and written back by compare-and-set at its // revision with what was read or why it could not be. A value answered already (this builder's own write, or another // instance's) or deleted is left. func queueRead(ctx context.Context, r queueReader, kv jetstream.KeyValue, e jetstream.KeyValueEntry, logf func(string, ...any)) { if e.Operation() != jetstream.KeyValuePut { return } a, err := build.DecodeQueueAsk(e.Value()) if err != nil { logf("%s.%s holds what is not a queue read, left: %v", build.QueuesState, e.Key(), err) return } if !a.Answered.IsZero() { return } read, cancel := context.WithTimeout(ctx, 20*time.Second) q, err := r.Queue(read, e.Key(), max(1, min(a.Limit, build.MaxQueueLimit))) cancel() if err != nil { a.Error = err.Error() } a.Queue, a.Answered = &q, time.Now().UTC() data, err := json.Marshal(a) if err != nil { return } if _, err := kv.Update(ctx, e.Key(), data, e.Revision()); err != nil && !errors.Is(err, jetstream.ErrKeyExists) && !errors.Is(err, jetstream.ErrKeyRevisionMismatch) { logf("%s.%s: the read could not be written: %v", build.QueuesState, e.Key(), err) } }