Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                

queue

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package queue keeps queues of messages in a SQLite database opened with github.com/liustack/sqlite: work a request should not wait for, or should only start once its own writes are committed.

q, err := queue.New(ctx, db, "emails")
err = q.Publish(ctx, body)
err = q.Consume(ctx, func(ctx context.Context, m *queue.Message) error {
	return send(ctx, m.Body) // nil: handled, an error or a panic: again later
})

A message published and committed stays in the database file until it is handled. PublishTx publishes in a transaction of the program, so that the message is there with what else the transaction wrote, and never if it is rolled back.

A queue with named subscriptions, declared with Subscriptions, gives each message to each of them.

A queue cleans up after itself. A message that came due and is not taken for 7 days is dead. A dead message is deleted 30 days after it died, or once its subscription has 10,000 dead messages that died after it. What is left of a message kept for its key is deleted once the key is no longer kept. A process cleans up each queue it uses at most once a minute, in a round that runs in a goroutine of its own. Consume starts one as it starts, unless one started in the last minute, and one each minute after, and waits for its round before it returns. New, Publish and PublishTx start one once the process has used the queue for a minute, and do not wait for it: when the program closes the database, such a round stops, but may still end the statement it runs after Close returned. A round that fails stops, and the next one tries again.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NoRetry added in v0.3.0

func NoRetry(err error) error

NoRetry, returned by a handler, makes the message dead now with err as its error, however many attempts it has left, also once the context of the handler was cancelled.

func RetryIn added in v0.3.0

func RetryIn(d time.Duration) error

RetryIn, returned by a handler, gives the message back to be taken again after d, and this take does not count: for a handler that cannot do its work yet, as when a service it calls asks it to wait.

Types

type ConsumeOption added in v0.3.0

type ConsumeOption interface {
	// contains filtered or unexported methods
}

ConsumeOption is an option of Consume.

func Dead added in v0.3.0

func Dead() ConsumeOption

Dead has Consume hand h the dead messages of the subscription instead of the live ones: to handle them with a program, say one that reports them or keeps them elsewhere. When h returns nil, the dead message is deleted, and one with a key is kept for it as a message handled. When h fails, the message comes again as a live one does, its takes counted from 0 again. A dead message taken MaxAttempts times and not handled, or whose handler returns NoRetry, is given up: it stays dead and listed by Dead, and no Consume hands it out again. Requeue makes it live, and Delete or the limits on dead messages delete it.

A dead message keeps why it died as its error, the Error that Dead lists and that h gets: the errors of h go to OnError, if one is given, and not to the table.

func MaxAttempts

func MaxAttempts(n int) ConsumeOption

MaxAttempts is how many times a message may be taken: 20 if not given. Each take counts, also when the process stops or dies before the handler returns, so that a message that makes the process crash stops coming. A message taken that many times and not handled is dead.

func MaxRun added in v0.3.0

func MaxRun(d time.Duration) ConsumeOption

MaxRun is how long a handler may run: 30 minutes if not given. Then its context is cancelled, and its message is no longer held for it, so that another Consume takes it once the hold ends. If the handler then returns an error, RetryIn too, the attempt is a failure. If it returns nil, the message is handled, and NoRetry still makes it dead.

func OnError added in v0.5.0

func OnError(f func(error)) ConsumeOption

OnError has Consume give f each error it meets and does not return, as it goes on. Each is one of these, which errors.As tells apart:

  • *MessageError: a handler failed or panicked, a message died, a message taken and not run could not be given back, or the result of a handler was not written.
  • *DatabaseError: a statement of the database failed, Consume tries again. Of each kind of statement (Op), f gets at most one each 5 seconds, counted from when it got the last, and the next one it gets says how many failed in between and it did not get.
  • *StuckError: a handler ran past MaxRun and has not returned 30 seconds after its context was cancelled, and later returned.

