manager

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package manager owns timeline recording, cache coordination and persistence lifecycles.

Example
package main

import (
	"context"
	"fmt"

	"github.com/compforge/go-stdx/timeline/manager"
	timelinestore "github.com/compforge/go-stdx/timeline/store"
)

func main() {
	m, err := manager.New(timelinestore.NewMemoryStore(), manager.Config{Actor: manager.Actor{Name: "test"}, MaxTimelines: 1024})
	if err != nil {
		panic(err)
	}
	previous := manager.SetDefault(m)
	defer manager.SetDefault(previous)
	defer m.Shutdown(context.Background())

	// Stage recording needs neither Start nor Finish.
	if _, err := manager.Begin("task-42", "prepare_files"); err != nil {
		panic(err)
	}
	if err := manager.End("task-42", "prepare_files", nil); err != nil {
		panic(err)
	}
	snapshot, err := manager.Read(context.Background(), "task-42", false)
	if err != nil {
		panic(err)
	}
	fmt.Println(snapshot.Status, snapshot.Stages[0].Status)
}
Output:
unknown succeeded

Index

Examples

Constants

View Source
const (
	Unknown   = model.Unknown
	Running   = model.Running
	Succeeded = model.Succeeded
	Failed    = model.Failed
	Canceled  = model.Canceled
)

Variables

View Source
var ErrActiveStages = errors.New("timeline: operation still has active stages")
View Source
var ErrAmbiguousStage = errors.New("timeline manager: multiple running stages share this name")
View Source
var ErrBufferFull = cache.ErrBufferFull
View Source
var ErrClosed = cache.ErrClosed
View Source
var ErrEmptyID = model.ErrEmptyID
View Source
var ErrInvalidAttribute = model.ErrInvalidAttribute
View Source
var ErrInvalidStage = model.ErrInvalidStage
View Source
var ErrNoDefault = errors.New("timeline manager: no default installed")
View Source
var ErrNotStarted = errors.New("timeline: operation attributes require a locally recorded start")
View Source
var ErrStageNotFound = errors.New("timeline manager: stage not found")

Functions

func End

func End(id, name string, stageErr error, options ...EndOption) error

func Finish

func Finish(id string, operationErr error) error

func NewContext added in v0.3.0

func NewContext(ctx context.Context, t Timeline) context.Context

NewContext optionally carries t without changing ctx's lifetime. Passing Timeline directly as a function argument needs no context binding.

func NewStageContext added in v0.3.0

func NewStageContext(ctx context.Context, ref StageRef) context.Context

func Record

func Record(id string, stage Stage) error

func Start

func Start(id, operation string, attributes ...Attribute) error

Types

type Actor added in v0.3.0

type Actor = model.Actor

Actor identifies the executor; new records require ID or Name. ID takes precedence.

type Attribute added in v0.3.0

type Attribute struct {
	Key   string `json:"key"`
	Value any    `json:"value"`
}

Attribute is recording input. Values must be JSON serializable and must not be mutated during the recording call. Implementations encode them before returning.

type Collection added in v0.3.0

type Collection = model.Collection

Collection reports local flush and store read success, not global completeness.

type Config

type Config = cache.Config

type EndOption added in v0.3.0

type EndOption func(*Stage) error

EndOption supplies a source end time, final attributes or a code.

func WithCode added in v0.3.0

func WithCode(code string) EndOption

WithCode records a caller-defined code independently of the stage result. An empty code is omitted from JSON.

func WithEndActor added in v0.3.0

func WithEndActor(actor Actor) EndOption

WithEndActor selects the actor for a named End; it cannot change a handle identity.

func WithEndAttributes added in v0.3.0

func WithEndAttributes(attributes ...Attribute) EndOption

func WithEndTime added in v0.3.0

func WithEndTime(at time.Time) EndOption

type Handle added in v0.3.0

type Handle struct {
	// contains filtered or unexported fields
}

Handle groups the optional object-style API for one recording identity. The primary business API is Begin/End/Record/Read with optional Start/Finish. A standalone handle shares Manager's cache/Store implementation and checkpoints explicitly; NewWriter binds a handle to an existing Manager's background saves.

func NewHandle added in v0.3.0

func NewHandle(id string, options ...Option) (*Handle, error)

NewHandle creates a standalone handle. Without WithStore, its cache is the only document owner and NoopStore accepts checkpoints without retaining data.

func (*Handle) Begin added in v0.3.0

func (h *Handle) Begin(name string, options ...StageOption) StageHandle

func (*Handle) Err added in v0.3.0

func (h *Handle) Err() error

func (*Handle) Finish added in v0.3.0

func (h *Handle) Finish(ctx context.Context, err error) (Snapshot, error)

