timeline

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package timeline defines a queryable timeline of an operation and its stages. Implementations own recording and snapshot synchronization; callers own the operation's business result and decide where snapshots are exported.

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 ErrAlreadyExists = errors.New("timeline: ID is already registered")
View Source
var ErrEmptyID = model.ErrEmptyID
View Source
var ErrInvalidAttribute = model.ErrInvalidAttribute
View Source
var ErrInvalidStage = model.ErrInvalidStage
View Source
var ErrNotStarted = errors.New("timeline: operation attributes require a locally recorded start")

Functions

func AttributeValue

func AttributeValue[T any](attributes map[string]json.RawMessage, key string) (T, bool)

AttributeValue decodes the most recent value for key using encoding/json. It returns false for a missing key or a JSON value incompatible with T.

func NewContext

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

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

Types

type Actor

type Actor = model.Actor

Actor optionally identifies the executor; ID and Name are independently optional.

type Attribute

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

type Collection = model.Collection

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

type EndOption

type EndOption func(*Stage) error

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

func WithCode

func WithCode(code string) EndOption

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

func WithEndAttributes

func WithEndAttributes(attributes ...Attribute) EndOption

func WithEndTime

func WithEndTime(at time.Time) EndOption

type Factory

type Factory func(ctx context.Context, id, operation string, attributes ...Attribute) (Timeline, error)

Factory creates a fresh Timeline with the supplied ID. It must not publish the instance elsewhere: the Registry owns registration and completion cleanup. On error it must release any resources it allocated.

type Option

type Option func(*Recorder)

Option configures a writer without performing remote IO.

func WithActor

func WithActor(actor Actor) Option

func WithStore

func WithStore(backend store.Store) Option

func WithWriter

func WithWriter(writer Writer) Option

WithWriter selects the local submission policy. store.Store remains the read backend. The writer must submit to the same store and operation ID as the Recorder.

type Recorder

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

Recorder owns one writer's revisions, operation facts and stage timing. It has no process cache, worker or expiry policy. Multiple writers contribute to one ID.

func New

func New(id string, options ...Option) (*Recorder, error)

New binds a writer to an ID without recording a start or querying storage.

Example
package main

import (
	"context"
	"fmt"

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

func main() {
	ctx := context.Background()
	// A persistent Store can connect these handles across process boundaries.
	store := timelinestore.NewMemoryStore()
	owner, _ := timeline.New("sandbox-42", timeline.WithStore(store))
	if err := owner.Start(ctx, "sandbox_start"); err != nil {
		panic(err)
	}
	worker, _ := timeline.New("sandbox-42", timeline.WithStore(store),
		timeline.WithActor(timeline.Actor{Name: "scheduler-pod"}))
	_, stage := timeline.BeginWithContext(ctx, worker, "acquire_carrier")
	stage.End(nil)
	if err := worker.Flush(ctx); err != nil {
		panic(err)
	}
	snapshot, err := owner.Finish(ctx, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println(snapshot.ID, snapshot.Operation, snapshot.Status)
	fmt.Println(snapshot.Stages[0].Name, snapshot.Stages[0].Actor.Name)
}
Output:
sandbox-42 sandbox_start succeeded
acquire_carrier scheduler-pod

func Restore

func Restore(doc store.Document, options ...Option) (*Recorder, error)

Restore resumes operation facts from a detached document without recording a new start or querying storage. It does not claim ownership over other writers.

func (*Recorder) Begin

func (t *Recorder) Begin(name string, opts ...StageOption) StageHandle

Begin records a running stage. Use Err to inspect admission/encoding errors when a noop handle is returned. Manager.Begin returns the error directly.

func (*Recorder) Err

func (t *Recorder) Err() error

Err reports recording errors on this handle. Submission failures are returned immediately; accepted-data loss remains visible through the writer's checkpoint.

func (*Recorder) Finish

func (t *Recorder) Finish(ctx context.Context, operationErr error) (Snapshot, error)

Finish records an optional result and reads a snapshot for standalone callers.

func (*Recorder) Flush

func (t *Recorder) Flush(ctx context.Context) error

Flush checkpoints the configured writer. A Manager-backed writer checkpoints its ID; a standalone writer checkpoints only its own buffer.

func (*Recorder) ID

func (t *Recorder) ID() string

func (*Recorder) Record

func (t *Recorder) Record(stage Stage) error

Record buffers an already completed interval, without inventing timestamps or an executor identity. Use a stable ID to retry the same external fact.

func (*Recorder) RecordFinish

func (t *Recorder) RecordFinish(operationErr error) error

RecordFinish accepts an optional result even without RecordStart. It never ends stages or prevents late recording. Repeating the same result is idempotent.

func (*Recorder) RecordStart

func (t *Recorder) RecordStart(operation string, attributes ...Attribute) error

RecordStart accepts an optional beginning without forcing a flush. Repeating the same facts is idempotent and retains the original time. Finish may arrive first.

func (*Recorder) RestoreStage

func (r *Recorder) RestoreStage(record store.StageUpdate) StageHandle

RestoreStage resumes a stage read from this recorder's document. Revisions and terminal state are preserved. Restored intervals use their recorded wall times; a monotonic clock cannot be recovered from persistent data.

func (*Recorder) SetAttributes

func (t *Recorder) SetAttributes(attributes ...Attribute)

func (*Recorder) Snapshot

func (t *Recorder) Snapshot(ctx context.Context) (Snapshot, error)

func (*Recorder) Start

func (t *Recorder) Start(ctx context.Context, operation string, attributes ...Attribute) error

Start records the optional beginning and checkpoints this standalone writer. Manager's ID-based Start uses RecordStart and submits in the background.

func (*Recorder) UpdateAttributes

func (t *Recorder) UpdateAttributes(attributes ...Attribute) error

UpdateAttributes updates a locally recorded start's attributes, returning admission errors immediately. It does not require an operation to remain open.

type Registry

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

Registry indexes active timelines within one process. Share an instance across components; business code owns ID generation, propagation and completion. Construct it with NewRegistry. It must not be copied after first use.

Example
package main

import (
	"context"
	"fmt"

	"github.com/compforge/go-stdx/timeline"
	gospantimeline "github.com/compforge/go-stdx/timeline/gospan"
)

func main() {
	registry := timeline.NewRegistry(gospantimeline.New)
	ctx := context.Background()
	tl, err := registry.Create(ctx, "start-42", "sandbox_start")
	if err != nil {
		panic(err)
	}

	// Pass Timeline directly along a call chain.
	prepare := func(ctx context.Context, tl timeline.Timeline) {
		_, stage := timeline.BeginWithContext(ctx, tl, "prepare")
		stage.End(nil)
	}
	prepare(ctx, tl)

	// An independent component needs only the shared registry and operation ID.
	joined, ok := registry.Lookup("start-42")
	if !ok {
		panic("operation missing")
	}
	_, stage := timeline.BeginWithContext(ctx, joined, "provision")
	stage.End(nil)

	// Context propagation is an optional caller choice.
	bound, _ := timeline.FromContext(timeline.NewContext(ctx, tl))
	fmt.Println(joined == tl, bound == tl)
	result, err := tl.Finish(ctx, nil)
	if err != nil {
		panic(err)
	}
	_, active := registry.Lookup(tl.ID())
	fmt.Println(result.ID, len(result.Stages), active)
}
Output:
true true
start-42 2 false

func NewRegistry

func NewRegistry(factory Factory) *Registry

NewRegistry uses factory to create timelines without binding them to context. The factory must be non-nil. A Registry does not store completed history or automatically finish operations when a request's context is canceled.

func (*Registry) Create

func (r *Registry) Create(ctx context.Context, id, operation string, attributes ...Attribute) (Timeline, error)

Create reserves a non-empty ID and creates an operation. Concurrent creates for the same ID return ErrAlreadyExists, including while its factory is running. A failed creation releases the ID. The caller owns Finish on the returned Timeline; independent components should only end their own stages.

func (*Registry) Lookup

func (r *Registry) Lookup(id string) (Timeline, bool)

Lookup returns the instance published by Create. It returns false while the factory is running and after Finish has returned without ErrActiveStages. It never creates an operation. A concurrent Finish may seal a returned instance before its next Begin; recording then follows Timeline's inert rules.

type Snapshot

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.

type Stage

type Stage = model.Stage

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

type StageHandle

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 represents running work or a wait. A leaf stage is the basic recording unit of one component's execution flow: callers should begin and end it in the same goroutine. Parallel execution flows contribute separate stages. A parent stage may group parallel child stages across components; its own lifecycle remains owned by the coordinating component. A parent may end before its children.

func BeginWithContext

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 only inherits a parent from this timeline.

type StageID

type StageID = model.StageID

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

type StageOption

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

func WithAttributes(attributes ...Attribute) StageOption

func WithParent

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

func WithStageActor(actor Actor) StageOption

func WithStageID

func WithStageID(id StageID) StageOption

func WithStartTime

func WithStartTime(at time.Time) StageOption

type StageRef

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

StageRef can cross a process boundary as plain data. Only identity is carried; cancellation, deadlines and a mutable recorder never cross with it.

func StageFromContext

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

type Status

type Status = model.Status

Status describes an observed stage or operation result.

type Timeline

type Timeline interface {
	// Record copies and buffers a completed stage. It performs no IO; Flush
	// confirms persistence. ID, name, actual start/end times and a terminal status
	// must be supplied. An omitted ParentID defaults to the root; a supplied parent
	// need not exist and is preserved for later association. Actor is preserved.
	// Repeated identical IDs are idempotent; conflicting persisted facts fail Flush.
	Record(Stage) error
	// Flush confirms this handle's preceding records reached its backend.
	// It does not wait for records buffered by other handles.
	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; BeginWithContext is an optional context convenience.
	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

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

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.

type Writer

type Writer interface {
	Write(store.Update) error
	// RecordError retains collection loss independently of pending queue membership.
	RecordError(error)
	Flush(context.Context) error
}

Writer accepts immutable recording facts and provides a persistence checkpoint. A rejected write must not be retained. Acceptance and retention depend on the implementation: Manager uses a best-effort loading cache; standalone Recorder buffers until an explicit Flush. Implementations support concurrent callers.

Directories

Path Synopsis
Package gospantimeline implements timeline.Timeline with gospan spans and an in-memory projection.
Package gospantimeline implements timeline.Timeline with gospan spans and an in-memory projection.
Package model holds values shared by recording and storage, without either lifecycle.
Package model holds values shared by recording and storage, without either lifecycle.
Package store defines the timeline persistence protocol and its in-memory implementation.
Package store defines the timeline persistence protocol and its in-memory implementation.
sqlstore
Package sqlstore persists one document per timeline using an application-owned database/sql pool.
Package sqlstore persists one document per timeline using an application-owned database/sql pool.

Jump to

Keyboard shortcuts

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