mono

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2026 License: Apache-2.0 Imports: 6 Imported by: 1

README

Mono Framework

Go Reference Go Version License Coverage

A Go framework for building distributed modular monolith applications powered by NATS.io.

Mono Framework enables building applications as a collection of loosely-coupled modules that communicate via NATS messaging. Start with a single binary monolith for simplicity, then scale horizontally to a distributed cluster when needed—without changing your code. Powered by NATS.io's distributed architecture, your application can seamlessly evolve from a single instance to a highly scalable distributed system.

Features

  • Distributed Modular Monolith - Start simple, scale horizontally without code changes
  • NATS.io Powered - Built on NATS distributed messaging for high scalability and resilience
  • Embedded or External NATS - Run embedded for development, connect to NATS clusters in production
  • Event-Driven Communication - Publish/subscribe patterns for inter-module messaging
  • Four Service Patterns - Channel, Request-Reply, Queue Group, and Stream Consumer
  • JetStream Persistence - Durable messaging with at-least-once delivery guarantees
  • Lifecycle Management - Automatic dependency resolution and ordered startup/shutdown
  • Built-in Middleware - Access logging, audit trails, and request ID injection
  • Plugin System - Extensible architecture for custom functionality

Why Distributed Modular Monolith?

Approach Development Deployment Scaling
Traditional Monolith Simple Single binary Vertical only
Microservices Complex Many services Horizontal
Distributed Modular Monolith Simple Single binary Horizontal

Mono Framework gives you the best of both worlds:

  • Develop like a monolith: single codebase, simple debugging, no network complexity during development
  • Deploy like microservices: run multiple instances behind a load balancer, scale horizontally on demand
  • Communicate through NATS: modules use messaging patterns that work identically whether running in one process or distributed across a cluster

Quick Start

Installation
go get github.com/go-monolith/mono
Basic Example
package main

import (
    "context"
    "log"
    "time"

    "github.com/go-monolith/mono"
)

// HelloModule implements a simple module
type HelloModule struct{}

func (m *HelloModule) Name() string              { return "hello" }
func (m *HelloModule) Start(_ context.Context) error { return nil }
func (m *HelloModule) Stop(_ context.Context) error  { return nil }

func main() {
    // Create application with configuration
    app, err := mono.NewMonoApplication(
        mono.WithLogLevel(mono.LogLevelInfo),
        mono.WithShutdownTimeout(10*time.Second),
    )
    if err != nil {
        log.Fatal(err)
    }

    // Register module and start
    app.Register(&HelloModule{})

    if err := app.Start(context.Background()); err != nil {
        log.Fatal(err)
    }

    // Application is now running with embedded NATS server
    // Handle shutdown...

    app.Stop(context.Background())
}

Architecture

┌───────────────────────────────────────────────────────────────────────┐
│                         Application Layer                             │
│            (Your Modules implementing mono.Module)                    │
├───────────────────────────────────────────────────────────────────────┤
│                          Framework Layer                              │
│  ┌──────────────────┐ ┌──────────────────┐ ┌───────────────────────┐  │
│  │ ServiceContainer │ │     EventBus     │ │    EventRegistry      │  │
│  │  (DI & Services) │ │    (Pub/Sub)     │ │  (EDA & Consumers)    │  │
│  └──────────────────┘ └──────────────────┘ └───────────────────────┘  │
├───────────────────────────────────────────────────────────────────────┤
│                       Infrastructure Layer                            │
│              (NATS.io + JetStream Persistence)                        │
└───────────────────────────────────────────────────────────────────────┘
                                  │
       ┌──────────────────────────┼──────────────────────────┐
       ▼                          ▼                          ▼
  ┌──────────┐              ┌──────────┐              ┌──────────┐
  │  Node 1  │◄────────────►│  Node 2  │◄────────────►│  Node 3  │
  │(Instance)│ NATS Cluster │(Instance)│ NATS Cluster │(Instance)│
  └──────────┘              └──────────┘              └──────────┘

Modules communicate through NATS messaging patterns rather than direct method calls. This enables loose coupling, clear module boundaries, and horizontal scaling—deploy multiple instances that automatically coordinate through the NATS cluster.

Service Communication Patterns

Pattern Use Case Latency Durability
Channel In-process communication ~microseconds None
Request-Reply Synchronous service calls ~1ms None
Queue Group Load-balanced async processing ~1ms None
Stream Consumer Durable message processing ~1ms JetStream

