mjdi docsv0.10.0latest
Linear services
Linear services are mjdi's answer to resources that must be used exactly
Source: mjdi/docs/linear-services.md
Linear services are mjdi's answer to resources that must be used exactly
once and released explicitly: leases, pooled connections, transactions,
locks, scoped handles. They are built on Mojo's linear types — structs
that opt out of Movable and Deinitable — and they are recognized by
mjdi through the @__annotation(mjdi_linear) compile-time annotation.
This page documents behavior implemented and tested on Mojo 1.2.0
(build 2016d0cd); the annotation-reflection surface it rests on is
verified by experiments/exp7_annotations.mojo.
The language-level contract
Mojo gives every struct automatic destruction and move support by default
(all structs implement Deinitable and Movable). A struct can opt out of
both, which turns it into a linear type:
- it cannot be copied (copy was already opt-in via
ImplicitlyCopyable), - it cannot be moved (no
Movable, so no transfer of ownership), - it is not destroyed implicitly (no
Deinitable), so destruction must happen through an explicit method call:
@__annotation(mjdi_linear)
struct DbLease(
Deinitable where (False, "DbLease must be destroyed explicitly with destroy()"),
Movable where False,
LinearService,
):
...
The where (False, "...") clause is what turns the trait conformance into
an opt-out, and its message is what the compiler reports if the value
would be destroyed implicitly. The consequence for a DI library is
fundamental: every regular provider hands the instance out by value
(which requires a move), and every cached lifetime stores and copies the
canonical instance (which requires Copyable). A linear type can do
neither — so linear services get their own registration kind, their own
lifetime, and their own consumption path.
Declaring a linear service
A linear service is a struct that carries all three of:
- the annotation —
@__annotation(mjdi_linear)above the struct.mjdi_linearis a comptime value exported by mjdi (typeLinearMarker, carrying the canonical literal"mjdi:linear"as itslabel); the decorator accepts any comptime value, and mjdi recognizes the marker by its type, - the
LinearServicetrait conformance, - the linear opt-outs —
Deinitable where (False, ...),Movable where False.
from mjdi import Container, Inject, LinearService, Registry, mjdi_linear
@__annotation(mjdi_linear)
struct DbLease(
Deinitable where (False, "DbLease must be destroyed explicitly with destroy()"),
Movable where False,
LinearService,
):
var pool: Inject[DbPool]
var opened_at: Int
def __init__(out self):
self.pool = Inject[DbPool]()
self.opened_at = 0
def __init__[R: DependencyResolver](out self, mut r: R) raises:
self.pool = Inject[DbPool]()
self.opened_at = 0
try:
self.populate_fields[R](/docs/0.10.0/r)
except e:
self^.destroy()
raise e
Dependencies are declared with Inject[T] fields exactly as for regular
services, and they must be non-linear: an Inject marker stores the
resolved value, which a linear type forbids, so the compiler rejects
Inject[SomeLinearService] outright.
LinearService extends Defaultable and declares three members:
-
__init__(out self, mut resolver)— the resolver-taking constructor overload, required with no default implementation: it constructs the instance in place (no move, no copy). A trait-default body cannot default-initialize an explicitly-destroyedSelfon the current compiler, so each linear service spells its construction out. TheInjectable-analogue two-phase shape is the recommended body: initialize every field by hand, then resolve everyInjectfield withself.populate_fields[R](/docs/0.10.0/r), wrapped in the linear error-path discipline (an explicitly-destroyed value must be consumed on every path out of a raising function):def __init__[R: DependencyResolver](out self, mut r: R) raises: self.pool = Inject[DbPool]() self.opened_at = 41 try: self.populate_fields[R](/docs/0.10.0/r) # resolves every Inject field in place except e: self^.destroy() raise eInitialize every field before the first raising call so
destroyalways sees fully initialized storage. -
populate_fields[R](mut self, mut r: R) raises— provided by the trait (the linear analogue of the scanner'spopulate_inject_fields): it walksSelf's fields through reflection and assigns eachInjectmarker its resolved wrapper. It runs on the receiver (amutmethod), so the linear value never escapes into a generic callee — the current compiler rejects passing an explicitly-destroyed type bymutinto generic code, which is why the movable-service scanner helper cannot be reused here. -
destroy(deinit self)— required, no default. Mojo never destroys a linear type implicitly, so this method is the only sanctioned release path. mjdi invokes it immediately after the single use (and on the construction error path, if wiring fails).
Registering
comptime app_registry = (
Registry()
.register[DbPool, provider_scope.singleton]()
.register[DbLease]()
)
The second call selects the linear overload of register — there is no
dedicated registration method. Overload resolution does the routing:
- the regular overload —
register[T: Movable & Deinitable, scope]— carries the clausewhere not conforms_to(T, LinearService), so a linear service never matches it; - the linear overload —
register[T: LinearService]— carries theLinearServicetrait bound, so an ordinary service never matches it.
The two candidates are provably disjoint, and the same method name
registers both kinds. register[DbLease] requires the annotation (a
LinearService conformer without @__annotation(mjdi_linear) is
rejected with a dedicated diagnostic — the annotation is what makes the
type recognizable to tooling and to mjdi's compile-time queries) and
rejects duplicates like every other registration.
Linear services have exactly one lifetime: constructed fresh per use
(the linear analogue of transient). No other lifetime can apply:
register[T, provider_scope.singleton]caches a canonical instance and hands out copies — impossible withoutCopyable,register[T, provider_scope.scoped]caches per scope — same objection,register_value[T]stores and copies the value — same objection,register_factory[T, f]returns the product by value, which requires a move — impossible withoutMovable,register_aliasresolves through a by-value provider — same objection.
All of those paths are closed by the type system itself: their
Movable & Deinitable bounds exclude linear types, so the compiler rejects
them before mjdi's own diagnostics apply. The linear overload of
register is the only door in, and LinearProvider — the descriptor it
installs — is the only provider kind that constructs its service in place.
Consuming: container.resolve[T](/docs/0.10.0/visitor)
A linear service cannot be resolved by value — the value-returning
overload of resolve hands the instance out through a move, and its
Movable & Deinitable trait bounds reject linear types outright (a linear
type conforms to neither trait). Instead, resolution goes through the
visitor overload of the same method:
def with_lease(lease: DbLease) raises:
print("lease opened at", lease.opened_at)
lease.query("select 1")
def main() raises:
var app = Container[type_of(app_registry)]()
app.resolve[DbLease](/docs/0.10.0/with_lease) # construct → lend → destroy
The visitor overload of resolve performs three steps, in order:
- Construct —
var instance = T(self)invokes the service's resolver-taking constructor, which builds the instance in the overload's own storage, resolving itsInjectfields through the container. If construction raises, the constructor's error path has already destroyed the half-wired instance before the error propagates. - Lend — the visitor receives the service as a borrowed reference (Mojo's default argument convention for non-movable types). The visitor is a thin, capture-free function; it can read the service and call its methods, but it cannot store, return, or transfer it.
- Destroy — immediately after the visitor returns, mjdi calls
destroy(deinit self)on the instance (consuming it with the transfer operator). If the visitor raises,resolvedestroys the instance on the error path before re-raising — a linear value never outlives its single use. The release is deterministic and visible: whateverdestroydoes (close the connection, unlock, print) happens beforeresolveunwinds.
Calling resolve[T](/docs/0.10.0/visitor) twice constructs two independent instances —
there is no caching at any level. Each call is a complete
construct-use-destroy cycle.
Compile-time guarantees
| Rule | Enforced by |
|---|---|
Linear services enter the graph only through the linear overload of register | Movable & Deinitable bounds on every other registration path |
The linear overload of register requires the mjdi_linear annotation | reject_unannotated_linear comptime assert, re-checked in LinearProvider.validate_with (compile-time registry chains resolve without running method bodies, so validation is the reliable enforcement point) |
| Linear services cannot be registered twice | duplicate check over the relaxed-bound chain query |
| Linear services cannot be resolved by value | resolve's Movable & Deinitable bounds (compiler rejection) |
Linear services cannot be injected as Inject fields | Inject's Movable & Deinitable bound (compiler rejection) |
The visitor overload of resolve requires a LinearService-conforming, annotated, registered T | the T: LinearService trait bound plus two comptime asserts in Container.resolve |
Every mjdi-diagnostic rejection in the table has a compile-fail fixture in
tests/compile_fail/ (cf_linear_*.mojo) asserting the exact message; the
trait-bound rejection is demonstrated by
tests/compile_fail/cf_linear_resolve_non_linear.mojo and the bound-level
behavior documented in docs/diagnostics.md.
The linear service's own dependencies are validated like any class
provider's: LinearProvider.validate_with runs the standard graph walk
(missing providers, cycles, lifetime relationships) over the linear
service's Inject fields, so a linear service with an unregistered
dependency fails compilation at container construction.
Introspection
Linear registrations answer the relaxed-bound query provides_any[T]()
(the regular provides[T] cannot even be called with a linear type). The
linear provider reports the class_provider kind — it constructs through
the service's declared contract — and the transient lifetime — it
constructs fresh per use:
comptime provides = type_of(app_registry).provides_any[DbLease]() # True
The regular movable-bound introspection (scope_of, kind_of with the
linear type as the argument) is not callable for linear types by the same
bound reasoning as resolve.
Limitations
- Borrow-only visitors. The visitor receives the service by immutable borrow; it cannot hand the service to longer-lived code, return it, or transfer it. That is the linear contract working as intended — a linear value has exactly one use.
- Error-path discipline is spelled out per type. A raising function
that owns a linear value must consume it on the error path; the compiler
enforces this ("value was not consumed when an error is thrown"), and
the recommended constructor body and the container's visitor path both
follow it.
destroymust therefore tolerate a partially wired instance (reading an unresolvedInjectmarker aborts with mjdi's standard diagnostic). create-style custom construction is per-type. UnlikeInjectable, there is no cross-type construction override protocol beyond writing the resolver-taking constructor body on the service itself.- Third-party linear types. The linear contract requires conforming to
LinearServiceand annotating the struct, which is only possible for types you own. Wrap foreign resources in a linear service you control.