progress

package
v0.1.0-alpha.6 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

progress

A workflow's progress as a stream of events over a tree of steps. The tree follows the code's own composition: a workflow opens its steps under whatever step the context carries, and never knows who called it. The package declares no kinds and knows nothing of arcave; the examples publish a photo album (example_test.go, and the runnable examples/). It owns its types (event.go) and imports only the standard library and zerolog, so it can leave the repository whole; the terminal renderer's Bubble Tea and Lip Gloss stay in renderer/tty, and

go list -deps ./pkg/progress ./pkg/progress/renderer | grep charm

stays empty.

Steps

Constructor Type Opens Measures
Tracker.Begin workflow, the root lazily none
Begin on WithTracker(ctx, t) workflow, t's root, when ctx carries no step lazily none
Begin workflow lazily — on its first child or Warn none
Batch workflow over objects of one kind at once, with Items.Total items, counted by the tracker
Run activity — one action, no children at once what the caller declares

A step is either made of other steps or does the work itself, and only the second measures:

  • it will open steps of its own → Begin;
  • it loops over objects of one kind, to be counted done/total → Batch, each object a Run;
  • it is one action — a copy, a call, a wait — whether or not it measures anything → Run.

Nothing opens under a Run: code below an activity reports into it, through Current(ctx).

Step.Kind is the consumer's; Type is set by the constructor and never by the caller. Name names a workflow's instance (album.publish summer), ID an object under a batch (file beach.jpg).

WithTracker lets a workflow open its own root without knowing whether it is one: the same Begin opens the tracker's root at the top of a run, and a child when another workflow calls it.

Every constructor returns a context carrying the new step, and the *StepReporter it reports through. Code deeper down that holds only the context reaches its activity through Current(ctx). WithStep(ctx, step) puts a step back on a context derived from an activity's — a lock's, say, whose context the rest of the workflow runs on. A constructor under an activity, or under a step that has ended, returns a mute step and logs a warning; so does every constructor when the context carries no tracker, and under Discard(). Every method of a mute step is a no-op, so a consumer's tests change nothing. IsMute() tells a caller that would set something up only to report into the step — a sink for another library's events, say — that nothing would be reported.

A lazy workflow that ends without a child reports nothing: what never ran is never mentioned. Update and Progress keep it unopened; only a child, Warn or a failure opens it. A batch still counts such a child among its done. There is no plan, no pending and no skipped; a unit left out is a warning on its parent. Items.Total of a batch is a fact, the count it will really process once filtered, 0 if unknown.

Kinds

A progress.Kind is a string the consumer declares. By convention an action is <namespace>.<action> (queue.pause, photo.resize) and an object a bare noun (photo, file). A batch's children are objects, whose kind is not derived from the batch's: cdn.upload loops over file. The convention is for readers; no renderer depends on it.

The stream

activity (Run):   started+Open ──► (in_progress | warned)* ──► succeeded | failed | cancelled
batch (Batch):    started+Open ──► in_progress per finished child ──► succeeded | failed | cancelled
workflow (Begin): [lazy] ──first child / Warn──► started+Open ──► (warned)* ──► succeeded | failed | cancelled
  • Steps are numbered from 1 in the order they open; a lazy workflow opens its unopened ancestors top down first, so a parent's started always precedes its child's.
  • node in the stream is the step's StepID, and open.parent its parent's: on the wire the stream is a tree, and the words are the tree's.
  • started carries Open — the parent, the step and the declared Measures — once. Every later event names the step by number only: a renderer reads the stream from its start and builds a step's widget once, as compose's and OpenTelemetry's do.
  • Every event is a full snapshot: the step's own msg — the last Update's — the last sample, a fresh Elapsed counted from the constructor; a warned event's or a resource's msg is that event's alone. A caller reports only what changed: Done(sample) and Progress(sample) replace the fields they set and keep the rest; Fail keeps the last sample.
  • A step ends once; every call after is ignored.

Samples

Elapsed (always, elapsed_ns in JSON), Bytes{Done, Total, Stored, Reused} and Items{Done, Failed, Cancelled, Total}, accumulated rather than deltas. Items.Done counts successes only — 3/5 failed=1 is three done and one failed of five. A Total of 0 is unknown and left out of the JSON: a renderer shows Done alone, with no bar; a Total may appear later in the same stream, and a Done past it is shown without one. Anything not a count goes in msg.

A step reports only the measures it declared; the rest is dropped with a warning. A batch counts its children's outcomes itself and takes no Items from its caller; it never sums their bytes.

Failure and cancellation

Fail(msg, err), or End(err) for a non-nil err, ends a step failed — or cancelled when errors.Is(err, context.Canceled), or when the context the step was opened on is cancelled and err is its context.Cause: the siblings an errgroup cancels after the first failure are counted Cancelled, not Failed, and carry no error. A deadline is a failure.

A step opens on the context outside the cancellation it reports. A workflow that cancels its own work with a cause — a lost lock, a missed heartbeat — opens its step before deriving that context: its children end cancelled and the step itself failed, carrying the cause once. Opened under that context, it would end cancelled too, and the cause would not be in the stream at all. Likewise a Batch opens before errgroup.WithContext, and its children open on the group's context:

ctx, batch := progress.Batch(ctx, progress.Step{Kind: kindCDNUpload}, len(files))
defer func() { batch.End(err) }()
eg, egCtx := errgroup.WithContext(ctx)
for _, f := range files {
	eg.Go(func() error {
		ctx, step := progress.Run(egCtx, progress.Step{Kind: kindFile, ID: f.name}, progress.MeasureBytes)
		err := upload(ctx, f) // ctx, not egCtx: Current(ctx) is the file's step, which counts the bytes
		step.End(err)
		return err
	})
}

The context a constructor returns is the one to pass down: the step's code below reaches it through Current(ctx) and nothing else. Passed the parent's instead, NewReader counts on the batch, which declares no bytes, and the bytes are dropped.

The error is reported where it arose: always on an activity, on a workflow only when none of its descendants failed — an error raised by the workflow's own code. The ancestors of a failed step end failed with no error, so the cause is in the stream exactly once.

A best-effort step whose failure does not fail the operation calls Warn and then Done. WarnInResult is Warn for a warning the operation's result repeats: its event carries "in_result": true, a log or a JSON stream reports it as any warning, and a renderer printing the result beside the tree may leave it out.

End under defer must close over a named error, or it reports success:

func (p publisher) exportAlbum(ctx context.Context, photos []photo) (err error) {
	ctx, step := progress.Begin(ctx, progress.Step{Kind: kindAlbumExport})
	defer func() { step.End(err) }() // not defer step.End(err)
	...
}

Activities over resources

