session

package
v0.5.3 Latest Latest
Warning

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

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

Documentation

Overview

Package session ports the pi-durable Session kernel: one mutation line, the loaded document tracker cache, transactions, document forks, and committed publication and observation.

Ports packages/durable/src/session/session.ts

Go mapping decisions:

  • Upstream's Promise chain of line jobs is a FIFO ticket queue: each job waits for its predecessor's completion, so jobs run in admission order.
  • Deliveries upstream schedules with queueMicrotask run on a goroutine the Session tracks. A started watch with no callback in flight takes the committed frame into delivery before the publishing commit returns, and a Harness wait awaits the deliveries scheduled before it resumes its caller (AwaitDeliveriesEntered): upstream's drain microtask enters the listener before the code awaiting the commit's promise resumes. A state attachment drains on the committing goroutine after the Session line is free and before the commit returns.
  • An AbortSignal is the context's cancellation; withoutAbortSignal is context.WithoutCancel, which keeps context values.

Index

Constants

This section is empty.

Variables

View Source
var ErrSessionClosed = errors.New("Session is closed")

ErrSessionClosed is upstream's "Session is closed".

Functions

func Contained

func Contained(callback func(), onError func(error))

Contained is contained for the Harness: it runs a callback that must not fail its caller and hands a panic to onError. Ports session.ts contained.

func DocumentRetention

func DocumentRetention(ms *float64) float64

DocumentRetention returns ms when it is a number of milliseconds, 0 or more (+Inf keeps documents); otherwise the default. A nil ms and a NaN are not such a number.

Types

type AnyTaskRecord

AnyTaskRecord is a task record with JSON input, checkpoint, and result.

type CommittedWatch

type CommittedWatch[T any] struct {
	// contains filtered or unexported fields
}

CommittedWatch is a serialized exact-frame watch bound to one document incarnation or conversation view. Its source ends it explicitly: Retire for a retired document, SourceEnded for a closed or failed Session. Termination drops every reference the watch holds into its source, so a stopped watch that is still referenced keeps nothing but its last value alive.

func NewCommittedWatch

func NewCommittedWatch[T any](session *SessionImpl, value T, detach func(), replace func() T) *CommittedWatch[T]

NewCommittedWatch returns a watch holding value whose deliveries run on session's delivery scheduler. detach runs once when the watch ends; replace gives the value an overflow delivers, and nil delivers the newest value. Ports observation.ts:174 CommittedWatch constructor (view.ts:104, events.ts:132).

func NewCommittedWatchOn

func NewCommittedWatchOn[T any](scheduler *DeliveryScheduler, value T, detach func(), replace func() T, report func(error)) *CommittedWatch[T]

NewCommittedWatchOn is NewCommittedWatch for a host whose deliveries run on scheduler (the native Durable core driver). report receives a listener's failure, which also ends the watch, as the Session's report does for NewCommittedWatch.

func (*CommittedWatch[T]) Advance

func (watch *CommittedWatch[T]) Advance(ctx context.Context, value T, ops []durable.Op)

func (*CommittedWatch[T]) Cancel

func (watch *CommittedWatch[T]) Cancel()

func (*CommittedWatch[T]) Closed

func (watch *CommittedWatch[T]) Closed() <-chan struct{}

Closed is closed when the watch terminates.

func (*CommittedWatch[T]) End

func (watch *CommittedWatch[T]) End() durable.WatchEnd

End returns the terminal result once Closed is closed.

func (*CommittedWatch[T]) ObserveCancellation

func (watch *CommittedWatch[T]) ObserveCancellation(ctx context.Context)

ObserveCancellation ends the watch with reason cancelled when ctx is done.

func (*CommittedWatch[T]) Retire

func (watch *CommittedWatch[T]) Retire(ctx context.Context)

Retire is the document incarnation retiring: it queues the last frame, a root replacement with nil ([["r", null]]) and the zero value, after which the watch ends retired. An overflowing backlog is dropped, since the frame replaces the root anyway.