Without OnError, Consume gives them to no one and writes no log: sqlite.Stats still shows the last error of the database, how many came, and the workers that are stuck. To log each, give OnError(func(err error) { slog.Error("queue", "err", err) }).

f is called with no lock of Consume held, and may run in several goroutines at once. A *MessageError comes in the goroutine of the worker once the result of its message is written, and before the worker takes its next message, or in the goroutine of Consume once the handlers of the take that made the message dead started: a slow f slows the handling of messages, but never lets the hold of a message end. A *DatabaseError and a *StuckError come in a goroutine of their own, one at a time and in the order Consume met them, so that the renewals of the holds never wait for f. While f does not return, those that wait are kept few, at most one of each kind of statement and 2 for each worker: an error of a kind that still waits is not given to f, and counts in the Skipped of the next of that kind, and a handler stuck that returned before f heard of it is not told.

f may cancel the context of Consume, which then stops as when the context ends, but f must not wait for Consume to return. As it returns, Consume waits for the call of f that runs, and makes no new call of the goroutine of its own: a *DatabaseError or a *StuckError that still waits is dropped. An f that never returns keeps Consume from returning. A panic in f is not recovered: it ends the program, as a panic in any goroutine does.

func Prefetch added in v0.3.1

func Prefetch(n int) ConsumeOption

Prefetch lets Consume hold up to n messages more than its workers run: 0 if not given, at most 1000. They are messages taken ahead, which wait for a worker in the order they came due, and messages whose handler returned and whose result is not yet written: the worker goes on to the next message while the result is written. The messages taken ahead hold at most 16 MiB of bodies. It drains a backlog faster when handlers take less than a millisecond or so, as each worker no longer waits for a write before its next message.

The cost is in what a crash does. When the process dies, these messages come again once their hold ends, within 30 seconds (those taken ahead up to n milliseconds more, which keeps their order), as those of the handlers that ran: each take counts, and those whose handler returned run again. While they wait in this process, no other Consume takes them, also when its workers are free, and they may wait behind a slow handler. When ctx ends, those taken ahead go back at once, the take not counted, and Consume waits for the results being written as for the handlers that run. 100 is a good start for a large backlog of fast handlers: the gain is largest with few workers.

func Workers added in v0.3.0

func Workers(n int) ConsumeOption

Workers is how many messages Consume handles at once, each in a goroutine of its own: 10 if not given. Without Prefetch, Consume takes a message only for a worker that is free, and a worker takes its next message only once the result of its last one is written, so it holds at most n.

type DatabaseError added in v0.5.0

type DatabaseError struct {
	// Queue and Sub are the queue and the subscription of the Consume.
	Queue, Sub string
	// Op is the kind of statement that failed: "read", a look for
	// messages or for the subscription, "take", "renew", a renewal of the
	// holds, "result", the write of the result of a handler, or "cleanup",
	// a round of cleanup.
	Op string
	// Err is the error of the database.
	Err error
	// Skipped is how many statements of the same Op failed after the
	// *DatabaseError of that Op that OnError got before this one, and
	// before this one, and were not given to OnError: it gets at most one
	// of each Op each 5 seconds, counted from when it got the last.
	Skipped int
	// contains filtered or unexported fields
}

DatabaseError says that a statement of the database failed for a Consume. Consume tries again on its own, and goes on once it works.

func (*DatabaseError) Error added in v0.5.0

func (e *DatabaseError) Error() string

func (*DatabaseError) Unwrap added in v0.5.0

func (e *DatabaseError) Unwrap() error

type DeadMessage added in v0.3.0

type DeadMessage struct {
	ID   int64
	Body []byte
	// Attempt is how many times the message was taken before it died.
	Attempt int
	// Error is why the message died: the error of its last attempt, or
	// what the queue says, such as a hold that ended or a message due and
	// not taken. A Consume with Dead does not change it.
	Error       string
	PublishedAt time.Time
	DeadAt      time.Time
}

