session

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package session is the Durable core's Session layer: the Session line, the transaction that stages one atomic commit (conversations, entries, tasks, submissions and documents), the document cache, and the task scheduler.

It ports pi-durable's session/session.ts, session/transaction.ts, session/forks.ts and harness/scheduler.ts as a synchronous state machine: a commit callback runs to completion, a read the loaded state cannot answer returns a *NeedRead error and the callback restarts after the host answers, and no goroutine, clock, I/O or package-level mutable state exists.

Records are ordered JSON objects (package jv) so a rewritten record keeps the field order and unknown fields Pi's object spreads keep.

Index

Constants

View Source
const (
	StatusPending    = "pending"
	StatusRunning    = "running"
	StatusWaiting    = "waiting"
	StatusSleeping   = "sleeping"
	StatusCompleting = "completing"
	StatusTerminal   = "terminal"
)

TaskStatus values of a task's state.

View Source
const DefaultDocumentRetentionMs = 600_000

DefaultDocumentRetentionMs is Pi's default document retention: ten minutes, as for kept contexts.

Variables

View Source
var (
	// ErrReadAfterWrite is Pi's ReadAfterWrite.
	// Read-only: assigned once at initialization.
	ErrReadAfterWrite = errors.New("ReadAfterWrite")
	// ErrSealed reports use of a transaction after it settled.
	// Read-only: assigned once at initialization.
	ErrSealed = errors.New("Transaction has settled")
	// ErrSessionFailed is Pi's SessionFailed: the Session failed after a storage error, so nothing runs or commits any more.
	// Read-only: assigned once at initialization.
	ErrSessionFailed = errors.New("Session failed after a storage error; close and reopen it")
	// ErrTypeError marks an error Pi throws as a TypeError.
	// Read-only: assigned once at initialization.
	ErrTypeError = errors.New("TypeError")
	// ErrStorageRequest is Pi's StorageRequestError: a Storage read the caller's request got wrong (an unknown conversation, an invalid cursor or scan
	// order, a document that keeps no history). It fails only that read, not the Session.
	// Read-only: assigned once at initialization.
	ErrStorageRequest = errors.New("StorageRequestError")
	// ErrClosed reports a closed Session.
	// Read-only: assigned once at initialization.
	ErrClosed = errors.New("Session is closed")
)

Error values of the Session layer, named as Pi names them.

View Source
var (
	// ErrHarnessClosed is Pi's closedError.
	// Read-only: assigned once at initialization.
	ErrHarnessClosed = errors.New("Harness is closed")
	// ErrAborted reports a cancelled wait.
	// Read-only: assigned once at initialization.
	ErrAborted = errors.New("The operation was aborted")
)

Task errors reported by the scheduler.

View Source
var Current = Point{Current: true}

Current is the point of the newest incarnation. Read-only.

View Source
var ErrParked = errors.New("loop parked on a read")

ErrParked is returned by Run when a job waits for host reads. Read-only: assigned once at initialization.

Functions

func DocAddress

func DocAddress(def *DocDef, args DocArgs) string

DocAddress returns the address a definition and arguments name; hosts key their per-transaction state by it.

func IsNeedGate

func IsNeedGate(err error) bool

IsNeedGate reports whether err is, or wraps, a *NeedGate.

func NewStorageRequestError

func NewStorageRequestError(msg string) error

NewStorageRequestError is Pi's `new StorageRequestError(message)`.

func NewTypeError

func NewTypeError(message string) error

NewTypeError is a TypeError Pi throws with message; it matches ErrTypeError with errors.Is.

Types

type Address

type Address struct {
	Kind   string
	Scope  Scope
	Key    string
	Family bool
}

Address names a document: its kind, scope and, for a family member, its key.

func DocumentAddress

func DocumentAddress(def *DocDef, args DocArgs) Address

DocumentAddress returns the document address a definition and arguments name.

type Cancel

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

Cancel is a cancellation signal: the AbortSignal of an invocation or of a caller's context.

func (*Cancel) Abort

func (c *Cancel) Abort()

Abort marks the signal aborted with the default reason (AbortController.abort()) and runs the registered hooks once.

func (*Cancel) AbortWith

func (c *Cancel) AbortWith(reason error)

AbortWith marks the signal aborted with reason (AbortController.abort(reason)); a signal keeps its first reason.

func (*Cancel) Aborted

func (c *Cancel) Aborted() bool

Aborted reports whether Abort ran.

func (*Cancel) Err

func (c *Cancel) Err() error

Err is the reason of an aborted signal (AbortSignal.throwIfAborted), or nil.

func (*Cancel) OnAbort

func (c *Cancel) OnAbort(fn func()) (remove func())

OnAbort registers fn to run on abort and returns a function that removes it.

type Change

type Change struct {
	Kind   ChangeKind
	Table  WriteKind // ChangeTable: the write's kind (its record is Record)
	Record *jv.Object
	// ConversationID is the conversation a document change belongs to (0: none).
	ConversationID ID
	Version        int
	Value          *jv.Object // nil: the document was retired
	Ops            []delta.Op
	Source         DocCopySource
}

Change is one published change of a commit: a table write, a document change or a document copy.

type ChangeKind

type ChangeKind uint8

ChangeKind is the kind of a published change.

const (
	ChangeTable ChangeKind = iota + 1
	ChangeDocument
	ChangeDocumentCopy
)

The published change kinds.

type ConversationQuery

type ConversationQuery struct {
	OwnerConversationID ID
	OwnerTaskID         ID
	Descending          bool
}

ConversationQuery filters a conversation scan.

type DocArgs

type DocArgs struct {
	Owner ID     // conversation or task ID for those scopes
	Key   string // family member
	Seed  any    // family seed
}

DocArgs addresses a document of a definition.

type DocCopySource

type DocCopySource struct {
	ID ID
	At Point
}

DocCopySource is the document a fork copies and the point it is read at.

type DocDef

type DocDef struct {
	Kind    string
	Version int
	Scope   ScopeKind
	// History and Fork apply to conversation documents only.
	History History
	Fork    ForkPolicy
	// Family marks a keyed family; Initial then receives the member's seed.
	Family bool
	// Initial returns the value of a new document. seed is nil for a singleton.
	Initial func(seed any) *jv.Object
	// Migrate converts a value stored at an older version.
	Migrate func(value *jv.Object, from int) *jv.Object
	// HostInitial and HostMigrate replace Initial and Migrate when the definition's code runs in a host: an error (a
	// *NeedRead asks the host for the value) fails the call that needed it.
	HostInitial func(seed any) (*jv.Object, error)
	HostMigrate func(value *jv.Object, from int) (*jv.Object, error)
	// CheckpointWhen returns true to store an ordinary change as a base.
	CheckpointWhen func(value *jv.Object, ops []delta.Op, deltasSinceBase int) bool
}

DocDef defines a document kind: its scope and semantics, the stored shape version and the functions that create, migrate and checkpoint its value. A definition is immutable after construction and shared by every Session.