func (*CommittedWatch[T]) SourceEnded

func (watch *CommittedWatch[T]) SourceEnded(failure error)

SourceEnded is the source closing: the watch ends ended, or failed with the error when the Session failed.

func (*CommittedWatch[T]) Start

func (watch *CommittedWatch[T]) Start(listener func(ctx context.Context, value T, ops []durable.Op) error)

Start installs the sole asynchronous listener; it never invokes it inline. It panics when the watch is started or stopped, as upstream throws.

func (*CommittedWatch[T]) Stop

func (watch *CommittedWatch[T]) Stop() (durable.WatchEnd, error)

Stop idempotently stops future callbacks and returns the terminal result.

func (*CommittedWatch[T]) Value

func (watch *CommittedWatch[T]) Value() T

Value is the acquisition revision before Start and the latest delivered revision afterward.

type CreateSessionOptions

type CreateSessionOptions struct {
	// Now is the wall clock in milliseconds for task times; the default is the system clock.
	Now func() float64
	// DocumentRetentionMs is how long a loaded document that no watch observes stays in memory after
	// its last read or write; the next access loads it from Storage. Observed documents always stay. Nil selects the
	// default, ten minutes; 0 drops a document right after use; +Inf keeps documents. Anything else that is not a
	// number of milliseconds, 0 or more, means the default.
	DocumentRetentionMs *float64
	// SetTimer arms the timers that evict idle documents; nil selects Go timers (see durable.SetTimer).
	SetTimer durable.SetTimer
}

CreateSessionOptions is the optional argument of CreateSession.

type DeliveryScheduler

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

DeliveryScheduler runs watch deliveries for a host that has no SessionImpl: each scheduled delivery is queued as upstream's microtask is, and Wait returns once every scheduled delivery has drained.

func NewDeliveryScheduler

func NewDeliveryScheduler() *DeliveryScheduler

NewDeliveryScheduler returns an idle delivery scheduler.

func (*DeliveryScheduler) Wait

func (s *DeliveryScheduler) Wait()

Wait blocks until no scheduled delivery is queued or running.

type DocumentCacheSizes

type DocumentCacheSizes struct {
	// Cached is the number of cached documents.
	Cached int
	// Idle is the number of cached documents with no observer attached.
	Idle int
	// Attached is the number of incarnations pinned by an observer.
	Attached int
	// Sweeps is the number of eviction jobs queued on the line so far.
	Sweeps int
}

DocumentCacheSizes is what the document cache holds.

type Hooks

type Hooks struct {
	// ConversationCreated runs inside every transaction that creates or forks a conversation, after the
	// conversation record is staged. A plain Session stages nothing.
	ConversationCreated func(tx *Transaction, record durable.ConversationRecord) error
	// BeforeClose runs after close seals admission and before the line closes Storage.
	BeforeClose func()
	// Report receives the Session's failure and the errors of listeners, which never fail what ran them; info says
	// which. A plain Session drops them.
	//
	// ctx carries the telemetry span the report is raised under (chord/context.Telemetry); context.Background() has none.
	Report func(ctx context.Context, err error, info durable.ReportInfo)
	// SetTimer arms the timers that evict idle documents (HarnessOptions.SetTimer); nil selects Go timers.
	SetTimer durable.SetTimer
	// ReadOnly refuses every commit with writes (HarnessOptions.ReadOnly).
	ReadOnly bool
}

Hooks are the extension points a Harness overrides on its Session.

type LineDocument

type LineDocument struct {
	Record  durable.DocumentRecord
	Version int
	Value   durable.JsonObject
}

LineDocument is a conversation document's current incarnation and value.

type LineTicket

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

LineTicket is a position on the mutation line taken before its job runs.

func (*LineTicket) Release

func (ticket *LineTicket) Release()

Release gives up the position. Jobs queued behind it keep waiting for the jobs queued before it.

type LoadedDocument