An activity handles its resources one of two ways. When a batch runs one object per resource, the resource's key is the object's Step.ID. When one call handles the whole set — a queue pausing every worker — the activity declares resources and reports each through UpdateResource while one is under way, SettleResource once it reaches its outcome — the event's settled — and WarnResource with a progress.Resource; the resources are not steps. The Log renderer writes a resource under way at debug and a settled one at info.

Sources deep in the call

A source that counts as it goes reports through a Sampler: its topic is the step to report on, its template the sample's shape and the values known upfront, such as a Total. Update(fn) changes the accumulated sample — adding as a stream flows, or replacing it with numbers the source counts itself — and sends it at most once per the tracker's interval (200ms on its clock); the first update goes at once, and the last is never flushed: the step's Done carries the total. Throttling in the source keeps the tracker's lock off every 32KB read of parallel streams. A sampler whose topic is mute, or does not declare the template's measures, is mute.

NewReader(ctx, r, total) and NewWriter(ctx, w, total) count a stream's bytes on Current(ctx) through a sampler, and return r or w itself when that step reports no bytes. Pass a total only when it is exact, else 0: an estimate draws a bar stuck at 100% or one that turns into a counter midway, which reads as a fault.

src = progress.NewReader(ctx, src, size) // the source knows ctx, not the tree

sampler := progress.NewSampler(step, progress.Sample{Bytes: &progress.Bytes{}})
sampler.Update(func(sample *progress.Sample) {
	sample.Bytes.Done = status.BytesDone
	sample.Bytes.Total = status.TotalBytes // 0 until the source has counted
})

Renderers

Renderer is the one seam: Render(progress.Event), called under the tracker's lock. renderer.NewJSON writes the stream as is, one event per line, and stops at a failed write, which Err returns; a consumer rebuilds the tree by open.parent. renderer.NewLog writes a record per event worth a line, named by the step's path, and skips a sample tick that changes nothing but bytes:

INF album.publish[summer]/album.export status=started
WRN album.publish[summer]/album.export msg="2 raw files skipped" status=warned
INF album.publish[summer]/album.export/photo.resize items=0/2 status=started
INF album.publish[summer]/album.export/photo.resize/photo[beach.jpg] status=started
INF album.publish[summer]/album.export/photo.resize/photo[beach.jpg] bytes=2.1MB/2.1MB elapsed=600ms status=succeeded stored=420KB
INF album.publish[summer]/album.export/photo.resize items=1/2 status=in_progress
ERR album.backup[summer]/cdn.upload/file[raw.dng] error="403 forbidden" bytes=450KB elapsed=250ms msg="unable to upload" status=failed
WRN album.backup[summer]/cdn.upload/file[cover.jpg] elapsed=0s status=cancelled
{"node":8,"status":"started","open":{"parent":6,"step":{"kind":"file","type":"activity","id":"raw.dng"},"measures":["bytes"]},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:01Z"}
{"node":8,"status":"in_progress","sample":{"elapsed_ns":0,"bytes":{"done":450000}},"at":"2026-10-29T12:00:01Z"}
{"node":8,"status":"failed","msg":"unable to upload","error":"403 forbidden","sample":{"elapsed_ns":250000000,"bytes":{"done":450000}},"at":"2026-10-29T12:00:01.25Z"}
The terminal

tty.New(out) draws the stream on a terminal as a tree redrawn in place, through Bubble Tea:

⠦ album.publish summer                                               3.6s
├── ✔ queue.pause                                                    0.3s
├── ✔ album.export                                                   2.1s
│     ! 2 raw files skipped
│   ├── ✔ photo.resize  8/8                                          1.9s
│   └── ✔ manifest.write                                             0.1s
└── ⠦ cdn.upload  5/8                                                1.3s
    └── ⠦ file cliffs.jpg  ████████████░░░░░░░░ 1.8MB/2.7MB 7.0MB/s  0.3s
  • A line is <icon> <kind> <name or id> <widget> <msg>, the time right-aligned in one column just past the widest line, which a live frame never moves left: a spinner while running, ✔, ✘ or ⊘ once ended. bytes is a bar, the count and the average speed — the count alone while the total is unknown or exceeded, or once every byte is in, stored/reused once ended; items is done/total, ✘failed, ⊘cancelled; resources is a line per resource under the node. A warning is a ! line under its node, an error an error: line. A node cancelled before it took any time shows none. What does not fit the width gives way: the label, the message, the bar.
  • Each root is its own tree. A success with no warning or failure below it is one line. Under a batch, running or ended, only what has something to say is shown — running, failed, warned, or cancelled after it began; a quiet success and a cancellation that stopped nothing under way are left to the batch's count. A quiet success stays open for 1.5s after it ends, so a quick step's resource lines are seen; under a batch it goes at once. A frame taller than the terminal folds the earliest finished children into … N more finished; running and failed nodes always show.
  • Stop(StopOptions) clears the frame and writes the final tree into the scrollback, collapsed by the same rules but neither cut nor folded, a root always open, five warnings at most per node and the rest counted, MoreHint after the count. Essential, for a caller printing a result beside the tree, writes the roots and each root's children as a line with its time, and below them only the paths to what the result does not say: failures, cancellations, warned resources and warnings not marked in_result. OmitRootError leaves a root's error: line to the caller, which writes the error itself:
✘ album.backup summer                                  2.5s
├── ✔ album.export                                     1.2s
│     ! 2 raw files skipped
│   ├── ✔ photo.resize  3/3                            1.0s
│   └── ✔ manifest.write                               0.1s
├── ✘ cdn.upload  3/6 ✘1 ⊘2                            1.0s
│   └── ✘ file raw.dng  450KB/900KB  unable to upload  0.1s
│         error: 403 forbidden
└── ✔ album.rollback                                   0.3s
    └── ✔ cdn.purge  3/3                               0.3s
        └── ✔ file beach.jpg                           0.1s
              ! purge failed, the file stays on the CDN: edge timeout

While the program runs, Render and LogWriter only change the renderer's state under its own lock; the program reads it on a 100ms tick, so the tracker never waits on the terminal. Log lines go through LogWriter() — an io.Writer of whole lines, filtered by the logger's level — and print above the tree, or straight to the terminal while there is none. The program reads no input and handles no signal: Ctrl-C stays the caller's, to cancel its context. The first event starts it, so a run that reports none never takes the terminal; Stop must follow on every path a panic of the calling goroutine takes, and reports whether it wrote a tree:

progressRenderer := tty.New(os.Stderr)
logger := zerolog.New(zerolog.ConsoleWriter{Out: progressRenderer.LogWriter()}).Level(zerolog.WarnLevel)
defer progressRenderer.Stop(tty.StopOptions{})
tracker := progress.New(progressRenderer, time.Now)

go run ./pkg/progress/examples -scenario all runs four workflows through it — success, failure with cancellation and rollback, four uploads at once, a source with no total — or through -renderer log|json; -speed scales them.

Testing

A test that is not about progress needs nothing: without a tracker every step is mute. A test that is records the stream through its own Renderer on a tracker with a fixed clock, put on the context the code under test is handed:

type recorder struct{ events []progress.Event }

func (r *recorder) Render(evt progress.Event) { r.events = append(r.events, evt) }

rec := &recorder{}
tracker := progress.New(rec, func() time.Time { return time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC) })
err := svc.Publish(progress.WithTracker(ctx, tracker), album)