DeadMessage is a dead message as Dead lists it.

type DeadOption added in v0.3.0

type DeadOption interface {
	// contains filtered or unexported methods
}

DeadOption is an option of Dead: Sub and After.

func After added in v0.3.0

func After(id int64) DeadOption

After has Dead list the dead messages after the one with ID id: the next page.

type Message

type Message struct {
	// ID is the same each time the message is handed out to its
	// subscription, and no other row of the table ever has it. Each
	// subscription has a copy of a message with an ID of its own. When a
	// queue gets its first named subscriptions, the messages of the default
	// subscription that wait or are held go to each of them with new IDs:
	// one that a handler of the default subscription ran may come again
	// under another ID.
	ID   int64
	Body []byte
	// Attempt is how many times the message was taken for its
	// subscription, this time with them: 1 the first time. A take that
	// RetryIn or a shutdown gave back does not count. For a Consume with
	// Dead, it is how many times the message was taken since it died.
	Attempt int
	// PublishedAt is when the message was published, to the millisecond.
	PublishedAt time.Time
	// Error is the error of the attempt before, "" the first time. For a
	// Consume with Dead, it is why the message died, each time.
	Error string
	// DeadAt is when the message died, for a Consume with Dead, to the
	// millisecond. It is the zero time for the others.
	DeadAt time.Time
}

Message is a message as a handler gets it.

type MessageError added in v0.5.0

type MessageError struct {
	// Queue and Sub are the queue and the subscription of the message, ""
	// for the default one.
	Queue, Sub string
	// ID is the ID of the message, and Attempt the number of its take.
	ID      int64
	Attempt int
	// Err is what the handler returned, a *PanicError when it panicked,
	// or, when the message died with no handler, why it died. It is nil
	// when the result was not written and the handler returned nil.
	Err error
	// Dead says that the message is dead now: it failed for the last
	// time, the handler returned NoRetry, or it was taken MaxAttempts
	// times and not handled. With Dead(), it says that the dead message is
	// given up.
	Dead bool
	// NotWritten says that the result was not written, and Dead and
	// RetryAt are not set: the message was no longer held for the handler,
	// as it went to the subscriptions the queue got, was removed with its
	// subscription (Unsubscribe) or deleted (Delete), or its hold ended and
	// it was taken again, or Consume returned or the database was closed
	// while the database failed to take the result. The message does not
	// come again from this result: in the last case it comes again once its
	// hold ends, the take counted.
	NotWritten bool
	// NotGivenBack says that the message was taken, and no handler ran it:
	// taken ahead with Prefetch, or taken as Consume stopped. The write that
	// gives it back, the take not counted, failed with Err. If it is still
	// held, it comes again once its hold ends, the take counted: Consume
	// does not look whether it is, and Delete may have deleted it, or
	// Unsubscribe removed it, in the meantime. ID is 0 for the messages
	// of a take that Consume could not read: all of them, or, after those it
	// read, the rest, so that a last one with ID 0 says the list is not
	// complete.
	NotGivenBack bool
	// RetryAt is when the message comes again after a handler that
	// failed, the zero time when it does not.
	RetryAt time.Time
	// contains filtered or unexported fields
}

MessageError is an error of a message that Consume handed out: what its handler returned, or why the message died without a handler.

func (*MessageError) Error added in v0.5.0

func (e *MessageError) Error() string

func (*MessageError) Unwrap added in v0.5.0

func (e *MessageError) Unwrap() error

type Option

type Option func(*config)

Option is an option of New.

func Subscriptions added in v0.3.0

func Subscriptions(names ...string) Option

Subscriptions declares named subscriptions of the queue: each message published from then on goes to each of them, and each is handled on its own. They are kept in the database, so a process that only publishes need not declare them. A queue has at most 64.