type LoadedDocument struct {
	AddressId string
	Record    durable.DocumentRecord
	// ValueVersion is the definition version whose shape the tracked value has; access with another version reloads
	// from Storage.
	ValueVersion int
	Tracker      *delta.Tracker
	// contains filtered or unexported fields
}

LoadedDocument is one committed document incarnation owned by the Session tracker cache.

func (*LoadedDocument) StoredVersion

func (loaded *LoadedDocument) StoredVersion() int

StoredVersion returns the persisted definition version.

type SessionImpl

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

SessionImpl is the Session kernel: one mutation line, the loaded document tracker cache, and committed publication.

Only committed state is observable. Every commit callback, preparation, Storage settlement, adoption, and publication runs while the line is held; asynchronous listeners run later.

func CreateSession

func CreateSession(storage durable.Storage, options ...CreateSessionOptions) *SessionImpl

CreateSession opens a Session kernel over one storage backend.

func NewSessionImpl

func NewSessionImpl(storage durable.Storage, hooks Hooks, now func() float64, documentRetentionMs func() *float64) *SessionImpl

NewSessionImpl opens a Session kernel with extension hooks. now is the wall clock in milliseconds for task times; nil selects the system clock. documentRetentionMs is read at each use and yields the document retention (see CreateSessionOptions.DocumentRetentionMs); nil selects the default.

func (*SessionImpl) AwaitDeliveriesEntered

func (session *SessionImpl) AwaitDeliveriesEntered(ctx context.Context) error

AwaitDeliveriesEntered blocks until every watch delivery scheduled before the call has entered: its listener returned, is parked in a wait, or is blocked behind a lock, which a Go listener does where an upstream one awaits and which the caller may hold. A Harness wait that resumes its caller calls it, as upstream's drain microtask enters the listener before the code awaiting the wait's promise resumes; the listener a caller's own goroutine runs is not waited for, so a listener may itself wait for the Harness. It returns the cause of ctx when ctx ends the wait.

func (*SessionImpl) Close

func (session *SessionImpl) Close(ctx context.Context) error

Close seals admission, settles admitted commits, then closes Storage. Close listeners run synchronously when close begins, before the BeforeClose hook. Cancelling ctx stops waiting without interrupting the close; an already cancelled ctx returns its cause at once, as upstream's awaitWithContext rejects for an aborted signal.

func (*SessionImpl) Closed

func (session *SessionImpl) Closed() <-chan struct{}

Closed returns a channel closed once the Session ended: after close reached the backend, or a failure ended it.

func (*SessionImpl) Commit

func (session *SessionImpl) Commit(ctx context.Context, change func(tx durable.Tx) (any, error)) (any, error)

Commit runs one atomic transaction on the Session mutation line.

func (*SessionImpl) CommitSubscriptions

func (session *SessionImpl) CommitSubscriptions() int

CommitSubscriptions reports the number of live commit subscriptions. Upstream tests count them by wrapping subscribeCommits (harness-lifecycle.test.ts:331); a Go method cannot be patched.

func (*SessionImpl) CommitWith

func (session *SessionImpl) CommitWith(ctx context.Context, change func(tx *Transaction) (any, error), scope TransactionScope) (any, error)

CommitWith is the internal commit exposing the concrete transaction and its internal operations, such as the reserved-ID root bootstrap and task replacement. scope sets the default task conversation and the task attributed to appended entries.

func (*SessionImpl) CommitWithTicket

func (session *SessionImpl) CommitWithTicket(ticket *LineTicket, ctx context.Context, change func(tx *Transaction) (any, error), scope TransactionScope) (any, error)

CommitWithTicket runs a commit at the ticket's position and releases it.

func (*SessionImpl) ConversationDocumentOnLine

func (session *SessionImpl) ConversationDocumentOnLine(ctx context.Context, token durable.AnyDocToken, conversationId durable.ConversationId) (*LineDocument, error)

ConversationDocumentOnLine returns a conversation document's current incarnation and value for a job already running on the line (see ReadOnLine); nil when absent.