Render is called under the tracker's lock, so the recorder needs none of its own. example_test.go moves its clock by hand and asserts the stream through renderer.NewLog.

Documentation

Overview

Package progress reports a workflow's progress as a stream of events over a tree of workflows, batches and activities, carried through the context; see README.md.

Example (Lazy)

Example_lazy shows a workflow that reports nothing until it has something to report.

package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"time"

	"github.com/rs/zerolog"

	"github.com/greenmaskio/arcave/pkg/progress"
	"github.com/greenmaskio/arcave/pkg/progress/renderer"
)

// The kinds a consumer declares.
const (
	kindAlbumPublish progress.Kind = "album.publish"

	kindAlbumExtras   progress.Kind = "album.extras"
	kindAlbumRollback progress.Kind = "album.rollback"
)

type photo struct {
	name string
	size int64
}

type exampleClock struct {
	now time.Time
}

func (c *exampleClock) Now() time.Time {
	return c.now
}

func (c *exampleClock) advance(d time.Duration) {
	c.now = c.now.Add(d)
}

var start = time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC)

func main() {
	var (
		clock   = &exampleClock{now: start}
		tracker = progress.New(renderer.NewLog(newExampleLogger()), clock.Now)
	)

	ctx, root := tracker.Begin(context.Background(), progress.Step{Kind: kindAlbumPublish, Name: "summer"})
	_, extras := progress.Begin(ctx, progress.Step{Kind: kindAlbumExtras})
	extras.End(nil)
	fmt.Println("an empty workflow that succeeded reported nothing")
	clock.advance(time.Second)
	_, rollback := progress.Begin(ctx, progress.Step{Kind: kindAlbumRollback})
	rollback.End(errors.New("queue unreachable"))
	root.End(errors.New("rollback: queue unreachable"))

}

func newExampleLogger() zerolog.Logger {
	return zerolog.New(zerolog.ConsoleWriter{
		Out:          os.Stdout,
		NoColor:      true,
		PartsExclude: []string{zerolog.TimestampFieldName},
	})
}
Output:
an empty workflow that succeeded reported nothing
INF album.publish[summer] status=started
INF album.publish[summer]/album.rollback status=started
ERR album.publish[summer]/album.rollback error="queue unreachable" elapsed=0s status=failed
ERR album.publish[summer] elapsed=1s status=failed
Example (Publish)

Example_publish runs a workflow to success through the log reporter.

package main

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"time"

	"github.com/rs/zerolog"

	"github.com/greenmaskio/arcave/pkg/progress"
	"github.com/greenmaskio/arcave/pkg/progress/renderer"
)

// The kinds a consumer declares.
const (
	kindAlbumPublish  progress.Kind = "album.publish"
	kindAlbumBackup   progress.Kind = "album.backup"
	kindAlbumExport   progress.Kind = "album.export"
	kindAlbumExtras   progress.Kind = "album.extras"
	kindAlbumRollback progress.Kind = "album.rollback"
	kindPhotoResize   progress.Kind = "photo.resize"
	kindCDNUpload     progress.Kind = "cdn.upload"
	kindCDNPurge      progress.Kind = "cdn.purge"
	kindQueuePause    progress.Kind = "queue.pause"
	kindQueueResume   progress.Kind = "queue.resume"
	kindManifestWrite progress.Kind = "manifest.write"
	kindPhoto         progress.Kind = "photo"
	kindFile          progress.Kind = "file"

	resourceWorker progress.ResourceKind = "worker"
)

var errDenied = errors.New("403 forbidden")

type photo struct {
	name string
	size int64
}

// publisher stands for a consumer's service; its clock is the example's, moved by hand.
type publisher struct {
	clock *exampleClock
}

type exampleClock struct {
	now time.Time
}

func (c *exampleClock) Now() time.Time {
	return c.now
}

func (c *exampleClock) advance(d time.Duration) {
	c.now = c.now.Add(d)
}

var (
	summer = []photo{{"beach.jpg", 2_100_000}, {"dunes.jpg", 1_800_000}, {"sunset.jpg", 2_400_000}}
	start  = time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC)
)

func main() {
	var (
		clock   = &exampleClock{now: start}
		logger  = newExampleLogger()
		tracker = progress.New(renderer.NewLog(logger), clock.Now)
		p       = publisher{clock: clock}
	)

	err := p.publish(context.Background(), tracker, summer[:2])

	fmt.Println("err:", err)
}

func (p publisher) publish(ctx context.Context, tracker *progress.Tracker, photos []photo) (err error) {
	ctx, root := tracker.Begin(ctx, progress.Step{Kind: kindAlbumPublish, Name: "summer"})
	defer func() { root.End(err) }()

	if err = p.pauseQueue(ctx); err != nil {
		return err
	}
	if err = p.exportAlbum(ctx, photos); err != nil {
		return err
	}
	if _, err = p.uploadFiles(ctx, photos, -1); err != nil {
		return err
	}
	return p.resumeQueue(ctx)
}

func (p publisher) backup(ctx context.Context, tracker *progress.Tracker, photos []photo, failAt int) (err error) {
	ctx, root := tracker.Begin(ctx, progress.Step{Kind: kindAlbumBackup, Name: "summer"})
	defer func() { root.End(err) }()

	if err = p.exportAlbum(ctx, photos); err != nil {
		return err
	}
	uploaded, err := p.uploadFiles(ctx, append(photos, photo{"raw.dng", 900_000}, photo{"cover.jpg", 300_000}, photo{"map.png", 100_000}), failAt)
	if err != nil {
		if rollbackErr := p.rollbackAlbum(ctx, uploaded); rollbackErr != nil {
			return errors.Join(err, rollbackErr)
		}
		return err
	}
	return nil
}

// pauseQueue is a summary activity: one call handles every worker, each a resource.
func (p publisher) pauseQueue(ctx context.Context) error {
	_, step := progress.Run(ctx, progress.Step{Kind: kindQueuePause}, progress.MeasureResources)
	for _, worker := range []string{"worker-1", "worker-2"} {
		resource := progress.Resource{Kind: resourceWorker, ID: worker}
		step.UpdateResource(resource, "Draining")
		p.clock.advance(200 * time.Millisecond)
		step.SettleResource(resource, "Paused")
	}
	step.Done(progress.Sample{})
	return nil
}

func (p publisher) resumeQueue(ctx context.Context) error {
	_, step := progress.Run(ctx, progress.Step{Kind: kindQueueResume}, progress.MeasureResources)
	p.clock.advance(100 * time.Millisecond)
	step.SettleResource(progress.Resource{Kind: resourceWorker, ID: "worker-1"}, "Running")
	step.Done(progress.Sample{})
	return nil
}

// exportAlbum is a shared workflow: it does not know which root it runs under.
func (p publisher) exportAlbum(ctx context.Context, photos []photo) (err error) {
	ctx, step := progress.Begin(ctx, progress.Step{Kind: kindAlbumExport})
	defer func() { step.End(err) }()

	step.Warn("2 raw files skipped")
	batchCtx, batch := progress.Batch(ctx, progress.Step{Kind: kindPhotoResize}, len(photos))
	for _, item := range photos {
		if err = p.resizePhoto(batchCtx, item); err != nil {
			batch.End(err)
			return err
		}
	}
	batch.End(nil)

	_, extras := progress.Begin(ctx, progress.Step{Kind: kindAlbumExtras})
	extras.End(nil)

	_, manifest := progress.Run(ctx, progress.Step{Kind: kindManifestWrite})
	p.clock.advance(50 * time.Millisecond)
	manifest.Done(progress.Sample{})
	return nil
}

func (p publisher) resizePhoto(ctx context.Context, item photo) (err error) {
	ctx, step := progress.Run(ctx, progress.Step{Kind: kindPhoto, ID: item.name}, progress.MeasureBytes)
	defer func() { step.End(err) }()

	resized, err := p.resize(ctx, bytes.NewReader(make([]byte, item.size)), item.size)
	if err != nil {
		return err
	}
	step.Done(progress.Sample{Bytes: &progress.Bytes{Done: item.size, Total: item.size, Stored: resized}})
	return nil
}

// resize is a source deep in the call: it knows ctx and nothing of the tree.
func (p publisher) resize(ctx context.Context, src io.Reader, size int64) (int64, error) {
	src = progress.NewReader(ctx, src, size)
	buf := make([]byte, 1_000_000)
	for {
		p.clock.advance(150 * time.Millisecond)
		if _, err := src.Read(buf); errors.Is(err, io.EOF) {
			return size / 5, nil
		} else if err != nil {
			return 0, err
		}
	}
}

// uploadFiles is a batch whose objects report what the CDN counts itself; the first failure
// cancels the rest, as an errgroup would.
func (p publisher) uploadFiles(ctx context.Context, photos []photo, failAt int) (uploaded []photo, err error) {
	ctx, batch := progress.Batch(ctx, progress.Step{Kind: kindCDNUpload}, len(photos))
	defer func() { batch.End(err) }()

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	for i, item := range photos {
		uploadErr := p.uploadFile(ctx, item, i == failAt)
		if uploadErr == nil {
			uploaded = append(uploaded, item)
			continue
		}
		if err == nil {
			err = uploadErr
			cancel()
		}
	}
	return uploaded, err
}

func (p publisher) uploadFile(ctx context.Context, item photo, deny bool) (err error) {
	_, step := progress.Run(ctx, progress.Step{Kind: kindFile, ID: item.name}, progress.MeasureBytes)
	defer func() { step.End(err) }()

	if err = ctx.Err(); err != nil {
		return err
	}

	sampler := progress.NewSampler(step, progress.Sample{Bytes: &progress.Bytes{}})
	sampler.Update(func(sample *progress.Sample) {
		sample.Bytes.Done = item.size / 2
	})
	p.clock.advance(250 * time.Millisecond)
	if deny {
		step.Fail("unable to upload", errDenied)
		return errDenied
	}
	sampler.Update(func(sample *progress.Sample) {
		sample.Bytes.Done = item.size * 3 / 4
		sample.Bytes.Total = item.size
	})
	p.clock.advance(100 * time.Millisecond)
	sampler.Update(func(sample *progress.Sample) {
		sample.Bytes.Done = item.size * 7 / 8
	})
	step.Done(progress.Sample{Bytes: &progress.Bytes{Done: item.size, Total: item.size}})
	return nil
}

// rollbackAlbum purges what was uploaded; a purge that fails only warns.
func (p publisher) rollbackAlbum(ctx context.Context, uploaded []photo) (err error) {
	ctx, step := progress.Begin(ctx, progress.Step{Kind: kindAlbumRollback})
	defer func() { step.End(err) }()

	ctx, batch := progress.Batch(ctx, progress.Step{Kind: kindCDNPurge}, len(uploaded))
	defer func() { batch.End(err) }()
	for _, item := range uploaded {
		_, purge := progress.Run(ctx, progress.Step{Kind: kindFile, ID: item.name})
		p.clock.advance(50 * time.Millisecond)
		purge.Warn("purge failed, the file stays on the CDN: edge timeout")
		purge.Done(progress.Sample{})
	}
	return nil
}

func newExampleLogger() zerolog.Logger {
	return zerolog.New(zerolog.ConsoleWriter{
		Out:          os.Stdout,
		NoColor:      true,
		PartsExclude: []string{zerolog.TimestampFieldName},
	})
}
Output:
INF album.publish[summer] status=started
INF album.publish[summer]/queue.pause status=started
DBG album.publish[summer]/queue.pause msg=Draining resource=worker:worker-1 status=in_progress
INF album.publish[summer]/queue.pause msg=Paused resource=worker:worker-1 status=in_progress
DBG album.publish[summer]/queue.pause msg=Draining resource=worker:worker-2 status=in_progress
INF album.publish[summer]/queue.pause msg=Paused resource=worker:worker-2 status=in_progress
INF album.publish[summer]/queue.pause elapsed=400ms status=succeeded
INF album.publish[summer]/album.export status=started
WRN album.publish[summer]/album.export msg="2 raw files skipped" status=warned
INF album.publish[summer]/album.export/photo.resize items=0/2 status=started
INF album.publish[summer]/album.export/photo.resize/photo[beach.jpg] status=started
INF album.publish[summer]/album.export/photo.resize/photo[beach.jpg] bytes=2.1MB/2.1MB elapsed=600ms status=succeeded stored=420KB
INF album.publish[summer]/album.export/photo.resize items=1/2 status=in_progress
INF album.publish[summer]/album.export/photo.resize/photo[dunes.jpg] status=started
INF album.publish[summer]/album.export/photo.resize/photo[dunes.jpg] bytes=1.8MB/1.8MB elapsed=450ms status=succeeded stored=360KB
INF album.publish[summer]/album.export/photo.resize items=2/2 status=in_progress
INF album.publish[summer]/album.export/photo.resize elapsed=1.05s items=2/2 status=succeeded
INF album.publish[summer]/album.export/manifest.write status=started
INF album.publish[summer]/album.export/manifest.write elapsed=50ms status=succeeded
INF album.publish[summer]/album.export elapsed=1.1s status=succeeded
INF album.publish[summer]/cdn.upload items=0/2 status=started
INF album.publish[summer]/cdn.upload/file[beach.jpg] status=started
INF album.publish[summer]/cdn.upload/file[beach.jpg] bytes=2.1MB/2.1MB elapsed=350ms status=succeeded
INF album.publish[summer]/cdn.upload items=1/2 status=in_progress
INF album.publish[summer]/cdn.upload/file[dunes.jpg] status=started
INF album.publish[summer]/cdn.upload/file[dunes.jpg] bytes=1.8MB/1.8MB elapsed=350ms status=succeeded
INF album.publish[summer]/cdn.upload items=2/2 status=in_progress
INF album.publish[summer]/cdn.upload elapsed=700ms items=2/2 status=succeeded
INF album.publish[summer]/queue.resume status=started
INF album.publish[summer]/queue.resume msg=Running resource=worker:worker-1 status=in_progress
INF album.publish[summer]/queue.resume elapsed=100ms status=succeeded
INF album.publish[summer] elapsed=2.3s status=succeeded
err: <nil>
Example (PublishFailure)

Example_publishFailure runs the same export under another root and fails an upload, through the JSON reporter: the error is on the file alone, the rest of the batch is cancelled.

package main

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"time"

	"github.com/greenmaskio/arcave/pkg/progress"
	"github.com/greenmaskio/arcave/pkg/progress/renderer"
)

// The kinds a consumer declares.
const (
	kindAlbumPublish  progress.Kind = "album.publish"
	kindAlbumBackup   progress.Kind = "album.backup"
	kindAlbumExport   progress.Kind = "album.export"
	kindAlbumExtras   progress.Kind = "album.extras"
	kindAlbumRollback progress.Kind = "album.rollback"
	kindPhotoResize   progress.Kind = "photo.resize"
	kindCDNUpload     progress.Kind = "cdn.upload"
	kindCDNPurge      progress.Kind = "cdn.purge"
	kindQueuePause    progress.Kind = "queue.pause"
	kindQueueResume   progress.Kind = "queue.resume"
	kindManifestWrite progress.Kind = "manifest.write"
	kindPhoto         progress.Kind = "photo"
	kindFile          progress.Kind = "file"

	resourceWorker progress.ResourceKind = "worker"
)

var errDenied = errors.New("403 forbidden")

type photo struct {
	name string
	size int64
}

// publisher stands for a consumer's service; its clock is the example's, moved by hand.
type publisher struct {
	clock *exampleClock
}

type exampleClock struct {
	now time.Time
}

func (c *exampleClock) Now() time.Time {
	return c.now
}

func (c *exampleClock) advance(d time.Duration) {
	c.now = c.now.Add(d)
}

var (
	summer = []photo{{"beach.jpg", 2_100_000}, {"dunes.jpg", 1_800_000}, {"sunset.jpg", 2_400_000}}
	start  = time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC)
)

func main() {
	var (
		clock   = &exampleClock{now: start}
		tracker = progress.New(renderer.NewJSON(os.Stdout), clock.Now)
		p       = publisher{clock: clock}
	)

	err := p.backup(context.Background(), tracker, summer[:1], 1)

	fmt.Println("err:", err)
}

func (p publisher) publish(ctx context.Context, tracker *progress.Tracker, photos []photo) (err error) {
	ctx, root := tracker.Begin(ctx, progress.Step{Kind: kindAlbumPublish, Name: "summer"})
	defer func() { root.End(err) }()

	if err = p.pauseQueue(ctx); err != nil {
		return err
	}
	if err = p.exportAlbum(ctx, photos); err != nil {
		return err
	}
	if _, err = p.uploadFiles(ctx, photos, -1); err != nil {
		return err
	}
	return p.resumeQueue(ctx)
}

func (p publisher) backup(ctx context.Context, tracker *progress.Tracker, photos []photo, failAt int) (err error) {
	ctx, root := tracker.Begin(ctx, progress.Step{Kind: kindAlbumBackup, Name: "summer"})
	defer func() { root.End(err) }()

	if err = p.exportAlbum(ctx, photos); err != nil {
		return err
	}
	uploaded, err := p.uploadFiles(ctx, append(photos, photo{"raw.dng", 900_000}, photo{"cover.jpg", 300_000}, photo{"map.png", 100_000}), failAt)
	if err != nil {
		if rollbackErr := p.rollbackAlbum(ctx, uploaded); rollbackErr != nil {
			return errors.Join(err, rollbackErr)
		}
		return err
	}
	return nil
}

// pauseQueue is a summary activity: one call handles every worker, each a resource.
func (p publisher) pauseQueue(ctx context.Context) error {
	_, step := progress.Run(ctx, progress.Step{Kind: kindQueuePause}, progress.MeasureResources)
	for _, worker := range []string{"worker-1", "worker-2"} {
		resource := progress.Resource{Kind: resourceWorker, ID: worker}
		step.UpdateResource(resource, "Draining")
		p.clock.advance(200 * time.Millisecond)
		step.SettleResource(resource, "Paused")
	}
	step.Done(progress.Sample{})
	return nil
}

func (p publisher) resumeQueue(ctx context.Context) error {
	_, step := progress.Run(ctx, progress.Step{Kind: kindQueueResume}, progress.MeasureResources)
	p.clock.advance(100 * time.Millisecond)
	step.SettleResource(progress.Resource{Kind: resourceWorker, ID: "worker-1"}, "Running")
	step.Done(progress.Sample{})
	return nil
}

// exportAlbum is a shared workflow: it does not know which root it runs under.
func (p publisher) exportAlbum(ctx context.Context, photos []photo) (err error) {
	ctx, step := progress.Begin(ctx, progress.Step{Kind: kindAlbumExport})
	defer func() { step.End(err) }()

	step.Warn("2 raw files skipped")
	batchCtx, batch := progress.Batch(ctx, progress.Step{Kind: kindPhotoResize}, len(photos))
	for _, item := range photos {
		if err = p.resizePhoto(batchCtx, item); err != nil {
			batch.End(err)
			return err
		}
	}
	batch.End(nil)

	_, extras := progress.Begin(ctx, progress.Step{Kind: kindAlbumExtras})
	extras.End(nil)

	_, manifest := progress.Run(ctx, progress.Step{Kind: kindManifestWrite})
	p.clock.advance(50 * time.Millisecond)
	manifest.Done(progress.Sample{})
	return nil
}