The first time a queue gets named subscriptions, the messages of its default subscription that are not handled yet go to each of them, the dead ones too, so that what a process published before the one that declares them started is not left behind. A message that a handler of the default subscription holds goes once the hold ends, and the context of the handler is cancelled before (Consume): the message may then be handled twice, but not at once by a handler that stops when its context is cancelled, as at MaxRun. From then on the default subscription gets no message, and a Consume of it that runs takes none and returns the error a Consume of it started then gets (Consume). New hands the messages over a batch at a time, so that other writes go on in between, and returns once it is done. A New that stops before, as when its ctx ends, leaves the rest to the next New or round of cleanup of the queue. A subscription declared later gets only what is published after it, and what is left to hand over then: declare all the subscriptions of a queue in one New.

func Table

func Table(name string) Option

Table names the table the queue keeps its messages in: letters, digits and underscores. Its subscriptions are kept in the table of that name with "_subs" after it. The queues of one table share it. If not given, the tables are _liustack_queue and _liustack_queue_subs.

type PanicError added in v0.5.0

type PanicError struct {
	// Value is what the handler panicked with, nil after runtime.Goexit.
	Value any
	// Stack is the stack of the goroutine of the handler as it panicked.
	Stack []byte
	// Goexit says the handler called runtime.Goexit, and did not panic.
	Goexit bool
}

PanicError is the error of a handler that panicked, or that called runtime.Goexit, as t.Fatal does.

func (*PanicError) Error added in v0.5.0

func (p *PanicError) Error() string

type PublishOption added in v0.3.0

type PublishOption func(*publishConfig)

PublishOption is an option of Publish and PublishTx.

func At added in v0.3.0

func At(t time.Time) PublishOption

At keeps the message from being handed out until t. A time that passed is now. Of Delay and At, the last given counts.

func Dedup added in v0.3.0

func Dedup(key string) PublishOption

Dedup gives the message a key, which lets one message of the queue in: a Publish with a key the queue has does nothing and returns nil. The queue has the key from the time the message is published until 24 hours after no subscription has it to handle any more (it was handled, or its subscription was removed, or it was dead and deleted). To run a message that died again, requeue it: do not publish it again.

func Delay

func Delay(d time.Duration) PublishOption

Delay keeps the message from being handed out until d has passed. Of Delay and At, the last given counts.

type Queue

type Queue struct {
	// contains filtered or unexported fields
}

Queue is one queue of a database. It is safe for use by many goroutines.

func New

func New(ctx context.Context, db *sql.DB, name string, opts ...Option) (*Queue, error)

New gives the queue name of the database db, which must be a database file opened with github.com/liustack/sqlite. It makes the tables on first use, and declares the subscriptions given.

A Queue has nothing to close. A round of cleanup that Publish started stops once the program closes the database, and the one a Consume started stops before Consume returns.

func (*Queue) Consume added in v0.3.0

func (q *Queue) Consume(ctx context.Context, h func(context.Context, *Message) error, opts ...ConsumeOption) error

Consume hands the messages of a subscription of the queue to h, until ctx ends: up to Workers at once, each in a goroutine of its own, the oldest first. When h returns nil, the message is handled. When h returns an error or panics, the message comes again after n⁴ seconds, n the number of times it was taken, 10% less to 10% more, and at most 24 hours. A message taken MaxAttempts times and not handled is dead: it is not taken again, and keeps its last error. NoRetry and RetryIn, returned by h, say otherwise.

A message may be handled more than once: when the process dies after h did its work, or when the database fails for longer than the hold of the message before its result is written. Write h so that a second run does no harm.

While h runs, its message is held for it, and no other Consume takes it. The context h gets ends at MaxRun, and at shutdown. It also ends once the message is no longer held for it, at the next renewal of the hold (each 10 seconds): when the queue gets its first named subscriptions and the message goes to them, when Unsubscribe removes its subscription, or when Delete deletes it. The subscriptions take the message only once the hold ends, 20 seconds later: a handler that stops when its context ends does not run it at once with theirs, as with MaxRun. And it ends 10 seconds before the hold would, when the hold could not be renewed by then, as while the database fails or is busy: once the hold ends, another Consume may take the message.

