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
- Variables
- func DocAddress(def *DocDef, args DocArgs) string
- func IsNeedGate(err error) bool
- func NewStorageRequestError(msg string) error
- func NewTypeError(message string) error
- type Address
- type Cancel
- type Change
- type ChangeKind
- type ConversationQuery
- type DocArgs
- type DocCopySource
- type DocDef
- type EntryQuery
- type Env
- type FailedError
- type ForkPolicy
- type History
- type ID
- type IndexSizes
- type Loop
- func (l *Loop) Busy() bool
- func (l *Loop) ClientReadLine(run func() error, done func(error))
- func (l *Loop) Defer(fn func())
- func (l *Loop) EndingClient() bool
- func (l *Loop) Idle() bool
- func (l *Loop) Kick()
- func (l *Loop) Line(run func() error, done func(error))
- func (l *Loop) LineAfterTail(run func() error, done func(error))
- func (l *Loop) LineBare(run func() error)
- func (l *Loop) NextTick(fn func())
- func (l *Loop) OnComplete(fn func())
- func (l *Loop) Parked() *NeedRead
- func (l *Loop) Publish()
- func (l *Loop) QueuedOrigins(f func(origin uint32))
- func (l *Loop) QuietEnd() bool
- func (l *Loop) QuietRelease() func()
- func (l *Loop) ReadLine(run func() error, done func(error))
- func (l *Loop) Resume() error
- func (l *Loop) Run() error
- func (l *Loop) Settle() bool
- func (l *Loop) TakeStartDelay() int
- func (l *Loop) Ungate()
- type NeedGate
- type NeedRead
- type Ownership
- type Page
- type Point
- type Publication
- type ReadRequest
- type ReportFrom
- type Runtime
- func (r *Runtime) AbandonHost(tx *Tx, err error)
- func (r *Runtime) AbortOwned(id ID, then func(error))
- func (r *Runtime) BeginHost() (tx *Tx, current *jv.Object, err error)
- func (r *Runtime) Commit(change func(tx *Tx, current *jv.Object) (next *jv.Object, err error), ...)
- func (r *Runtime) ConversationID() ID
- func (r *Runtime) Ended() bool
- func (r *Runtime) EndedError() error
- func (r *Runtime) Extension() string
- func (r *Runtime) FinishHost(tx *Tx, current, next *jv.Object) (*Publication, error)
- func (r *Runtime) FinishHostSettled(tx *Tx) (*Publication, error)
- func (r *Runtime) GetTask(id ID, then func(*jv.Object, error))
- func (r *Runtime) Memo(name string, candidate any, then func(winner any, err error))
- func (r *Runtime) MemoGet(name string) (any, bool, error)
- func (r *Runtime) Now() (float64, error)
- func (r *Runtime) OnEnded(fn func())
- func (r *Runtime) Outcomes(ids []ID, then func([]*jv.Object, error))
- func (r *Runtime) OwnedTasks(then func([]*jv.Object, error))
- func (r *Runtime) Read(job func() error, then func(error))
- func (r *Runtime) Report(err error, from ...ReportFrom) error
- func (r *Runtime) Signal() *Cancel
- func (r *Runtime) SleepUntil(until float64, checkpoint any, then func(error))
- func (r *Runtime) Snapshot() Snapshot
- func (r *Runtime) TaskID() ID
- func (r *Runtime) WaitForTask(id ID, then func(rec *jv.Object, err error, waited bool))
- type Scheduler
- func (s *Scheduler) Abort(id ID, keepRestart bool, cancel *Cancel, then func(result string, err error))
- func (s *Scheduler) AbortConversation(conversationID ID, background bool, cancel *Cancel, then func(error))
- func (s *Scheduler) BlockedReason(rec *jv.Object) string
- func (s *Scheduler) Bound(taskID ID) *Cancel
- func (s *Scheduler) CloseWrites() []*jv.Object
- func (s *Scheduler) IndexSizes() IndexSizes
- func (s *Scheduler) Inspect(snapshot Snapshot) (scheduling string, tasks []TaskInspection, err error)
- func (s *Scheduler) Join(then func())
- func (s *Scheduler) KeepContext(conversationID, head, tail ID, invocationEnded bool)
- func (s *Scheduler) KeptContext(conversationID ID) (head, tail ID, ok bool)
- func (s *Scheduler) Open(done func(error))
- func (s *Scheduler) RegistryChanged()
- func (s *Scheduler) Resume()
- func (s *Scheduler) Retry(id ID, cancel *Cancel, then func(error))
- func (s *Scheduler) Seal()
- func (s *Scheduler) SetOnWake(fn func(w Wake))
- func (s *Scheduler) WaitForIdle(conversationID ID, cancel *Cancel, then func(error))
- func (s *Scheduler) WaitForTask(id ID, cancel *Cancel, then func(rec *jv.Object, err error))
- func (s *Scheduler) WaitForTaskFound(id ID, cancel *Cancel, then func(rec *jv.Object, err error, waited bool))
- func (s *Scheduler) Wake() Wake
- func (s *Scheduler) WriteBack(records []*jv.Object) error
- type Scope
- type ScopeKind
- type Seq
- type Session
- func (s *Session) Abandon(tx *Tx, err error)
- func (s *Session) Admit() error
- func (s *Session) Begin(scope TxScope) (*Tx, error)
- func (s *Session) Close()
- func (s *Session) Commit(change func(tx *Tx) error, scope TxScope) (*Publication, error)
- func (s *Session) DocumentCacheSizes() (cached, idle int)
- func (s *Session) DocumentsAttached() int
- func (s *Session) Failure() error
- func (s *Session) Finish(tx *Tx) (*Publication, error)
- func (s *Session) FinishSettled(tx *Tx) (*Publication, error)
- func (s *Session) HasUnrevealedLoads() bool
- func (s *Session) HeldPublications() []*Publication
- func (s *Session) HoldPublications()
- func (s *Session) InJob() bool
- func (s *Session) Loaded(def *DocDef, args DocArgs) bool
- func (s *Session) NextID() ID
- func (s *Session) OnFailed(f func(error)) (remove func())
- func (s *Session) PeekTicks() int
- func (s *Session) PinDocument(def *DocDef, args DocArgs) (release func())
- func (s *Session) Publish(pub *Publication)
- func (s *Session) RunCommit(change func(tx *Tx) error, scope TxScope) (*Publication, error)
- func (s *Session) Seal()
- func (s *Session) SetHopProfile(p hopcost.Profile)
- func (s *Session) SettleCached() int
- func (s *Session) SettleReads() int
- func (s *Session) Snapshot(def *DocDef, args DocArgs) (*jv.Object, error)
- func (s *Session) SnapshotAsOf(def *DocDef, args DocArgs, at ID) (any, error)
- func (s *Session) SubscribeClose(fn func())
- func (s *Session) SubscribeCommits(fn func(*Publication))
- func (s *Session) TakeTicks() int
- func (s *Session) UnloadDocuments()
- func (s *Session) WriteTasks(records []*jv.Object) error
- type Snapshot
- type Store
- type StoredDoc
- type SubmissionQuery
- type TaskDef
- type TaskImpl
- type TaskInspection
- type TaskOptions
- type TaskQuery
- type Tx
- func (tx *Tx) AppendEntry(conversationID ID, draft *jv.Object) (*jv.Object, error)
- func (tx *Tx) Await(n int)
- func (tx *Tx) Conversation(id ID) (*jv.Object, error)
- func (tx *Tx) ConversationCreated(id ID) bool
- func (tx *Tx) CreateConversation(own Ownership) (*jv.Object, error)
- func (tx *Tx) CreateRootConversation() (*jv.Object, error)
- func (tx *Tx) CreateSubmission(create *jv.Object) (*jv.Object, error)
- func (tx *Tx) CreateTask(def *TaskDef, input any, opts TaskOptions) (ID, error)
- func (tx *Tx) Doc(def *DocDef, args DocArgs) (*delta.Obj, error)
- func (tx *Tx) DocEntry(def *DocDef, args DocArgs) int
- func (tx *Tx) DocRecordID(def *DocDef, args DocArgs) ID
- func (tx *Tx) Entry(id ID) (*jv.Object, error)
- func (tx *Tx) ForkConversation(parent, at ID, own Ownership) (*jv.Object, error)
- func (tx *Tx) HostDoc(def *DocDef, args DocArgs) (value any, deltasSinceBase int, loaded bool, err error)
- func (tx *Tx) LatestHeadMarker(conversationID ID) (*jv.Object, error)
- func (tx *Tx) PlaceSubmission(id, entry ID) error
- func (tx *Tx) RetireDoc(def *DocDef, args DocArgs) error
- func (tx *Tx) ScanConversations(q ConversationQuery, limit int, after ID) (Page, error)
- func (tx *Tx) ScanEntries(q EntryQuery, limit int, after ID) (Page, error)
- func (tx *Tx) ScanTasks(q TaskQuery, limit int, after ID) (Page, error)
- func (tx *Tx) SetDocOps(def *DocDef, args DocArgs, entry int, ops []delta.Op) error
- func (tx *Tx) SetTask(value *jv.Object) error
- func (tx *Tx) SettleSubmission(id ID, settlement *jv.Object) error
- func (tx *Tx) StagedConversations() []*jv.Object
- func (tx *Tx) StagedTasks() []*jv.Object
- func (tx *Tx) Submission(id ID) (*jv.Object, error)
- func (tx *Tx) SubmissionByRequest(conversationID ID, requestID string) (*jv.Object, error)
- func (tx *Tx) Task(id ID) (*jv.Object, error)
- type TxScope
- type Wake
- type Write
- type WriteKind
Constants ¶
const ( StatusPending = "pending" StatusRunning = "running" StatusWaiting = "waiting" StatusSleeping = "sleeping" StatusCompleting = "completing" StatusTerminal = "terminal" )
TaskStatus values of a task's state.
const DefaultDocumentRetentionMs = 600_000
DefaultDocumentRetentionMs is Pi's default document retention: ten minutes, as for kept contexts.
Variables ¶
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.
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.
var Current = Point{Current: true}
Current is the point of the newest incarnation. Read-only.
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 ¶
DocAddress returns the address a definition and arguments name; hosts key their per-transaction state by it.
func IsNeedGate ¶
IsNeedGate reports whether err is, or wraps, a *NeedGate.
func NewStorageRequestError ¶
NewStorageRequestError is Pi's `new StorageRequestError(message)`.
func NewTypeError ¶
NewTypeError is a TypeError Pi throws with message; it matches ErrTypeError with errors.Is.
Types ¶
type Address ¶
Address names a document: its kind, scope and, for a family member, its key.
func DocumentAddress ¶
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 ¶
AbortWith marks the signal aborted with reason (AbortController.abort(reason)); a signal keeps its first reason.
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 ¶
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 ¶
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
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 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 ¶
Busy reports whether a line job is queued, running, held or waiting for the host.
func (*Loop) ClientReadLine ¶
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 ¶
EndingClient reports whether the job whose completion Hold holds answers a host caller (ClientReadLine).
func (*Loop) Kick ¶
func (l *Loop) Kick()
Kick starts the next line job after the holder of the line released it.
func (*Loop) Line ¶
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 ¶
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 ¶
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) 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) 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 ¶
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 ¶
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 ¶
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 ¶
Resume re-runs the parked job and continues; the host must have answered its reads.
func (*Loop) Run ¶
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 ¶
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 ¶
TakeStartDelay returns the start ticks the running job has not yet spent and clears them.
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.
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 ¶
IsNeedRead reports whether err is, or wraps, a *NeedRead.
type Ownership ¶
type Ownership struct {
// Task is the owning task; zero means ownerless.
Task ID
}
Ownership is how a created conversation is attributed.
type Publication ¶
Publication is what one applied commit changed.
type ReadRequest ¶
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 ¶
AbandonHost ends the host transaction of BeginHost without a commit.
func (*Runtime) AbortOwned ¶
AbortOwned aborts a task this task owns and calls then once it is terminal (scheduler.ts abortOwned).
func (*Runtime) BeginHost ¶
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 ¶
ConversationID is the task's conversation.
func (*Runtime) EndedError ¶
EndedError is the error of an operation of an ended invocation.
func (*Runtime) Extension ¶
Extension is the extension that installed the definition this invocation runs, as of its reservation; empty for a built-in task.
func (*Runtime) FinishHost ¶
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) Memo ¶
Memo stores candidate unless a memo of that name exists and returns the durable winner.
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) OwnedTasks ¶
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 ¶
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 ¶
Signal is aborted when the run is signalled by AbortTask, the Harness closes or the invocation ends.
func (*Runtime) SleepUntil ¶
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).
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
KeptContext returns the head marker and tail of the range kept for the conversation.
func (*Scheduler) Open ¶
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 ¶
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 ¶
SetOnWake makes the scheduler tell fn each change of Wake instead of arming a timer for sleeping tasks.
func (*Scheduler) WaitForIdle ¶
WaitForIdle calls then when the conversation (0: every root) has no live non-background task or queued input below it.
func (*Scheduler) WaitForTask ¶
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 ¶
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.
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 ¶
New returns a Session over a store. nextID is the next unminted record ID and now the Harness clock.
func (*Session) Abandon ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
DocumentsAttached is the number of incarnations an observer pins (session.ts documentCacheSizes.attached).
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 ¶
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) Loaded ¶
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) OnFailed ¶
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 ¶
PeekTicks is the Change of the transaction callback that just succeeded, without clearing it: -1 when none ran.
func (*Session) PinDocument ¶
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 ¶
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 ¶
SetHopProfile names the Storage profile whose await ticks transactions are charged (open.storageProfile).
func (*Session) SettleCached ¶
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 ¶
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) SnapshotAsOf ¶
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 ¶
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 ¶
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 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 SubmissionQuery ¶
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 ¶
AppendEntry stages a new entry. The draft's head may be the string "self".
func (*Tx) Await ¶
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 ¶
Conversation returns a committed conversation record, or nil.
func (*Tx) ConversationCreated ¶
ConversationCreated reports whether this transaction created the conversation (transaction.ts #createdConversationIds).
func (*Tx) CreateConversation ¶
CreateConversation stages a new conversation.
func (*Tx) CreateRootConversation ¶
CreateRootConversation stages the root conversation under its reserved ID.
func (*Tx) CreateSubmission ¶
CreateSubmission stages a submission; its record is {...create, id}.
func (*Tx) CreateTask ¶
CreateTask stages a pending task and returns its ID.
func (*Tx) Doc ¶
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 ¶
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 ¶
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) ForkConversation ¶
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 ¶
LatestHeadMarker returns the newest head-marker entry of a conversation, or nil.
func (*Tx) PlaceSubmission ¶
PlaceSubmission stages the placement of a queued submission at an entry.
func (*Tx) ScanConversations ¶
ScanConversations scans committed conversations.
func (*Tx) ScanEntries ¶
ScanEntries scans committed entries visible from a conversation.
func (*Tx) SetDocOps ¶
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 ¶
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 ¶
SettleSubmission stages a settlement: status "done" with answer, or "unanswered" with reason and optional detail.
func (*Tx) StagedConversations ¶
StagedConversations returns the staged conversation records.
func (*Tx) StagedTasks ¶
StagedTasks returns the staged task records in staging order.
func (*Tx) Submission ¶
Submission returns a committed submission, or nil.
func (*Tx) SubmissionByRequest ¶
SubmissionByRequest returns the submission with the request ID, or nil.
type TxScope ¶
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 ¶
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.
Source Files
¶
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. |