### GoBus quick start example Source: https://github.com/assurrussa/gobus/blob/master/README.md Complete example showing how to create a bus, register handlers, subscribe to events, and dispatch commands, queries, and events. Uses Register, RegisterResult, Subscribe, Dispatch, DispatchResult, and Publish. ```go package main import ( "context" "fmt" "github.com/assurrussa/gobus" ) type CreateUser struct { Name string } type FindUser struct { Name string } type User struct { Name string } type UserCreated struct { Name string } type CreateUserHandler struct{} func (CreateUserHandler) Execute(_ context.Context, command CreateUser) error { // Store the user. return nil } type FindUserHandler struct{} func (FindUserHandler) Execute(_ context.Context, query FindUser) (User, error) { return User{Name: query.Name}, nil } type UserCreatedHandler struct{} func (UserCreatedHandler) Execute(_ context.Context, event UserCreated) error { fmt.Println("created:", event.Name) return nil } func main() { ctx := context.Background() bus := gobus.New() bus.Register(CreateUserHandler{}) bus.RegisterResult(FindUserHandler{}) bus.Subscribe(UserCreatedHandler{}) if err := bus.Dispatch(ctx, CreateUser{Name: "Amir"}); err != nil { panic(err) } user, err := bus.DispatchResult[User](ctx, FindUser{Name: "Amir"}) if err != nil { panic(err) } fmt.Println(user.Name) if err := bus.Publish(ctx, UserCreated{Name: user.Name}); err != nil { panic(err) } } ``` -------------------------------- ### Start error handling example Source: https://github.com/assurrussa/gobus Shows a basic call to Start with error handling. Returns the error if Start fails. ```go if err := runtime.Start(); err != nil { return err } ``` -------------------------------- ### Create async runtime with queues and submit command Source: https://github.com/assurrussa/gobus/blob/master/README.md Sets up a bounded in-memory async runtime with a mandatory default queue and an additional 'reports' queue, routes a command type, starts the runtime, submits a command, and shuts down. The default queue capacity and workers must be positive; configuration is frozen by Start. Submit waits for capacity or context cancellation. ```go runtime, err := async.New(bus, async.QueueConfig{ Capacity: 1024, Workers: 16, }) if err != nil { return err } if err := runtime.AddQueue("reports", async.QueueConfig{ Capacity: 64, Workers: 2, }); err != nil { return err } if err := runtime.RouteCommand[GenerateReport]("reports"); err != nil { return err } if err := runtime.Start(); err != nil { return err } result, err := runtime.Submit(ctx, GenerateReport{ID: id}) if err != nil { // Admission failed. return err } if err := <-result; err != nil { // Handler failed. return err } shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() return runtime.Shutdown(shutdownCtx) ``` -------------------------------- ### Runtime.Start Source: https://github.com/assurrussa/gobus/blob/master/README.md Starts the runtime workers. Configuration is frozen after this call. ```APIDOC ## Runtime.Start ### Description Starts the runtime workers. Configuration is frozen after this call. ### Method Start ### Returns - **err** (error) - Error if starting fails. ### Request Example ```go if err := runtime.Start(); err != nil { return err } ``` ``` -------------------------------- ### Install GoBus with go get Source: https://github.com/assurrussa/gobus/blob/master/README.md Install the GoBus library at version v1.2.2 using the go get command. Requires Go 1.27 or later. ```sh go get github.com/assurrussa/gobus@v1.2.2 ``` -------------------------------- ### Start idempotent-unsafe guard example Source: https://github.com/assurrussa/gobus Demonstrates guarding against double starts. The second call to Start returns ErrRuntimeStarted, which is checked with errors.Is. ```go // Start is idempotent-unsafe: the second call is an error. if err := runtime.Start(); err != nil { return err } if err := runtime.Start(); err != nil { if errors.Is(err, async.ErrRuntimeStarted) { log.Print("runtime already started") // guard against double starts } } ``` -------------------------------- ### Full configuration assembly with async runtime Source: https://github.com/assurrussa/gobus Assembles a GoBus runtime: registers handlers, creates a default queue, adds a 'reports' queue, routes commands and results to it, then starts the runtime. After Start, configuration is frozen. Submissions before Start fail with ErrRuntimeNotStarted; after Shutdown begins, new jobs are rejected with ErrRuntimeClosed. ```go bus := gobus.New() bus.Register(CreateUserHandler{}) bus.RegisterResult(FindUserHandler{}) runtime, err := async.New(bus, async.QueueConfig{Capacity: 1024, Workers: 16}) // default queue if err != nil { return err } if err := runtime.AddQueue("reports", async.QueueConfig{Capacity: 64, Workers: 2}); err != nil { return err } if err := runtime.RouteCommand[GenerateReport]("reports"); err != nil { return err } if err := runtime.RouteResult[LookupReport, Report]("reports"); err != nil { return err } if err := runtime.Start(); err != nil { return err } // Configuration is frozen from here on. ``` -------------------------------- ### Runtime.Submit with WithExecutionContext Source: https://github.com/assurrussa/gobus/blob/master/README.md Submits a command with independent admission and execution contexts. The execution context is stored with the job and used when the worker starts. ```APIDOC ## Runtime.Submit with WithExecutionContext ### Description Submits a command with independent admission and execution contexts. The execution context is stored with the job and used when the worker starts. ### Method Submit ### Parameters #### Arguments - **admissionCtx** (context.Context) - Required - Controls admission. - **command** (Command) - Required - The command to execute. - **option** (Option) - Required - WithExecutionContext(executionCtx). ### Returns - **result** (<-chan error) - Channel that receives the execution result. - **err** (error) - Admission error if any. ### Request Example ```go admissionCtx, cancel := context.WithTimeout(request.Context(), 100*time.Millisecond) defer cancel() executionCtx := context.WithoutCancel(request.Context()) result, err := runtime.Submit( admissionCtx, SendEmail{UserID: id}, async.WithExecutionContext(executionCtx), ) ``` ``` -------------------------------- ### Start Source: https://github.com/assurrussa/gobus Starts the runtime by freezing configuration and spawning workers for each queue. It transitions the state to StateRunning and begins accepting submissions. ```APIDOC ## Start ### Description Starts the runtime by freezing configuration and spawning workers for each queue. It transitions the state to StateRunning and begins accepting submissions. ### Method Start ### Endpoint `func (r *Runtime) Start() error` ### Parameters No arguments. ### Response #### Success Response Returns `error`. #### Errors - `ErrRuntimeStarted` - `Start` called while already `StateRunning` (a second start). - `ErrRuntimeClosed` - `Start` called while `StateClosing` or `StateClosed`. - `fmt.Errorf("async: unknown runtime state %q", state)` - Unreachable state value. ### Request Example ```go if err := runtime.Start(); err != nil { return err } ``` ```go // Start is idempotent-unsafe: the second call is an error. if err := runtime.Start(); err != nil { return err } if err := runtime.Start(); err != nil { if errors.Is(err, async.ErrRuntimeStarted) { log.Print("runtime already started") // guard against double starts } } ``` ``` -------------------------------- ### Start method signature Source: https://github.com/assurrussa/gobus Declares the Start method that freezes configuration and starts every queue's workers. It spawns exactly Workers goroutines per queue and transitions to StateRunning. ```go // Start freezes configuration and starts every queue's workers. func (r *Runtime) Start() error ``` -------------------------------- ### AddQueue after Start returns ErrConfigFrozen Source: https://github.com/assurrussa/gobus Shows that calling AddQueue after Start is refused because the runtime freezes all configuration. The error is checked with errors.Is to detect ErrConfigFrozen and log a message. ```go // Configuring after Start is refused: the runtime freezes all configuration. if err := runtime.Start(); err != nil { return err } if err := runtime.AddQueue("late", async.QueueConfig{Capacity: 1, Workers: 1}); err != nil { if errors.Is(err, async.ErrConfigFrozen) { log.Print("queue configuration is frozen after Start") } } ``` -------------------------------- ### Routing usage example Source: https://github.com/assurrussa/gobus Shows how to route commands, results, and events to a named queue. Each call returns an error that should be handled. ```go if err := runtime.RouteCommand[GenerateReport]("reports"); err != nil { return err } if err := runtime.RouteResult[LookupReport, Report]("reports"); err != nil { return err } if err := runtime.RouteEvent[ReportGenerated]("reports"); err != nil { return err } ``` -------------------------------- ### DispatchAsync Source: https://github.com/assurrussa/gobus/blob/master/README.md Asynchronously dispatches a command to a handler. Starts one goroutine per call and immediately returns a receive-only channel that receives exactly one value (nil on success) and is then closed. ```APIDOC ## DispatchAsync ### Description Asynchronously dispatches a command to a handler. Starts one goroutine per call and immediately returns a receive-only channel that receives exactly one value (nil on success) and is then closed. ### Method DispatchAsync ### Parameters - **ctx** (context.Context) - Required - The context passed to the handler. - **command** (C) - Required - The command to dispatch. ### Response - **<-chan error** - Receives nil on success or a *gobus.PanicError if the handler panics, or gobus.ErrHandlerGoexit if the handler terminates via runtime.Goexit. ### Request Example ```go err := <-bus.DispatchAsync(ctx, command) ``` ``` -------------------------------- ### Runtime.Stats Source: https://github.com/assurrussa/gobus/blob/master/README.md Returns runtime statistics including queue configuration, depth, active work, and cumulative counters. ```APIDOC ## Runtime.Stats ### Description Returns runtime statistics including queue configuration, depth, active work, and cumulative counters. ### Method Stats ### Returns - **stats** (Stats) - Statistics object. ``` -------------------------------- ### RouteCommand[Q] Source: https://github.com/assurrussa/gobus Configures the queue for Submit/TrySubmit of command type Q. Returns an error if the queue is unknown or if called after Start. ```APIDOC ## RouteCommand[Q] ### Description Configures the queue for Submit/TrySubmit of command type Q. Returns an error if the queue is unknown or if called after Start. ### Method N/A (configuration function) ### Parameters #### Function Signature - `queueName` (string) - Required - The name of the queue to route commands of type Q to. ### Response #### Success Response - No return value on success. #### Error Response - `ErrQueueNotFound` - Returned if the queue name is unknown. - `ErrConfigFrozen` - Returned if called after Start. ``` -------------------------------- ### DispatchResultAsync Source: https://github.com/assurrussa/gobus/blob/master/README.md Asynchronously dispatches a query and returns a channel that receives an envelope containing the result and error. Starts one goroutine per call and immediately returns a receive-only channel that receives exactly one envelope and is then closed. ```APIDOC ## DispatchResultAsync ### Description Asynchronously dispatches a query and returns a channel that receives an envelope containing the result and error. Starts one goroutine per call and immediately returns a receive-only channel that receives exactly one envelope and is then closed. ### Method DispatchResultAsync ### Parameters - **ctx** (context.Context) - Required - The context passed to the handler. - **query** (Q) - Required - The query to dispatch. ### Response - **<-chan Envelope[Result]** - Receives an envelope with Result and Error fields. The Error may be a *gobus.PanicError if the handler panics, or gobus.ErrHandlerGoexit if the handler terminates via runtime.Goexit. ### Request Example ```go envelope := <-bus.DispatchResultAsync[Result](ctx, query) result, err := envelope.Result, envelope.Error ``` ``` -------------------------------- ### New Source: https://github.com/assurrussa/gobus Constructs a configurable Runtime with a required default queue. It does not start workers until Start is called. ```APIDOC ## New ### Description Constructs a configurable Runtime with a required default queue. It does not start workers until Start is called. ### Method New ### Parameters - **bus** (*gobus.Bus) - Required - The bus whose handlers the runtime executes. Must not be nil. - **defaultQueue** (QueueConfig) - Required - Capacity (jobs waiting for a worker) and Workers (parallel handlers) of the reserved `default` queue. ### Returns (*Runtime, error) ### Errors - **ErrNilBus** - bus == nil. - **ErrInvalidQueueConfig** - Capacity <= 0 (capacity must be positive) or Workers <= 0 (workers must be positive). ### Request Example ```go runtime, err := async.New(bus, async.QueueConfig{Capacity: 1024, Workers: 16}) if err != nil { return err } ``` ```go runtime, err := async.New(nil, async.QueueConfig{Capacity: 8, Workers: 1}) if errors.Is(err, async.ErrNilBus) { return fmt.Errorf("async runtime requires a bus: %w", err) } ``` ``` -------------------------------- ### Run complete repository gate with make check Source: https://github.com/assurrussa/gobus/blob/master/README.md Runs formatting, build, vet, lint, tests, race detection, checkptr, coverage, and an isolated consumer build. Requires golangci-lint v2.13.1 or newer built with Go 1.27 support. ```shell make check ``` -------------------------------- ### Import GoBus package Source: https://github.com/assurrussa/gobus/blob/master/README.md Import the GoBus package in Go code to use its dispatcher API. ```go import "github.com/assurrussa/gobus" ``` -------------------------------- ### TrySubmitEvent usage example Source: https://github.com/assurrussa/gobus Shows how to call TrySubmitEvent and handle ErrQueueFull by dropping the event when the queue is saturated. ```go result, err := runtime.TrySubmitEvent(ctx, UserCreated{Name: "Amir"}) if errors.Is(err, async.ErrQueueFull) { return nil // drop: queue saturated, event not critical } if err != nil { return err } return <-result ``` -------------------------------- ### DispatchAsync and DispatchResultAsync usage Source: https://github.com/assurrussa/gobus/blob/master/README.md Shows asynchronous dispatch methods that start one goroutine per call and return a receive-only channel. Each channel receives exactly one value and is closed; successful DispatchAsync sends nil. Panics are recovered and reported as *gobus.PanicError, and runtime.Goexit is reported as gobus.ErrHandlerGoexit. ```go err := <-bus.DispatchAsync(ctx, command) envelope := <-bus.DispatchResultAsync[Result](ctx, query) result, err := envelope.Result, envelope.Error ``` -------------------------------- ### Shutdown with timeout example Source: https://github.com/assurrussa/gobus Shows a typical Shutdown call with a 10-second timeout. Returns a wrapped error if shutdown fails. ```go shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := runtime.Shutdown(shutdownCtx); err != nil { return fmt.Errorf("shutdown: %w", err) } ``` -------------------------------- ### TrySubmit usage example Source: https://github.com/assurrussa/gobus Shows how to call TrySubmit and handle ErrQueueFull for graceful degradation. The result channel is read to detect handler errors. ```go result, err := runtime.TrySubmit(ctx, RefreshCache{Key: key}) if errors.Is(err, async.ErrQueueFull) { log.Print("queue full; dropping refresh") // graceful degradation return nil } if err != nil { return err } if err := <-result; err != nil { log.Printf("refresh failed: %v", err) } ``` -------------------------------- ### Run 12-CPU benchmark suite with make bench-all Source: https://github.com/assurrussa/gobus/blob/master/README.md Runs the same 12-CPU benchmark suite locally. Exact timings depend on the machine; allocation regression tests enforce command dispatch at 0 allocs/op and result dispatch at most 1 alloc/op. ```shell make bench-all ``` -------------------------------- ### Stats usage example Source: https://github.com/assurrussa/gobus Calls Stats() and prints state, depth, and active count for the default queue. Uses async.DefaultQueueName to access per-queue metrics. ```go stats := runtime.Stats() fmt.Printf("state=%s depth=%d active=%d\n", stats.State, stats.Queues[async.DefaultQueueName].Depth, stats.Queues[async.DefaultQueueName].Active) ``` -------------------------------- ### Inject *gobus.Bus into a Service Source: https://github.com/assurrussa/gobus/blob/master/README.md Create and populate a bus in the application composition root, then pass the same instance to services that need it. Use a separate bus for another application boundary or for each test; registrations on one bus never affect another. The type should not be copied after first use. ```go type Service struct { bus *gobus.Bus } func NewService(bus *gobus.Bus) *Service { return &Service{bus: bus} } ``` -------------------------------- ### RouteResult[Q, T] Source: https://github.com/assurrussa/gobus Configures the queue for SubmitResult/TrySubmitResult of query/result pair (Q, T). Returns an error if the queue is unknown or if called after Start. ```APIDOC ## RouteResult[Q, T] ### Description Configures the queue for SubmitResult/TrySubmitResult of query/result pair (Q, T). Returns an error if the queue is unknown or if called after Start. ### Method N/A (configuration function) ### Parameters #### Function Signature - `queueName` (string) - Required - The name of the queue to route query/result pairs of type (Q, T) to. ### Response #### Success Response - No return value on success. #### Error Response - `ErrQueueNotFound` - Returned if the queue name is unknown. - `ErrConfigFrozen` - Returned if called after Start. ``` -------------------------------- ### Publish usage example Source: https://github.com/assurrussa/gobus Shows subscribing two handlers and publishing an event. If Publish returns an error, the fan-out partially failed and the joined error is logged. ```go bus.Subscribe(AuditLog{}) bus.Subscribe(NofifierDispatch{}) if err := bus.Publish(ctx, UserCreated{Name: "Amir"}); err != nil { log.Printf("fan-out partially failed: %v", err) } ``` -------------------------------- ### WithExecutionContext Source: https://github.com/assurrussa/gobus Creates a SubmitOption that stores an execution context with an accepted job, used for handler execution instead of the admission context. The deadline starts when the context is created, not when a worker starts the job. ```APIDOC ## WithExecutionContext ### Description Stores ctx with an accepted job and uses it for handler execution instead of the admission context. Its deadline starts when ctx is created, not when a worker starts the job. When repeated, the last option wins. ### Method WithExecutionContext ### Parameters #### Parameters - **ctx** (`context.Context`) - Required - Execution context stored with the accepted job; replaced if repeated. Must not be nil. ### Returns `SubmitOption` — an option struct with unexported fields; only the zero value is invalid (option kind 0). Passing `WithExecutionContext(nil)` makes the submission fail with `ErrInvalidSubmitOption` (`execution context is nil`). ### Request Example ```go result, err := runtime.Submit( admissionCtx, SendEmail{UserID: id}, async.WithExecutionContext(context.WithoutCancel(request.Context())), ) if err != nil { return err } if err := <-result; err != nil { return err } ``` ```go // Deadline measured from creation time — the caller's clock, not the queue's. deadline, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() result, err := runtime.Submit(ctx, Reindex{Index: "search"}, async.WithExecutionContext(deadline)) if err != nil { return err } if err := <-result; err != nil { // err may be context.DeadlineExceeded if the job waited past the deadline. } ``` ``` -------------------------------- ### Publish Source: https://github.com/assurrussa/gobus/blob/master/README.md Publishes an event to all subscribed handlers. It loads one immutable subscriber snapshot and invokes every handler sequentially in subscription order. Returns nil when there are no subscribers and combines subscriber errors with errors.Join. ```APIDOC ## Publish ### Description Publishes an event to all subscribed handlers. It loads one immutable subscriber snapshot and invokes every handler sequentially in subscription order. Returns nil when there are no subscribers and combines subscriber errors with errors.Join. ### Method Publish ### Parameters - **ctx** (context.Context) - Required - The context passed to handlers. - **event** (E) - Required - The event to publish. ### Response - **error** - nil if no subscribers, otherwise combined subscriber errors. ### Request Example ```go err := bus.Publish(ctx, event) ``` ``` -------------------------------- ### RouteEvent[E] Source: https://github.com/assurrussa/gobus Configures the queue for SubmitEvent/TrySubmitEvent of event type E. Returns an error if the queue is unknown or if called after Start. ```APIDOC ## RouteEvent[E] ### Description Configures the queue for SubmitEvent/TrySubmitEvent of event type E. Returns an error if the queue is unknown or if called after Start. ### Method N/A (configuration function) ### Parameters #### Function Signature - `queueName` (string) - Required - The name of the queue to route events of type E to. ### Response #### Success Response - No return value on success. #### Error Response - `ErrQueueNotFound` - Returned if the queue name is unknown. - `ErrConfigFrozen` - Returned if called after Start. ``` -------------------------------- ### Subscribe Source: https://github.com/assurrussa/gobus/blob/master/README.md Registers an event handler for a specific event type. Subscriptions are append-only for the lifetime of the bus, and each call creates a distinct subscription. ```APIDOC ## Subscribe ### Description Registers an event handler for a specific event type. Subscriptions are append-only for the lifetime of the bus, and each call creates a distinct subscription. ### Method Subscribe ### Parameters - **handler** (EventExecutor[E]) - Required - The handler to subscribe. ### Response No return value. ### Request Example ```go bus.Subscribe(firstHandler) bus.Subscribe(secondHandler) ``` ``` -------------------------------- ### AddQueue Source: https://github.com/assurrussa/gobus Adds a named bounded queue to the runtime. Configuration is frozen by Start, and the queue can be targeted by RouteCommand, RouteResult, and RouteEvent. ```APIDOC ## AddQueue ### Description Adds a named bounded queue to the runtime. Configuration is frozen by Start, and the queue can be targeted by RouteCommand, RouteResult, and RouteEvent. ### Method AddQueue ### Endpoint func (r *Runtime) AddQueue(name string, config QueueConfig) error ### Parameters #### Path Parameters - **name** (string) - Required - Queue name; must be non-empty and not "default". - **config** (QueueConfig) - Required - Independent capacity and worker count (both must be positive). ### Response #### Success Response - **error** - Returns an error if the operation fails. ### Errors - **ErrInvalidQueueConfig** - Empty name, reserved name "default", or non-positive capacity/workers. - **ErrConfigFrozen** - Runtime state is no longer StateNew (called after Start or Shutdown). - **ErrQueueExists** - A queue with name already exists (wrapped with the name: `async: queue already exists: reports`). ### Request Example ```go if err := runtime.AddQueue("reports", async.QueueConfig{Capacity: 64, Workers: 2}); err != nil { return err } ``` ```go // Configuring after Start is refused: the runtime freezes all configuration. if err := runtime.Start(); err != nil { return err } if err := runtime.AddQueue("late", async.QueueConfig{Capacity: 1, Workers: 1}); err != nil { if errors.Is(err, async.ErrConfigFrozen) { log.Print("queue configuration is frozen after Start") } } ``` ``` -------------------------------- ### EventExecutor interface and subscribe/publish usage Source: https://github.com/assurrussa/gobus/blob/master/README.md Defines the typed EventExecutor contract and shows subscribing handlers and publishing an event. Subscribe is append-only; Publish invokes handlers sequentially and returns nil when no subscribers, combining errors with errors.Join. ```go type EventExecutor[E any] interface { Execute(context.Context, E) error } bus.Subscribe(firstHandler) bus.Subscribe(secondHandler) err := bus.Publish(ctx, event) ``` -------------------------------- ### AddQueue usage example Source: https://github.com/assurrussa/gobus Adds a queue named 'reports' with capacity 64 and 2 workers. Returns an error if the queue cannot be added, such as when the name is invalid or already exists. ```go if err := runtime.AddQueue("reports", async.QueueConfig{Capacity: 64, Workers: 2}); err != nil { return err } ``` -------------------------------- ### Submit with explicit execution context Source: https://github.com/assurrussa/gobus/blob/master/README.md Shows that Submit without an execution context option uses the admission context for execution, and the equivalent call with WithExecutionContext. Use WithExecutionContext when admission and execution need independent lifetimes. ```go result, err := runtime.Submit(ctx, command) // Equivalent to: result, err = runtime.Submit( ctx, command, async.WithExecutionContext(ctx), ) ``` -------------------------------- ### Runtime.Shutdown Source: https://github.com/assurrussa/gobus/blob/master/README.md Shuts down the runtime: rejects new work, drains accepted jobs, and waits for workers. If the context expires, queued jobs receive ErrRuntimeShutdown and running contexts are cancelled. ```APIDOC ## Runtime.Shutdown ### Description Shuts down the runtime: rejects new work, drains accepted jobs, and waits for workers. If the context expires, queued jobs receive ErrRuntimeShutdown and running contexts are cancelled. ### Method Shutdown ### Parameters #### Arguments - **ctx** (context.Context) - Required - Shutdown context with timeout. ### Returns - **err** (error) - Error if shutdown fails or context expires. ### Request Example ```go shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() return runtime.Shutdown(shutdownCtx) ``` ``` -------------------------------- ### SubmitResult usage example Source: https://github.com/assurrussa/gobus Shows how to call SubmitResult and read the envelope. The envelope's Error field is checked before using Result. ```go envelope := <-mustSubmit(runtime.SubmitResult[Report](ctx, LookupReport{ID: id})) if envelope.Error != nil { return envelope.Error } return envelope.Result ``` -------------------------------- ### GoBus type inference for Register, RegisterResult, Dispatch, DispatchResult Source: https://github.com/assurrussa/gobus/blob/master/README.md Shows that Register, RegisterResult, and Dispatch infer type parameters from arguments, while DispatchResult requires only the expected output type. ```go bus.Register(commandHandler) bus.RegisterResult(queryHandler) err := bus.Dispatch(ctx, command) result, err := bus.DispatchResult[Result](ctx, query) ``` -------------------------------- ### Create a new Bus with gobus.New() Source: https://github.com/assurrussa/gobus Returns an initialized *Bus with empty command, result, and event registries. Never throws. Use this to start a bus and register handlers. ```go // New returns an initialized Bus with isolated handler registries. func New() *Bus ``` ```go bus := gobus.New() bus.Register(CreateUserHandler{}) err := bus.Dispatch(context.Background(), CreateUser{Name: "Amir"}) ``` -------------------------------- ### Basic Submit usage Source: https://github.com/assurrussa/gobus Shows a typical Submit call. The returned channel receives exactly one error then closes; the direct error is an admission failure. The example checks both the direct error and the channel error. ```go result, err := runtime.Submit(ctx, GenerateReport{ID: id}) if err != nil { return err // Admission failed. } if err := <-result; err != nil { return err // Handler failed. } ``` -------------------------------- ### Shutdown deadline exceeded handling example Source: https://github.com/assurrussa/gobus Handles forced cancellation when the drain exceeds the deadline. Checks for context.DeadlineExceeded and logs a message. ```go // Handlers that ignore context cancellation cannot be forcibly terminated. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := runtime.Shutdown(ctx); err != nil { if errors.Is(err, context.DeadlineExceeded) { log.Print("drain exceeded deadline; forced cancellation issued") return err } } ``` -------------------------------- ### New function signature Source: https://github.com/assurrussa/gobus Constructs a configurable Runtime with a required default queue. It does not start workers. The default queue's Capacity and Workers must both be positive. ```go // New constructs a configurable Runtime with a required default queue. // It does not start workers. func New(bus *gobus.Bus, defaultQueue QueueConfig) (*Runtime, error) ``` -------------------------------- ### Register a decorated handler with bus.Register Source: https://github.com/assurrussa/gobus/blob/master/README.md Wrap a CommandExecutor or ResultCommandExecutor before registration to add cross-cutting behavior like logging, metrics, tracing, authorization, retries, and similar policies. Extensions should depend only on the exported handler contracts; the immutable registry snapshots and atomic copy-on-write implementation are internal implementation details. ```go decorated := mymiddleware.WithLogging(handler) bus.Register(decorated) ``` -------------------------------- ### SubmitEvent enqueue event publication with error handling Source: https://github.com/assurrussa/gobus Enqueues a complete event publication; one worker runs bus.Publish(ctx, event) and all subscribers run sequentially. The example submits an event and checks the returned channel for publication errors. ```go // SubmitEvent enqueues a complete event publication, waiting for capacity or // admissionContext cancellation. Without WithExecutionContext, // admissionContext also controls handler execution. func (r *Runtime) SubmitEvent[E gobus.ObjectIn]( admissionContext context.Context, event E, options ...SubmitOption, ) (<-chan error, error) ``` ```go result, err := runtime.SubmitEvent(ctx, UserCreated{Name: "Amir"}) if err != nil { return err } if err := <-result; err != nil { log.Printf("event fan-out had errors: %v", err) // errors.Is still works on each } ``` -------------------------------- ### Submit with separate admission and execution contexts Source: https://github.com/assurrussa/gobus/blob/master/README.md Uses a short timeout for admission and a detached execution context. Cancelling the admission context after success does not affect execution. The runtime stores the execution context with the job; if already cancelled, the handler is skipped and the completion channel receives that context error. ```go admissionCtx, cancel := context.WithTimeout(request.Context(), 100*time.Millisecond) defer cancel() executionCtx := context.WithoutCancel(request.Context()) result, err := runtime.Submit( admissionCtx, SendEmail{UserID: id}, async.WithExecutionContext(executionCtx), ) ``` -------------------------------- ### AddQueue method signature Source: https://github.com/assurrussa/gobus Adds a named bounded queue with independent capacity and worker count. Configuration is frozen by Start; name must be non-empty and not 'default', and capacity/workers must be positive. Returns ErrInvalidQueueConfig, ErrConfigFrozen, or ErrQueueExists on failure. ```go // AddQueue adds a named bounded queue. Configuration is frozen by Start. func (r *Runtime) AddQueue(name string, config QueueConfig) error ``` -------------------------------- ### DispatchResult usage example Source: https://github.com/assurrussa/gobus Calls DispatchResult with a FindUser query and a User output type. On success, prints the user's name; on error, returns the error. ```go user, err := bus.DispatchResult[User](ctx, FindUser{Name: "Amir"}) if err != nil { return err } fmt.Println(user.Name) ``` -------------------------------- ### State type and constants Source: https://github.com/assurrussa/gobus Defines the State string type and the four lifecycle constants: StateNew, StateRunning, StateClosing, StateClosed. StateNew is configurable with workers not started; StateRunning accepts and executes jobs; StateClosing rejects new jobs with ErrRuntimeClosed while accepted jobs drain; StateClosed is terminal and cannot be restarted. ```go type State string const ( StateNew State = "new" StateRunning State = "running" StateClosing State = "closing" StateClosed State = "closed" ) ``` -------------------------------- ### Before: Global registration and dispatch Source: https://github.com/assurrussa/gobus/blob/master/MIGRATION.md Shows the old global API before migration. Use this as a reference when updating code. ```go gobus.Register[CreateUser](createUserHandler) gobus.RegisterResult[FindUser, User](findUserHandler) err := gobus.Dispatch[CreateUser](ctx, command) user, err := gobus.DispatchResult[FindUser, User](ctx, query) ``` -------------------------------- ### Catching ErrHandlerGoexit with errors.Is Source: https://github.com/assurrussa/gobus Example of checking for ErrHandlerGoexit after DispatchAsync. Use errors.Is to match the sentinel. ```go err := <-bus.DispatchAsync(ctx, CreateUser{Name: "Amir"}) if errors.Is(err, gobus.ErrHandlerGoexit) { log.Print("handler terminated via runtime.Goexit") } ``` -------------------------------- ### Catching ErrHandlerNotFound with errors.Is Source: https://github.com/assurrussa/gobus Example of checking for ErrHandlerNotFound after a DispatchResult call. The error is wrapped, so errors.Is is required. ```go user, err := bus.DispatchResult[User](ctx, FindUser{Name: "Amir"}) if errors.Is(err, gobus.ErrHandlerNotFound) { // Missing command or (input, output) registration. } ``` -------------------------------- ### New with nil bus error handling Source: https://github.com/assurrussa/gobus Attempts to create a Runtime with a nil bus and a small queue. Checks for ErrNilBus and wraps the error with context. ```go runtime, err := async.New(nil, async.QueueConfig{Capacity: 8, Workers: 1}) if errors.Is(err, async.ErrNilBus) { return fmt.Errorf("async runtime requires a bus: %w", err) } ``` -------------------------------- ### New with valid queue config Source: https://github.com/assurrussa/gobus Creates a Runtime with a default queue of capacity 1024 and 16 workers. Returns an error if the bus is nil or the queue config is invalid. ```go runtime, err := async.New(bus, async.QueueConfig{Capacity: 1024, Workers: 16}) if err != nil { return err } ``` -------------------------------- ### Verify release with make test-consumer-release Source: https://github.com/assurrussa/gobus/blob/master/MIGRATION.md After publishing, verify the actual tag without a replace directive using this command. ```sh make test-consumer-release VERSION=vX.Y.Z ``` -------------------------------- ### After: Instance-based bus with inferred types Source: https://github.com/assurrussa/gobus/blob/master/MIGRATION.md New API using a bus instance. Register and RegisterResult infer type arguments from the handler; Dispatch infers input type from the DTO, and result dispatch only needs the output type. ```go bus := gobus.New() bus.Register(createUserHandler) bus.RegisterResult(findUserHandler) err := bus.Dispatch(ctx, command) user, err := bus.DispatchResult[User](ctx, query) ``` -------------------------------- ### Monitoring HTTP handler with Stats Source: https://github.com/assurrussa/gobus Exposes a snapshot to an HTTP handler. Checks if runtime is not running and logs a message, then writes per-queue metrics including depth, active, accepted, completed, and rejected counts. ```go // Monitoring: expose a snapshot to an HTTP handler. func handleMetrics(w http.ResponseWriter, _ *http.Request) { stats := runtime.Stats() if stats.State != async.StateRunning { log.Print("runtime not running") } for name, q := range stats.Queues { fmt.Fprintf(w, "queue %s: depth=%d active=%d accepted=%d completed=%d rejected=%d\n", name, q.Depth, q.Active, q.Accepted, q.Completed, q.Rejected) } } ``` -------------------------------- ### TrySubmit Source: https://github.com/assurrussa/gobus Attempts to enqueue a command without waiting for capacity. Returns ErrQueueFull immediately if the target queue is full. ```APIDOC ## TrySubmit ### Description Attempts to enqueue a command without waiting for capacity. Returns ErrQueueFull immediately if the target queue is full. ### Method TrySubmit ### Signature ```go func (r *Runtime) TrySubmit[Q gobus.ObjectIn]( admissionContext context.Context, command Q, options ...SubmitOption, ) (<-chan error, error) ``` ### Parameters - **admissionContext** (`context.Context`) - Required - Checked before enqueue; without an option, also controls execution. - **command** (`Q`) - Required - Command dispatched via `bus.Dispatch`. - **options** (`...SubmitOption`) - Optional - Job options. ### Returns `(<-chan error, error)` — same as `Submit`, plus `ErrQueueFull` on a full queue. ### Request Example ```go result, err := runtime.TrySubmit(ctx, RefreshCache{Key: key}) if errors.Is(err, async.ErrQueueFull) { log.Print("queue full; dropping refresh") // graceful degradation return nil } if err != nil { return err } if err := <-result; err != nil { log.Printf("refresh failed: %v", err) } ``` ``` -------------------------------- ### TrySubmitResult non-blocking submit with ErrQueueFull handling Source: https://github.com/assurrussa/gobus Non-blocking variant of SubmitResult; returns ErrQueueFull directly when the queue is full. The example checks for ErrQueueFull and other errors before reading the envelope. ```go // TrySubmitResult checks admissionContext and attempts to enqueue a query // without waiting for capacity. Without WithExecutionContext, // admissionContext also controls handler execution. func (r *Runtime) TrySubmitResult[T gobus.ObjectOut, Q gobus.ObjectIn]( admissionContext context.Context, query Q, options ...SubmitOption, ) (<-chan gobus.Envelope[T], error) ``` ```go envelope, err := runtime.TrySubmitResult[Report](ctx, LookupReport{ID: id}) if errors.Is(err, async.ErrQueueFull) { return nil, ErrReportsBacklogged } if err != nil { return nil, err } env := <-envelope return env.Result, env.Error ``` -------------------------------- ### Submit with WithExecutionContext and deadline Source: https://github.com/assurrussa/gobus Shows that the deadline is measured from creation time, not queue wait; the error may be context.DeadlineExceeded if the job waited past the deadline. ```go // Deadline measured from creation time — the caller's clock, not the queue's. deadline, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() result, err := runtime.Submit(ctx, Reindex{Index: "search"}, async.WithExecutionContext(deadline)) if err != nil { return err } if err := <-result; err != nil { // err may be context.DeadlineExceeded if the job waited past the deadline. } ``` -------------------------------- ### Subscribe and Publish synchronous event in v1.1.0 Source: https://github.com/assurrussa/gobus/blob/master/MIGRATION.md Shows the new synchronous in-process event API added in v1.1.0. Subscribe a handler, then publish an event; Publish calls subscriber snapshots sequentially and joins errors. ```go bus.Subscribe(userCreatedHandler) err := bus.Publish(ctx, UserCreated{UserID: id}) ``` -------------------------------- ### RouteCommand method signature Source: https://github.com/assurrussa/gobus Routes commands of type Q to a named queue. The queue must exist at routing time. Returns ErrConfigFrozen if runtime is not in StateNew, or ErrQueueNotFound if the queue is not configured. ```go // RouteCommand routes commands of type Q to a named queue. func (r *Runtime) RouteCommand[Q gobus.ObjectIn](queueName string) error ``` -------------------------------- ### Submit method signature Source: https://github.com/assurrussa/gobus Declares the Submit method on Runtime. It enqueues a command, waiting for capacity or admissionContext cancellation. Without WithExecutionContext, admissionContext also controls handler execution. The zero value of options is invalid. ```go // Submit enqueues a command, waiting for capacity or admissionContext // cancellation. Without WithExecutionContext, admissionContext also controls // handler execution. func (r *Runtime) Submit[Q gobus.ObjectIn]( admissionContext context.Context, command Q, options ...SubmitOption, ) (<-chan error, error) ``` -------------------------------- ### WithExecutionContext Source: https://github.com/assurrussa/gobus Sets the execution context for a job, replacing the admission context for handler execution. The context must be provided; nil results in an error at submission. ```APIDOC ## WithExecutionContext ### Description Sets the execution context for a job, replacing the admission context for handler execution. The context must be provided; nil results in an error at submission. ### Method N/A (option function) ### Parameters #### Option Parameters - `ctx` (context.Context) - Required - The execution context to store with the accepted job. ### Response #### Success Response - No return value on success. #### Error Response - `ErrInvalidSubmitOption` - Returned if `ctx` is nil at submission. ``` -------------------------------- ### TrySubmit function signature Source: https://github.com/assurrussa/gobus Declares TrySubmit, which enqueues a command without waiting for capacity. Returns ErrQueueFull immediately if the target queue is full. The admission context is checked before the enqueue attempt. ```go // TrySubmit checks admissionContext and attempts to enqueue a command without // waiting for capacity. Without WithExecutionContext, admissionContext also // controls handler execution. func (r *Runtime) TrySubmit[Q gobus.ObjectIn]( admissionContext context.Context, command Q, options ...SubmitOption, ) (<-chan error, error) ``` -------------------------------- ### SubmitOption / WithExecutionContext Source: https://github.com/assurrussa/gobus SubmitOption is a type that configures submission behavior. WithExecutionContext is a constructor that sets a separate execution context, allowing admission and execution lifetimes to differ. ```APIDOC ## SubmitOption / WithExecutionContext ### Description SubmitOption is a type that configures submission behavior. WithExecutionContext is a constructor that sets a separate execution context, allowing admission and execution lifetimes to differ. ### Method WithExecutionContext ### Parameters - **executionContext** (context.Context) - Required - The context that controls handler execution. ### Returns - **SubmitOption** - The option to pass to submission methods. ``` -------------------------------- ### async.QueueConfig struct Source: https://github.com/assurrussa/gobus Defines bounded capacity and fixed concurrency. Capacity bounds waiting jobs, Workers bounds parallel execution; total accepted jobs ≤ Capacity + Workers. Accepted by async.New and async.Runtime.AddQueue. ```go // QueueConfig defines the bounded capacity and fixed concurrency of a queue. // Capacity bounds jobs waiting for a worker; Workers bounds jobs executing in // parallel. At most Capacity + Workers accepted jobs can wait or execute. type QueueConfig struct { Capacity int Workers int } ``` -------------------------------- ### Stats method signature Source: https://github.com/assurrussa/gobus Returns a concurrency-safe snapshot of runtime and queue state. Because queue depth and counters are individually atomic and update concurrently with running workers, the result is a best-effort, eventually consistent metrics snapshot rather than a linearizable point-in-time state. ```go // Stats returns a concurrency-safe snapshot of runtime and queue state. // Because queue depth and counters are individually atomic and update // concurrently with running workers, the result is a best-effort, // eventually consistent metrics snapshot rather than a linearizable // point-in-time state. func (r *Runtime) Stats() Stats ``` -------------------------------- ### RouteResult method signature Source: https://github.com/assurrussa/gobus Routes the query/result pair Q,T to a named queue, mirroring Bus.RegisterResult keying. Unrouted pairs use the default queue. Same errors as RouteCommand. ```go // RouteResult routes the query/result pair Q,T to a named queue. func (r *Runtime) RouteResult[Q gobus.ObjectIn, T gobus.ObjectOut](queueName string) error ``` -------------------------------- ### SubmitOption struct and WithExecutionContext function Source: https://github.com/assurrussa/gobus SubmitOption configures admission-independent behavior; WithExecutionContext stores a context for handler execution. The zero value is invalid. ```go // SubmitOption configures admission-independent behavior for a submitted job. // The zero value is invalid. type SubmitOption struct { kind submitOptionKind executionContext context.Context } // WithExecutionContext stores ctx with an accepted job and uses it for handler // execution instead of the admission context. Its deadline starts when ctx is // created, not when a worker starts the job. When repeated, the last option wins. func WithExecutionContext(ctx context.Context) SubmitOption ``` -------------------------------- ### Submit Source: https://github.com/assurrussa/gobus Enqueues a command, waiting for capacity or admissionContext cancellation. Without WithExecutionContext, admissionContext also controls handler execution. ```APIDOC ## Submit ### Description Enqueues a command, waiting for capacity or admissionContext cancellation. Without WithExecutionContext, admissionContext also controls handler execution. ### Method Submit ### Signature ```go func (r *Runtime) Submit[Q gobus.ObjectIn]( admissionContext context.Context, command Q, options ...SubmitOption, ) (<-chan error, error) ``` ### Parameters - **admissionContext** (`context.Context`) - Required - Controls waiting for capacity; without an option, also handler execution. - **command** (`Q`) - Required - Command dispatched via `bus.Dispatch` on a worker. - **options** (`...SubmitOption`) - Optional - Job options; currently `WithExecutionContext`. The zero value is invalid. ### Returns `(<-chan error, error)` — the channel receives exactly one error then closes; the direct error is an admission failure. ### Errors (direct return) - **ErrNilContext** - `admissionContext == nil`. - **ErrInvalidSubmitOption** - Option has unknown kind or a nil execution context. - **ErrRuntimeNotStarted** - Runtime not yet `Start`ed. - **ErrRuntimeClosed** - Runtime closing or closed. - **admissionContext.Err()** - Context cancelled while waiting for capacity. - **ErrQueueFull** - `Try` variant only — queue is full. ### Request Example ```go result, err := runtime.Submit(ctx, GenerateReport{ID: id}) if err != nil { return err // Admission failed. } if err := <-result; err != nil { return err // Handler failed. } ``` ```go // Separate admission and execution lifetimes. admissionCtx, cancel := context.WithTimeout(request.Context(), 100*time.Millisecond) defer cancel() executionCtx := context.WithoutCancel(request.Context()) result, err := runtime.Submit(admissionCtx, SendEmail{UserID: id}, async.WithExecutionContext(executionCtx)) if err != nil { return err } select { case err := <-result: if err != nil { log.Printf("send email: %v", err) } case <-time.After(30 * time.Second): log.Print("send email still queued or running") } ``` ```