LiteBus

repository·main·Indexed 42 days ago

https://github.com/litenova/litebus

A mediation library for .NET 10 applications implementing CQS (Command Query Separation) and DDD (Domain-Driven Design) patterns. LiteBus provides support for commands, queries, and events, featuring durable messaging capabilities such as inbox/outbox patterns and saga management. It supports various storage adapters including PostgreSQL, Entity Framework Core, and in-memory options, and integrates with brokers like AMQP, Kafka, AWS SQS, and Azure Service Bus.

Tokens
273.1K
Snippets
470
Records
1.1K
Agent score
51%

What's inside LiteBus

  1. Overview of LiteBus Durable Core Capabilities

    main

    LiteBus Durable Core provides a mechanism for persisting commands and events before they are executed or published. This ensures reliable messaging through background processors that support at-least-once delivery, leases, retries, and dead-lettering.

    Key functional areas include:

    • Inbox/Outbox Patterns: Managing incoming commands and outgoing events.
    • Reliable Semantics: Ensuring transactional writes and idempotent processing.
    • Lifecycle Management: Handling envelope lifecycles, scheduling metadata, and payload encryption at rest.
    • Processing: Utilizing inbox/outbox processors, lease/retry/dead-letter mechanisms, and processor hooks.
    • Connectivity: Ingress capabilities for various transports (AMQP is GA; Kafka, AWS SQS, and Azure Service Bus are in Beta).

    Note: This core focus is on dispatch and ingress capabilities; broker-specific transport guides are handled separately via transport adapters.

  2. Overview of LiteBus package structure

    main

    LiteBus is a modular messaging system composed of several specialized packages. The core functionality is distributed across abstractions, runtime, and specific implementation modules for commands, events, queries, inbox, outbox, and sagas.

    Key functional areas include:

    • Core Messaging: LiteBus.Messaging, LiteBus.Commands, LiteBus.Events, and LiteBus.Queries.
    • Reliability Patterns: LiteBus.Inbox (for message consumption) and LiteBus.Outbox (for reliable message publishing).
    • State Management: LiteBus.Saga for long-running processes.
    • Transport: LiteBus.Transport provides the underlying communication layer (e.g., AMQP, AWS SQS, Azure Service Bus, Kafka, or In-Memory).
    • Storage: Specialized packages for persisting inbox/outbox data using EntityFrameworkCore, PostgreSql, or InMemory providers.
  3. Understand the LiteBus Capability Catalog

    main
    The LiteBus Capability Catalog is a central index used to discover, plan, and trace the behaviors (capabilities) provided by LiteBus across its various feature axes. Because LiteBus is distributed as granular NuGet packages, the catalog helps you identify which packages to install for specific use cases, perform gap analysis between your requirements and LiteBus features, and understand the dependencies between different axes (e.g., knowing that ingress requires transport and storage).
  4. Explore LiteBus documentation areas

    main

    LiteBus documentation is organized into several specialized areas to help you navigate the library's surface:

    • Concepts: Learn about Commands, Queries, Events, handler pipelines, filtering, and dispatch.
    • Architecture: Understand dependency roles, module registration, API rules, hosting, and design decisions.
    • Reliable Messaging: Deep dive into Inbox, Outbox, Saga, transactions, retries, leases, and delivery semantics.
    • Integrations: Information on storage, transport, dispatch, ingress, and schema adapters.
    • Operations: Guidance on diagnostics, security, management, performance, and troubleshooting.
    • Testing: Learn about application testing, repository suites, and integration categories.
    • Extending: How to implement custom modules, stores, dispatchers, and host adapters.
    • Reference: Access the feature inventory, analyzers, glossary, and semantic validation.
    • Catalog: Find contract-level capability pages grouped by subsystem.
    • Migration: View historical version and MediatR migration procedures.
  5. Use the Outbox PostgreSQL Adapter

    main

    The PostgreSqlOutboxStore provides a unified implementation for all outbox roles using a single PostgreSQL instance. It acts as a feature bridge via the LiteBus.Outbox.Storage.PostgreSql package and relies on LiteBus.Storage.PostgreSql as its technology adapter.

    A single instance of PostgreSqlOutboxStore implements the following interfaces:

    • IOutboxStore: Appending messages via AddAsync and AddBatchAsync.
    • IOutboxLeaseStore: Managing message claims via LeasePendingAsync and RenewLeaseAsync.
    • IOutboxStateWriter: Persisting message state via PersistAsync.
    • IOutboxDeadLetterStore: Replaying failed messages via RequeueAsync.
    • IOutboxRetentionStore: Cleaning up old messages via DeletePublishedOlderThanAsync.
    • IOutboxDiagnosticsStore: Retrieving health metrics via GetStatusCountsAsync and GetSchemaInfoAsync.
    • IOutboxMessageQuery & IOutboxPurgeStore: Querying and purging via QueryAsync and PurgeAsync.
    • ITransactionalOutboxStore: Performing atomic writes using an existing Npgsql transaction.
  6. Use LiteBus brand assets

    main

    LiteBus provides several brand assets for use in NuGet packages, repositories, and documentation:

    • icon.png: A 128x128 raster reference for NuGet packages.
    • icon.svg: A resolution-independent version of the icon.
    • litebus-logo.svg: A combination of the icon mark and the LiteBus wordmark, intended for repository and documentation headers.
  7. What is Durable Dispatch in LiteBus

    main

    Durable Dispatch is the mechanism that turns leased inbox and outbox envelopes into side effects. It acts as the bridge between the durable storage (the inbox/outbox) and the actual execution of logic (in-process mediation or external message brokers).

    Key Behaviors:

    • In-Process Dispatch: Deserializes the payload and routes it to a mediator (e.g., ICommandMediator for in-process inbox or IEventMediator for in-process outbox).
    • Transport Dispatch: Publishes the message through an ITransportPublisher using contract headers and optional tenant routing.

    Important Invariants:

    • Exactly one dispatcher must be registered per durable module. Startup will fail if a processor is enabled without a dispatcher.
    • Error Handling: Throwing an exception during DispatchAsync drives the retry or dead-letter logic in the processor.
    • Topology: Inbox transport dispatch uses a dual-hop topology (publishes the leased envelope), while outbox transport dispatch publishes before terminal persist (at-least-once publication window).
  8. What is the Execution Context in LiteBus?

    main

    The Execution Context is the shared state for a single mediation call (e.g., a single SendAsync, QueryAsync, or PublishAsync invocation). It allows pre-handlers, the main handler, and post-handlers to communicate without modifying the message contract itself.

    It is stored in an AsyncLocal<IExecutionContext>, meaning it flows correctly across async/await boundaries and can be accessed statically from anywhere within the logical call.

    Key components include:

    • Items: A dictionary for sharing state between handlers.
    • Tags: Metadata associated with the mediation call.
    • CancellationToken: The operation's cancellation token.
    • MessageResult: A slot used to abort the pipeline with a result or to override the final result in post-handlers.
  9. What is a Saga in LiteBus?

    main

    LiteBus saga support implements a process-manager pattern providing correlated state persistence around inbox command dispatch.

    It works via a SagaProcessorHook that loads saga state before a command is dispatched and saves or completes that state after a successful dispatch. This allows handlers to mutate durable state keyed by a CorrelationId while the inbox processor ensures at-least-once delivery.

    Key Characteristics:

    • Not a full workflow engine: It lacks a built-in scheduler, timeout framework, compensation DSL, or outbox-driven choreography.
    • Triggered by Inbox: It only responds to inbox commands, not events or outbox messages.
    • State Management: Handlers access state through an injected ISagaContext.
    • Concurrency: Uses durable optimistic concurrency across hosts.
  10. Overview of the Mediator Axis

    main

    The Mediator Axis provides in-process mediation for commands, queries, and events built on top of the shared message module. It manages semantic contracts, execution pipelines, routing, and handler behavior.

    Key capabilities include:

    • Semantic Contracts: Support for ICommand, IQuery<T>, and IEvent.
    • Pipeline Stages: Execution through pre, main, post, and error stages.
    • Routing & Control: Routing filters, handler priority, and execution context management.
  11. Overview of EF Core Shared Infrastructure

    main

    The LiteBus.Storage.EntityFrameworkCore package provides low-level relational primitives and utilities for building durable stores using Entity Framework Core. It handles provider-specific logic that allows LiteBus to work across different database engines.

    Key capabilities include:

    • Provider Detection: Automatically identifies if you are using PostgreSQL, SQL Server, MySQL, SQLite, or InMemory.
    • Lease Management: Provides provider-specific SQL for row-level locking and leasing (e.g., FOR UPDATE SKIP LOCKED for PostgreSQL).
    • Relational Utilities: Handles table qualification, JSON text normalization, and mapping payload/trace columns to appropriate text types.
    • Bulk Operations: Probes for bulk update capabilities supported by the underlying database provider.

    This package is primarily consumed internally by the Inbox and Outbox EF adapters, but it can be reused when building custom EF-backed durable store adapters.

  12. How the Consumer Handler Invoker works

    main

    The TransportConsumerHandlerInvoker is a wrapper used in raw IMessageConsumer hosts to execute TransportMessage handlers within a guarded boundary. It manages the lifecycle of a message delivery by wrapping the handler in a process {destination} consumer activity.

    Key Behaviors:

    • Success Path: If the handler succeeds, the invoker does not automatically acknowledge the message. The handler must explicitly call AcceptAsync, DiscardAsync, or ReturnToQueueAsync to complete the lifecycle.
    • Failure Path: If the handler throws an exception (that is not a cancellation exception) while the host is running, the invoker automatically calls ReturnToQueueAsync to requeue the delivery.
    • Shutdown Path: If a cancellation is requested due to host shutdown, OperationCanceledException is propagated, and the invoker does not trigger an explicit requeue.

    Important Note for AMQP/RabbitMQ Users: AMQP consumers copy the delivery body before invocation. RabbitMQ delivery buffers are owned by the client callback and must not be retained after the callback returns.