When ctx ends, Consume takes no new message and gives the handlers up to 8 seconds to return. Then it cancels their contexts, gives back the messages of those that return an error, at once, or RetryIn, after its wait, as if they were not taken, and returns ctx.Err(). NoRetry and a panic count as at any other time. The message of a handler that does not return stays held for it for up to 30 seconds more, so that two handlers do not run it at once, and its goroutine stays. Once Consume returned, it writes nothing to the database: what such a handler returns later is not written, and its message comes again. Messages taken as ctx ended go back at once, the take not counted: if that write fails, OnError gets its error, and those still held come again once their hold ends. With Prefetch, the messages taken ahead also go back at once, the take not counted, and Consume waits for the results being written as it waits for the handlers.

Consume returns only when it cannot go on, and never nil:

  • ctx.Err(), once ctx ended.
  • An error at once, when its options are wrong or the subscription is not declared.
  • The error of database/sql, once the program closed the database.
  • An error once Unsubscribe removed its subscription, also when it was declared again since, and once the queue of the default subscription got named ones, with the error a Consume started then gets. Then it ends as when ctx ends, and the contexts of the handlers that run end as their messages are no longer held for them.

Any other error it gives to OnError, and goes on. While the database fails, as it starts too, Consume tries again, 100 ms later and then twice as long each time up to 5 seconds, and takes messages again once the database works. The result of a handler is tried until it is written, and the holds of the messages are renewed while the database lets them. While each worker is held by a handler stuck past MaxRun, Consume takes no message and gives back those taken ahead, the take not counted, until one returns.

func (*Queue) Dead added in v0.3.0

func (q *Queue) Dead(ctx context.Context, n int, opts ...DeadOption) ([]DeadMessage, error)

Dead lists up to n dead messages of a subscription, by ID: those of the default subscription, or with Sub those of a named one. With After it lists those after a message, to go through them a page at a time.

A dead message stays until it is requeued or deleted, or for 30 days from when it died. A subscription keeps at most 10,000: past that, the oldest are deleted.

func (*Queue) Delete added in v0.3.0

func (q *Queue) Delete(ctx context.Context, ids ...int64) (int, error)

Delete deletes dead messages. A message with a key keeps it for 24 hours more, as a message handled does (Dedup). An ID that is not a dead message of the queue is left out. It says how many messages it deleted, also when it fails: it works on up to 1,000 IDs at a time.

Delete also deletes a dead message that a Consume with Dead holds for its handler: the context of that handler is cancelled at the next renewal of the hold, and what it returns finds no message, and is not written. Requeue leaves such a message out until the hold ends.

func (*Queue) Publish added in v0.3.0

func (q *Queue) Publish(ctx context.Context, body []byte, opts ...PublishOption) error

Publish adds a message to the queue: one for each of its subscriptions, or for the default subscription when it has none. When Publish returns nil, the message is committed, as durable as any write of the database.

Publish writes outside any transaction, so that the driver can commit it with the writes of other goroutines. Inside a transaction of the program use PublishTx: Publish would wait for that transaction to end. It waits for a connection and the write lock up to the busy timeout of the database (5 seconds unless the DSN sets busy_timeout), and fails then. With a busy timeout of 0 it does not wait for the write lock, and waits up to 5 seconds for a connection.

func (*Queue) PublishTx added in v0.3.0

func (q *Queue) PublishTx(ctx context.Context, tx *sql.Tx, body []byte, opts ...PublishOption) error

PublishTx adds a message to the queue as Publish does, in tx, a transaction of the database of the queue: the message is there once tx commits, with what else tx wrote, and never if tx is rolled back.

func (*Queue) Requeue added in v0.3.0

