memory

package module
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 22 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package memory is the in-process storage plugin for cyoda-go.

It serves both as the default backend (no external dependencies) and as the minimal reference implementation for plugin authors — it implements every required interface method, nothing more.

Registration happens at init() time via spi.Register. A binary picks up this plugin by blank-importing it:

import _ "github.com/cyoda/cyoda-go/plugins/memory"

Configuration: none. The plugin reads no environment variables and does not implement spi.DescribablePlugin.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidFilterPath = fmt.Errorf("%w", spi.ErrInvalidFilterPath)

ErrInvalidFilterPath is returned when a Filter.Path or an OrderSpec.Path is outside the vocabulary the search contract defines. Named and behaved identically to the sqlite and postgres sentinels of the same name so the same input is classified the same way on every backend — memory has no SQL to inject into, but a backend that silently accepts what the others reject is a divergence, not a leniency, and answering a malformed path with an empty page is a wrong-but-available result.

It wraps spi.ErrInvalidFilterPath, the cross-backend sentinel, so errors.Is matches against either this one or the SPI one. The "%w"-only wrap adds no prefix, leaving the message text unchanged.

Functions

This section is empty.

Types

type ApplyFunc

type ApplyFunc func(base []byte, deltas []spi.SchemaDelta) ([]byte, error)

ApplyFunc replays opaque SchemaDeltas, in order, onto a base schema in one call. An empty list re-encodes base.

type AsyncSearchStore

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

AsyncSearchStore is a tenant-scoped, in-memory implementation of spi.AsyncSearchStore.

func (*AsyncSearchStore) Cancel

func (s *AsyncSearchStore) Cancel(ctx context.Context, jobID string, finishTime time.Time) error

Cancel marks the job CANCELLED and stamps finishTime on the transition. Idempotent: cancelling a job already in a terminal state returns nil and does not overwrite the existing finish time. Cancelling a non-existent job returns spi.ErrNotFound.

func (*AsyncSearchStore) ClaimStale

func (s *AsyncSearchStore) ClaimStale(ctx context.Context, staleAfter time.Duration, limit int) ([]*spi.SearchJob, error)