type EntryQuery

type EntryQuery struct {
	ConversationID ID
	MinEntryID     ID   // 0: unbounded
	MaxEntryID     ID   // 0: unbounded
	Ascending      bool // the default order is descending
}

EntryQuery bounds an entry scan of one conversation, through its ancestry.

type Env

type Env struct {
	// Snapshot returns the current registry snapshot.
	Snapshot func() Snapshot
	// FreshSnapshot, when set, is the registry.snapshot() call of a step's decide (scheduler.ts:955), which runs user
	// code inside the step job: it returns a *NeedRead with no reads while the host is asked, and the Loop reruns the
	// job once the host answered. Unset, decide uses Snapshot.
	FreshSnapshot func() (Snapshot, error)
	// ContextRetentionMs is settings.contextRetentionMs: how long a conversation's kept context range outlives its idleness.
	ContextRetentionMs func() float64
	// ReleaseContext, when set, is told each conversation whose kept context range the scheduler drops for idleness
	// (scheduler.ts #settleIdle): what the core derived for it may go, as Pi's range does. It runs at an idle check, never
	// while a caller still reads a view of that conversation.
	ReleaseContext func(conversationID ID)
	// Report forwards a non-fatal failure to HarnessOptions.onReport; info says what happened (types.ts ReportInfo as
	// an object: type, and task, extension, reason, callback or conversationId where they apply).
	Report func(err error, info *jv.Object)
	// RestartLimit is settings.restartLimit, read at each use; nil selects the default.
	RestartLimit func() float64
	// BlockedChanged is told when blocked reasons may have changed without a commit: a registry change, a failed
	// migration, or a task newly parked or no longer parked (scheduler.ts #notifyBlocked).
	BlockedChanged func()
	// Now is the Harness clock.
	Now func() float64
	// Timer arms a background timer that calls fire at the Harness time at (a timer effect, ABI section 6) and returns its
	// cancel function: it only frees memory, and a host may keep none.
	Timer func(at float64, fire func()) (cancel func())
	// WakeTimer arms the timer that resumes the earliest sleeping task (a durable timer effect, ABI section 6): a host
	// that wakes its process itself keeps the object alarm at its time. Used while OnWake is nil.
	WakeTimer func(at float64, fire func()) (cancel func())
	// OnWake, when set (SetOnWake), replaces WakeTimer: the scheduler offers it each recomputed Wake (HarnessOptions.onWake)
	// and arms no timer for sleeping tasks. The host drops a value it already delivered.
	OnWake func(w Wake)
	// SettleOutcome runs in the transaction that settles a task with a
	// scheduler-written outcome (faulted or orphaned): harness.live.ts settleSchedulerOutcome.
	SettleOutcome func(tx *Tx, record *jv.Object, outcome *jv.Object) error
	// WithdrawInputs runs in the transaction that withdraws a conversation's
	// queued inputs (inbox.ts withdrawQueuedInputs).
	WithdrawInputs func(tx *Tx, conversationID ID) error
	// ReadTicks is the ticks the running line job's Storage reads have taken so far, and After runs then once a chain of n
	// hops ran: a reconcile a chain load schedules after its read starts when Pi's microtask does, not at the job's start.
	ReadTicks func() int
	// GateRead asks the host's Storage to run the Pi Storage read of method (task, conversation) that a chain load makes, so a Storage that
	// counts, holds or fails it sees it (scheduler.ts #loadChain); nil asks nothing.
	GateRead func(method string, id ID)
	After    func(n int, then func())
}

Env connects the scheduler to its host.

type FailedError

type FailedError struct{ Cause error }

FailedError is what a call on a failed Session returns: Pi's SessionFailed, with the Storage error that failed the Session as its cause. Its message is fixed; the cause does not cross the host wire.

func (*FailedError) Error

func (e *FailedError) Error() string

func (*FailedError) Is

func (e *FailedError) Is(target error) bool

Is matches ErrSessionFailed.

func (*FailedError) Unwrap

func (e *FailedError) Unwrap() error

Unwrap returns the cause.

type ForkPolicy

type ForkPolicy string

ForkPolicy is how a conversation document behaves when its conversation is forked.

const (
	ForkAsOf    ForkPolicy = "asOf"
	ForkCurrent ForkPolicy = "current"
	ForkInitial ForkPolicy = "initial"
)

The fork policies.

type History

type History string

History is how a conversation document keeps its past.

const (
	HistoryLatest     History = "latest"
	HistoryRewindable History = "rewindable"
)

The conversation document histories.

type ID

type ID = int64

ID is the number of a conversation, entry, task, submission or document.

const RootConversationID ID = 1

RootConversationID is the reserved ID of the root conversation.

type IndexSizes

type IndexSizes struct{ Live, Settled, Edges, Below, Roots, Unloaded, DropQueue int }

IndexSizes are the sizes of the scheduler's ownership indexes, for tests that bound its memory (scheduler.ts indexSizes); the host replicates them into its synchronous getter.

type Loop

type Loop struct {
	// Blocked reports that something outside the Loop holds the Session line (a host transaction, ABI section 8): queued line
	// jobs wait until it reports false and Kick runs them.
	Blocked func() bool
	// Admit, when set, is the admission check of a line job as it is enqueued (session.ts #assertUsable): a job it
	// rejects never runs, and its done receives the error as a microtask.
	Admit func() error
	// Session, when set, is the Session whose commits the line jobs make: a job's publication runs at the job's
	// completion, with its done, rather than inside the job.
	Session *Session
	// Hold, when set, is asked as each line job finishes whether its completion (publication, done, and the release of
	// the line) waits for Pi's duration of the job (dcore-trace A1; ABI section 5.3): it returns true after it parked
	// release, and calls release once that time passed. Line jobs queued meanwhile wait behind it.
	Hold func(release func()) bool
	// Tail, when set, is asked as a job finishes whether the line stays held for one more tick: it returns true after it parked
	// release. session.ts #enqueue :530-537 starts a job through `this.#tail.then(job)` where the tail is `run.then(...)` of the
	// previous job, so the next job starts a tick after the finished one, a read job or a commit job: a job queued behind it, and
	// one its publication or continuation queues as it finishes, as Pi queues those before the run resolves. A bare job (a host
	// transaction's turn) holds the line only for a job queued behind it.
	Tail func(release func()) bool
	// Begin, when set, is asked before a job queued on an idle line through LineAfterTail or ReadLine starts whether the line
	// waits one tick for it: it returns true after it parked start. session.ts #enqueue :530-531 starts a job through
	// `this.#tail.then(job)`, a tick after the call when the tail is already resolved.
	Begin func(start func()) bool
	// Answered is set while a Tail is asked after a ClientReadLine job answered its caller a hop before its end (Settle): the tail
	// then holds the line for the hop it gave up, so the next job starts where Pi's does.
	Answered bool
	// StartDelay is the ticks an idle-line job waited for its start (Begin) that its Hold adds to the job's duration: Hold takes it
	// with TakeStartDelay.
	StartDelay int

	// Origin is the host async context of the code that is running (ABI section 5.4): Defer and the line capture it, and the
	// Loop makes it current again when it runs the item or job. 0 is none. Retain and Release, when set, are told of every
	// origin the line holds a job for, from the job's queuing to the end of its run.
	Origin          uint32
	Retain, Release func(origin uint32)
	// Started, when set, runs as each line job starts.
	Started func()
	// Reading is set while a Session.readOnLine job (ReadLine) runs and when it finishes: Hold asks it for the job's duration.
	Reading bool
	// contains filtered or unexported fields
}