func (p publisher) resizePhoto(ctx context.Context, item photo) (err error) {
	ctx, step := progress.Run(ctx, progress.Step{Kind: kindPhoto, ID: item.name}, progress.MeasureBytes)
	defer func() { step.End(err) }()

	resized, err := p.resize(ctx, bytes.NewReader(make([]byte, item.size)), item.size)
	if err != nil {
		return err
	}
	step.Done(progress.Sample{Bytes: &progress.Bytes{Done: item.size, Total: item.size, Stored: resized}})
	return nil
}

// resize is a source deep in the call: it knows ctx and nothing of the tree.
func (p publisher) resize(ctx context.Context, src io.Reader, size int64) (int64, error) {
	src = progress.NewReader(ctx, src, size)
	buf := make([]byte, 1_000_000)
	for {
		p.clock.advance(150 * time.Millisecond)
		if _, err := src.Read(buf); errors.Is(err, io.EOF) {
			return size / 5, nil
		} else if err != nil {
			return 0, err
		}
	}
}

// uploadFiles is a batch whose objects report what the CDN counts itself; the first failure
// cancels the rest, as an errgroup would.
func (p publisher) uploadFiles(ctx context.Context, photos []photo, failAt int) (uploaded []photo, err error) {
	ctx, batch := progress.Batch(ctx, progress.Step{Kind: kindCDNUpload}, len(photos))
	defer func() { batch.End(err) }()

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	for i, item := range photos {
		uploadErr := p.uploadFile(ctx, item, i == failAt)
		if uploadErr == nil {
			uploaded = append(uploaded, item)
			continue
		}
		if err == nil {
			err = uploadErr
			cancel()
		}
	}
	return uploaded, err
}

func (p publisher) uploadFile(ctx context.Context, item photo, deny bool) (err error) {
	_, step := progress.Run(ctx, progress.Step{Kind: kindFile, ID: item.name}, progress.MeasureBytes)
	defer func() { step.End(err) }()

	if err = ctx.Err(); err != nil {
		return err
	}

	sampler := progress.NewSampler(step, progress.Sample{Bytes: &progress.Bytes{}})
	sampler.Update(func(sample *progress.Sample) {
		sample.Bytes.Done = item.size / 2
	})
	p.clock.advance(250 * time.Millisecond)
	if deny {
		step.Fail("unable to upload", errDenied)
		return errDenied
	}
	sampler.Update(func(sample *progress.Sample) {
		sample.Bytes.Done = item.size * 3 / 4
		sample.Bytes.Total = item.size
	})
	p.clock.advance(100 * time.Millisecond)
	sampler.Update(func(sample *progress.Sample) {
		sample.Bytes.Done = item.size * 7 / 8
	})
	step.Done(progress.Sample{Bytes: &progress.Bytes{Done: item.size, Total: item.size}})
	return nil
}

