How itimofeev/go-saga works
Project type and purpose
• This is a Go library (open-source tool) implementing the Choreography-based Saga pattern for distributed transactions.
• It provides a way to define a sequence of steps (each with a forward function and a compensation function). On any failure, it automatically rolls back previously executed steps.
File structure
• coordinator.go – the “orchestrator” (Coordinator) that drives saga execution and rollback.
• saga.go – defines the Saga type, Step struct, methods to add steps.
• memory.go – an in-memory implementation of the Store interface.
• log.go – Log type and Store interface (AppendLog, GetAllLogsByExecutionID, GetStepLogsToCompensate).
• saga_test.go – usage examples demonstrating how steps, coordinator, and store interact.
README for additional insights
• Describes how to create a Saga, add steps, run the Coordinator, and handle errors.
• Mentions Choreography-based saga pattern and links to a deeper explanation.
a. Main components
– Client / Consumer code (your application using go-saga)
– Saga (holds metadata + ordered Step list)
– Coordinator (executes steps, writes logs, triggers compensations)
– Store interface (persistence abstraction)
– In-memory store (default implementation) / External DB (optional implementation)
– External services or systems invoked by each Step.Func and Step.CompensateFunc
– Log entries (persisted events capturing step execution and status)
b. Relationships and interactions
1. Client initializes Saga and adds Step definitions.
2. Client instantiates Coordinator, passing Saga, Store, and Contexts.
3. Coordinator begins execution:
• For each Step:
– Invoke Step.Func → on success, write a Log via Store.AppendLog
– On error:
• Query Store.GetStepLogsToCompensate to retrieve prior success logs
• Invoke corresponding Step.CompensateFunc in reverse order
4. Coordinator reports final outcome (success or ExecutionError).
5. Store.GetAllLogsByExecutionID can be used to inspect complete saga history.
c. Architectural patterns and design principles
– Choreography-based Saga: decentralized compensation logic co-located with each step.
– Dependency inversion via Store interface for pluggable persistence.
– Event sourcing style: each step execution writes a log entry.
d. Key technologies and libraries
– Go (golang)
– context package for cancellation/timeouts
– errors package for propagation
– Interfaces for testability and extensibility