func (q *Queue) Requeue(ctx context.Context, ids ...int64) (int, error)

Requeue gives dead messages back to their subscriptions, to be taken now as if just published: their attempts count from 0 again, and the error that Dead lists is gone. An ID that is not a dead message of the queue is left out, and so is a dead message that a Consume with Dead holds for its handler, until the hold ends. It says how many messages it gave back, also when it fails: it works on up to 1,000 IDs at a time.

func (*Queue) Stats added in v0.3.0

func (q *Queue) Stats(ctx context.Context) ([]SubStats, error)

Stats gives how the messages of each subscription of the queue stand, by name: of the default subscription when the queue has no named one. A message held whose hold ended, as when its process died, is waiting. It reads all the subscriptions at one time.

Stats reads an entry of an index for each message of the queue, so with a large backlog it takes longer.

func (*Queue) Unsubscribe added in v0.3.0

func (q *Queue) Unsubscribe(ctx context.Context, name string) error

Unsubscribe removes the named subscription name of the queue, and its messages at once, those dead too. A message with a key keeps it for 24 hours (Dedup). A message published from then on does not go to the subscription. A Consume of it fails, and one that runs returns an error that says so the next time it looks for messages, also when the subscription is declared again by then. The contexts of its handlers that run are cancelled at the next renewal of their holds, and what they write then finds no message. Once a queue has no named subscription left, its messages go to the default subscription again.

The messages are removed a batch at a time while the subscription is still declared, so that other writes go on in between, and the last of them with the declaration. If Unsubscribe stops before that, as when ctx ends, the subscription is still declared, with the messages not removed yet: Unsubscribe again ends the work. While messages are published faster than it removes them, it goes on until ctx ends. A queue that does not have the subscription is left as it is, and Unsubscribe returns nil. So is a subscription removed and declared again while Unsubscribe runs, as by another Unsubscribe: the new one is not Unsubscribe's to remove.

type StuckError added in v0.5.0

type StuckError struct {
	// Queue and Sub are the queue and the subscription of the message.
	Queue, Sub string
	// ID is the ID of the message, and Attempt the number of its take.
	ID      int64
	Attempt int
	// Started is when the handler started, the same in both errors of a
	// run: it tells apart two runs of a message with the same Attempt, as
	// after Requeue.
	Started time.Time
	// Returned says the handler returned: its worker is free again.
	Returned bool
	// contains filtered or unexported fields
}

StuckError says that a handler ran past MaxRun and has not returned 30 seconds after its context was cancelled, or that it returned since. While it does not return, it holds its worker, and its message is no longer held for it: another Consume may take the message once its hold ends. Once each worker is stuck, Consume takes no message until one returns.

func (*StuckError) Error added in v0.5.0

func (e *StuckError) Error() string

type SubOption added in v0.3.0

type SubOption struct {
	// contains filtered or unexported fields
}

SubOption names a named subscription of the queue. Sub gives it.

func Sub added in v0.3.0

func Sub(name string) SubOption

Sub names the subscription to handle, one declared with Subscriptions. Without it, Consume handles the default subscription, that of a queue with no named subscription.

type SubStats added in v0.3.0

type SubStats struct {
	// Sub is the name of the subscription, "" for the default one.
	Sub string
	// Waiting is how many messages may be taken now. Delayed is how many
	// come due later: published with Delay or At, given back with RetryIn,
	// or waiting after their handler failed.
	Waiting, Delayed int
	// Held is how many are held for a Consume: for a handler that runs and,
	// with Prefetch, taken ahead or with the result not yet written.
	Held int
	// Dead is how many are dead.
	Dead int
	// OldestWait is how long the message that came due first has waited
	// to be taken, 0 when none waits. When it grows, no Consume takes the
	// messages of the subscription, or not as fast as they come.
	OldestWait time.Duration
}

SubStats is how the messages of a subscription stand.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL