session

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 9 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, as upstream's drain microtask enters the listener before the commit's caller 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

This section is empty.

Functions

This section is empty.

Types

type AnyTaskRecord

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

type CommittedStateSource

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

CommittedStateSource is the Session-to-Chord bridge owned one-to-one by one attached state: a document, or a conversation view. A nil value retires it.

func NewCommittedStateSource

func NewCommittedStateSource[T any](session *SessionImpl, value T, release func()) *CommittedStateSource[T]

NewCommittedStateSource returns a source holding value whose deliveries run on session's delivery scheduler; release runs once when the source finishes disposal. Ports observation.ts:24 CommittedStateSource constructor (the Harness builds conversation views on it, view.ts:90).

func (*CommittedStateSource[T]) Advance

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

func (*CommittedStateSource[T]) Attach

Attach implements chord.ReplicatedStateSource.

func (*CommittedStateSource[T]) CloseSession

func (source *CommittedStateSource[T]) CloseSession()

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. A nil value retires it.

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 (*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]) CloseSession

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

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]) 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 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()
}

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 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 PoisonedError

type PoisonedError struct{ Cause error }

PoisonedError rejects every operation after a commit failed once Storage admitted it: memory may be behind durable state.

func (*PoisonedError) Error

func (err *PoisonedError) Error() string

func (*PoisonedError) Unwrap

func (err *PoisonedError) Unwrap() error

Unwrap returns the failure that poisoned the Session.

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) *SessionImpl

CreateSession opens a Session kernel over one storage backend.

func NewSessionImpl

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

NewSessionImpl opens a Session kernel with extension hooks.

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) 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) 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) DocumentStateErased

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

DocumentStateErased returns a disposable read-only state of a document's committed value, or nil when absent.

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) 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) 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) 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) 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 and state 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.

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) 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.

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