timeline

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: 8 Imported by: 0

Documentation

Overview

Package timeline provides ID-based recording and queries for operation timelines. Manager owns recording and persistence; callers own business results and exports.

Example
package main

import (
	"context"
	"fmt"

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

func main() {
	m, err := timeline.NewManager(nil, timeline.Config{})
	if err != nil {
		panic(err)
	}
	previous := timeline.SetDefault(m)
	defer timeline.SetDefault(previous)
	defer m.Shutdown(context.Background())

	// Stage recording needs neither Start nor Finish nor persistent storage.
	if _, err := timeline.Begin("task-42", "prepare_files"); err != nil {
		panic(err)
	}
	if err := timeline.End("task-42", "prepare_files", nil); err != nil {
		panic(err)
	}
	snapshot, err := timeline.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 = manager.ErrActiveStages
View Source
var ErrAlreadyExists = errors.New("timeline: ID is already registered")
View Source
var ErrAmbiguousStage = manager.ErrAmbiguousStage
View Source
var ErrBufferFull = manager.ErrBufferFull
View Source
var ErrClosed = manager.ErrClosed
View Source
var ErrEmptyID = model.ErrEmptyID
View Source
var ErrInvalidAttribute = model.ErrInvalidAttribute
View Source
var ErrInvalidStage = model.ErrInvalidStage
View Source
var ErrNoDefault = manager.ErrNoDefault
View Source
var ErrNotStarted = manager.ErrNotStarted
View Source
var ErrStageNotFound = manager.ErrStageNotFound

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 End added in v0.3.0

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

func Finish added in v0.3.0

func Finish(id string, err error) error

func NewContext

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

NewContext optionally carries t without changing ctx's lifetime.

func NewStageContext

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

func Record added in v0.3.0

func Record(id string, stage Stage) error

func Start added in v0.3.0

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

Types

type Actor

type Actor = model.Actor

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

type Attribute

type Attribute = manager.Attribute

Attribute is recording input. Values must be JSON serializable and must not be mutated during the recording call.

type Collection

type Collection = model.Collection

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

type Config added in v0.3.0

type Config = manager.Config

type EndOption

type EndOption = manager.EndOption

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 WithEndActor added in v0.3.0

func WithEndActor(actor Actor) EndOption

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 Handle added in v0.3.0

type Handle = manager.Handle

Handle groups the optional object-style API for one recording identity. The primary business API is Begin/End/Record/Read with optional Start/Finish.

func New

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

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

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.WithActor(timeline.Actor{Name: "test"}), timeline.WithStore(store))
	if err := owner.Start(ctx, "sandbox_start"); err != nil {
		panic(err)
	}
	worker, _ := timeline.New("sandbox-42", timeline.WithActor(timeline.Actor{Name: "test"}), 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

type Manager added in v0.3.0

type Manager = manager.Manager

Manager coordinates recording and background persistence for multiple IDs.

func NewManager added in v0.3.0

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

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

func SetDefault added in v0.3.0

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.

type Option

type Option = manager.Option

Option configures a recording handle without performing remote IO.

func WithActor

func WithActor(actor Actor) Option

func WithStore

func WithStore(backend store.Store) Option

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", timeline.WithStageActor(timeline.Actor{Name: "test"}))
		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", timeline.WithStageActor(timeline.Actor{Name: "test"}))
	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.

func Read added in v0.3.0

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

type Stage

type Stage = model.Stage

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

type StageHandle

type StageHandle = manager.StageHandle

StageHandle identifies a stage and supports ending it or updating its attributes.

func Begin added in v0.3.0

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

func BeginWithContext

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

BeginWithContext preserves cancellation and binds the new stage identity. Only WithParent sets parentage; context binding never supplies a parent.

type StageID

type StageID = model.StageID

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

type StageOption

type StageOption = manager.StageOption

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.

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 = manager.StageRef

StageRef carries timeline and stage identity across process boundaries.

func StageFromContext

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

type Stats added in v0.3.0

type Stats = manager.Stats

type Status

type Status = model.Status

Status describes an observed stage or operation result.

type Timeline

type Timeline = manager.Timeline

Timeline is the optional object-style recording contract for one operation.

func FromContext

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

FromContext retrieves a Timeline explicitly attached with NewContext.

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.

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 manager owns timeline recording, cache coordination and persistence lifecycles.
Package manager owns timeline recording, cache coordination and persistence lifecycles.
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