func (*SessionImpl) DeferUntilPublished

func (session *SessionImpl) DeferUntilPublished(run func())

DeferUntilPublished runs run once every listener of the publication in progress has run, and at once when none is. Upstream settles a waiter by resolving a promise inside a listener, and the awaiting code resumes after the synchronous listener loop; a goroutine woken inside a listener would race the listeners that follow, so waiters wake through this. Listeners call it from the publishing goroutine, as publications are serialized on the line.

func (*SessionImpl) DocumentCacheSizes

func (session *SessionImpl) DocumentCacheSizes() DocumentCacheSizes

DocumentCacheSizes reports how many documents the cache holds, how many are idle, how many incarnations are pinned, and how many eviction jobs were queued on the line so far.

func (*SessionImpl) End

func (session *SessionImpl) End() durable.SessionEnd

End returns how the Session ended once Closed is closed.

func (*SessionImpl) Fail

func (session *SessionImpl) Fail(ctx context.Context, err error)

Fail fails the Session with err: the first wins, and it is reported once. Admission ends, and the close listeners run now; they read the error from Failure. The Storage guard calls it; the Harness also calls it for an error in its scheduler's own commits.

func (*SessionImpl) Failed

func (session *SessionImpl) Failed() <-chan struct{}

Failed returns a channel closed the moment the Session fails, before work underway has ended.

func (*SessionImpl) Failure

func (session *SessionImpl) Failure() error

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

func (*SessionImpl) LineJobs

func (session *SessionImpl) LineJobs() int

LineJobs reports the number of admitted line jobs that have not finished, so a caller can wait until work is queued behind a held job without sleeping.

func (*SessionImpl) ObserveCommits

func (session *SessionImpl) ObserveCommits(listener func(ctx context.Context, publication durable.CommitPublication)) func()

ObserveCommits is SubscribeCommits for the Session's own components, whose state follows each commit. A panic leaves that state behind storage, so it fails the Session instead of being reported. They run before the host's listeners.

func (*SessionImpl) ReadOnLine

func (session *SessionImpl) ReadOnLine(job func() (any, error)) (any, error)

ReadOnLine runs a read-only job on the mutation line so multi-read derivations observe one committed state.

func (*SessionImpl) ReadWithTicket

func (session *SessionImpl) ReadWithTicket(ticket *LineTicket, job func() (any, error)) (any, error)

ReadWithTicket runs a read-only job at the ticket's position on the mutation line and releases it.

func (*SessionImpl) Report

func (session *SessionImpl) Report(err error)

Report is session.ts report with its default info: it hands a non-fatal failure, such as the error of a state or watch listener, to the host; a plain Session drops it.

func (*SessionImpl) ReportAs

func (session *SessionImpl) ReportAs(ctx context.Context, err error, info durable.ReportInfo)

ReportAs is session.ts report with info: it hands a non-fatal failure to the host; a plain Session drops it.

func (*SessionImpl) SnapshotAsOfErased

func (session *SessionImpl) SnapshotAsOfErased(ctx context.Context, token durable.AnyDocToken, at durable.EntryId, args ...any) (durable.JsonObject, error)

SnapshotAsOfErased returns the committed value of a rewindable conversation document as of the visible entry at; args are the conversation ID, then the family key for families.

func (*SessionImpl) SnapshotErased

func (session *SessionImpl) SnapshotErased(ctx context.Context, token durable.AnyDocToken, args ...any) (durable.JsonObject, error)

SnapshotErased returns the committed value of a document, or nil when absent. It never creates the document.

func (*SessionImpl) Storage

func (session *SessionImpl) Storage() durable.Storage

Storage returns the Session's Storage behind its failure guard; every component of the Session reads and writes through it, also the reads off the Session line. A Harness passes it to its scheduler and context reads.

func (*SessionImpl) SubscribeClose

func (session *SessionImpl) SubscribeClose(listener func()) func()