Examples

Example Description
basic Hello World module with lifecycle management
multi-module Order system with dependencies and service patterns
analytics Channel services for high-performance in-process communication
event-emitter Event publishing with EventEmitter and EventConsumer

Built-in Components

Middleware
  • accesslog - HTTP-style access logging for service calls
  • audit - Security event auditing
  • requestid - Request ID injection and propagation
Plugins
  • fs-jetstream - File storage using JetStream Object Store
  • kv-jetstream - Key-value storage using JetStream KV Store

Security

The framework includes built-in security features:

  • Sensitive Data Redaction - Automatic redaction of passwords, tokens, API keys, and credentials from logs
  • Audit Logging - Security event tracking with optional hash chaining for tamper detection
  • Input Validation - Validation helpers for service handlers

For security best practices and vulnerability reporting, see SECURITY.md.

Documentation

Resource Description
Official Documentation Complete framework guide (GitBook format)
Quick Start Guide Get started in 5 minutes
Core Concepts Modules, services, and architecture
API Reference Detailed API documentation
Go Documentation Generated godoc reference
Examples Runnable example applications

Development

For contributing to the framework, building from source, and running tests, see DEVELOPMENT.md.

Contributing

See CONTRIBUTING.md for guidelines on how to contribute to this project.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Documentation

Overview

Package mono provides a modular monolith framework for building Go applications.

The mono framework enables building applications as a collection of loosely-coupled modules that communicate via NATS messaging, while running as a single binary. This approach combines the simplicity of a monolith with the architectural benefits of microservices.

Quick Start

Import the framework:

import "github.com/go-monolith/mono"

Create a simple module and run the framework:

type MyModule struct {
    logger mono.Logger
}

func (m *MyModule) Name() string { return "my-module" }

func (m *MyModule) Start(ctx context.Context) error { return nil }
func (m *MyModule) Stop(ctx context.Context) error { return nil }

// In main()
app, _ := mono.NewMonoApplication(
    mono.WithNATSPort(4222),
    mono.WithLogLevel(mono.LogLevelInfo),
)
app.Register(&MyModule{})
app.Start(context.Background())

Core Concepts

The framework is built around several key abstractions:

  • Module: The basic unit of functionality with lifecycle management
  • EventBus: NATS-backed message bus for inter-module communication
  • ServiceContainer: Service registration and discovery
  • Logger: Structured logging with module context

Architecture

The framework follows a layered architecture with clear separation of concerns:

┌─────────────────────────────────────────────────────────────────────┐
│                       Application Layer                              │
│            (Your Modules implementing mono.Module)                   │
├─────────────────────────────────────────────────────────────────────┤
│                        Framework Layer                               │
│  ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────┐│
│  │ ServiceContainer│ │    EventBus     │ │     EventRegistry       ││
│  │  (DI & Services)│ │   (Pub/Sub)     │ │   (EDA & Consumers)     ││
│  └─────────────────┘ └─────────────────┘ └─────────────────────────┘│
├─────────────────────────────────────────────────────────────────────┤
│                     Infrastructure Layer                             │
│               (Embedded NATS Server + JetStream)                     │
└─────────────────────────────────────────────────────────────────────┘

Modules communicate through NATS messaging patterns rather than direct method calls, enabling loose coupling and clear module boundaries.

Design Patterns

The framework employs several established Go patterns:

Functional Options Pattern

Configuration uses functional options for clean, composable API:

app, err := mono.NewMonoApplication(
    mono.WithNATSPort(4222),
    mono.WithLogLevel(mono.LogLevelInfo),
    mono.WithShutdownTimeout(30*time.Second),
)

Each option validates its input and returns an error if invalid. Options are applied in order, and the first error stops processing. This pattern enables backwards-compatible API evolution and clear defaults.

Dependency Injection Pattern

Modules receive dependencies via interface injection rather than creating them directly. The framework injects ServiceContainers before Start() is called:

func (m *MyModule) SetDependencyServiceContainer(dep string, container mono.ServiceContainer) {
    if dep == "payment" {
        m.paymentServices = container
    }
}

This enables testability and decouples modules from their dependencies.

Module Lifecycle Pattern

Modules implement Start/Stop for controlled initialization and cleanup:

func (m *MyModule) Start(ctx context.Context) error {
    // Initialize resources, establish connections
    return nil
}

func (m *MyModule) Stop(ctx context.Context) error {
    // Release resources, close connections
    return nil
}