// rollbackAlbum purges what was uploaded; a purge that fails only warns.
func (p publisher) rollbackAlbum(ctx context.Context, uploaded []photo) (err error) {
	ctx, step := progress.Begin(ctx, progress.Step{Kind: kindAlbumRollback})
	defer func() { step.End(err) }()

	ctx, batch := progress.Batch(ctx, progress.Step{Kind: kindCDNPurge}, len(uploaded))
	defer func() { batch.End(err) }()
	for _, item := range uploaded {
		_, purge := progress.Run(ctx, progress.Step{Kind: kindFile, ID: item.name})
		p.clock.advance(50 * time.Millisecond)
		purge.Warn("purge failed, the file stays on the CDN: edge timeout")
		purge.Done(progress.Sample{})
	}
	return nil
}
Output:
{"node":1,"status":"started","open":{"step":{"kind":"album.backup","type":"workflow","name":"summer"}},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:00Z"}
{"node":2,"status":"started","open":{"parent":1,"step":{"kind":"album.export","type":"workflow"}},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:00Z"}
{"node":2,"status":"warned","msg":"2 raw files skipped","sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:00Z"}
{"node":3,"status":"started","open":{"parent":2,"step":{"kind":"photo.resize","type":"workflow"},"measures":["items"]},"sample":{"elapsed_ns":0,"items":{"done":0,"total":1}},"at":"2026-10-29T12:00:00Z"}
{"node":4,"status":"started","open":{"parent":3,"step":{"kind":"photo","type":"activity","id":"beach.jpg"},"measures":["bytes"]},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:00Z"}
{"node":4,"status":"in_progress","sample":{"elapsed_ns":150000000,"bytes":{"done":1000000,"total":2100000}},"at":"2026-10-29T12:00:00.15Z"}
{"node":4,"status":"in_progress","sample":{"elapsed_ns":450000000,"bytes":{"done":2100000,"total":2100000}},"at":"2026-10-29T12:00:00.45Z"}
{"node":4,"status":"succeeded","sample":{"elapsed_ns":600000000,"bytes":{"done":2100000,"total":2100000,"stored":420000}},"at":"2026-10-29T12:00:00.6Z"}
{"node":3,"status":"in_progress","sample":{"elapsed_ns":600000000,"items":{"done":1,"total":1}},"at":"2026-10-29T12:00:00.6Z"}
{"node":3,"status":"succeeded","sample":{"elapsed_ns":600000000,"items":{"done":1,"total":1}},"at":"2026-10-29T12:00:00.6Z"}
{"node":5,"status":"started","open":{"parent":2,"step":{"kind":"manifest.write","type":"activity"}},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:00.6Z"}
{"node":5,"status":"succeeded","sample":{"elapsed_ns":50000000},"at":"2026-10-29T12:00:00.65Z"}
{"node":2,"status":"succeeded","sample":{"elapsed_ns":650000000},"at":"2026-10-29T12:00:00.65Z"}
{"node":6,"status":"started","open":{"parent":1,"step":{"kind":"cdn.upload","type":"workflow"},"measures":["items"]},"sample":{"elapsed_ns":0,"items":{"done":0,"total":4}},"at":"2026-10-29T12:00:00.65Z"}
{"node":7,"status":"started","open":{"parent":6,"step":{"kind":"file","type":"activity","id":"beach.jpg"},"measures":["bytes"]},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:00.65Z"}
{"node":7,"status":"in_progress","sample":{"elapsed_ns":0,"bytes":{"done":1050000}},"at":"2026-10-29T12:00:00.65Z"}
{"node":7,"status":"in_progress","sample":{"elapsed_ns":250000000,"bytes":{"done":1575000,"total":2100000}},"at":"2026-10-29T12:00:00.9Z"}
{"node":7,"status":"succeeded","sample":{"elapsed_ns":350000000,"bytes":{"done":2100000,"total":2100000}},"at":"2026-10-29T12:00:01Z"}
{"node":6,"status":"in_progress","sample":{"elapsed_ns":350000000,"items":{"done":1,"total":4}},"at":"2026-10-29T12:00:01Z"}
{"node":8,"status":"started","open":{"parent":6,"step":{"kind":"file","type":"activity","id":"raw.dng"},"measures":["bytes"]},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:01Z"}
{"node":8,"status":"in_progress","sample":{"elapsed_ns":0,"bytes":{"done":450000}},"at":"2026-10-29T12:00:01Z"}
{"node":8,"status":"failed","msg":"unable to upload","error":"403 forbidden","sample":{"elapsed_ns":250000000,"bytes":{"done":450000}},"at":"2026-10-29T12:00:01.25Z"}
{"node":6,"status":"in_progress","sample":{"elapsed_ns":600000000,"items":{"done":1,"failed":1,"total":4}},"at":"2026-10-29T12:00:01.25Z"}
{"node":9,"status":"started","open":{"parent":6,"step":{"kind":"file","type":"activity","id":"cover.jpg"},"measures":["bytes"]},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:01.25Z"}
{"node":9,"status":"cancelled","sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:01.25Z"}
{"node":6,"status":"in_progress","sample":{"elapsed_ns":600000000,"items":{"done":1,"failed":1,"cancelled":1,"total":4}},"at":"2026-10-29T12:00:01.25Z"}
{"node":10,"status":"started","open":{"parent":6,"step":{"kind":"file","type":"activity","id":"map.png"},"measures":["bytes"]},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:01.25Z"}
{"node":10,"status":"cancelled","sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:01.25Z"}
{"node":6,"status":"in_progress","sample":{"elapsed_ns":600000000,"items":{"done":1,"failed":1,"cancelled":2,"total":4}},"at":"2026-10-29T12:00:01.25Z"}
{"node":6,"status":"failed","sample":{"elapsed_ns":600000000,"items":{"done":1,"failed":1,"cancelled":2,"total":4}},"at":"2026-10-29T12:00:01.25Z"}
{"node":11,"status":"started","open":{"parent":1,"step":{"kind":"album.rollback","type":"workflow"}},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:01.25Z"}
{"node":12,"status":"started","open":{"parent":11,"step":{"kind":"cdn.purge","type":"workflow"},"measures":["items"]},"sample":{"elapsed_ns":0,"items":{"done":0,"total":1}},"at":"2026-10-29T12:00:01.25Z"}
{"node":13,"status":"started","open":{"parent":12,"step":{"kind":"file","type":"activity","id":"beach.jpg"}},"sample":{"elapsed_ns":0},"at":"2026-10-29T12:00:01.25Z"}
{"node":13,"status":"warned","msg":"purge failed, the file stays on the CDN: edge timeout","sample":{"elapsed_ns":50000000},"at":"2026-10-29T12:00:01.3Z"}
{"node":13,"status":"succeeded","sample":{"elapsed_ns":50000000},"at":"2026-10-29T12:00:01.3Z"}
{"node":12,"status":"in_progress","sample":{"elapsed_ns":50000000,"items":{"done":1,"total":1}},"at":"2026-10-29T12:00:01.3Z"}
{"node":12,"status":"succeeded","sample":{"elapsed_ns":50000000,"items":{"done":1,"total":1}},"at":"2026-10-29T12:00:01.3Z"}
{"node":11,"status":"succeeded","sample":{"elapsed_ns":50000000},"at":"2026-10-29T12:00:01.3Z"}
{"node":1,"status":"failed","sample":{"elapsed_ns":1300000000},"at":"2026-10-29T12:00:01.3Z"}
err: 403 forbidden

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewReader

func NewReader(ctx context.Context, r io.Reader, total int64) io.Reader

NewReader counts the bytes read from r on the step of ctx, out of total, 0 if unknown. It returns r itself when that step does not report bytes.

func NewWriter

func NewWriter(ctx context.Context, w io.Writer, total int64) io.Writer

NewWriter counts the bytes written to w on the step of ctx, out of total, 0 if unknown. It returns w itself when that step does not report bytes.

func WithStep

func WithStep(ctx context.Context, reporter *StepReporter) context.Context

WithStep returns ctx carrying reporter: the work that follows an activity, on a context derived from the activity's, goes on under reporter again.

func WithTracker

func WithTracker(ctx context.Context, t *Tracker) context.Context

WithTracker returns ctx carrying t: a Begin on it with no step opens t's root.

Types

type Bytes

type Bytes struct {
	Done   int64 `json:"done"`
	Total  int64 `json:"total,omitempty"`
	Stored int64 `json:"stored,omitempty"`
	Reused int64 `json:"reused,omitempty"`
}

Bytes counts bytes, accumulated; a Total of 0 is unknown.

type Event

type Event struct {
	// StepID is the step's id, "node" on the wire.
	StepID StepID `json:"node"`
	Status Status `json:"status"`
	// Open is set on started only.
	Open *Open  `json:"open,omitempty"`
	Msg  string `json:"msg,omitempty"`
	// Error is set on failed only, on the step the error arose on.
	Error    string    `json:"error,omitempty"`
	Resource *Resource `json:"resource,omitempty"`
	// Settled marks an in_progress event of a resource that has reached its outcome, while the
	// step goes on; one without it is the resource still under way.
	Settled bool `json:"settled,omitempty"`
	// InResult marks a warning the operation's result repeats: a renderer beside the result may
	// leave it out.
	InResult bool      `json:"in_result,omitempty"`
	Sample   Sample    `json:"sample"`
	At       time.Time `json:"at"`
}

Event is one event of a progress stream, a full snapshot of its step.

type Items

type Items struct {
	Done      int64 `json:"done"`
	Failed    int64 `json:"failed,omitempty"`
	Cancelled int64 `json:"cancelled,omitempty"`
	Total     int64 `json:"total,omitempty"`
}

Items counts items, accumulated: Done only the succeeded; a Total of 0 is unknown.

type Kind

type Kind string

Kind names a step: "<namespace>.<action>" for an action, a bare noun for an object. The consumer declares its kinds.

type Measure

type Measure string

Measure names what a step reports, and so which widget renders it. A step declaring none is a spinner: a status and a message.

const (
	// MeasureBytes is a byte bar, Sample.Bytes: a copy or a transfer of one object
	// (2.1MB/4.0MB). Without a Total it is a running count.
	MeasureBytes Measure = "bytes"
	// MeasureItems is a counter, Sample.Items: a batch's finished children (3/5 failed=1).
	MeasureItems Measure = "items"
	// MeasureResources is a line per resource, Event.Resource: the set one call
	// handles, as compose's per-container rows (worker-1 Paused).
	MeasureResources Measure = "resources"
)

type Open

type Open struct {
	// Parent is 0 for the root.
	Parent   StepID    `json:"parent,omitempty"`
	Step     Step      `json:"step"`
	Measures []Measure `json:"measures,omitempty"`
}

Open describes a step once, on its started event: where it is and how to render it.

type Renderer

type Renderer interface {
	Render(evt Event)
}

Renderer renders a progress stream. A Tracker calls it under its own lock, one event at a time.

type Resource

type Resource struct {
	Kind ResourceKind `json:"kind"`
	ID   string       `json:"id"`
	Name string       `json:"name,omitempty"`
}

Resource is one resource a summary activity handles.

type ResourceKind

type ResourceKind string

ResourceKind names what a resource of a summary activity is. The consumer declares it.

type Sample

type Sample struct {
	Elapsed time.Duration `json:"elapsed_ns"`
	Bytes   *Bytes        `json:"bytes,omitempty"`
	Items   *Items        `json:"items,omitempty"`
}

Sample is a step's accumulated state at an event.

type Sampler

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

Sampler accumulates a step's sample for a source deep in the call and sends it at most once per the tracker's interval. The last value is not flushed: the step's Done carries the total.

func NewSampler

func NewSampler(topic *StepReporter, template Sample) *Sampler

NewSampler returns a Sampler for topic, its sample shaped by template and starting from its values. It is mute when topic is, or when topic does not declare a measure template sets.

func (*Sampler) Update

func (s *Sampler) Update(fn func(sample *Sample))

Update changes the accumulated sample through fn — adding to it or replacing it — and sends it when the interval has passed. Fields template does not set are dropped.

type Status

type Status string

Status is the state an event reports a step in.

const (
	StatusStarted    Status = "started"
	StatusInProgress Status = "in_progress"
	StatusWarned     Status = "warned"
	StatusSucceeded  Status = "succeeded"
	StatusFailed     Status = "failed"
	StatusCancelled  Status = "cancelled"
)

func (Status) IsTerminal

func (s Status) IsTerminal() bool

IsTerminal reports whether no event follows this one on its step.

type Step

type Step struct {
	Kind Kind     `json:"kind"`
	Type StepType `json:"type"`
	// ID is the object's resource key under a batch; empty elsewhere.
	ID   string `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
}

Step says what a step does.

type StepID

type StepID uint64

StepID numbers a step within one operation, from 1.

type StepReporter

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

StepReporter is the handle through which one step reports its progress. Its methods are safe for concurrent use.

func Batch

func Batch(ctx context.Context, step Step, total int) (context.Context, *StepReporter)

Batch opens a loop over total objects under the step of ctx, at once; it counts its children's outcomes itself. A total of 0 is unknown.

func Begin

func Begin(ctx context.Context, step Step) (context.Context, *StepReporter)

Begin opens a workflow under the step of ctx, or the root of the tracker ctx carries when it carries no step. It reports nothing until its first child or Warn.

func Current

func Current(ctx context.Context) *StepReporter

Current returns the step of ctx, a mute one when ctx carries none.

func Run

func Run(ctx context.Context, step Step, measures ...Measure) (context.Context, *StepReporter)

Run opens an activity under the step of ctx, at once, reporting the measures it declares.

func (*StepReporter) Done

func (r *StepReporter) Done(sample Sample)

Done ends the step succeeded, merging sample as Progress does. A lazy workflow never opened reports nothing, though a batch above it counts it.

func (*StepReporter) End

func (r *StepReporter) End(err error)

End ends the step: Done with no sample for a nil err, Fail otherwise. Deferred, it takes a closure over a named error — defer func() { step.End(err) }() — or it reports success.

func (*StepReporter) Fail

func (r *StepReporter) Fail(msg string, err error)

Fail ends the step failed, or cancelled when err is a context.Canceled or the cause the context it was opened on was cancelled with; a deadline is a failure. A workflow carries err only when none of its descendants failed: the error is reported where it arose.

func (*StepReporter) IsMute

func (r *StepReporter) IsMute() bool

IsMute reports whether the step reports nothing: a context without a tracker carries one.

func (*StepReporter) Progress

func (r *StepReporter) Progress(sample Sample)

Progress reports the step's accumulated sample; the fields it leaves nil keep their values. Like Update, it does not open a lazy workflow.

func (*StepReporter) SettleResource

func (r *StepReporter) SettleResource(resource Resource, msg string)

SettleResource reports msg about one resource of a summary activity that has reached its outcome; the step goes on.

func (*StepReporter) Update

func (r *StepReporter) Update(msg string)

Update reports msg as the step's current message; a lazy workflow keeps it unopened.

func (*StepReporter) UpdateResource

func (r *StepReporter) UpdateResource(resource Resource, msg string)

UpdateResource reports msg about one resource of a summary activity, still under way.

func (*StepReporter) Warn

func (r *StepReporter) Warn(msg string)

Warn reports a warning; it opens a lazy workflow.

func (*StepReporter) WarnInResult

func (r *StepReporter) WarnInResult(msg string)

WarnInResult is Warn for a warning the operation's result repeats, marked InResult.

func (*StepReporter) WarnResource

func (r *StepReporter) WarnResource(resource Resource, msg string)

WarnResource reports a warning about one resource of a summary activity.

type StepType

type StepType string

StepType says whether a step is made of other steps or is one action.

const (
	// StepTypeWorkflow is a step made of other steps, a batch included.
	StepTypeWorkflow StepType = "workflow"
	// StepTypeActivity is one action; it has no children.
	StepTypeActivity StepType = "activity"
)

type Tracker

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

Tracker numbers the steps of one operation and hands their events to a Renderer.

func Discard

func Discard() *Tracker

Discard returns a Tracker whose every step is mute.

func New

func New(renderer Renderer, now func() time.Time) *Tracker

New returns a Tracker rendering to renderer, timing on now.

func (*Tracker) Begin

func (t *Tracker) Begin(ctx context.Context, step Step) (context.Context, *StepReporter)

Begin opens the root workflow, lazily, whatever step ctx carries.

Directories

Path Synopsis
Command examples runs a photo album's workflows through a progress renderer:
Command examples runs a photo album's workflows through a progress renderer:
Package renderer holds progress.Renderers that render a stream as JSON lines or log records.
Package renderer holds progress.Renderers that render a stream as JSON lines or log records.
internal/format
Package format renders what the renderers print alike.
Package format renders what the renderers print alike.
tty
Package tty renders a progress stream as a live tree on a terminal, through Bubble Tea.
Package tty renders a progress stream as a live tree on a terminal, through Bubble Tea.

Jump to

Keyboard shortcuts

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