SubscribeClose registers a listener called synchronously when close begins. It must not panic, block, or call Session operations.

func (*SessionImpl) SubscribeCommits

func (session *SessionImpl) SubscribeCommits(listener func(ctx context.Context, publication durable.CommitPublication)) func()

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

func (*SessionImpl) TakeLineTicket

func (session *SessionImpl) TakeLineTicket() *LineTicket

TakeLineTicket takes the next line position now, or returns nil once close began.

func (*SessionImpl) UnloadDocuments

func (session *SessionImpl) UnloadDocuments() error

UnloadDocuments drops every loaded tracker on the mutation line; later access cold-loads from Storage.

func (*SessionImpl) WaitDeliveries

func (session *SessionImpl) WaitDeliveries()

WaitDeliveries blocks until every scheduled watch delivery has drained.

func (*SessionImpl) WatchDocErased

func (session *SessionImpl) WatchDocErased(ctx context.Context, token durable.AnyDocToken, args ...any) (durable.WatchHandle[durable.JsonObject], error)

WatchDocErased returns a watch of a document's committed value, or nil when absent. Cancelling ctx before the watch is returned rejects with the cancellation cause; afterwards it ends the watch with reason cancelled.

func (*SessionImpl) WriteAtClose

func (session *SessionImpl) WriteAtClose(ctx context.Context, writes func() []durable.StorageWrite) error

WriteAtClose is for BeforeClose (session.ts writeAtClose): on the line, after every commit admitted before the seal has settled, it writes what writes returns then straight to Storage. Nothing is published, since the Session is closing; a failed Session writes nothing.

type Transaction

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

Transaction is the transaction of one Session commit callback.

Every operation is tracked so callback settlement can reject and drain unfinished work. Session calls one settlement method, then either discards prepared changes or adopts them once after Storage succeeds.

func (*Transaction) AppendEntry

func (tx *Transaction) AppendEntry(conversationId durable.ConversationId, value durable.EntryDraft) (durable.EntryRecord, error)

AppendEntry appends an entry; the returned record is Session-owned and immutable.

func (*Transaction) Conversation

Conversation returns the committed conversation, or nil.

func (*Transaction) CreateConversation

func (tx *Transaction) CreateConversation(options durable.CreateConversationOptions) (durable.ConversationRecord, error)

CreateConversation creates a conversation with explicitly selected ownership.

func (*Transaction) CreateRootConversation

func (tx *Transaction) CreateRootConversation() (durable.ConversationRecord, error)

CreateRootConversation is the internal bootstrap path for the reserved root identity.

func (*Transaction) CreateSubmission

func (tx *Transaction) CreateSubmission(create durable.SubmissionCreate) (durable.SubmissionRecord, error)

CreateSubmission creates a raw submission record with a fresh ID; no admission rules apply.

func (*Transaction) CreateTaskErased

func (tx *Transaction) CreateTaskErased(task durable.AnyTask, input durable.JsonValue, options durable.TaskOptions) (durable.TaskId, error)

CreateTaskErased creates a task of an erased definition.

func (*Transaction) CreateTaskFromSubmissions

func (tx *Transaction) CreateTaskFromSubmissions(task durable.AnyTask, input durable.JsonValue, options durable.TaskOptions, submissionIds []durable.SubmissionId) (durable.TaskId, error)

CreateTaskFromSubmissions is CreateTaskErased with transaction.ts's internal TaskCreationOptions.submissionIds: run creation resolves the carriers of the submissions it starts for against staged records before reading storage. The first submission's carrier becomes the task's trace ("root" when it has none) and the carriers of the others its links.

func (*Transaction) Doc

func (tx *Transaction) Doc(token durable.AnyDocToken, args ...any) (*delta.Object, error)

Doc returns the document's *delta.Object draft, creating the document when absent. args are the owner ID (conversation or task scope), then the family key and seed (families). A family access without a seed fails as upstream's undefined seed does; an explicit nil seed is JSON null.

