{"modulePath":"github.com/DoNewsCode/core-queue","version":"v0.1.3","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package queue\n\nPackage queue provides a deferrableDecorator queue implementation that supports reflectionJob retires and deferred dispatch.\n\nIt is recommended to read documentation on the core package before getting started on the queue package.\n\n### Introduction {#hdr-Introduction}\n\nQueues in go is not as prominent as in some other languages, since go excels at handling concurrency. However, the deferrableDecorator queue can still offer some benefit missing from the native mechanism, say go channels. The queued reflectionJob won't be lost even if the system shutdown. In other words, it means jobs can be retried until success. Plus, it is also possible to queue the execution of a particular reflectionJob until a lengthy period of time. Useful when you need to implement \"send email after 30 days\" type of Job handler.\n\n### Simple Usage {#hdr-Simple_Usage}\n\nFirst and foremost we should create a reflectionJob, waiting the queue to dispatch. A reflectionJob can be any struct that implements the Job interface.\n\n\t type Job interface {\n\t\t\tType() string\n\t\t\tData() interface{}\n\t\t}\n\nAlthough the object that implements the reflectionJob interface can be dispatched immediately, it only minimally describes the reflectionJob's property . We can tune the properties with the Adjust helper. For example, we want to run the reflectionJob after 3 minutes with maximum 5 retries:\n\n\tnewJob := queue.Adjust(reflectionJob, queue.Defer(3 * time.Minute), queue.MaxAttempts(5))\n\nLike the Job package, you don't have to use this helper. Manually create a queueable Job by implementing this interface on top of the normal Job interface:\n\n\ttype deferrableDecorator interface {\n\t  Defer() time.Duration\n\t  Decorate(s *PersistedJob)\n\t}\n\nThe PersistentJob passed to the Decorate method contains the tunable configuration such as maximum retries.\n\nNo matter how you create a persisted Job, to fire it, send it though a dispatcher. The normal dispatcher in the Jobs package won't work, as a queue implementation is required. Luckily, it is deadly simple to convert a standard dispatcher to a queue.JobDispatcher.\n\n\tqueueableDispatcher := queue.NewQueue(\u0026queue.RedisDriver{})\n\tqueueableDispatcher.dispatch(newJob)\n\nAs you can see, how the queue persist the Jobs is subject to the underlying driver. The default driver bundled in this package is the redis driver.\n\nOnce the persisted Job are stored in the external storage, a goroutine should consume them and pipe the reconstructed Job to the listeners. This is done by calling the Consume method JobFrom queue.JobDispatcher\n\n\tgo dispatcher.Consume(context.Background())\n\nNote if a Job is retryable, it is your responsibility to ensure the idempotency. Also, be aware if a persisted Job have many listeners, the Job is up to retry when any of the listeners fail.\n\n### Integrate {#hdr-Integrate}\n\nThe queue package exports configuration in this format:\n\n\tqueue:\n\t  default:\n\t    redisName: default\n\t    parallelism: 3\n\t    checkQueueLengthIntervalSecond: 15\n\nWhile manually constructing the queue.JobDispatcher is absolutely feasible, users can use the bundled dependency provider without breaking a sweat. Using this approach, the life cycle of consumer goroutine will be managed automatically by the core.\n\n\tvar c *core.C\n\tc.Provide(otredis.Providers()) // to provide the redis driver\n\tc.Provide(queue.Providers())\n\nA module is also bundled, providing the queue command (for reloading and flushing).\n\n\tc.AddModuleFunc(queue.New)\n\nSometimes there are valid reasons to use more than one queue. Each dispatcher however is bounded to only one queue. To use multiple queues, multiple dispatchers are required. Inject queue.DispatcherMaker to factory a dispatcher with a specific name.\n\n\tc.Invoke(function(maker queue.DispatcherMaker) {\n\t  dispatcher, err := maker.Make(\"default\")\n\t  // see examples for details\n\t})\n\n### Event-based Jobs {#hdr-Event_based_Jobs}\n\nWhen an attempt to execute the Job handler failed, two kinds of special eventDispatcher-based Job will be fired. If the failed Job can be retried, \"queue.RetryingJob\" will be fired. If not, \"queue.AbortedJob\" will be fired.\n\n### Metrics {#hdr-Metrics}\n\nTo gain visibility on how the length of the queue, inject a gauge into the core and alias it to queue.Gauge. The queue length of the all internal queues will be periodically reported to metrics collector (Presumably Prometheus).\n\n\tc.provideDispatcherFactory(di.Deps{func(appName contract.AppName, env contract.Env) queue.Gauge {\n\t  return prometheus.NewGaugeFrom(\n\t    stdprometheus.GaugeOpts{\n\t      Namespace: appName.String(),\n\t      Subsystem: env.String(),\n\t      Owner:      \"queue_length\",\n\t      Help:      \"The gauge of queue length\",\n\t    }, []string{\"name\", \"channel\"},\n\t  )\n\t}})\n\n## Constants\n\n```go\nconst (\n\t// BeforeRetry is an event that triggers when the job failed previously is going to be retried.\n\t// Note: if retry attempts are exhausted, this event won't be triggered.\n\tBeforeRetry event = \"beforeRetry\"\n\t// BeforeAbort is an event that triggers when the job failed previously is going\n\t// to be aborted. If the Job still has retry attempts remaining, this event won't\n\t// be triggered.\n\tBeforeAbort event = \"beforeAbort\"\n)\n```\n\n## Variables\n\n```go\nvar ErrEmpty = errors.New(\"no message available\")\n```\nErrEmpty means the queue is empty.\n\n## Functions\n\n```go\nfunc Providers(optionFunc ...ProvidersOptionFunc) di.Deps\n```\nProviders returns a set JobFrom dependencies related to queue. It includes the DispatcherMaker, the JobDispatcher and the exported configs.\n\n\tDepends On:\n\t\tcontract.ConfigAccessor\n\t\tcontract.Dispatcher\n\t\tDriver        `optional:\"true\"`\n\t\totredis.Maker `optional:\"true\"`\n\t\tlog.Logger\n\t\tcontract.AppName\n\t\tcontract.Env\n\t\tGauge `optional:\"true\"`\n\tProvides:\n\t\tDispatcherMaker\n\t\tDispatcherFactory\n\t\tJobDispatcher\n\t\t*Queue\n\n```go\nfunc UseCodec(codec contract.Codec) func(*Queue)\n```\nUseCodec allows consumer to replace the default Packer with a custom one. UsePacker is an option for NewQueue.\n\n```go\nfunc UseEventDispatcher(dispatcher contract.Dispatcher) func(*Queue)\n```\nUseEventDispatcher is an option for NewQueue to receive events such as fail and retry.\n\n```go\nfunc UseGauge(gauge metrics.Gauge, interval time.Duration) func(*Queue)\n```\nUseGauge is an option for NewQueue that collects a gauge metrics\n\n```go\nfunc UseJobDispatcher(dispatcher JobDispatcher) func(*Queue)\n```\nUseJobDispatcher is an option for NewQueue to swap jobDispatcher dispatcher implementation\n\n```go\nfunc UseLogger(logger log.Logger) func(*Queue)\n```\nUseLogger is an option for NewQueue that feeds the queue with a Logger JobFrom choice.\n\n```go\nfunc UseParallelism(parallelism int) func(*Queue)\n```\nUseParallelism is an option for NewQueue that sets the parallelism for queue consumption\n\n## Types\n\n```go\ntype BeforeAbortPayload struct {\n\tErr error\n\tJob *PersistedJob\n}\n```\n\n```go\ntype BeforeRetryPayload struct {\n\tErr error\n\tJob *PersistedJob\n}\n```\n\n```go\ntype ChannelConfig struct {\n\tDelayed  string\n\tFailed   string\n\tReserved string\n\tWaiting  string\n\tTimeout  string\n}\n```\nChannelConfig describes the key name JobFrom each queue, also known as channel.\n\n```go\ntype ConsumableDispatcher interface {\n\tJobDispatcher\n\tConsume(ctx context.Context) error\n}\n```\nConsumableDispatcher is the key of \\*Queue in the dependencies graph. Used as a type hint for injection.\n\n```go\ntype DeferrablePersistentJob struct {\n\tJob\n\t// contains filtered or unexported fields\n}\n```\nDeferrablePersistentJob is a persisted Job.\n\n```go\nfunc Adjust(job Job, opts ...PersistOption) DeferrablePersistentJob\n```\nAdjust converts any Job to DeferrablePersistentJob. Namely, store them in external storage.\n\n```go\nfunc (d DeferrablePersistentJob) Decorate(s *PersistedJob)\n```\nDecorate decorates the PersistedJob JobFrom this Job by adding some meta info. it is called in the Queue, after the Packer compresses the Job.\n\n```go\nfunc (d DeferrablePersistentJob) Defer() time.Duration\n```\nDefer defers the execution JobFrom the reflectionJob for the period JobFrom time returned.\n\n```go\ntype DispatcherFactory struct {\n\t*di.Factory\n}\n```\nDispatcherFactory is a factory for \\*Queue. Note DispatcherFactory doesn't contain the factory method itself. ie. How to factory a dispatcher left there for users to define. Users then can use this type to create their own dispatcher implementation.\n\nHere is an example on how to create a custom DispatcherFactory with an InProcessDriver.\n\n\tfactory := di.NewFactory(func(name string) (di.Pair, error) {\n\t\tqueuedDispatcher := queue.NewQueue(\n\t\t\t\u0026Jobs.SyncDispatcher{},\n\t\t\tqueue.NewInProcessDriver(),\n\t\t)\n\t\treturn di.Pair{Conn: queuedDispatcher}, nil\n\t})\n\tdispatcherFactory := DispatcherFactory{Factory: factory}\n\n```go\nfunc (s DispatcherFactory) Make(name string) (*Queue, error)\n```\nMake returns a Queue by the given name. If it has already been created under the same name, the that one will be returned.\n\n```go\ntype DispatcherMaker interface {\n\tMake(string) (*Queue, error)\n}\n```\nDispatcherMaker is the key of \\*DispatcherFactory in the dependencies graph. Used as a type hint for injection.\n\n```go\ntype Driver interface {\n\t// Push pushes the message onto the queue. It is possible to specify a time delay. If so the message\n\t// will be read after the delay. Use zero value if a delay is not needed.\n\tPush(ctx context.Context, message *PersistedJob, delay time.Duration) error\n\t// Pop pops the message out JobFrom the queue. It blocks until a message is available or a timeout is reached.\n\tPop(ctx context.Context) (*PersistedJob, error)\n\t// Ack acknowledges a message has been processed.\n\tAck(ctx context.Context, message *PersistedJob) error\n\t// \\Fail marks a message has failed.\n\tFail(ctx context.Context, message *PersistedJob) error\n\t// Reload put failed/timeout message back to the Waiting queue. If the temporary outage have been cleared,\n\t// messages can be tried again via Reload. Reload is not a normal retry.\n\t// It similarly gives otherwise dead messages one more chance,\n\t// but this chance is not subject to the limit JobFrom MaxAttempts, nor does it reset the number JobFrom time attempted.\n\tReload(ctx context.Context, channel string) (int64, error)\n\t// Flush empties the queue under channel\n\tFlush(ctx context.Context, channel string) error\n\t// Info lists QueueInfo by inspecting queues one by one. Useful for metrics and monitor.\n\tInfo(ctx context.Context) (QueueInfo, error)\n\t// Retry put the message back onto the delayed queue.\n\tRetry(ctx context.Context, message *PersistedJob) error\n}\n```\nDriver is the interface for queue engines. See RedisDriver for usage.\n\n```go\ntype DriverArgs struct {\n\tName      string\n\tPopulator contract.DIPopulator\n}\n```\nDriverArgs are arguments to construct the driver. See WithDriverConstructor.\n\n```go\ntype Gauge metrics.Gauge\n```\nGauge is an alias used for dependency injection\n\n```go\ntype Handler interface {\n\t// Listen should return a Job instance with zero value. It tells the dispatcher what type of jobDispatcher this handler is expecting.\n\tListen() Job\n\t// Process will be called when a jobDispatcher is ready from queue.\n\tProcess(ctx context.Context, Job Job) error\n}\n```\nHandler is the handler for Job.\n\n```go\ntype InProcessDriver struct {\n\t// contains filtered or unexported fields\n}\n```\nInProcessDriver is a test replacement for redis driver. It doesn't persist your Job in any way, so not suitable for production use.\n\n```go\nfunc NewInProcessDriver() *InProcessDriver\n```\nNewInProcessDriverWithPopInterval creates an \\*InProcessDriver for testing\n\n```go\nfunc NewInProcessDriverWithPopInterval(duration time.Duration) *InProcessDriver\n```\nNewInProcessDriverWithPopInterval creates an \\*InProcessDriver with an pop interval.\n\n```go\nfunc (i *InProcessDriver) Ack(ctx context.Context, message *PersistedJob) error\n```\n\n```go\nfunc (i *InProcessDriver) Fail(ctx context.Context, message *PersistedJob) error\n```\n\n```go\nfunc (i *InProcessDriver) Flush(ctx context.Context, channel string) error\n```\n\n```go\nfunc (i *InProcessDriver) Info(ctx context.Context) (QueueInfo, error)\n```\n\n```go\nfunc (i *InProcessDriver) Pop(ctx context.Context) (*PersistedJob, error)\n```\n\n```go\nfunc (i *InProcessDriver) Push(ctx context.Context, message *PersistedJob, delay time.Duration) error\n```\n\n```go\nfunc (i *InProcessDriver) Reload(ctx context.Context, channel string) (int64, error)\n```\n\n```go\nfunc (i *InProcessDriver) Retry(ctx context.Context, message *PersistedJob) error\n```\n\n```go\ntype Job interface {\n\tType() string\n\tData() interface{}\n}\n```\n\n```go\nfunc JobFrom(Job interface{}) Job\n```\nJobFrom wraps any struct, making it a valid Job.\n\n```go\ntype JobDispatcher interface {\n\tDispatch(ctx context.Context, Job Job) error\n\tSubscribe(listener Handler)\n}\n```\nJobDispatcher is the Job registry that is able to send reflectionJob to each Handler.\n\n```go\ntype ListenFunc struct {\n\tJob Job\n\t// contains filtered or unexported fields\n}\n```\nListenFunc is a listener implemented with a callback.\n\n```go\nfunc Listen(job Job, callback func(ctx context.Context, job Job) error) ListenFunc\n```\nListen creates a functional listener in one line.\n\n```go\nfunc (f ListenFunc) Listen() Job\n```\nListen implement Handler\n\n```go\nfunc (f ListenFunc) Process(ctx context.Context, Job Job) error\n```\nProcess implements Handler\n\n```go\ntype Module struct {\n\tFactory *DispatcherFactory\n}\n```\nModule exports queue commands, for example queue flush and queue reload.\n\n```go\nfunc New(factory *DispatcherFactory) Module\n```\nNew creates a new module.\n\n```go\nfunc (m Module) ProvideCommand(command *cobra.Command)\n```\nProvideCommand implements CommandProvider for the Module. It registers flush and reload command to the parent command.\n\n```go\ntype PersistOption func(Job *DeferrablePersistentJob)\n```\nPersistOption defines some options for Adjust\n\n```go\nfunc Defer(duration time.Duration) PersistOption\n```\nDefer is a PersistOption that defers the execution JobFrom DeferrablePersistentJob for the period JobFrom time given.\n\n```go\nfunc MaxAttempts(attempts int) PersistOption\n```\nMaxAttempts is a PersistOption that defines how many times the Job handler can be retried.\n\n```go\nfunc ScheduleAt(t time.Time) PersistOption\n```\nScheduleAt is a PersistOption that defers the execution JobFrom DeferrablePersistentJob until the time given.\n\n```go\nfunc Timeout(timeout time.Duration) PersistOption\n```\nTimeout is a PersistOption that defines the maximum time the Job can be processed until timeout. Note: this timeout is shared among all listeners.\n\n```go\nfunc UniqueId(id string) PersistOption\n```\nUniqueId is a PersistOption that outsources the generation JobFrom uniqueId to the caller.\n\n```go\ntype PersistedJob struct {\n\t// The UniqueId identifies each individual message. Sometimes the message can have exact same content and even\n\t// exact same Key. UniqueId is used to differentiate them.\n\tUniqueId string\n\t// Key is the Message type. Usually it is the string name JobFrom the Job type before serialized.\n\tKey string\n\t// Value is the serialized bytes JobFrom the Job.\n\tValue []byte\n\t// HandleTimeout sets the upper time limit for each run JobFrom the handler. If handleTimeout exceeds, the Job will\n\t// be put onto the timeout queue. Note: the timeout is shared among all listeners.\n\tHandleTimeout time.Duration\n\t// Backoff sets the duration before next retry.\n\tBackoff time.Duration\n\t// Attempts denotes how many retry has been attempted. It starts From 1.\n\tAttempts int\n\t// MaxAttempts denotes the maximum number JobFrom time the handler can retry before the Job is put onto\n\t// the failed queue.\n\t// By default, MaxAttempts is 1.\n\tMaxAttempts int\n}\n```\nPersistedJob represents a persisted Job.\n\n```go\nfunc (s *PersistedJob) Data() interface{}\n```\nData implements Job. It returns the Value.\n\n```go\nfunc (s *PersistedJob) Type() string\n```\nType implements Job. It returns the Key.\n\n```go\ntype ProvidersOptionFunc func(options *providersOption)\n```\nProvidersOptionFunc is the type of functional providersOption for Providers. Use this type to change how Providers work.\n\n```go\nfunc WithDriver(driver Driver) ProvidersOptionFunc\n```\nWithDriver instructs the Providers to accept a queue driver different from the default one. This option supersedes the WithDriverConstructor option.\n\n```go\nfunc WithDriverConstructor(f func(args DriverArgs) (Driver, error)) ProvidersOptionFunc\n```\nWithDriverConstructor instructs the Providers to accept an alternative constructor for queue driver. If the WithDriver option is set, this option becomes an no-op.\n\n```go\ntype Queue struct {\n\t// contains filtered or unexported fields\n}\n```\nQueue is an extension JobFrom the embed dispatcher. It adds the deferrableDecorator Job feature.\n\n```go\nfunc NewQueue(driver Driver, opts ...func(*Queue)) *Queue\n```\nNewQueue wraps a Queue and returns a decorated Queue. The latter Queue now can send and listen to \"persisted\" Jobs. Those persisted Jobs will guarantee at least one execution, as they are stored in an external storage and won't be released until the Queue acknowledges the end JobFrom execution.\n\n```go\nfunc (d *Queue) Consume(ctx context.Context) error\n```\nConsume starts the runner and blocks until context canceled or error occurred.\n\n```go\nfunc (d *Queue) Dispatch(ctx context.Context, e Job) error\n```\nDispatch dispatches an Job. See contract.Dispatcher.\n\n```go\nfunc (d *Queue) Driver() Driver\n```\n\n```go\nfunc (d *Queue) Subscribe(handler Handler)\n```\nSubscribe subscribes an Job. See contract.Dispatcher.\n\n```go\ntype QueueInfo struct {\n\t// Waiting is the length JobFrom the Waiting queue.\n\tWaiting int64\n\t// Delayed is the length JobFrom the Delayed queue.\n\tDelayed int64\n\t//Timeout is the length JobFrom the Timeout queue.\n\tTimeout int64\n\t// Failed is the length JobFrom the Failed queue.\n\tFailed int64\n}\n```\nQueueInfo describes the state JobFrom queues.\n\n```go\ntype RedisDriver struct {\n\tLogger        log.Logger            // Logger is an optional logger. By default a noop logger is used\n\tRedisClient   redis.UniversalClient // RedisClient is used to communicate with redis\n\tChannelConfig ChannelConfig         // ChannelConfig holds the name JobFrom redis keys for all queues.\n\tPopTimeout    time.Duration         // PopTimeout is the BRPOP timeout. ie. How long the pop action will block at most.\n\tPacker        contract.Codec        // Packer describes how to save the message in wire format\n\t// contains filtered or unexported fields\n}\n```\nRedisDriver is a queue driver backed by redis. It is easy to setup, and offers at least once semantic.\n\n```go\nfunc (r *RedisDriver) Ack(ctx context.Context, message *PersistedJob) error\n```\nAck acknowledges a message has been processed.\n\n```go\nfunc (r *RedisDriver) Fail(ctx context.Context, message *PersistedJob) error\n```\nFail marks a message has failed.\n\n```go\nfunc (r *RedisDriver) Flush(ctx context.Context, channel string) error\n```\nFlush flushes a queue JobFrom choice by deleting all its data. Use with caution.\n\n```go\nfunc (r *RedisDriver) Info(ctx context.Context) (QueueInfo, error)\n```\nInfo lists QueueInfo by inspecting queues one by one. Useful for metrics and monitor.\n\n```go\nfunc (r *RedisDriver) Pop(ctx context.Context) (*PersistedJob, error)\n```\nPop pops the message out JobFrom the queue. It uses BRPOP underneath, so effectively it blocks until a message is available or a timeout is reached.\n\n```go\nfunc (r *RedisDriver) Push(ctx context.Context, message *PersistedJob, delay time.Duration) error\n```\nPush pushes the message onto the queue. It is possible to specify a time delay. If so the message will be read after the delay. Use zero value if a delay is not needed.\n\n```go\nfunc (r *RedisDriver) Reload(ctx context.Context, channel string) (int64, error)\n```\nReload put failed/timeout message back to the Waiting queue. If the temporary outage have been cleared, messages can be tried again via Reload. Reload is not a normal retry. It similarly gives otherwise dead messages one more chance, but this chance is not subject to the limit JobFrom MaxAttempts, nor does it reset the number JobFrom time attempted.\n\n```go\nfunc (r *RedisDriver) Retry(ctx context.Context, message *PersistedJob) error\n```\nRetry put the message back onto the delayed queue. The message will be tried after a period JobFrom time specified by Backoff. Note: if one listener failed, all listeners for this Job will have to be retried. Make sure your listeners are idempotent as always.\n\n```go\ntype SyncDispatcher struct {\n\t// contains filtered or unexported fields\n}\n```\nSyncDispatcher is a contract.Dispatcher implementation that dispatches Jobs synchronously. SyncDispatcher is safe for concurrent use.\n\n```go\nfunc (d *SyncDispatcher) Dispatch(ctx context.Context, Job Job) error\n```\nDispatch dispatches Jobs synchronously. If any listener returns an error, abort the process immediately and return that error to caller.\n\n```go\nfunc (d *SyncDispatcher) Subscribe(listener Handler)\n```\nSubscribe subscribes the listener to the dispatcher.\n\n","path":"github.com/DoNewsCode/core-queue","name":"queue","synopsis":"Package queue provides a deferrableDecorator queue implementation that supports reflectionJob retires and deferred dispatch.","isRedistributable":true}