Loop is the core's stand-in for the JavaScript event loop and the Session line. Continuations that Pi runs as promise reactions or queueMicrotask callbacks run here as queue items in FIFO order; a commit job runs to completion in one item, so jobs serialize as they do on Pi's mutation line.

A job whose store read needs the host (*NeedRead) parks the Loop with that request: Run returns it, and after the host answered, Run resumes with the same job from the start. Nothing else runs while a job is parked, as nothing else runs while Pi's line awaits storage.

func (*Loop) Busy

func (l *Loop) Busy() bool

Busy reports whether a line job is queued, running, held or waiting for the host.

func (*Loop) ClientReadLine

func (l *Loop) ClientReadLine(run func() error, done func(error))

ClientReadLine is ReadLine for a job a host call queues and whose done answers that caller (an api_result). The caller awaits the `run` promise of #enqueue, which settles a hop before the line tail resolves, so Hold calls Settle a hop before the job's end and the tail holds the line one hop longer (session.ts :105-115, :530-537).

func (*Loop) Defer

func (l *Loop) Defer(fn func())

Defer queues fn as a microtask. When the array is full and at least half of it is spent front, the queued items move to the front instead of the array growing: the array stays proportional to what is queued, and each move is paid for by the items that ran since the last one.

func (*Loop) EndingClient

func (l *Loop) EndingClient() bool

EndingClient reports whether the job whose completion Hold holds answers a host caller (ClientReadLine).

func (*Loop) Idle

func (l *Loop) Idle() bool

Idle reports whether the Loop has nothing queued and is not parked.

func (*Loop) Kick

func (l *Loop) Kick()

Kick starts the next line job after the holder of the line released it.

func (*Loop) Line

func (l *Loop) Line(run func() error, done func(error))

Line queues a job on the Session line. run is the job body; it restarts from scratch after a NeedRead. done receives the job's final error (nil on success) as a microtask.

func (*Loop) LineAfterTail

func (l *Loop) LineAfterTail(run func() error, done func(error))

LineAfterTail is Line for a commit job queued through `#enqueue` (session.ts :530-531): on an idle line it starts a tick later (Begin), as `this.#tail.then(job)` does on an already resolved tail.

func (*Loop) LineBare

func (l *Loop) LineBare(run func() error)

LineBare queues a job that only takes the line for someone else, a host transaction that holds it until Blocked reports false: it keeps its place in the line's order and takes no job duration of its own.

func (*Loop) NextTick

func (l *Loop) NextTick(fn func())

func (*Loop) OnComplete

func (l *Loop) OnComplete(fn func())

NextTick runs fn one tick later: the resumption of an `await` of an async function that returned in the tick the line job it awaited resolved (scheduler.ts #run awaits #step, which awaits commitWith). Without a Begin hold it runs fn at once.

A NextTick asked in the step whose Tail chain just started rides that chain: both resume after the same one hop, the tail's reaction (the line's next job) before this one, so a single hops chain carries both. OnComplete runs fn when the running line job completes after a successful commit: right after its publication, ahead of the line's next job, as the code that resumes after the awaited commit does. A job that runs again (a *NeedRead or *NeedGate) drops what it asked for.

func (*Loop) Parked

func (l *Loop) Parked() *NeedRead

Parked returns the read request the Loop waits on, or nil.

func (*Loop) Publish

func (l *Loop) Publish()

Publish delivers the finished job's publications now. Pi publishes a commit when `#runCommit` resumes from Storage.commit (session.ts :446-449), two ticks before the job's run resolves; Hold calls it at that point, and the job's completion publishes whatever is still held.

func (*Loop) QueuedOrigins

func (l *Loop) QueuedOrigins(f func(origin uint32))

QueuedOrigins calls f with the origin of every microtask still queued: a Loop parked on a host answer keeps them across steps.

func (*Loop) QuietEnd

func (l *Loop) QuietEnd() bool

QuietEnd reports whether the completion of the job whose end Hold holds has nothing to do but the tail tick Tail asks for: no done to run, no publication, no continuation of its own and no load to reveal. Such a job and its tail need no step of their own between them: the line stays held from the job's last tick to the tail's and QuietRelease frees it there.

func (*Loop) QuietRelease

func (l *Loop) QuietRelease() func()

QuietRelease is the release of a QuietEnd job: its end and the end of its tail, which both did nothing, in one.

func (*Loop) ReadLine

func (l *Loop) ReadLine(run func() error, done func(error))

ReadLine queues a Session.readOnLine job (session.ts:105-115): a read-only job on the line, whose duration is its reads plus the three ticks of the return through #enqueue (hopcost.ReadOnLine).

func (*Loop) Resume

func (l *Loop) Resume() error

Resume re-runs the parked job and continues; the host must have answered its reads.

func (*Loop) Run

func (l *Loop) Run() error

Run processes queued items until none remain or a job parks. It returns ErrParked when parked; call Resume after the host served the reads.

func (*Loop) Settle

func (l *Loop) Settle() bool

Settle answers the finished job's host caller now when the job came through ClientReadLine: Hold calls it a hop before the job's end. It reports whether it answered.

func (*Loop) TakeStartDelay

func (l *Loop) TakeStartDelay() int

TakeStartDelay returns the start ticks the running job has not yet spent and clears them.

func (*Loop) Ungate

func (l *Loop) Ungate()

Ungate runs the job that returned a *NeedGate again, from the start, after the host's Storage answered.

type NeedGate

type NeedGate struct{}