func (*Transaction) Entry

func (tx *Transaction) Entry(id durable.EntryId) (*durable.EntryRecord, error)

Entry returns the committed entry, or nil.

func (*Transaction) ForkConversation

func (tx *Transaction) ForkConversation(parentConversationId durable.ConversationId, at durable.EntryId, options durable.CreateConversationOptions) (durable.ConversationRecord, error)

ForkConversation creates a history fork at one concrete visible entry.

func (*Transaction) LatestHeadMarker

func (tx *Transaction) LatestHeadMarker(conversationId durable.ConversationId) (*durable.EntryRecord, error)

LatestHeadMarker returns the newest visible entry of the conversation that carries a head.

func (*Transaction) PlaceSubmission

func (tx *Transaction) PlaceSubmission(id durable.SubmissionId, entry durable.EntryId) error

PlaceSubmission places a queued submission at entry; resolved like SettleSubmission.

func (*Transaction) RetireDoc

func (tx *Transaction) RetireDoc(token durable.AnyDocToken, args ...any) error

RetireDoc retires a document; args are the owner ID and family key, without a seed.

func (*Transaction) ScanConversations

func (tx *Transaction) ScanConversations(query durable.ConversationQuery, limit int, cursor durable.Cursor) (durable.Page[durable.ConversationRecord, durable.Cursor], error)

ScanConversations scans committed conversations.

func (*Transaction) ScanEntries

func (tx *Transaction) ScanEntries(query durable.EntryQuery, limit int, cursor durable.Cursor) (durable.Page[durable.EntryRecord, durable.Cursor], error)

ScanEntries scans committed visible entries newest-first.

func (*Transaction) ScanTasks

func (tx *Transaction) ScanTasks(query durable.TaskQuery, limit int, cursor durable.Cursor) (durable.Page[AnyTaskRecord, durable.Cursor], error)

ScanTasks scans committed task records.

func (*Transaction) SetTask

func (tx *Transaction) SetTask(value AnyTaskRecord) error

SetTask replaces one task record completely. Tasks change their own state through their runtime.

func (*Transaction) SettleSubmission

func (tx *Transaction) SettleSubmission(id durable.SubmissionId, settlement durable.SubmissionSettlement) error

SettleSubmission stages a settlement, resolved during assembly against the transaction's latest candidate record, falling back to committed state.

Upstream order: the open check, then the table-write mark, then the JSON copy of the settlement, so a settlement that is not strict JSON still ends the transaction's table reads.

func (*Transaction) StagedConversations

func (tx *Transaction) StagedConversations() []durable.ConversationRecord

StagedConversations returns the conversations this transaction created or forked so far.

func (*Transaction) StagedTasks

func (tx *Transaction) StagedTasks() []AnyTaskRecord

StagedTasks returns the candidate records of the tasks this transaction created or replaced so far.

func (*Transaction) Submission

Submission returns the committed submission record, or nil.

func (*Transaction) SubmissionByRequest

func (tx *Transaction) SubmissionByRequest(conversationId durable.ConversationId, requestId string) (*durable.SubmissionRecord, error)

SubmissionByRequest returns the committed submission with a conversation-scoped request ID, or nil.

func (*Transaction) Task

func (tx *Transaction) Task(id durable.TaskId) (*AnyTaskRecord, error)

Task returns the committed task, or nil.

type TransactionScope

type TransactionScope struct {
	// ConversationId is the default Tx.CreateTaskErased conversation.
	ConversationId *durable.ConversationId
	// TaskId is the task whose runtime commit this is; stamped as ByTaskId on appended entries.
	TaskId *durable.TaskId
}

TransactionScope holds the defaults a commit binds to.

Directories

Path Synopsis
Package sessiontest holds the shared Session test support: a controlled memory storage and an opened Session kernel with its publications.
Package sessiontest holds the shared Session test support: a controlled memory storage and an opened Session kernel with its publications.

Jump to

Keyboard shortcuts

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