The framework manages lifecycle ordering based on declared dependencies, starting modules in dependency order and stopping in reverse order.

Service Communication Patterns

The framework supports four communication patterns:

  • Channel Services: In-process Go channels for lowest latency
  • Request-Reply Services: Synchronous NATS request/reply
  • Queue Group Services: Load-balanced async processing
  • Stream Consumer Services: Durable JetStream consumption

Documentation

For detailed information, see:

  • Architecture: docs/spec/foundation.md
  • Examples: examples/
  • Types: pkg/types (core interfaces and type definitions)
  • Helpers: pkg/helper (convenience functions for common patterns)

Index

Constants

View Source
const (
	StateCreated  = types.StateCreated
	StateStarting = types.StateStarting
	StateRunning  = types.StateRunning
	StateStopping = types.StateStopping
	StateStopped  = types.StateStopped
)

Framework state constants

View Source
const (
	ServiceTypeChannel        = types.ServiceTypeChannel
	ServiceTypeRequestReply   = types.ServiceTypeRequestReply
	ServiceTypeQueueGroup     = types.ServiceTypeQueueGroup
	ServiceTypeStreamConsumer = types.ServiceTypeStreamConsumer
)

Service type constants

View Source
const (
	LogLevelDebug = types.LogLevelDebug
	LogLevelInfo  = types.LogLevelInfo
	LogLevelWarn  = types.LogLevelWarn
	LogLevelError = types.LogLevelError
)

Log level constants

View Source
const (
	LogFormatJSON = types.LogFormatJSON
	LogFormatText = types.LogFormatText
)

Log format constants

View Source
const (
	ModuleStartedEvent = types.ModuleStartedEvent
	ModuleStoppedEvent = types.ModuleStoppedEvent
)

Module lifecycle event type constants

View Source
const (
	LimitsPolicy    = types.LimitsPolicy
	InterestPolicy  = types.InterestPolicy
	WorkQueuePolicy = types.WorkQueuePolicy
)

Retention policy constants

View Source
const (
	FileStorage   = types.FileStorage
	MemoryStorage = types.MemoryStorage
)

Storage type constants

View Source
const (
	AckExplicitPolicy = types.AckExplicitPolicy
	AckAllPolicy      = types.AckAllPolicy
	AckNonePolicy     = types.AckNonePolicy
)

Ack policy constants

View Source
const (
	DeliverAllPolicy             = types.DeliverAllPolicy
	DeliverLastPolicy            = types.DeliverLastPolicy
	DeliverNewPolicy             = types.DeliverNewPolicy
	DeliverByStartSequencePolicy = types.DeliverByStartSequencePolicy
	DeliverByStartTimePolicy     = types.DeliverByStartTimePolicy
	DeliverLastPerSubjectPolicy  = types.DeliverLastPerSubjectPolicy
)

Deliver policy constants

View Source
const (
	ReplayInstantPolicy  = types.ReplayInstantPolicy
	ReplayOriginalPolicy = types.ReplayOriginalPolicy
)

Replay policy constants

View Source
const (
	DiscardOld = types.DiscardOld
	DiscardNew = types.DiscardNew
)

Discard policy constants

View Source
const (
	NoCompression = types.NoCompression
	S2Compression = types.S2Compression
)

Store compression constants

View Source
const (
	ConfigurationUpdatedEvent = types.ConfigurationUpdatedEvent
)

Configuration event type constants

Variables

View Source
var FormatServiceType = types.FormatServiceType

FormatServiceType returns a human-readable string for the service type.

Functions

func DefaultConfig

func DefaultConfig() *types.MonoFrameworkConfig

DefaultConfig returns a MonoFrameworkConfig with sensible defaults. This is primarily useful for testing.

Types

type AckPolicy

type AckPolicy = types.AckPolicy

AckPolicy defines the acknowledgement policy for a consumer.

type BaseEventDefinition

type BaseEventDefinition = types.BaseEventDefinition

BaseEventDefinition is the non-generic representation of an event definition.

type ConfigurationEvent

type ConfigurationEvent = types.ConfigurationEvent

ConfigurationEvent contains data for configuration events.

type ConfigurationEventType

type ConfigurationEventType = types.ConfigurationEventType

ConfigurationEventType identifies configuration event types.

type ConsumerConfig

type ConsumerConfig = types.ConsumerConfig

ConsumerConfig configures a JetStream consumer.

type DeliverPolicy