NeedGate is the error a Store returns from Commit when the host's Storage must see the writes first: the host calls the user's Storage.commit with them, and the commit applies only when that resolves (a rejection fails it as Pi's storage.commit rejection does). A line job that returns it keeps the line while it waits and runs again from the start once the host answers; a host transaction keeps its writes and commits them when the answer arrives.

func (*NeedGate) Error

func (e *NeedGate) Error() string

type NeedRead

type NeedRead struct {
	Reads []ReadRequest
}

NeedRead is the error a Store returns when the loaded state cannot answer a read. The callback that hit it is discarded and runs again after the host answers; Reads names what the host must fetch.

func IsNeedRead

func IsNeedRead(err error) (*NeedRead, bool)

IsNeedRead reports whether err is, or wraps, a *NeedRead.

func (*NeedRead) Error

func (e *NeedRead) Error() string

type Ownership

type Ownership struct {
	// Task is the owning task; zero means ownerless.
	Task ID
}

Ownership is how a created conversation is attributed.

type Page

type Page struct {
	Items []*jv.Object
	After ID
}

Page is one page of a scan. After is the cursor for the next page, 0 when none.

type Point

type Point struct {
	Current bool
	Seq     Seq
}

Point addresses a document at "current" or as of a commit sequence.

func AsOf

func AsOf(seq Seq) Point

AsOf is the point of commit seq.

type Publication

type Publication struct {
	Seq     Seq
	Changes []Change
}

Publication is what one applied commit changed.

type ReadRequest

type ReadRequest struct {
	Kind string
	Args []any
}

ReadRequest identifies one read of committed state the host must serve.

type ReportFrom

type ReportFrom struct{ Extension, Callback string }

ReportFrom is whose code a task's Report is about when not the task's own: an extension's (Extension, when known), or a host callback (Callback, a HostCallback name such as env or models).

type Runtime

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

Runtime is the facade a task phase handler uses, bound to one invocation (TaskRuntime of types.ts). Every operation fails once the invocation ended. Operations that Pi returns as promises take a continuation that runs as a microtask after the operation settles.

func (*Runtime) AbandonHost

func (r *Runtime) AbandonHost(tx *Tx, err error)

AbandonHost ends the host transaction of BeginHost without a commit.

func (*Runtime) AbortOwned

func (r *Runtime) AbortOwned(id ID, then func(error))

AbortOwned aborts a task this task owns and calls then once it is terminal (scheduler.ts abortOwned).

func (*Runtime) BeginHost

func (r *Runtime) BeginHost() (tx *Tx, current *jv.Object, err error)

BeginHost opens a commit whose callback runs in the host, one operation per event (ABI section 8): the checks of Commit run now, at the moment the host's transaction takes the Session line, and the returned transaction is scoped to the task. The caller must hold the line until FinishHost or AbandonHost.

func (*Runtime) Commit

func (r *Runtime) Commit(change func(tx *Tx, current *jv.Object) (next *jv.Object, err error), then func(error))

Commit commits on the Session line after rereading the task. change may stage writes through tx and return the state the task commits for itself (nil leaves it unchanged). It fails when the task is terminal, the invocation ended, the Harness is closing or, in a run invocation, the task carries an abort mark.

func (*Runtime) ConversationID

func (r *Runtime) ConversationID() ID

ConversationID is the task's conversation.

func (*Runtime) Ended

func (r *Runtime) Ended() bool

Ended reports whether the invocation ended.

func (*Runtime) EndedError

func (r *Runtime) EndedError() error

EndedError is the error of an operation of an ended invocation.

func (*Runtime) Extension

func (r *Runtime) Extension() string

Extension is the extension that installed the definition this invocation runs, as of its reservation; empty for a built-in task.

func (*Runtime) FinishHost

func (r *Runtime) FinishHost(tx *Tx, current, next *jv.Object) (*Publication, error)

FinishHost commits the host transaction of BeginHost: next, when not nil, is the state the task commits for itself.

func (*Runtime) FinishHostSettled

func (r *Runtime) FinishHostSettled(tx *Tx) (*Publication, error)

FinishHostSettled commits again the host transaction of BeginHost whose commit returned a *NeedGate (Session.FinishSettled).

func (*Runtime) GetTask

func (r *Runtime) GetTask(id ID, then func(*jv.Object, error))

GetTask returns a committed task record, or nil.

func (*Runtime) Memo

func (r *Runtime) Memo(name string, candidate any, then func(winner any, err error))

Memo stores candidate unless a memo of that name exists and returns the durable winner.

func (*Runtime) MemoGet

func (r *Runtime) MemoGet(name string) (any, bool, error)

MemoGet reads a memo of this task.

func (*Runtime) Now

func (r *Runtime) Now() (float64, error)

Now is the Harness clock.

func (*Runtime) OnEnded

func (r *Runtime) OnEnded(fn func())

OnEnded runs fn when the invocation ends (scheduler.ts #end), or at once when it already has.

func (*Runtime) Outcomes

func (r *Runtime) Outcomes(ids []ID, then func([]*jv.Object, error))

Outcomes returns the outcomes of terminal tasks, in order.

func (*Runtime) OwnedTasks

func (r *Runtime) OwnedTasks(then func([]*jv.Object, error))

OwnedTasks calls then with copies of the live tasks this task owns directly, in ID order, whichever invocation created them (scheduler.ts ownedTasks): every live task is listed under its parent node, its owner task when it has one. Tasks in conversations it owns are not included. It fails when the invocation has ended.

func (*Runtime) Read

func (r *Runtime) Read(job func() error, then func(error))

Read runs job as a read-only job on the Session line (scheduler.ts #read with Session.readOnLine): it waits behind the commits already queued, so a read observes the state those commits left, and then calls then with its error. It fails when the invocation has ended, before and after the wait.

func (*Runtime) Report

func (r *Runtime) Report(err error, from ...ReportFrom) error

Report forwards a non-fatal failure to the host with this task in its info: a task_error about the task's own code, or, with from, an extension_error about extension code it called, such as a section, or a host_error about a host callback, such as the environment builder (scheduler.ts runtime.report).

func (*Runtime) Signal

func (r *Runtime) Signal() *Cancel

Signal is aborted when the run is signalled by AbortTask, the Harness closes or the invocation ends.

func (*Runtime) SleepUntil

func (r *Runtime) SleepUntil(until float64, checkpoint any, then func(error))

SleepUntil commits a sleep: the task holds no invocation until the Harness clock reaches until, then resumes at checkpoint. then runs once the sleep is stored, not when the time comes (scheduler.ts sleepUntil, a #gated #commitState).

func (*Runtime) Snapshot

func (r *Runtime) Snapshot() Snapshot

Snapshot is the registry snapshot of the current phase.

func (*Runtime) TaskID

func (r *Runtime) TaskID() ID

TaskID is the running task.

func (*Runtime) WaitForTask

func (r *Runtime) WaitForTask(id ID, then func(rec *jv.Object, err error, waited bool))

WaitForTask resolves with the task's terminal record; it fails when the invocation ends first.

type Scheduler

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

Scheduler is pi-durable's TaskScheduler (harness/scheduler.ts) as a synchronous state machine over a Session and a Loop: it keeps the live tasks, reserves them for invocation, runs their phases through continuation-passing handlers, and settles ownership, abort and join rules.

func NewScheduler

func NewScheduler(sess *Session, loop *Loop, env Env) *Scheduler

NewScheduler returns a scheduler over the Session, on the Loop.

func (*Scheduler) Abort

func (s *Scheduler) Abort(id ID, keepRestart bool, cancel *Cancel, then func(result string, err error))

Abort marks a task for abort. then receives "marked" or "terminal"; for a task whose invocation runs, it is called after that invocation ended.

func (*Scheduler) AbortConversation

func (s *Scheduler) AbortConversation(conversationID ID, background bool, cancel *Cancel, then func(error))

AbortConversation marks every task below a conversation for abort and waits for idle; with background, background tasks too, waiting for each.

func (*Scheduler) BlockedReason

func (s *Scheduler) BlockedReason(rec *jv.Object) string

BlockedReason is why a live task cannot run here, if it cannot: its definition (missing_task, task_too_old, migration_failed) or the restart limit (restart_limit); empty when it can. A running task, an abort-marked one, and one holding its outcome are never blocked (scheduler.ts blockedReason).

func (*Scheduler) Bound

func (s *Scheduler) Bound(taskID ID) *Cancel

Bound is the signal of an operation made through an invocation-bound handle (harness.ts boundConversation, withAbortSignal(binding.signal, ...)): the operation's line job checks it at start (session.ts:411 throwIfAborted). A task without a running invocation yields a signal already aborted as ended.

func (*Scheduler) CloseWrites

func (s *Scheduler) CloseWrites() []*jv.Object

CloseWrites is the records of the tasks the close stopped, as pending, to write back straight to Storage with nothing published, as a close is not a crash: the next open counts no restart for them (scheduler.ts join through session.ts writeAtClose). A live task that is running when the close ends is one this Harness reserved, since open writes every other running task back as pending: its invocation was stopped by the close, or its reservation settled while the close began. It reads the records as they stand now, so the write keeps what commits admitted before the seal wrote, such as an abort mark.

func (*Scheduler) IndexSizes

func (s *Scheduler) IndexSizes() IndexSizes

IndexSizes returns the sizes of the scheduler's ownership indexes.

func (*Scheduler) Inspect

func (s *Scheduler) Inspect(snapshot Snapshot) (scheduling string, tasks []TaskInspection, err error)

Inspect is scheduler.ts inspect: the scheduling state and every live task with its derived state. It runs no task code: a pending migration shows as ready with Migrates, and only a migration the scheduler already tried, or one that cannot exist, shows as failed.

func (*Scheduler) Join

func (s *Scheduler) Join(then func())

Join calls then once every running invocation has ended.

func (*Scheduler) KeepContext

func (s *Scheduler) KeepContext(conversationID, head, tail ID, invocationEnded bool)

KeepContext keeps the range a runtime read returned unless the invocation ended, the Harness is closing, or a concurrent read already kept a newer range. A read of another, idle conversation starts or continues its retention period.

func (*Scheduler) KeptContext

func (s *Scheduler) KeptContext(conversationID ID) (head, tail ID, ok bool)

KeptContext returns the head marker and tail of the range kept for the conversation.

func (*Scheduler) Open

func (s *Scheduler) Open(done func(error))

Open loads the live tasks in one commit, resets running tasks to pending and arms reconciliation. The scheduler observes the Session's commits from here on.

func (*Scheduler) RegistryChanged

func (s *Scheduler) RegistryChanged()

RegistryChanged is the registry subscription: a new snapshot may make blocked tasks runnable.

func (*Scheduler) Resume

func (s *Scheduler) Resume()

Resume enables scheduling, makes sleeping tasks that are due runnable (a host wakeup, such as an alarm, calls this), and starts any reservable task.

func (*Scheduler) Retry

func (s *Scheduler) Retry(id ID, cancel *Cancel, then func(error))

Retry runs a task parked by the restart limit again: it clears its restart count and enables scheduling. It does nothing for a task that is not parked, and fails for an unknown one (scheduler.ts retry).

func (*Scheduler) Seal

func (s *Scheduler) Seal()

Seal stops scheduling: waiters reject, and the invocation signals abort in a microtask (signalInvocations).

func (*Scheduler) SetOnWake

func (s *Scheduler) SetOnWake(fn func(w Wake))

SetOnWake makes the scheduler tell fn each change of Wake instead of arming a timer for sleeping tasks.

func (*Scheduler) WaitForIdle

func (s *Scheduler) WaitForIdle(conversationID ID, cancel *Cancel, then func(error))

WaitForIdle calls then when the conversation (0: every root) has no live non-background task or queued input below it.

func (*Scheduler) WaitForTask

func (s *Scheduler) WaitForTask(id ID, cancel *Cancel, then func(rec *jv.Object, err error))

WaitForTask calls then with the task's terminal record. A task that is not live is read from the store on the line.

func (*Scheduler) WaitForTaskFound

func (s *Scheduler) WaitForTaskFound(id ID, cancel *Cancel, then func(rec *jv.Object, err error, waited bool))

WaitForTaskFound is WaitForTask for a host caller: a read job on the line (readOnLine, scheduler.ts :306-316) whose caller resumes at the job's run and returns `found.promise`. then reports whether the record came from a waiter the job registered (a live task, resolved by the terminal publication) or from the store (an already settled promise).

func (*Scheduler) Wake

func (s *Scheduler) Wake() Wake

Wake is scheduler.ts wake: synchronous, from memory; a task whose chain is not loaded yet counts as it would alone.

Wake runs after every commit, so its cost must not grow with the live tasks while one runs: the earliest sleep comes from the sleeping index, as wakeDue reads it, and the walk over the live tasks that looks for one that can run now (anyRunnable) is skipped when a running invocation or a reconcile pass with work already answers that. Walking every live task each time made ending a chain of 20,000 held tasks 20,000 walks of 20,000 records, each record a key search here, not the property read it is in scheduler.ts.

func (*Scheduler) WriteBack

func (s *Scheduler) WriteBack(records []*jv.Object) error

WriteBack writes the records CloseWrites returned; a *NeedGate error means the host's Storage holds the commit, and the job that called it runs again after the answer.

type Scope

type Scope struct {
	Kind  ScopeKind
	Owner ID // conversation or task ID; zero for the session
}

Scope is the owner of a document: the Session, a conversation or a task.

type ScopeKind

type ScopeKind string

ScopeKind is the owner kind of a document.

const (
	ScopeSession      ScopeKind = "session"
	ScopeConversation ScopeKind = "conversation"
	ScopeTask         ScopeKind = "task"
)

The document scopes.

type Seq

type Seq = int64

Seq is the sequence of one storage commit.

type Session

type Session struct {

	// SweepJobs counts the sweep jobs queued on the line so far (documentCacheSizes.sweeps). EnqueueSweep queues a job on the
	// Session line, Microtask runs fn as a microtask, ArmTimer arms a host timer that calls fire at the time at; a Session without
	// them keeps no sweep job or timer.
	SweepJobs    int
	EnqueueSweep func(job func())
	Microtask    func(fn func())
	ArmTimer     func(at float64, fire func()) (cancel func())
	// DocumentRetention is the document retention in milliseconds read at each use (HarnessSettings.documentRetentionMs); nil or
	// a nil result means the default.
	DocumentRetention func() *float64

	// OnFail reports the storage error that failed the Session, once (session.ts fail).
	OnFail func(error)

	// HostAdmits: the host admits calls itself, so the seal does not reject a call it admitted before the seal (assertUsable).
	HostAdmits bool

	// ConversationCreated runs inside every transaction that creates or forks a
	// conversation, after the conversation record is staged. A plain Session
	// stages nothing; a Harness stages its built-in documents.
	ConversationCreated func(tx *Tx, record *jv.Object) error
	// contains filtered or unexported fields
}

Session is the Session kernel: the mutation line's committed-state cache and the commit procedure of session/session.ts. It is single-threaded; its owner serializes calls.

func New

func New(store Store, nextID ID, now func() float64) *Session

New returns a Session over a store. nextID is the next unminted record ID and now the Harness clock.

func (*Session) Abandon

func (s *Session) Abandon(tx *Tx, err error)

Abandon seals a transaction whose callback failed with err; it stages nothing. A *NeedRead failure restores the ID counter, since the callback runs again from scratch.

func (*Session) Admit

func (s *Session) Admit() error

Admit is the admission check of an operation as it is enqueued on the Session line (session.ts #assertUsable in commitWith and readOnLine): it fails once the Session is closed or poisoned.

func (*Session) Begin

func (s *Session) Begin(scope TxScope) (*Tx, error)

Begin opens a transaction whose callback runs outside this call: a host drives it one operation at a time (ABI section 8) and ends it with Finish or Abandon. Commit is Begin, the callback, and Finish.

func (*Session) Close

func (s *Session) Close()

Close seals the Session and drops its commit listeners and loaded documents, as the close job does after the Harness joined its invocations.

func (*Session) Commit

func (s *Session) Commit(change func(tx *Tx) error, scope TxScope) (*Publication, error)

Commit runs change on the Session line as one commit and returns the commit's publication. A callback that errors stages nothing: the error is returned and IDs it minted stay consumed, as a rolled-back Pi callback leaves a gap. When any read returns a *NeedRead the callback restarts from scratch after the host answers: Commit restores the ID counter and returns the NeedRead. An empty write set commits nothing and returns a nil publication.

func (*Session) DocumentCacheSizes

func (s *Session) DocumentCacheSizes() (cached, idle int)

DocumentCacheSizes is the number of cached documents and how many of them are idle (session.ts documentCacheSizes); the rest are pinned by observers, and the core has none.

func (*Session) DocumentsAttached

func (s *Session) DocumentsAttached() int

DocumentsAttached is the number of incarnations an observer pins (session.ts documentCacheSizes.attached).

func (*Session) Failure

func (s *Session) Failure() error

Failure returns the first storage error that failed the Session, or nil.

func (*Session) Finish

func (s *Session) Finish(tx *Tx) (*Publication, error)

Finish settles a transaction whose callback succeeded and commits its writes, as the tail of Commit.

func (*Session) FinishSettled

func (s *Session) FinishSettled(tx *Tx) (*Publication, error)

FinishSettled commits again a transaction whose commit returned a *NeedGate: its writes are settled and the host's Storage answered the gate.

func (*Session) HasUnrevealedLoads

func (s *Session) HasUnrevealedLoads() bool

revealLoads makes the documents the finished job loaded visible to Loaded. HasUnrevealedLoads reports whether a line job's loads wait for its publication to show (revealLoads has something to do).

func (*Session) HeldPublications

func (s *Session) HeldPublications() []*Publication

HeldPublications ends HoldPublications and returns the publications it kept, in commit order.

func (*Session) HoldPublications

func (s *Session) HoldPublications()

HoldPublications makes the next commits keep their publications until HeldPublications takes them: a host transaction's commit publishes when its job's duration has passed, as a Loop line job's does.

func (*Session) InJob

func (s *Session) InJob() bool

InJob reports whether a Loop line job body is running.

func (*Session) Loaded

func (s *Session) Loaded(def *DocDef, args DocArgs) bool

Loaded reports whether Snapshot would answer from the loaded-document cache (session.ts snapshot: a cached tracker of the definition's version), which Pi reads without a job on the Session line.

func (*Session) NextID

func (s *Session) NextID() ID

NextID returns the next unminted record ID.

func (*Session) OnFailed

func (s *Session) OnFailed(f func(error)) (remove func())

OnFailed registers f to run once with the error that fails the Session, before the seal (a race against session.ts `failed`), and returns its removal. It never runs for a Session that has already failed: the caller reads Failure.

func (*Session) PeekTicks

func (s *Session) PeekTicks() int

PeekTicks is the Change of the transaction callback that just succeeded, without clearing it: -1 when none ran.

func (*Session) PinDocument

func (s *Session) PinDocument(def *DocDef, args DocArgs) (release func())

PinDocument keeps the cached incarnation of a document in the cache for one observer (session.ts #pinDocument): it leaves the idle order, and the returned release unpins it once; the incarnation is idle again after the last release, when it is still the cached one. It returns nil when the document is not cached.

func (*Session) Publish

func (s *Session) Publish(pub *Publication)

Publish runs the commit listeners on a held publication.

func (*Session) RunCommit

func (s *Session) RunCommit(change func(tx *Tx) error, scope TxScope) (*Publication, error)

RunCommit is the body of a commit job already admitted to the Session line (session.ts #runCommit): it checks only that the Session is healthy, so a job enqueued before Seal still commits.

func (*Session) Seal

func (s *Session) Seal()

Seal is the synchronous start of Session.close (session.ts close): admission closes, so later operations fail with ErrClosed when they are enqueued (Admit), and the close listeners run once. Jobs admitted before keep running.

func (*Session) SetHopProfile

func (s *Session) SetHopProfile(p hopcost.Profile)

SetHopProfile names the Storage profile whose await ticks transactions are charged (open.storageProfile).

func (*Session) SettleCached

func (s *Session) SettleCached() int

SettleCached is the replaced tasks the settle of the transaction being committed found already read by its callback: their committed read costs one tick, not a Storage read; 0 outside a commit.

func (*Session) SettleReads

func (s *Session) SettleReads() int

SettleReads is the Storage reads the settle of the transaction being committed made for its staged submission changes; it is 0 outside a commit.

func (*Session) Snapshot

func (s *Session) Snapshot(def *DocDef, args DocArgs) (*jv.Object, error)

Snapshot returns the current value of a document, or nil when absent.

func (*Session) SnapshotAsOf

func (s *Session) SnapshotAsOf(def *DocDef, args DocArgs, at ID) (any, error)

SnapshotAsOf is Session.snapshotAsOf: the value of a conversation document as of the commit of entry at, which must be visible from the conversation, or nil when the document did not exist then.

func (*Session) SubscribeClose

func (s *Session) SubscribeClose(fn func())

SubscribeClose registers a listener that runs when Close begins.

func (*Session) SubscribeCommits

func (s *Session) SubscribeCommits(fn func(*Publication))

SubscribeCommits registers a synchronous post-adoption listener. It must not throw, block or call Session operations.

func (*Session) TakeTicks

func (s *Session) TakeTicks() int

TakeTicks returns and clears the Change of the last transaction callback that succeeded on the line: the ticks of Pi's change callback for its Transaction method awaits and Scheduler wrapper (hopcost), -1 when none ran.

func (*Session) UnloadDocuments

func (s *Session) UnloadDocuments()

UnloadDocuments drops every cached document; later access loads from the store.

func (*Session) WriteTasks

func (s *Session) WriteTasks(records []*jv.Object) error

WriteTasks writes complete task records straight to the Storage, with nothing published and the records not stamped (session.ts writeAtClose). It writes nothing once the Session failed; a failing Storage fails the Session.

type Snapshot

type Snapshot interface {
	Task(name string) *TaskImpl
}

Snapshot is a registry snapshot: the task definitions of one phase.

type Store

type Store interface {
	Conversation(id ID) (*jv.Object, error)
	ScanConversations(q ConversationQuery, limit int, after ID) (Page, error)
	// Entry returns the entry with its commit sequence.
	Entry(id ID) (*jv.Object, Seq, error)
	// EntryIn returns the entry when it is visible from the conversation.
	EntryIn(conversationID, id ID) (*jv.Object, Seq, error)
	// LatestHeadMarker returns the newest head-marker entry visible from the
	// conversation at or before atOrBefore (0: no bound), through fork ancestry.
	LatestHeadMarker(conversationID, atOrBefore ID) (*jv.Object, error)
	ScanEntries(q EntryQuery, limit int, after ID) (Page, error)
	Task(id ID) (*jv.Object, error)
	ScanTasks(q TaskQuery, limit int, after ID) (Page, error)
	Submission(id ID) (*jv.Object, error)
	ScanSubmissions(q SubmissionQuery, limit int, after ID) (Page, error)
	SubmissionByRequest(conversationID ID, requestID string) (*jv.Object, error)
	FindDocument(a Address, at Point) (*jv.Object, error)
	Document(id ID, at Point) (*StoredDoc, error)
	// ScanDocuments returns the documents of a scope alive at the point, optionally of one kind, ascending by ID.
	ScanDocuments(scope Scope, at Point, kind string, limit int, after ID) (Page, error)
	// Commit applies the writes as one atomic commit and returns its sequence;
	// nextID is the Session's next unminted ID, which the store keeps as
	// max(its stored next ID, nextID, the largest written ID + 1). Any error fails the Session.
	Commit(writes []Write, nextID ID) (Seq, error)
}

Store is the committed state a Session reads and the place it commits to.

Every read returns a nil record for an absent one. A read the loaded state cannot answer returns a *NeedRead. Commit never returns NeedRead.

type StoredDoc

type StoredDoc struct {
	Record          *jv.Object
	Version         int
	Value           *jv.Object
	DeltasSinceBase int
}

StoredDoc is a document's materialized content at a point.

type SubmissionQuery

type SubmissionQuery struct {
	ConversationID ID
	Status         string
	Descending     bool
}

SubmissionQuery filters a submission scan.

type TaskDef

type TaskDef struct {
	Name    string
	Version int
	// Initial returns the first checkpoint for a new task's input.
	Initial func(input any) any
}

TaskDef is the part of a task definition the Session layer needs to create a task: its kind, its version and its first checkpoint. Phases, abort and migration belong to the scheduler.

type TaskImpl

type TaskImpl struct {
	Def TaskDef
	// Extension is the name of the extension that installed the definition; empty for a built-in task.
	Extension string
	// Migrate converts a record stored by an older version; nil when the
	// definition has none. It runs at reservation.
	Migrate func(input, checkpoint any, fromVersion int) (newInput, newCheckpoint any, err error)
	// MigrateAsync is Migrate for a definition whose migrate() is host code: it starts the migration and calls done once,
	// later, with its result. The scheduler asks again after done (it kicks), so a reservation that needed a migration
	// is retried with the answer in hand and never blocks the Session line on the host.
	MigrateAsync func(input, checkpoint any, fromVersion int, done func(newInput, newCheckpoint any, err error))
	// Phase runs the handler for the checkpoint's phase of a running task and
	// calls done once, with the handler's error or nil. The handler drives the
	// runtime and ends by committing durable progress.
	Phase func(rt *Runtime, task *jv.Object, done func(error))
	// Abort runs in a fresh invocation after an abort mark and must commit a
	// terminal outcome.
	Abort func(rt *Runtime, task *jv.Object, done func(error))
	// AbortReturnHops is the hops between the end of Abort's final commit job and `#runAbort`'s step enqueue when the
	// handler is an async function of Pi that awaits that commit: the commit's `#gated` await, the handler's own await and
	// its async return, then runAbort's await (scheduler.ts :1399-1411). A handler that runs in the host spends these hops
	// itself and leaves it zero.
	AbortReturnHops int
}

TaskImpl is an executable task definition registered in the registry.

type TaskInspection

type TaskInspection struct {
	Record *jv.Object
	// Kind is "running", "ready", "waiting", "sleeping", "completing" or "blocked".
	Kind     string
	Until    float64 // sleeping
	Migrates bool    // ready
	On       []ID    // waiting
	Reason   string  // blocked: missing_task, task_too_old, migration_failed or restart_limit
	Err      error   // blocked with migration_failed: why, when known
}

TaskInspection is one live task with the state the scheduler derives for it (types.ts TaskInspection).

type TaskOptions

type TaskOptions struct {
	// OwnerTask is the owning task of a child task; zero for a conversation-owned task.
	OwnerTask ID
	// ConversationID defaults to the owner task's conversation or the transaction's bound conversation.
	ConversationID ID
	Background     bool
	// AbandonOnRestart marks a task its creator awaits only in memory: a later Harness abort-marks it with reason restart.
	AbandonOnRestart bool
}

TaskOptions are the creation options of a task (types.ts TaskOptions).

type TaskQuery

type TaskQuery struct {
	ConversationID ID
	Kind           string
	Status         string
	AbortRequested *bool
	Background     *bool
	Descending     bool
}

TaskQuery filters a task scan. Zero values leave a field unconstrained.

type Tx

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

Tx stages one atomic commit. Every method must run inside the callback that received it; after the callback ends the transaction is sealed.

func (*Tx) AppendEntry

func (tx *Tx) AppendEntry(conversationID ID, draft *jv.Object) (*jv.Object, error)

AppendEntry stages a new entry. The draft's head may be the string "self".

func (*Tx) Await

func (tx *Tx) Await(n int)

Await charges the ticks of a callback's own `await` of Pi code that is not a Transaction method (hopcost: an async function without awaits of its own settles at once and its caller resumes one tick later).

func (*Tx) Conversation

func (tx *Tx) Conversation(id ID) (*jv.Object, error)

Conversation returns a committed conversation record, or nil.

func (*Tx) ConversationCreated

func (tx *Tx) ConversationCreated(id ID) bool

ConversationCreated reports whether this transaction created the conversation (transaction.ts #createdConversationIds).

func (*Tx) CreateConversation

func (tx *Tx) CreateConversation(own Ownership) (*jv.Object, error)

CreateConversation stages a new conversation.

func (*Tx) CreateRootConversation

func (tx *Tx) CreateRootConversation() (*jv.Object, error)

CreateRootConversation stages the root conversation under its reserved ID.

func (*Tx) CreateSubmission

func (tx *Tx) CreateSubmission(create *jv.Object) (*jv.Object, error)

CreateSubmission stages a submission; its record is {...create, id}.

func (*Tx) CreateTask

func (tx *Tx) CreateTask(def *TaskDef, input any, opts TaskOptions) (ID, error)

CreateTask stages a pending task and returns its ID.

func (*Tx) Doc

func (tx *Tx) Doc(def *DocDef, args DocArgs) (*delta.Obj, error)

Doc returns the draft of a document, creating the document when absent. A second call for the same address in one transaction returns the same draft.

func (*Tx) DocEntry

func (tx *Tx) DocEntry(def *DocDef, args DocArgs) int

DocEntry is the position of the document's latest entry in the transaction's documents: a host names the incarnation a draft belongs to by it, since a retired incarnation's draft outlives the new incarnation at its address.

func (*Tx) DocRecordID

func (tx *Tx) DocRecordID(def *DocDef, args DocArgs) ID

DocRecordID is the ID of the stored record a document's latest entry loaded, or 0 for a document this transaction creates: a host matches the Storage writes of a commit to the revisions its drafts prepared by it.

func (*Tx) Entry

func (tx *Tx) Entry(id ID) (*jv.Object, error)

Entry returns a committed entry, or nil.

func (*Tx) ForkConversation

func (tx *Tx) ForkConversation(parent, at ID, own Ownership) (*jv.Object, error)

ForkConversation stages a conversation that inherits the parent's history through the entry at.

func (*Tx) HostDoc

func (tx *Tx) HostDoc(def *DocDef, args DocArgs) (value any, deltasSinceBase int, loaded bool, err error)

HostDoc is Doc for a host that keeps its own draft (ABI section 8, `doc`): it acquires the document and returns the value the draft starts from and, for a stored document (loaded), the number of deltas after its base (Pi's CheckpointInfo). The host's operations come back through SetDocOps.

func (*Tx) LatestHeadMarker

func (tx *Tx) LatestHeadMarker(conversationID ID) (*jv.Object, error)

LatestHeadMarker returns the newest head-marker entry of a conversation, or nil.

func (*Tx) PlaceSubmission

func (tx *Tx) PlaceSubmission(id, entry ID) error

PlaceSubmission stages the placement of a queued submission at an entry.

func (*Tx) RetireDoc

func (tx *Tx) RetireDoc(def *DocDef, args DocArgs) error

RetireDoc retires a document at commit; an absent document is a no-op.

func (*Tx) ScanConversations

func (tx *Tx) ScanConversations(q ConversationQuery, limit int, after ID) (Page, error)

ScanConversations scans committed conversations.

func (*Tx) ScanEntries

func (tx *Tx) ScanEntries(q EntryQuery, limit int, after ID) (Page, error)

ScanEntries scans committed entries visible from a conversation.

func (*Tx) ScanTasks

func (tx *Tx) ScanTasks(q TaskQuery, limit int, after ID) (Page, error)

ScanTasks scans committed tasks.

func (*Tx) SetDocOps

func (tx *Tx) SetDocOps(def *DocDef, args DocArgs, entry int, ops []delta.Op) error

SetDocOps records the operations a host's tracker produced for the open draft of a document (ABI section 8, `doc.write`); settlement prepares the draft from them. A non-negative entry names the incarnation by DocEntry; a negative one the latest at the address.

func (*Tx) SetTask

func (tx *Tx) SetTask(value *jv.Object) error

SetTask stages a replacement of a task record, stamping start and end times. The staged record is a deep copy, as Pi's copyJson makes it, so the caller's value stays its own.

func (*Tx) SettleSubmission

func (tx *Tx) SettleSubmission(id ID, settlement *jv.Object) error

SettleSubmission stages a settlement: status "done" with answer, or "unanswered" with reason and optional detail.

func (*Tx) StagedConversations

func (tx *Tx) StagedConversations() []*jv.Object

StagedConversations returns the staged conversation records.

func (*Tx) StagedTasks

func (tx *Tx) StagedTasks() []*jv.Object

StagedTasks returns the staged task records in staging order.

func (*Tx) Submission

func (tx *Tx) Submission(id ID) (*jv.Object, error)

Submission returns a committed submission, or nil.

func (*Tx) SubmissionByRequest

func (tx *Tx) SubmissionByRequest(conversationID ID, requestID string) (*jv.Object, error)

SubmissionByRequest returns the submission with the request ID, or nil.

func (*Tx) Task

func (tx *Tx) Task(id ID) (*jv.Object, error)

Task returns the committed task record, or nil.

type TxScope

type TxScope struct {
	ConversationID ID
	TaskID         ID
}

TxScope binds a transaction to a conversation and a task: the default conversation of Tx.CreateTask and the task attributed to appended entries.

type Wake

type Wake struct {
	Active bool
	HasAt  bool
	At     float64
}

Wake is when the Session next needs a running process (scheduler.ts wake, Harness.wake): Active while some task can run now or is running, At for the earliest sleep not yet due.

type Write

type Write struct {
	Kind WriteKind
	// Record is the conversation, entry, task or submission record, or the
	// document record (DocumentCreate: no createdAt or retiredAt) of a create or copy.
	Record *jv.Object
	// ID is the document of a change or retire.
	ID      ID
	Version int
	// Base is true when the content is a complete value (create, or a change that stores a base).
	Base  bool
	Value *jv.Object // Base content
	Ops   []delta.Op // delta content
	// Source is the copied document of a WriteDocCopy.
	Source DocCopySource
}

Write is one storage write of a commit.

type WriteKind

type WriteKind uint8

WriteKind is the kind of a StorageWrite.

const (
	WriteConversation WriteKind = iota + 1
	WriteEntry
	WriteTask
	WriteSubmission
	WriteDocCreate
	WriteDocCopy
	WriteDocChange
	WriteDocRetire
)

The StorageWrite kinds, as pi-durable's StorageWrite union.

Directories

Path Synopsis
cmd
tgprobe command
Command tgprobe links the session layer's packages so the TinyGo build can prove they compile without reflection.
Command tgprobe links the session layer's packages so the TinyGo build can prove they compile without reflection.
Package hopcost derives, in microtask ticks, how long Pi's Storage adapters take, so the core can park a line job on a hops chain as long as Pi's job (ABI.md section 5.3).
Package hopcost derives, in microtask ticks, how long Pi's Storage adapters take, so the core can park a line job on a hops chain as long as Pi's job (ABI.md section 5.3).
Package sessiontest provides an in-memory session.Store that keeps all committed state, as pi-durable's MemoryStorage does.
Package sessiontest provides an in-memory session.Store that keeps all committed state, as pi-durable's MemoryStorage does.

Jump to

Keyboard shortcuts

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