ClaimStale atomically claims up to limit RUNNING jobs, across ALL tenants, whose staleness baseline — HeartbeatTime, stamped at CreateJob — is older than staleAfter (measured against the store's clock, the same domain Heartbeat stamps into). A claimed job has its Epoch bumped and HeartbeatTime refreshed to now, so a concurrent or immediately-following claim cannot re-take it. Terminal jobs are never claimed, regardless of staleness.

A limit-capped sweep takes the OLDEST candidates by CreateTime, matching sqlite's and postgres's ORDER BY on the same column. Cutting an unordered walk of the tenant maps at limit would claim a nondeterministic subset — Go randomises map iteration — so with more stale jobs than the reaper's batch (search.StaleClaimBatch) the oldest crashed job could be passed over on every sweep, indefinitely, which is precisely the job the reaper exists to recover. Equal CreateTime tie-breaks on job ID so the claimed set is reproducible rather than merely ordered.

func (*AsyncSearchStore) ClearResults

func (s *AsyncSearchStore) ClearResults(ctx context.Context, jobID string, epoch int64) error

ClearResults deletes the job's persisted result IDs, fenced like the write methods (missing/terminal/epoch): a refused clear deletes nothing. The fence and the delete run under one lock hold. Idempotent at the current epoch.

func (*AsyncSearchStore) CreateJob

func (s *AsyncSearchStore) CreateJob(ctx context.Context, job *spi.SearchJob) error

func (*AsyncSearchStore) DeleteJob

func (s *AsyncSearchStore) DeleteJob(ctx context.Context, jobID string) error

func (*AsyncSearchStore) GetJob

func (s *AsyncSearchStore) GetJob(ctx context.Context, jobID string) (*spi.SearchJob, error)

func (*AsyncSearchStore) GetResultIDs

func (s *AsyncSearchStore) GetResultIDs(ctx context.Context, jobID string, offset, limit int) ([]string, int, error)

func (*AsyncSearchStore) Heartbeat

func (s *AsyncSearchStore) Heartbeat(ctx context.Context, jobID string, epoch int64) error

Heartbeat stamps HeartbeatTime (using the store's clock — the same clock domain ClaimStale compares staleness against) on the job, fenced by epoch. Guarded like UpdateJobStatus: missing → ErrNotFound, terminal → ErrAlreadyTerminal, epoch mismatch → ErrStaleClaim.

func (*AsyncSearchStore) ReapExpired

func (s *AsyncSearchStore) ReapExpired(ctx context.Context, ttl time.Duration) (int, error)

func (*AsyncSearchStore) Release

func (s *AsyncSearchStore) Release(ctx context.Context, jobID string, epoch int64) error

Release marks a RUNNING job released without finishing it, so the next ClaimStale takes it regardless of staleAfter. Fenced exactly like the write methods (missing/terminal/epoch), idempotent at the same epoch, and it neither bumps Epoch nor touches StaleClaims. A stray Heartbeat at the same epoch does not clear the mark — only a claim does.

func (*AsyncSearchStore) SaveResults

func (s *AsyncSearchStore) SaveResults(ctx context.Context, jobID string, epoch int64, entityIDs iter.Seq[string]) error

SaveResults drains entityIDs, appending each chunk to the job's persisted result set under the lock. The write guard (existence, terminal status, epoch) is re-checked at every chunk boundary — including once up front, so a stale/terminal/missing job fails even against an empty sequence — and ctx cancellation is observed between chunks.

func (*AsyncSearchStore) UpdateJobStatus

func (s *AsyncSearchStore) UpdateJobStatus(ctx context.Context, jobID string, epoch int64, status string, resultCount int, errMsg string, finishTime time.Time, calcTimeMs int64) error

type Clock

type Clock interface {
	Now() time.Time
}

Clock abstracts time.Now so tests can advance it deterministically. Production uses wallClock; conformance tests use TestClock.

type EntityStore

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

func (*EntityStore) CompareAndSave

func (s *EntityStore) CompareAndSave(ctx context.Context, entity *spi.Entity, expectedTxID string) (int64, error)

CompareAndSave writes entity only if its stored transaction ID is still expectedTxID. expectedTxID must not be empty: it is compared literally, and the empty string is the transaction ID a missing or deleted entity reports — but also the one a write taken outside a transaction stores, so an empty expected ID cannot tell "no entity" from "an entity written outside a transaction" and would overwrite the latter. It is rejected as a caller error, before any read or write. CompareAndSave therefore never creates an entity and never resurrects a deleted one; Save does that.

func (*EntityStore) Count

func (s *EntityStore) Count(ctx context.Context, modelRef spi.ModelRef, asAt *time.Time) (int64, error)

func (*EntityStore) CountByState

func (s *EntityStore) CountByState(ctx context.Context, modelRef spi.ModelRef, states []string, asAt *time.Time) (map[string]int64, error)

CountByState returns counts of non-deleted entities grouped by state for the given model. See SPI godoc on EntityStore.CountByState for filter semantics.

func (*EntityStore) Delete

func (s *EntityStore) Delete(ctx context.Context, entityID string) error

func (*EntityStore) DeleteAll

func (s *EntityStore) DeleteAll(ctx context.Context, modelRef spi.ModelRef) error

func (*EntityStore) Exists

func (s *EntityStore) Exists(ctx context.Context, entityID string) (bool, error)

func (*EntityStore) Get

func (s *EntityStore) Get(ctx context.Context, entityID string) (*spi.Entity, error)

func (*EntityStore) GetAsAt

func (s *EntityStore) GetAsAt(ctx context.Context, entityID string, asAt time.Time) (*spi.Entity, error)

func (*EntityStore) GetPage

func (s *EntityStore) GetPage(ctx context.Context, modelRef spi.ModelRef, limit, offset int, asAt *time.Time) ([]*spi.Entity, error)

GetPage returns a page of modelRef's entities in memory's canonical byte-wise entity-ID order. See the spi.EntityStore.GetPage doc comment for the full contract: limit>=1 && offset>=0 is required; asAt==nil reads the live (in-tx overlay when a transaction is ambient) view and, in-tx, unconditionally records every returned entity in the transaction's read-set (unlike Search/Iterate's opt-in TrackingRead); asAt!=nil ignores any ambient transaction and reads committed-only state as of that instant.

func (*EntityStore) GetVersionByTransaction

func (s *EntityStore) GetVersionByTransaction(ctx context.Context, entityID, txID string) (*spi.EntityVersion, error)

GetVersionByTransaction returns the version of entityID that transaction txID wrote (a transaction writes at most one). DELETED tombstones never match (they carry no entity payload — see the SPI doc comment) and an empty txID never matches, even a stored-empty one from a non-transactional write.

func (*EntityStore) GetVersionMetadata

func (s *EntityStore) GetVersionMetadata(ctx context.Context, entityID string, opts spi.VersionMetadataOptions) ([]spi.EntityVersionMeta, error)

GetVersionMetadata returns entityID's version metadata — no entity payload — newest first, ties broken by Version DESC. opts.From/ opts.Until bound the window inclusively (nil side unbounded); opts.Limit caps the row count (0 means all). Deleted is true only on the DELETED tombstone row, and Version is populated on every returned row, including the tombstone (entityVersion.version is the source of truth for this — see its doc comment).

func (*EntityStore) GroupedAggregate

func (s *EntityStore) GroupedAggregate(
	ctx context.Context,
	model spi.ModelRef,
	groupBy []spi.GroupExpr,
	filter spi.Filter,
	opts spi.GroupedAggregationsOptions,
) ([]spi.GroupedAggregateBucket, error)

GroupedAggregate implements spi.GroupedAggregator. Walks the same snapshot used by Iterate, applies the filter, and tallies per-bucket counts and aggregations inline. Returns ErrGroupCardinalityExceeded the moment a new key would push the bucket map past opts.MaxBuckets.

Sorting/limiting is handled by the service-layer postProcessPushdown (and a nil-vs-zero aggregations map there); the plugin returns raw per-bucket results.

func (*EntityStore) Iterate

func (s *EntityStore) Iterate(
	ctx context.Context,
	model spi.ModelRef,
	filter spi.Filter,
	opts spi.IterateOptions,
) (spi.Iterator, error)

Iterate implements spi.EntityStore.Iterate. The filter is prepared once here and evaluated per row by the shared kernel — the same evaluator the sqlite (plugins/sqlite/post_filter.go) and postgres (plugins/postgres/ grouped_stats.go) backends use, so all three backends agree bit-for-bit on filter semantics, including CoerceTemporal and the canonical client-name meta vocabulary. A zero-value filter prepares to match-all, matching the historical "no filter" contract.

func (*EntityStore) Save

func (s *EntityStore) Save(ctx context.Context, entity *spi.Entity) (int64, error)

func (*EntityStore) SaveAll

func (s *EntityStore) SaveAll(ctx context.Context, entities iter.Seq[*spi.Entity]) ([]int64, error)

func (*EntityStore) Search

func (s *EntityStore) Search(ctx context.Context, filter spi.Filter, opts spi.SearchOptions) ([]*spi.Entity, error)

Search implements spi.EntityStore.Search for the in-memory entity store. It produces the same result set that GetPage + spi.Prepare(filter).Match would for the same transaction state, but filters/orders/bounds with the canonical SPI helpers (spi.Prepare/PreparedFilter.Match, spi.LessByOrder, spi.MergeBounded) so every backend agrees. Search is bounded-or-fail: opts.Limit >= 1 is REQUIRED and caps the matched set; a matched set larger than the limit is spi.ErrSearchResultLimitExceeded, never a truncated prefix. opts.Limit <= 0 is a contract violation, rejected up front.

Three branches:

  • non-tx: iterate the current committed model (or the PIT snapshot when opts.PointInTime is set), filter, sort, bound. No read-set.
  • in-tx with PointInTime: committed-only snapshot at the PIT — no buffer overlay, no read-set (mirrors GetPage's committed-only PIT branch).
  • in-tx, PointInTime==nil: read-your-own-writes overlay — a k-way merge of the committed snapshot (suppressing tx.Deletes and buffered ids) with the matching buffer entries, bounded by spi.MergeBounded. Returned committed ids enter tx.ReadSet ONLY when opts.TrackingRead is set (unlike GetPage, which records every read unconditionally).

type KeyValueStore

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

func (*KeyValueStore) CompareAndPut

func (s *KeyValueStore) CompareAndPut(ctx context.Context, namespace, key string, expected, value []byte) (bool, error)

func (*KeyValueStore) Delete

func (s *KeyValueStore) Delete(ctx context.Context, namespace string, key string) error

func (*KeyValueStore) DeleteIfEqual

func (s *KeyValueStore) DeleteIfEqual(ctx context.Context, namespace, key string, expected []byte) (bool, error)

func (*KeyValueStore) Get

func (s *KeyValueStore) Get(ctx context.Context, namespace string, key string) ([]byte, error)

func (*KeyValueStore) List

func (s *KeyValueStore) List(ctx context.Context, namespace string) (map[string][]byte, error)

func (*KeyValueStore) Put

func (s *KeyValueStore) Put(ctx context.Context, namespace string, key string, value []byte) error

func (*KeyValueStore) PutIfAbsent

func (s *KeyValueStore) PutIfAbsent(ctx context.Context, namespace, key string, value []byte) (bool, error)

type MessageStore

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

func (*MessageStore) Delete

func (s *MessageStore) Delete(_ context.Context, id string) error

func (*MessageStore) DeleteBatch

func (s *MessageStore) DeleteBatch(ctx context.Context, ids []string) error

func (*MessageStore) Get

func (*MessageStore) Save

func (s *MessageStore) Save(_ context.Context, id string, header spi.MessageHeader, metaData spi.MessageMetaData, payload io.Reader) error

Blob I/O goes through the factory's *os.Root and the hex names in blob_path.go. Encoding governs what a name can be; the root governs what that name is allowed to resolve to. Neither subsumes the other — a symlink planted under the blob directory is the root's job, a case-only collision between two tenant directories is the encoding's — and between them a traversing or colliding name is unrepresentable rather than rejected, so there is no spelling check left to keep in step.

type ModelStore

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

ModelStore is a tenant-scoped, in-memory implementation of spi.ModelStore.

func (*ModelStore) Delete

func (s *ModelStore) Delete(ctx context.Context, modelRef spi.ModelRef) error

func (*ModelStore) ExtendSchema

func (s *ModelStore) ExtendSchema(ctx context.Context, ref spi.ModelRef, delta spi.SchemaDelta) error

ExtendSchema applies the delta to the current schema via the injected ApplyFunc. Memory is single-writer so apply-in-place under the factory's model mutex is correct. The caller extends only a LOCKED model; the store does not check this.

func (*ModelStore) Get

func (s *ModelStore) Get(ctx context.Context, modelRef spi.ModelRef) (*spi.ModelDescriptor, error)

func (*ModelStore) GetAll

func (s *ModelStore) GetAll(ctx context.Context) ([]spi.ModelRef, error)

func (*ModelStore) IsLocked

func (s *ModelStore) IsLocked(ctx context.Context, modelRef spi.ModelRef) (bool, error)

func (*ModelStore) Lock

func (s *ModelStore) Lock(ctx context.Context, modelRef spi.ModelRef) error

func (*ModelStore) Save

func (s *ModelStore) Save(ctx context.Context, desc *spi.ModelDescriptor) error

func (*ModelStore) SetChangeLevel

func (s *ModelStore) SetChangeLevel(ctx context.Context, modelRef spi.ModelRef, level spi.ChangeLevel) error

func (*ModelStore) Unlock

func (s *ModelStore) Unlock(ctx context.Context, modelRef spi.ModelRef) error

type Option

type Option func(*StoreFactory)

Option is a functional option for NewStoreFactory.

func WithApplyFunc

func WithApplyFunc(fn ApplyFunc) Option

WithApplyFunc installs the replay function used by ExtendSchema.

func WithBusinessClock

func WithBusinessClock(c Clock) Option

WithBusinessClock injects the BUSINESS clock: the one behind submit time, snapshot time, consistency time and retention cutoffs. It defaults to the physical clock.

func WithClock

func WithClock(c Clock) Option

WithClock injects the PHYSICAL clock into the factory: the clock behind liveness (scheduler owner heartbeats and sweeps, search-job heartbeats and stale reclaim). Used by conformance tests to advance time deterministically.

type StateMachineAuditStore

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

func (*StateMachineAuditStore) GetEvents

func (s *StateMachineAuditStore) GetEvents(ctx context.Context, entityID string) ([]spi.StateMachineEvent, error)

GetEvents returns entityID's committed events, plus — when ctx carries a transaction — that transaction's own not-yet-committed events, so a read inside a transaction sees what it staged there.

func (*StateMachineAuditStore) GetEventsByTransaction

func (s *StateMachineAuditStore) GetEventsByTransaction(ctx context.Context, entityID string, transactionID string) ([]spi.StateMachineEvent, error)

func (*StateMachineAuditStore) Record

func (s *StateMachineAuditStore) Record(ctx context.Context, entityID string, event spi.StateMachineEvent) error

Record assigns the event its id (see spi.StateMachineAuditStore): a caller's TimeUUID is ignored. With a transaction on ctx the event is staged on it and joins the trail only if the transaction commits.

type StoreFactory

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

func NewStoreFactory

func NewStoreFactory(opts ...Option) *StoreFactory

func (*StoreFactory) AsyncSearchStore

func (f *StoreFactory) AsyncSearchStore(_ context.Context) (spi.AsyncSearchStore, error)

func (*StoreFactory) Close

func (f *StoreFactory) Close() error

func (*StoreFactory) EntityStore

func (f *StoreFactory) EntityStore(ctx context.Context) (spi.EntityStore, error)

func (*StoreFactory) GetTransactionManager

func (f *StoreFactory) GetTransactionManager() spi.TransactionManager

GetTransactionManager returns the registered TransactionManager, or nil.

func (*StoreFactory) KeyValueStore

func (f *StoreFactory) KeyValueStore(ctx context.Context) (spi.KeyValueStore, error)

func (*StoreFactory) MessageStore

func (f *StoreFactory) MessageStore(ctx context.Context) (spi.MessageStore, error)

func (*StoreFactory) ModelStore

func (f *StoreFactory) ModelStore(ctx context.Context) (spi.ModelStore, error)

func (*StoreFactory) NewTransactionManager

func (f *StoreFactory) NewTransactionManager(uuids spi.UUIDGenerator) *TransactionManager

NewTransactionManager creates and registers a TransactionManager on the StoreFactory, carrying over the submit-time floor of whatever it replaces (see seedLastSubmitTime).

func (*StoreFactory) Ping

func (f *StoreFactory) Ping(ctx context.Context) error

Ping implements spi.StoreFactory. The in-memory store always answers, so it fails only when ctx is done or the factory has been closed.

func (*StoreFactory) ScheduledTaskStore

func (f *StoreFactory) ScheduledTaskStore(_ context.Context) (spi.ScheduledTaskStore, error)

ScheduledTaskStore returns the scheduled-task store. No tenant is resolved from ctx: every tenant-facing method takes its tenant as an argument, and ClaimDue, GiveBackIdle and the owner and sweep methods are cross-tenant.

func (*StoreFactory) SetApplyFunc

func (f *StoreFactory) SetApplyFunc(fn func(base []byte, deltas []spi.SchemaDelta) ([]byte, error))

SetApplyFunc installs the replay function used by ExtendSchema. May be called at most once — typically immediately after Plugin.NewFactory in app/app.go. Panics on double-call (programmer error).

The parameter is the unnamed function type (not memory.ApplyFunc) so that an interface type-assertion in app/app.go can satisfy the setter uniformly across plugins.

func (*StoreFactory) StateMachineAuditStore

func (f *StoreFactory) StateMachineAuditStore(ctx context.Context) (spi.StateMachineAuditStore, error)

func (*StoreFactory) SupportsCompositeUniqueKeys

func (f *StoreFactory) SupportsCompositeUniqueKeys() bool

SupportsCompositeUniqueKeys advertises composite-unique-key enforcement.

func (*StoreFactory) TransactionManager

func (f *StoreFactory) TransactionManager(ctx context.Context) (spi.TransactionManager, error)

TransactionManager implements spi.StoreFactory. Returns the TM registered via NewTransactionManager. Errors if none is set.

func (*StoreFactory) WorkflowStore

func (f *StoreFactory) WorkflowStore(ctx context.Context) (spi.WorkflowStore, error)

type TestClock

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

TestClock is a mutable clock for tests. Advance(d) moves it forward; Now returns the current virtual time. Safe for concurrent use.

func NewTestClock

func NewTestClock() *TestClock

NewTestClock returns a TestClock starting at the current wall-clock time.

func NewTestClockAt

func NewTestClockAt(t time.Time) *TestClock

NewTestClockAt returns a TestClock whose virtual time starts at t. Tests that need a millisecond-aligned base (so sub-millisecond Advance steps land in a known millisecond) use this instead of NewTestClock.

func (*TestClock) Advance

func (c *TestClock) Advance(d time.Duration)

Advance moves the virtual clock forward by d. d must be > 0; d <= 0 panics. Matches the spitest.Harness.AdvanceClock contract.

func (*TestClock) Now

func (c *TestClock) Now() time.Time

Now returns the current virtual time.

type TransactionManager

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

TransactionManager implements spi.TransactionManager using Snapshot Isolation with First-Committer-Wins (SI+FCW) — see docs/CONSISTENCY.md for the contract. It lives in the memory package because it needs direct access to StoreFactory's entityData map and mu lock for the atomic commit flush.

func (*TransactionManager) Begin

Begin starts a new transaction. It resolves the tenant from the context, generates a unique transaction ID, captures a snapshot time, and returns a new context carrying the TransactionState.

func (*TransactionManager) Commit

func (m *TransactionManager) Commit(ctx context.Context, txID string) error

Commit validates the transaction against the committed log for SI+FCW conflicts, flushes the write buffer and deletes to the entity store, and records the commit in the log. The claims of the unique keys are computed here, from the transaction's final entities and the keys of their stored models; a save inside the transaction does none of that work.

A commit that aborts — on a conflict or on a unique-key violation — applies nothing and leaves the transaction rolled back as well as closed, so a later call with its ctx answers spi.ErrTxRolledBack, never spi.ErrTxAlreadyCommitted. Its state is discarded as Rollback discards it, so a Rollback after the abort answers spi.ErrTxNotFound.

func (*TransactionManager) CommittedLogLen

func (m *TransactionManager) CommittedLogLen() int

CommittedLogLen returns the current length of the committed log. Exported for testing only.

func (*TransactionManager) ConsistencyTime

func (m *TransactionManager) ConsistencyTime(ctx context.Context) (time.Time, error)

ConsistencyTime implements spi.TransactionManager. It reserves C = max(clock, lastSubmitTime) as the new floor, exactly as Begin does, so every later stamp is strictly after C. No wait is needed: every writer holds factory.entityMu from stamp to publish and every reader takes entityMu.RLock, so a read that starts after C was returned cannot observe a stamp <= C that is not yet published. The floor is shared by all tenants, which makes C complete across tenants. A restart loses every stamp and job with it, so there is no earlier C to stay above.

func (*TransactionManager) GetSubmitTime

func (m *TransactionManager) GetSubmitTime(ctx context.Context, txID string) (time.Time, error)

GetSubmitTime returns the submit time of a committed transaction. Returns an error if the transaction is still active or not found.

Tenant isolation: like every other tx-lifecycle method, the caller's tenant must match the transaction's tenant. The check runs before any state-dependent response so a cross-tenant caller learns neither the submit time nor whether the transaction is in flight or committed.

func (*TransactionManager) Join

Join returns a context carrying the TransactionState for an existing active transaction. This allows multiple goroutines to participate in the same transaction. Callers must coordinate access to the transaction's Buffer, ReadSet, WriteSet, and Deletes maps.

Locking discipline: Rollback writes tx.RolledBack inside m.mu only; Commit and Rollback both write tx.Closed in their defer under tx.OpMu.Lock only. Reading those fields requires tx.OpMu.RLock to be synchronised against the Closed-write — m.mu alone is not sufficient because Commit's defer runs outside the m.mu region.

func (*TransactionManager) LatestRecordedTime

func (m *TransactionManager) LatestRecordedTime(_ context.Context) (time.Time, error)

LatestRecordedTime implements spi.TransactionManager: the submit-time floor (lastSubmitTime), read under the mutex that every stamp, SnapshotTime and ConsistencyTime raises it under. It does not raise it. The floor is shared by all tenants, so ctx needs no tenant. Zero on a fresh store.

func (*TransactionManager) LostRace

func (m *TransactionManager) LostRace(ctx context.Context, txID string) (bool, error)

LostRace reports whether the transaction has already lost a write race: a transaction that committed after its snapshot wrote an entity in its write set or a task row in its staged task-row ops, or a RollbackToSavepoint discarded a write that had already lost (lostDiscardedWrite). It is the write half of Commit's check, and changes nothing.

Locking discipline: reads tx.WriteSet under tx.OpMu.RLock, as Savepoint does, and the log and staged ops under mu, taken after tx.OpMu as Commit takes them.

Tenant isolation: rejects callers whose UserContext tenant does not match the transaction's tenant, before it reads anything of the transaction.

func (*TransactionManager) ReleaseSavepoint

func (m *TransactionManager) ReleaseSavepoint(ctx context.Context, txID string, savepointID string) error

ReleaseSavepoint releases a savepoint and every savepoint taken after it, as SQL RELEASE does. The work done since is already in the parent transaction's buffer, so this just removes the snapshots.

Locking discipline: ReleaseSavepoint does not read or write tx.Buffer / tx.ReadSet / tx.WriteSet / tx.Deletes — it only mutates m.savepoints. Holds m.mu only; tx.OpMu is not required because there is no tx-state field to coordinate against Commit/Rollback.

Tenant isolation: rejects cross-tenant callers — m.savepoints is tenant-scoped state.

func (*TransactionManager) Rollback

func (m *TransactionManager) Rollback(ctx context.Context, txID string) error

Rollback discards an active transaction without committing any changes.

func (*TransactionManager) RollbackToSavepoint

func (m *TransactionManager) RollbackToSavepoint(ctx context.Context, txID string, savepointID string) error

RollbackToSavepoint restores the transaction's buffer maps from the snapshot captured when the savepoint was created, truncates the transaction's staged scheduledTaskOps and auditOps back to the lengths recorded at that savepoint. The savepoint itself is kept; savepoints taken after it are destroyed.

Locking discipline: RollbackToSavepoint replaces tx.Buffer / tx.ReadSet / tx.WriteSet / tx.Deletes — exclusive against every other tx-path op. Holds tx.OpMu.Lock (write) for the duration of the field replacement. Lock interleaving with m.mu follows Commit's pattern. The scheduledTaskOps truncation happens in the same m.mu section as the snapshot lookup, since that map is m.mu-protected (see stageTaskWrite), not tx.OpMu-protected.

Tenant isolation: rejects cross-tenant callers — RollbackToSavepoint is destructive on tx-state.

func (*TransactionManager) Savepoint

func (m *TransactionManager) Savepoint(ctx context.Context, txID string) (string, error)

Savepoint creates a named savepoint within the given transaction by deep-copying the transaction's buffer maps (including DeleteAttribution, paired 1:1 with Deletes) and recording the current length of the transaction's staged scheduledTaskOps.

Locking discipline: Savepoint reads tx.Buffer / tx.ReadSet / tx.WriteSet / tx.Deletes — the same fields Commit's flush phase iterates under tx.OpMu.Lock and that other tx-path ops (Save, Get, Delete, ...) mutate under tx.OpMu.RLock. Savepoint must therefore hold tx.OpMu.RLock across those reads. The lock interleaving with m.mu follows Commit's pattern: drop m.mu before taking tx.OpMu, re-take m.mu briefly for the m.savepoints update — the same m.mu section also reads len(m.scheduledTaskOps[txID]), since that map is m.mu-protected, not tx.OpMu-protected.

Tenant isolation: rejects callers whose UserContext tenant does not match the transaction's tenant, mirroring Commit/Rollback. Without this guard a caller authenticated as tenant A who learned a tenant B txID could record a snapshot against tenant B's tx-state.

type WorkflowStore

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

func (*WorkflowStore) Delete

func (s *WorkflowStore) Delete(ctx context.Context, modelRef spi.ModelRef) error

func (*WorkflowStore) Get

func (s *WorkflowStore) Get(ctx context.Context, modelRef spi.ModelRef) ([]spi.WorkflowDefinition, error)

func (*WorkflowStore) Save

func (s *WorkflowStore) Save(ctx context.Context, modelRef spi.ModelRef, workflows []spi.WorkflowDefinition) error

Jump to

Keyboard shortcuts

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