type DeliverPolicy = types.DeliverPolicy

DeliverPolicy defines when a consumer should start delivering messages.

type DependentModule

type DependentModule = types.DependentModule

DependentModule declares dependencies on other modules.

type DiscardPolicy

type DiscardPolicy = types.DiscardPolicy

DiscardPolicy determines how to proceed when limits are reached.

type EventBus

type EventBus = types.EventBus

EventBus is the NATS-backed message bus for inter-module communication.

type EventBusAwareModule

type EventBusAwareModule = types.EventBusAwareModule

EventBusAwareModule receives the EventBus instance.

type EventConsumerEntry

type EventConsumerEntry = types.EventConsumerEntry

EventConsumerEntry tracks an event consumer registration.

type EventConsumerHandler

type EventConsumerHandler = types.EventConsumerHandler

EventConsumerHandler handles event messages.

type EventConsumerModule

type EventConsumerModule = types.EventConsumerModule

EventConsumerModule registers event consumers.

type EventEmitterModule

type EventEmitterModule = types.EventEmitterModule

EventEmitterModule declares events that a module emits.

type EventRegistry

type EventRegistry = types.EventRegistry

EventRegistry manages event registration and discovery.

type EventStream

type EventStream = types.EventStream

EventStream provides JetStream operations.

type EventStreamConsumerEntry

type EventStreamConsumerEntry = types.EventStreamConsumerEntry

EventStreamConsumerEntry tracks a JetStream event consumer registration.

type EventStreamConsumerHandler

type EventStreamConsumerHandler = types.EventStreamConsumerHandler

EventStreamConsumerHandler handles batches of JetStream messages.

type ExternalStream

type ExternalStream = types.ExternalStream

ExternalStream describes an external stream.

type FetchConfig

type FetchConfig = types.FetchConfig

FetchConfig configures the fetch behavior for JetStream pull consumers.

type FrameworkHealth

type FrameworkHealth = types.FrameworkHealth

FrameworkHealth contains aggregated health status of the framework.

type Header = types.Header

Header is a map of header key-value pairs.

type HealthCheckableModule

type HealthCheckableModule = types.HealthCheckableModule

HealthCheckableModule provides health status.

type HealthStatus

type HealthStatus = types.HealthStatus

HealthStatus represents the health of a module.

type LogFormat

type LogFormat = types.LogFormat

LogFormat represents the log output format.

type LogLevel

type LogLevel = types.LogLevel

LogLevel represents the log level.

type Logger

type Logger = types.Logger

Logger is the framework's logging interface.

type LoggerFactory

type LoggerFactory = types.LoggerFactory

LoggerFactory creates logger instances.

type Marshaler

type Marshaler = types.Marshaler

Marshaler serializes data to bytes.

type MiddlewareChainRunner

type MiddlewareChainRunner = types.MiddlewareChainRunner

MiddlewareChainRunner executes the middleware chain.

type MiddlewareModule

type MiddlewareModule = types.MiddlewareModule

MiddlewareModule provides interceptor hooks for framework events.

type Module

type Module = types.Module

Module is the basic interface that all modules must implement.

type ModuleHealth

type ModuleHealth = types.ModuleHealth

ModuleHealth contains health status for a single module.

type ModuleLifecycleEvent

type ModuleLifecycleEvent = types.ModuleLifecycleEvent

ModuleLifecycleEvent contains data for module lifecycle events.

type ModuleLifecycleEventType

type ModuleLifecycleEventType = types.ModuleLifecycleEventType

ModuleLifecycleEventType identifies lifecycle event types.

type MonoApplication

type MonoApplication = types.MonoFramework

MonoApplication is the main framework interface. We use MonoApplication here to provide a clearer name that represents the application instance.

func NewMonoApplication

func NewMonoApplication(opts ...MonoFrameworkOption) (MonoApplication, error)

NewMonoApplication creates a new MonoFramework application instance with the given options.

The monolith application is created with sensible defaults that can be overridden using functional options. If no logger is provided, a default logger is created. If no audit logger is provided, audit logging is disabled (uses io.Discard).

Example:

app, err := mono.NewMonoApplication(
    mono.WithNATSPort(4222),
    mono.WithShutdownTimeout(30*time.Second),
    mono.WithLogLevel(mono.LogLevelDebug),
)
if err != nil {
    log.Fatal(err)
}
defer app.Stop(context.Background())

See docs/spec/foundation.md for detailed documentation.

type MonoFrameworkOption