func (*Handle) Flush added in v0.3.0

func (h *Handle) Flush(ctx context.Context) error

func (*Handle) ID added in v0.3.0

func (h *Handle) ID() string

func (*Handle) Record added in v0.3.0

func (h *Handle) Record(stage Stage) error

func (*Handle) SetAttributes added in v0.3.0

func (h *Handle) SetAttributes(attributes ...Attribute)

func (*Handle) Snapshot added in v0.3.0

func (h *Handle) Snapshot(ctx context.Context) (Snapshot, error)

func (*Handle) Start added in v0.3.0

func (h *Handle) Start(ctx context.Context, operation string, attributes ...Attribute) error

func (*Handle) UpdateAttributes added in v0.3.0

func (h *Handle) UpdateAttributes(attributes ...Attribute) error

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager joins ID-based recording with the shared loading and saving cache. Writes acknowledge memory acceptance; Flush optionally waits for Store submission.

func New

func New(backend store.Store, config Config) (*Manager, error)

New starts a Manager. A nil backend selects NoopStore for cache-only recording.

func SetDefault

func SetDefault(m *Manager) *Manager

SetDefault installs the process Manager and returns the previous one. Install before producers start; replacement neither moves state nor shuts down either instance. Tests changing the default must run serially and restore it.

func (*Manager) Begin

func (m *Manager) Begin(id, name string, options ...StageOption) (StageHandle, error)

Begin records a running stage. Same-name parallel stages are allowed; retain their handles to disambiguate completion.

func (*Manager) BeginContext

func (m *Manager) BeginContext(ctx context.Context, id, name string, options ...StageOption) (context.Context, StageHandle, error)

BeginContext binds the new stage identity without changing cancellation. Parentage comes only from an explicit WithParent option.

func (*Manager) End

func (m *Manager) End(id, name string, stageErr error, options ...EndOption) error

End completes the uniquely named running stage, restoring it on a cache miss. A rejected admission leaves it running and available for retry.

func (*Manager) Evict

func (m *Manager) Evict(id string)

Evict releases a cached document and schedules a final best-effort save. NoopStore cannot recover an evicted document.

func (*Manager) Finish

func (m *Manager) Finish(id string, operationErr error) error

Finish optionally records a result. It neither ends stages nor evicts cached data.

func (*Manager) Flush

func (m *Manager) Flush(ctx context.Context, id string, wait bool) error

Flush optionally triggers or waits for persistence. Long-running applications normally do not need to call it: Manager saves pending facts in the background. Use Flush for an explicit persistence checkpoint or to request an earlier save; use Shutdown to drain pending facts when stopping the application.

Flush waits for the ID's pending Store submissions when wait is true. With wait=false it queues the ID for the bounded save worker and returns immediately; save failures are reported through Config.OnError. The worker may save other IDs. +spec=`Nonblocking Flush uses the Manager lifetime and IO timeout independently of the caller context.`

func (*Manager) NewWriter

func (m *Manager) NewWriter(id string, actor Actor) (*Handle, error)

NewWriter creates an actor-scoped recorder. Its writes use the same cache; recording may load Store on a miss. Actors may share logical stage IDs.

func (*Manager) Read

func (m *Manager) Read(ctx context.Context, id string, fresh bool) (Snapshot, error)

Read returns the cached view or, with fresh=true, waits for a Store refresh. Both paths preserve pending local updates and never implicitly flush.

func (*Manager) Record

func (m *Manager) Record(id string, data Stage) error

Record accepts a completed source interval, preserving times and Actor.

func (*Manager) Shutdown

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown stops recording and tries to save remaining facts with the caller's context. The application owns the Store connection lifetime.

func (*Manager) Start

func (m *Manager) Start(id, operation string, attributes ...Attribute) error

Start optionally records the operation beginning. Identical repeats preserve its stored timestamp, including after a cache miss. Stages never require Start.

func (*Manager) Stats

func (m *Manager) Stats() Stats

Stats reports cache residency, pending submissions and known rejected/lost saves.

type Option added in v0.3.0

type Option func(*recorder)

Option configures a writer without performing remote IO.

func WithActor added in v0.3.0

func WithActor(actor Actor) Option

func WithStore added in v0.3.0

func WithStore(backend store.Store) Option

type Snapshot added in v0.3.0

type Snapshot = model.Snapshot

Snapshot is a detached, JSON-serializable view with read-time collection status. Duration, RunningStages, LatestFailedStage and Summary query its recorded facts.

func Read

func Read(ctx context.Context, id string, fresh bool) (Snapshot, error)

type Stage added in v0.3.0

type Stage = model.Stage

