mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

Linear resource patterns (P1-21 / P1-22)

Resource-oriented services — transactions, file leases, lock tokens,

Source: mjdi/docs/linear-patterns.md

Resource-oriented services — transactions, file leases, lock tokens, external handles — are the natural fit for linear services: constructed in place, consumed exactly once, destroyed explicitly. This page is the pattern guide; examples/linear_resources is the runnable, tested showcase (transactions, a file lease with a failing use, a lock token, and a shared pool that outlives them).

The pattern

from mjdi import Container, DependencyResolver, Inject, LinearService, Registry, mjdi_linear

@__annotation(mjdi_linear)
struct DbTransaction(LinearService):
    var pool: Inject[ConnectionPool]     # nested (non-linear) dependencies

    def __init__(out self):
        self.pool = Inject[ConnectionPool]()   # unresolved default

    def __init__[R: DependencyResolver](out self, mut r: R) raises:
        # Two-phase construction with the linear error-path discipline:
        # initialize every field, then populate; on failure destroy the
        # half-wired instance before re-raising.
        self.pool = Inject[ConnectionPool]()
        try:
            self.populate_fields[R](/docs/0.10.0/r)
        except e:
            self^.destroy()
            raise e

    def commit(self, amount: Int) -> String:
        return String("commit:") + String(amount)

    def destroy(deinit self):
        print("destroy: DbTransaction")   # the sanctioned release
def commit_txn(txn: DbTransaction) raises:
    # Single consumption: the visitor reads the service; mjdi destroys
    # it right after this returns.
    print("use:", txn.commit(100))

app.resolve[DbTransaction](/docs/0.10.0/commit_txn)

The guarantees in play

  • Construction in place — the resolver-taking constructor runs in the caller's storage; the value is never moved or copied.
  • Single consumption — the visitor is a thin function taking the service by immutable borrow; it can read but not transfer.
  • Correct destruction, exactly once — destroy runs immediately after the visitor returns. A second destroy is a compile error (compile-fail fixture cf_linear_double_destroy: use of uninitialized value).
  • Error-path cleanup — a visitor that raises mid-use still gets the destroy: mjdi catches, destroys, and re-raises (tests/ and the example pin the error-path marker).
  • Nested dependency cleanup — the linear service's own Inject dependencies resolve through the container; destroying the linear resource does not release them (the shared pool stays cached and alive across transactions — the example prints pool-alive: True after two consumed transactions).

Destruction diagnostics (P1-22)

Failure modeWhat happensWhere it is pinned
Constructor failureThe two-phase discipline destroys the half-wired instance and re-raisesExample + tests
Visitor failureDestroy runs on the error path, then the error propagatesexamples/linear_resources (failing lease), tests
Double destruction attemptCompile error — the consumed value is uninitializedcf_linear_double_destroy
Incorrect consumption (by-value resolve)Compile error — the Movable & Deinitable bounds exclude linear types from the value-returning overloadcf_linear_resolve_non_linear (family)
Destruction exactly onceTraced as linear-destroy on exactly one path per usetests/test_example_linear_resources

Compiler-represented failure modes (the table above) are enforced, not policed at runtime: a linear value that has been destroyed cannot be used again because the compiler rejects the read. This is the strongest available guarantee and it is documented as such rather than simulated.

When to use the pattern

Reach for a linear service when the resource has exclusive ownership semantics you want the compiler to enforce — acquire, use once, release exactly once. When sharing is fine, use a singleton; when per-request isolation matters, use a scope (see Scopes and lifetimes).