type MonoFrameworkOption func(*types.MonoFrameworkConfig) error

MonoFrameworkOption is a functional option for configuring the framework.

Options follow the functional options pattern for clean, composable configuration. Each option validates its parameters and returns an error if validation fails.

Example:

app, err := mono.NewMonoApplication(
    mono.WithNATSPort(4222),
    mono.WithShutdownTimeout(30*time.Second),
    mono.WithLogger(myLogger),
)

See docs/spec/foundation.md for detailed documentation.

func WithCustomLogger

func WithCustomLogger(logger types.Logger) MonoFrameworkOption

WithCustomLogger allows injection of a custom logger instance. This bypasses the logger factory and uses the provided logger directly. The logger cannot be nil.

Example:

customLogger := myLoggerFactory.NewLogger("application")
mono.NewMonoApplication(mono.WithCustomLogger(customLogger))

func WithJetStreamDomain

func WithJetStreamDomain(domain string) MonoFrameworkOption

WithJetStreamDomain sets the JetStream domain for the NATS server. The domain cannot be empty.

Example:

mono.NewMonoApplication(mono.WithJetStreamDomain("production"))

func WithJetStreamStorageDir

func WithJetStreamStorageDir(dir string) MonoFrameworkOption

WithJetStreamStorageDir sets the JetStream storage directory. The directory path cannot be empty.

Example:

mono.NewMonoApplication(mono.WithJetStreamStorageDir("./data/jetstream"))

func WithLogFormat

func WithLogFormat(format types.LogFormat) MonoFrameworkOption

WithLogFormat sets the log format (JSON or Text). Valid formats are: LogFormatJSON, LogFormatText.

Example:

mono.NewMonoApplication(mono.WithLogFormat(mono.LogFormatJSON))

func WithLogLevel

func WithLogLevel(level types.LogLevel) MonoFrameworkOption

WithLogLevel sets the log level for the framework logger. Valid levels are: LogLevelDebug, LogLevelInfo, LogLevelWarn, LogLevelError.

Example:

mono.NewMonoApplication(mono.WithLogLevel(mono.LogLevelDebug))

func WithLogOutput

func WithLogOutput(w io.Writer) MonoFrameworkOption

WithLogOutput sets the output writer for logs. The writer cannot be nil.

Example:

var buf bytes.Buffer
mono.NewMonoApplication(mono.WithLogOutput(&buf))

func WithLogSource

func WithLogSource(enable bool) MonoFrameworkOption

WithLogSource enables/disables source file and line number in log entries. When enabled, logs will include the file:line where the log was called.

Example:

mono.NewMonoApplication(mono.WithLogSource(true))

func WithLogger

func WithLogger(logger types.Logger) MonoFrameworkOption

WithLogger sets a custom logger for the framework. The logger cannot be nil.

To enable NATS server logging, use WithNATSLogging in addition to this option.

Example:

logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
mono.NewMonoApplication(mono.WithLogger(logger))

func WithNATSClustering

func WithNATSClustering(clusterName, clusterHost string, clusterPort int, routes []string) MonoFrameworkOption

WithNATSClustering enables NATS clustering with the specified configuration.

Parameters:

  • clusterName: Name of the NATS cluster (must not be empty)
  • clusterHost: Host address for cluster communication (e.g., "127.0.0.1")
  • clusterPort: Port for cluster communication (e.g., 6222), must be between 1024 and 65535
  • routes: URLs to other cluster nodes (e.g., "nats://node1:6222")

For a seed node (the first node in a cluster), routes can be empty. For non-seed nodes, routes should point to the seed node's cluster URL.

Example (seed node):

mono.NewMonoApplication(
    mono.WithNATSClustering("my-cluster", "127.0.0.1", 6222, nil),
)

Example (non-seed node):

mono.NewMonoApplication(
    mono.WithNATSClustering("my-cluster", "127.0.0.1", 6223, []string{"nats://127.0.0.1:6222"}),
)

func WithNATSConfigFile

func WithNATSConfigFile(path string) MonoFrameworkOption

WithNATSConfigFile sets the path to a NATS server configuration file. The file is processed using NATS server.ProcessConfigFile() during startup.

When both a config file and programmatic options (like WithNATSPort) are specified, the config file provides base settings and programmatic options override them. This allows using a standard NATS config file while customizing specific settings.

The path cannot be empty. File existence and validity are checked during Start().

Example:

// Use config file only
mono.NewMonoApplication(
    mono.WithNATSConfigFile("/etc/nats/server.conf"),
)

// Config file with programmatic overrides
mono.NewMonoApplication(
    mono.WithNATSConfigFile("/etc/nats/server.conf"),
    mono.WithNATSPort(4333), // Overrides port from config file
)

func WithNATSDontListen

func WithNATSDontListen() MonoFrameworkOption

WithNATSDontListen prevents the NATS server from listening on TCP. Useful for embedded servers that only need in-process connections.

IMPORTANT: When DontListen is enabled, you MUST also enable UseInProcessConn via WithNATSInProcessConn(), otherwise the server will start but be unreachable.

Example:

mono.NewMonoApplication(
    mono.WithNATSDontListen(),
    mono.WithNATSInProcessConn(), // Required when using DontListen
)

func WithNATSHost

func WithNATSHost(host string) MonoFrameworkOption

WithNATSHost sets the NATS server host address. The host cannot be empty.

Example:

mono.NewMonoApplication(mono.WithNATSHost("0.0.0.0"))

func WithNATSInProcessConn

func WithNATSInProcessConn() MonoFrameworkOption

WithNATSInProcessConn enables in-process client connections instead of TCP. This uses net.Pipe() for direct client-server communication without network overhead. Typically used with WithNATSDontListen() for fully in-process NATS communication.

Example:

mono.NewMonoApplication(
    mono.WithNATSDontListen(),
    mono.WithNATSInProcessConn(),
)

func WithNATSLogging

func WithNATSLogging(debug, trace, sysTrace bool) MonoFrameworkOption

WithNATSLogging configures NATS server logging flags. All flags are disabled by default. When any flag is enabled, NATS server logs are routed through the framework's logging system with a "nats-server" component identifier.

Parameters:

  • debug: enables debug-level logging (verbose operational info)
  • trace: enables trace-level logging (message tracing)
  • sysTrace: enables system trace logging (internal NATS operations)

This option is independent of WithLogger and can be used with either a custom logger or the default framework logger.

Example:

mono.NewMonoApplication(
    mono.WithLogger(logger),
    mono.WithNATSLogging(true, false, false),  // Enable debug logging only
)

func WithNATSMaxPayload

func WithNATSMaxPayload(bytes int32) MonoFrameworkOption

WithNATSMaxPayload sets the maximum payload size for NATS messages. The size must be between 1KB (1024 bytes) and 8MB (8388608 bytes).

Example:

mono.NewMonoApplication(mono.WithNATSMaxPayload(2 * 1024 * 1024)) // 2 MB

func WithNATSPort

func WithNATSPort(port int) MonoFrameworkOption

WithNATSPort sets the NATS server port. The port must be between 1024 and 65535.

Example:

mono.NewMonoApplication(mono.WithNATSPort(4222))

func WithQueueGroupOptimisticWindow

func WithQueueGroupOptimisticWindow(window time.Duration) MonoFrameworkOption

WithQueueGroupOptimisticWindow enables optimistic publish mode for queue group services.

When set to a duration > 0, queue group clients will use request-reply (with ACK) for the first send, then switch to fire-and-forget publish for subsequent sends within the specified window. This improves performance while maintaining service availability detection.

The window must be at least 100 milliseconds to be meaningful. Common values are 1-5 seconds. When set to 0 (default), optimistic mode is disabled and all sends use ACK.

Example:

mono.NewMonoApplication(mono.WithQueueGroupOptimisticWindow(1 * time.Second))

func WithShutdownTimeout

func WithShutdownTimeout(timeout time.Duration) MonoFrameworkOption

WithShutdownTimeout sets the graceful shutdown timeout. The timeout must be at least 1 second to allow proper cleanup.

Example:

mono.NewMonoApplication(mono.WithShutdownTimeout(30*time.Second))

type MonoFrameworkState

type MonoFrameworkState = types.MonoFrameworkState

MonoFrameworkState represents the state of the framework.

type Msg

type Msg = types.Msg

Msg represents a NATS message.

type MsgHandler

type MsgHandler = types.MsgHandler

MsgHandler is a callback for message handling.

type MsgPubAck

type MsgPubAck = types.MsgPubAck

MsgPubAck is the acknowledgment from JetStream publish.

type OutgoingMessageContext

type OutgoingMessageContext = types.OutgoingMessageContext

OutgoingMessageContext contains context for outgoing messages.

type Placement

type Placement = types.Placement

