Reference

IDataContext

Package Trax.Effect.DataNamespaces Trax.Effect.Data.Services.DataContext, Trax.Effect.Data.Services.DataContextTransactionSource IDataContext.cs, IDataContextTransaction.cs

Trax's own data context: an EF Core context over the trax tables (runs, logs, manifests, the work queue, dead letters and the rest), and the effect provider that persists a train's metadata. UsePostgres, UseSqlite and UseInMemory each register an implementation.

It is what IEnqueueContextAccessor takes to make a write commit with an enqueue. Application tables live in a domain data context.

Signature

namespace Trax.Effect.Data.Services.DataContext;
 
public interface IDataContext : IEffectProvider, IAsyncDisposable  // IEffectProvider is IDisposable
{
    DbSet<Metadata> Metadatas { get; }
    DbSet<Log> Logs { get; }
    DbSet<Manifest> Manifests { get; }
    DbSet<ManifestGroup> ManifestGroups { get; }
    DbSet<WorkQueue> WorkQueues { get; }
    DbSet<DeadLetter> DeadLetters { get; }
    DbSet<BackgroundJob> BackgroundJobs { get; }
    DbSet<SchedulerConfig> SchedulerConfigs { get; }
    DbSet<PersistedOperation> PersistedOperations { get; }
    DbSet<PersistedOperationHistory> PersistedOperationHistories { get; }
    DbSet<RunnerNonce> RunnerNonces { get; }
    DbSet<RecordedDecision> RecordedDecisions { get; }
    DbSet<JunctionRun> JunctionRuns { get; }
    DbSet<SnapshotDraft> SnapshotDrafts { get; }
    DbSet<EffectClaim> EffectClaims { get; }
    DbSet<Checkpoint> Checkpoints { get; }
    DbSet<SnapshotTransition> SnapshotTransitions { get; }
    DbSet<MachinePolicyFire> MachinePolicyFires { get; }
 
    int Changes { get; set; }
 
    Task<IDataContextTransaction> BeginTransaction();
    Task<IDataContextTransaction> BeginTransaction(CancellationToken cancellationToken);
    Task<IDataContextTransaction> BeginTransaction(IsolationLevel isolationLevel);
    Task<IDataContextTransaction> BeginTransaction(IsolationLevel isolationLevel, CancellationToken cancellationToken);
    Task CommitTransaction();
    Task RollbackTransaction();
    void Reset();
    DataContext<TDbContext> Raw<TDbContext>() where TDbContext : DbContext;
}
 
namespace Trax.Effect.Data.Services.DataContextTransaction;
 
public interface IDataContextTransaction : IDisposable
{
    Task Commit();
    Task Rollback();
}

From IEffectProvider it also has Track(IModel), Update(IModel) and SaveChanges(CancellationToken), which the effect runner uses to persist a run.

Members

Tables

PropertyTableHolds
Metadatastrax.metadataOne row per train run: state, input, output, timing, failure
Logstrax.logLog entries written by AddDataContextLogging
Manifeststrax.manifestScheduled jobs: train, input properties, schedule
ManifestGroupstrax.manifest_groupGroups of manifests that share dispatch settings
WorkQueuestrax.work_queueRuns waiting to be dispatched
DeadLetterstrax.dead_letterManifests that exhausted their retries
BackgroundJobstrax.background_jobDispatched runs waiting for, or held by, a worker; only in-flight work
SchedulerConfigstrax.scheduler_configThe persisted, dashboard-editable scheduler settings; zero or one row
PersistedOperations, PersistedOperationHistoriestrax.persisted_operation, trax.persisted_operation_historyPersisted GraphQL operations and their audit history
RunnerNoncestrax.runner_nonceNonces a runner accepted on signed requests
RecordedDecisionstrax.decisionEach decision a run made, written by AddDecisionRecording
JunctionRunstrax.junction_runEach step of a run, written by AddJunctionEvents. Read one run's steps in order with ForRun(metadataId).
SnapshotDraftstrax.snapshot_draftState-machine drafts, one per user and draft id
EffectClaimstrax.effect_claimRun-once state-machine effect intents
Checkpointstrax.checkpointThe state a train declared with Checkpoint<TState>(), one row per run and node, from which a later run resumes.
SnapshotTransitionstrax.snapshot_transitionEach state-machine instance's history: one row per snapshot write, deleted with the instance
MachinePolicyFirestrax.machine_policy_fireThe fires machine policies still owe: written with the transition that sets one off, deleted with the fire. Server-only

A Checkpoint row holds the run (MetadataId), the declared node (NodeId, and BranchPath inside a Parallel branch), the stored state as JSON (State) with its type (StateType), the tracks the routing steps before it took (Tracks), and the two values a resume compares with the running code: ChainHash, the declared chain's hash, and StateFingerprint, a fingerprint of the state type's serialized shape. A resume refuses when either differs. CreatedAt is when it was written. See Checkpoint.

A MachinePolicyFire row is one fire a machine policy still owes: the Policy it belongs to, the instance whose transition set it off (its row SourceRowId, its id SourceInstanceId, and the SourceRevision that transition gave it), the TargetRowId of the instance to fire once a broadcast is expanded into one row per target (null before), and CreatedAt. The store writes it in the transition's transaction, and the policy runner deletes it in the transaction that fires it. It holds no context and no owner key.

A SnapshotTransition row is one write of an instance's snapshot: the instance's row (DraftRowId), the Revision the write gave it, its Kind (SnapshotTransitionKind: Start, Command, Save, Timer or Outcome), the command's name (Trigger), the Actor (SnapshotTransitionActor: Owner, Host, Machine or Policy), FromState and ToState, when it was written (At), and the server-only InvokeToken of the run or child it started. The store writes it in the snapshot's transaction; it holds no context and no owner key. Operators read it as machineInstance { transitions }.

RunnerNonces, RecordedDecisions, JunctionRuns, SnapshotDrafts, EffectClaims, Checkpoints, SnapshotTransitions and MachinePolicyFires have default implementations on the interface, so an implementation written before they existed still loads.

Methods

MemberDescription
BeginTransaction(...)Starts a transaction, optionally at an isolation level. Returns an IDataContextTransaction to commit, roll back or dispose.
CommitTransaction() / RollbackTransaction()Commits or rolls back the context's current transaction
Reset()Clears the change tracker, so a long-lived context stops tracking what it loaded
ChangesA count of tracked changes not yet saved
Raw<TDbContext>()Casts to the concrete DataContext<TDbContext>, for EF members the interface does not surface. Throws InvalidCastException when the implementation is not that type.

Behavior

Getting one

HowLifetimeUse
Inject IDataContextScoped: one per scope, created from the provider's context factoryReads and writes inside a request or a train's scope
Inject IDataContextProviderFactory and call CreateDbContextAsync(ct)A new context per call; dispose itBackground services and anything outside a scope

Trax's services write the trax tables. A row changed outside them (a run's state, a work queue entry's status) can break the scheduler's invariants.

Example

using Microsoft.EntityFrameworkCore;
using Trax.Effect.Data.Services.DataContext;
using Trax.Effect.Enums;
 
public class FailedRunReport(IDataContext data)
{
    public Task<List<string>> TrainsFailingSince(DateTime sinceUtc, CancellationToken ct) =>
        data.Metadatas.AsNoTracking()
            .Where(m => m.TrainState == TrainState.Failed && m.EndTime > sinceUtc)
            .Select(m => m.Name)
            .Distinct()
            .ToListAsync(ct);
}

See also