Stage retains an interval, parentage, executor, attributes and business result.

type StageHandle added in v0.3.0

type StageHandle interface {
	ID() StageID
	// SetAttributes merges attributes; the last value for a key wins.
	SetAttributes(attributes ...Attribute) error
	// End fixes the first valid result and submits it. A submission error may be
	// retried; after acceptance, later calls have no effect. A nil input error means
	// business success, while the returned error describes recording failure.
	End(err error, opts ...EndOption) error
}

StageHandle captures a logical StageID and actor identity. Different actors may contribute to the same logical stage. Parent associations name logical stages and do not require any particular actor to finish first.

func Begin

func Begin(id, name string, options ...StageOption) (StageHandle, error)

func BeginWithContext added in v0.3.0

func BeginWithContext(ctx context.Context, t Timeline, name string, opts ...StageOption) (context.Context, StageHandle)

BeginWithContext is an optional adapter; Timeline itself does not require context binding. It preserves cancellation and binds the new stage identity. Parentage comes only from WithParent; the incoming context never supplies a parent.

type StageID added in v0.3.0

type StageID = model.StageID

StageID is an opaque identity generated by Begin or supplied for an external fact.

type StageOption added in v0.3.0

type StageOption func(*Stage) error

StageOption sets the identity, source start time or initial attributes of a stage. Implementations apply options synchronously before returning a handle.

func WithAttributes added in v0.3.0

func WithAttributes(attributes ...Attribute) StageOption

func WithParent added in v0.3.0

func WithParent(id StageID) StageOption

WithParent records an association without looking up or requiring the parent. The ID is preserved even when the parent is absent or arrives later; callers can link available stages when reading and display unresolved stages at the root.

func WithStageActor added in v0.3.0

func WithStageActor(actor Actor) StageOption

func WithStageID added in v0.3.0

func WithStageID(id StageID) StageOption

func WithStartTime added in v0.3.0

func WithStartTime(at time.Time) StageOption

type StageRef added in v0.3.0

type StageRef struct {
	TimelineID string  `json:"timeline_id"`
	StageID    StageID `json:"stage_id"`
}

StageRef carries explicit stage identity as data. Context binding does not assign a parent to subsequent stages.

func StageFromContext added in v0.3.0

func StageFromContext(ctx context.Context) (StageRef, bool)

type Stats

type Stats = cache.Stats

type Status added in v0.3.0

type Status = model.Status

Status describes an observed stage or operation result.

type Timeline added in v0.3.0

type Timeline interface {
	// Record copies and accepts a completed stage into the cache. Recording may
	// load Store on a miss; Flush confirms submission to the configured backend. ID, name, actual start/end times and a terminal status
	// must be supplied. An empty ParentID means no parent; a supplied parent
	// need not exist and is preserved for later association. Actor is preserved.
	// Repeated identical states are idempotent. The same ID with different actors
	// retains separate records; competing same-actor states use last accepted write.
	Record(Stage) error
	// Flush confirms preceding records reached the backend. A Manager-backed
	// handle checkpoints the shared local buffer for its operation ID.
	Flush(context.Context) error
	// ID is the immutable, caller-supplied identity of this operation.
	// Its meaning and uniqueness scope belong to the caller.
	ID() string
	// SetAttributes records attributes on this handle's operation start.
	SetAttributes(attributes ...Attribute)
	// Begin starts a stage using the local clock unless source times are supplied.
	// Parentage is explicit through WithParent; empty means no parent.
	Begin(name string, opts ...StageOption) StageHandle
	// Snapshot flushes this handle and collects its backend's current facts.
	// Collection reports local flush and backend read success, never global
	// completeness. On error it returns best-effort data alongside the error.
	Snapshot(ctx context.Context) (Snapshot, error)
	// Finish records the operation result and returns a snapshot. Shared stores
	// accept late stage updates; a local backend may seal and return
	// ErrActiveStages until its stages end. The returned error is a collection
	// error, independent of operationErr. Finish never closes a shared store.Store.
	Finish(ctx context.Context, operationErr error) (Snapshot, error)
}

Timeline is a recording handle for one business operation. Multiple handles may contribute through a shared store.Store. Methods and returned handles are safe for concurrent use. Business code owns completion and stage attribution.

func FromContext added in v0.3.0

func FromContext(ctx context.Context) (Timeline, bool)

FromContext retrieves a Timeline explicitly attached with NewContext. Constructors and Begin do not attach or replace this value.

func Noop added in v0.3.0

func Noop(id string) Timeline

Noop returns a disabled timeline retaining id. It records no intervals or attributes, and leaves contexts unchanged. An empty ID denotes untracked work.

Jump to

Keyboard shortcuts

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