Placement guides stream placement in clustered JetStream.

type PluginModule

type PluginModule = types.PluginModule

PluginModule is a special module type that starts before middleware. Plugins receive their own ServiceContainer and are excluded from the dependency graph and middleware hooks.

type QGHP

type QGHP = types.QGHP

QGHP is a queue group handler pair.

type QueueGroupHandler

type QueueGroupHandler = types.QueueGroupHandler

QueueGroupHandler handles queue group messages.

type QueueGroupServiceClient

type QueueGroupServiceClient = types.QueueGroupServiceClient

QueueGroupServiceClient is a client for queue group services.

type RePublish

type RePublish = types.RePublish

RePublish configures re-publishing of messages.

type ReplayPolicy

type ReplayPolicy = types.ReplayPolicy

ReplayPolicy determines how the consumer should replay messages.

type RequestReplyHandler

type RequestReplyHandler = types.RequestReplyHandler

RequestReplyHandler handles synchronous request-reply calls.

type RequestReplyServiceClient

type RequestReplyServiceClient = types.RequestReplyServiceClient

RequestReplyServiceClient is a client for request-reply services.

type RetentionPolicy

type RetentionPolicy = types.RetentionPolicy

RetentionPolicy defines the retention policy for a stream.

type ServiceContainer

type ServiceContainer = types.ServiceContainer

ServiceContainer manages service registration and discovery.

type ServiceEntry

type ServiceEntry = types.ServiceEntry

ServiceEntry represents a registered service.

type ServiceProviderModule

type ServiceProviderModule = types.ServiceProviderModule

ServiceProviderModule registers services in the container.

type ServiceRegistration

type ServiceRegistration = types.ServiceRegistration

ServiceRegistration contains service registration data.

type ServiceType

type ServiceType = types.ServiceType

ServiceType identifies the type of service.

type StorageType

type StorageType = types.StorageType

StorageType defines the storage backend for a stream.

type StoreCompression

type StoreCompression = types.StoreCompression

StoreCompression determines how messages are compressed.

type StreamConfig

type StreamConfig = types.StreamConfig

StreamConfig configures a JetStream stream.

type StreamConsumerConfig

type StreamConsumerConfig = types.StreamConsumerConfig

StreamConsumerConfig configures a JetStream durable pull consumer service.

type StreamConsumerHandler

type StreamConsumerHandler = types.StreamConsumerHandler

StreamConsumerHandler handles JetStream consumer messages.

type StreamConsumerLimits

type StreamConsumerLimits = types.StreamConsumerLimits

StreamConsumerLimits sets limits for stream consumers.

type StreamConsumerServiceClient

type StreamConsumerServiceClient = types.StreamConsumerServiceClient

StreamConsumerServiceClient is a client for stream consumer services.

type StreamSource

type StreamSource = types.StreamSource

StreamSource describes an external stream source.

type SubjectTransformConfig

type SubjectTransformConfig = types.SubjectTransformConfig

SubjectTransformConfig describes subject transformation.

type Subscription

type Subscription = types.Subscription

Subscription represents an active subscription.

type TypedEventConsumerHandler

type TypedEventConsumerHandler[T any] = types.TypedEventConsumerHandler[T]

TypedEventConsumerHandler is a type-safe event handler.

type TypedEventStreamConsumerHandler

type TypedEventStreamConsumerHandler[T any] = types.TypedEventStreamConsumerHandler[T]

TypedEventStreamConsumerHandler is a type-safe JetStream event handler.

type Unmarshaler

type Unmarshaler = types.Unmarshaler

Unmarshaler deserializes bytes to data.

type UsePluginModule

type UsePluginModule = types.UsePluginModule

UsePluginModule allows modules to declare plugin dependencies. The framework will inject plugin instances via SetPlugin() during module initialization.

Directories

Path Synopsis
Package bench provides shared types and helper functions for benchmarking the mono-framework.
Package bench provides shared types and helper functions for benchmarking the mono-framework.
cmd/benchparse command
Package main provides a tool to parse Go benchmark JSON output and convert it to a structured JSON format for benchmark result reporting.
Package main provides a tool to parse Go benchmark JSON output and convert it to a structured JSON format for benchmark result reporting.
examples
analytics command
analytics/analytics-module
Package analytics implements an analytics module for event tracking and retrieval using channel-based services and request-reply patterns.
Package analytics implements an analytics module for event tracking and retrieval using channel-based services and request-reply patterns.
basic command
event-emitter command
Package main demonstrates the EventEmitterModule pattern in mono-framework.
Package main demonstrates the EventEmitterModule pattern in mono-framework.
event-emitter/notification
Package notification provides a notification module that demonstrates EventConsumerModule.
Package notification provides a notification module that demonstrates EventConsumerModule.
event-emitter/tracking
Package tracking provides an order tracking module that demonstrates EventEmitterModule.
Package tracking provides an order tracking module that demonstrates EventEmitterModule.
multi-module command
Package main demonstrates the multi-module pattern in mono-framework.
Package main demonstrates the multi-module pattern in mono-framework.
multi-module/events
Package events provides shared event definitions for the multi-module example.
Package events provides shared event definitions for the multi-module example.
multi-module/inventory
Package inventory implements an inventory management module for stock tracking and availability checking.
Package inventory implements an inventory management module for stock tracking and availability checking.
multi-module/notification
Package notification implements a notification module for sending notifications via queue groups and event subscriptions.
Package notification implements a notification module for sending notifications via queue groups and event subscriptions.
multi-module/order
Package order implements an order management module that orchestrates order placement by coordinating with inventory, payment, and notification modules.
Package order implements an order management module that orchestrates order placement by coordinating with inventory, payment, and notification modules.
multi-module/payment
Package payment implements a payment processing module for handling payment transactions with simulated success rates for demonstration purposes.
Package payment implements a payment processing module for handling payment transactions with simulated success rates for demonstration purposes.
nats-config command
internal
app
Package app provides the framework implementation that ties together all internal packages.
Package app provides the framework implementation that ties together all internal packages.
container
Package container provides service container implementation for managing and invoking services (channel-based, request-reply, queue groups, stream consumers).
Package container provides service container implementation for managing and invoking services (channel-based, request-reply, queue groups, stream consumers).
eventbus
Package eventbus provides NATS-backed event bus implementation for publish-subscribe messaging patterns with support for JetStream persistence.
Package eventbus provides NATS-backed event bus implementation for publish-subscribe messaging patterns with support for JetStream persistence.
lifecycle
Package lifecycle provides lifecycle management for modules, coordinating initialization and shutdown sequences in dependency order.
Package lifecycle provides lifecycle management for modules, coordinating initialization and shutdown sequences in dependency order.
logger
Package logger provides logging functionality with support for redacting sensitive information from log output, such as passwords, tokens, API keys, and other credentials.
Package logger provides logging functionality with support for redacting sensitive information from log output, such as passwords, tokens, API keys, and other credentials.
middleware
Package middleware provides middleware chain execution for intercepting service registrations and module lifecycle events.
Package middleware provides middleware chain execution for intercepting service registrations and module lifecycle events.
nats
Package nats provides NATS server management including embedded server startup, client connections, and JetStream configuration.
Package nats provides NATS server management including embedded server startup, client connections, and JetStream configuration.
registry
Package registry provides thread-safe module registration and retrieval with dependency resolution capabilities.
Package registry provides thread-safe module registration and retrieval with dependency resolution capabilities.
middleware
accesslog
Package accesslog provides a middleware module for access logging.
Package accesslog provides a middleware module for access logging.
audit
Package audit provides a middleware module for tamper-evident audit logging.
Package audit provides a middleware module for tamper-evident audit logging.
requestid
Package requestid provides a middleware module for request ID tracking and propagation.
Package requestid provides a middleware module for request ID tracking and propagation.
pkg
errors
Package errors provides error types, sentinel errors, and error wrapping utilities for the mono-framework.
Package errors provides error types, sentinel errors, and error wrapping utilities for the mono-framework.
helper
Package helper provides convenience functions for working with the Mono framework.
Package helper provides convenience functions for working with the Mono framework.
storage
Package storage provides a unified storage interface for communicating with different database/key-value providers.
Package storage provides a unified storage interface for communicating with different database/key-value providers.
types
Package types provides all public interfaces and supporting types for the mono-framework.
Package types provides all public interfaces and supporting types for the mono-framework.
plugin
fs-jetstream
Package fsjetstream provides a file storage plugin using JetStream ObjectStore.
Package fsjetstream provides a file storage plugin using JetStream ObjectStore.
kv-jetstream
Package kvjetstream provides a key-value storage plugin using JetStream KV Store.
Package kvjetstream provides a key-value storage plugin using JetStream KV Store.

Jump to

Keyboard shortcuts

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