Repository navigation
Replies: 1 comment
|
This is implemented on main now and available in latest snapshots, would love if folks could give it a spin! |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Motivation
This MEEP proposes a new API for graph initialization and shutdown hooks to Metro.
These are ordinary functions implemented by the user. Metro calls them during graph initialization and shutdown and supplies their dependencies. That also lets Metro validate startup and shutdown work as part of the dependency graph. Contributed interfaces can bring their own callbacks too.
Proposed API
Graphs opt in through one of two interfaces:
The synchronous interface extends Kotlin's
AutoCloseable, giving it the usualusesupport.SuspendCloseableGraphallows cleanup to suspend.The callback annotations are
@OnGraphInitand@OnGraphClose:Both graph interfaces and both callback annotations require experimental opt-in.
Metro generates
close()and implementing it manually is an error. User-implemented cleanup only goes in the annotated functions.Annotated callbacks must have implementations and return
Unit. A graph can have any number of callbacks. Parameterless callbacks are fine too:Init callbacks run after the graph's ordinary initialization finishes. Dependencies requested by callbacks are initialized as needed. Init returns only after every callback completes successfully.
Initialization stops at the first failure and reports it to the caller. Metro doesn't run close callbacks to undo partial initialization. Applications are responsible for handling resources acquired before the failure. Cancellation during startup also aborts creation without automatic cleanup.
Contributions
A contributed interface can bring its own callbacks:
Metro checks that the assembled graph implements one of the closeable interfaces (i.e. contributions don't have to extend either interface to declare callbacks).
Inherited callbacks run once, including through diamond inheritance. An override must repeat the callback annotation. Metro invokes the override once. Calling an annotated
superfunction is prohibited by the direct-call restriction.Callbacks run sequentially. Their order isn't guaranteed. A future version could add callback priorities, similar to the existing priority support for contributions.
Suspending initialization
Graph startup can suspend because an init callback is suspending:
It can also suspend while resolving a callback parameter, even when the callback itself is synchronous:
Here, resolving
Databasesuspends before Metro callsinitializeDatabase(). This can remain non-suspending however ifDatabaseis wrapped in a provider (i.e.suspend () -> Database).A graph whose initialization requires suspension must declare a graph factory whose single abstract method (SAM) is
suspend:Obtaining the factory remains synchronous, but invoking the SAM obviously would then require a suspend context.
The call to
factory.create(config)returns only after all init callbacks complete successfully. The caller can use the returned graph immediately.Metro validates that SAM signature against the assembled graph. If any initialization suspends, a missing factory or non-suspending SAM results in an error diagnostic identifying the callback or dependency path that requires suspension.
A graph with only suspending close callbacks can still be created synchronously.
Graph extensions follow the same rule through
@GraphExtension.Factory. A parent can expose the factory synchronously, and callers invoke its suspend SAM to create the child. A property accessor can't directly create a child whose initialization suspends (since properties cannot suspend). Parents that implement an extension factory directly would also implement the suspend SAM for these children.Dynamic graph factories follow the same rules. Metro validates each concrete dynamic graph against its declared factory SAM because binding replacements can introduce suspension into callback arguments.
Injected callback parameters
Callback parameters use normal dependency resolution. They receive the same dependency checks as graph accessors.
A missing-binding diagnostic points to the callback parameter that requests the binding and shows which type is missing:
Close parameters have two traps worth calling out:
Databasehas never been requested, this can create it during shutdown.Normal injection semantics stay the same. Warnings flag these common mistakes.
Unscoped scalar parameters
Metro warns by default when a scalar parameter of
@OnGraphInitor@OnGraphCloserequests an unscoped binding. A direct request such asServicecan create an instance that's discarded after the callback. Other requests can receive different instances.Deferrable requests such as
() -> ServiceandLazy<Service>are allowed without this warning (including their suspend forms).A type supplied through a graph input parameter (i.e.
@Provides) counts as implicitly scoped for this warning. The graph reuses the supplied instance, so the type doesn't need a scope annotation.You can suppress the warning if the provider returns an externally cached instance or you intentionally want a temporary instance for the callback.
Bindings used only during
close()There's a separate warning for bindings that are only reachable from close callbacks:
The warning doesn't apply if a binding can be requested outside close callbacks, even indirectly. Requests from init callbacks or child graphs count as uses too.
This warning excludes externally supplied values, including bindings obtained through
@Includesaccessors.These are separate warnings with independent suppression. An unscoped scalar parameter can trigger the first warning even when the binding is used elsewhere. A scoped binding used only during close can trigger the second warning. A parameter that meets both conditions receives both warnings.
These checks identify where a binding can be requested. They can't determine whether an accessor is ever called or what the user's code does with the result.
Closing and cached bindings
The first call to
close()marks the graph closed and starts cleanup. Later calls return immediately, including calls made while cleanup is still running. Close callbacks run at most once.The graph stays closed if cleanup fails. The error reaches the caller immediately, and the remaining cleanup doesn't run. This includes failures while resolving a close callback's parameters or closing a child. Another call to
close()won't retry cleanup.Cancelling the caller doesn't interrupt suspending cleanup. An exception thrown by cleanup still stops it immediately and propagates the exception.
For now, closing doesn't block ordinary dependency requests after close. Creating a graph extension through a closed parent however does fail. Callers are responsible for ending use of the graph before closing it.
A later request can also initialize a binding for the first time. The absence of an automatic check doesn't make using the graph after cleanup safe. Whether a later version makes closed graphs unusable is an open question below.
Closing doesn't clear cached bindings. Holding onto a closed graph or one of its providers can keep those objects alive, so callers need to release those references when they're done with the graph.
Closing the graph doesn't invalidate objects you've already received. Whether those objects remain usable depends on their own cleanup behavior. User-owned state remains the caller's responsibility.
Graph extensions and factories
Closing a graph also closes its child extensions, provided both graphs support lifecycle callbacks. Children close before the parent's close callbacks run. This continues down the tree: each child closes its own children.
A child can also be closed independently:
Closing a child yourself removes it from the parent's cleanup once that attempt finishes, even if it fails. Until then, the parent holds onto the child even if you drop your own reference. It's a point worth emphasizing: If child graphs are closeable, you must call close() on them in order for them to be GC'd because the parent graph will hold on to a reference to them until they or the parent are closed.
A child is included in the parent's cleanup once its initialization succeeds, before it's returned to the caller. This also applies to children created through graph accessors or factories implemented by the parent. Passing an existing graph as an input doesn't transfer responsibility for closing it.
You can't create a child after its parent closes. Having obtained the factory earlier doesn't change that:
A child with suspending cleanup needs a
SuspendCloseableGraphparent. Metro rejects aCloseableGraphparent for that child.SuspendCloseableGraphalso supports children with synchronous cleanup.Wait for child creation to finish before closing the parent. If you're closing a child yourself, let that finish too. The order in which sibling graphs close (when closed by the parent's own close() call) isn't guaranteed.
Coroutine ownership and resource cleanup
Scoped suspend bindings currently initialize in the caller's coroutine. Graphs don't own those coroutine jobs.
This proposal doesn't add automatic cancellation or disposal of initialized bindings (i.e. if you have a
CoroutineScopebinding on your graph). You can cancel or close resources you own in a callback.Automatic disposal would need a separate ownership contract. The same applies to synchronously created resources.
Tracing
Tracing records how long graph initialization and close take. Each callback is recorded separately.
Since the graph doesn't own the tracer and extensions currently share the parent's tracer, closing a graph still leaves the tracer open and left to the user.
A span covering the graph's whole lifetime could be added in a future version. Whoever owns the tracer is still responsible for flushing and closing it.
Direct calls
Metro reports errors on direct calls to lifecycle callbacks:
Open questions
???
Making closed graphs unusable
Should a later version reject dependency requests after the graph closes? What happens to a lazy value obtained before close that's already initialized?
Should that also stop assisted factories from creating objects? An assisted factory whose arguments all come from the caller may have no graph dependencies. Tying its lifetime to the graph would still restrict its use.
How would automatic invalidation interact with requests already running when close starts? These questions are outside the initial feature. Callers are responsible for ending graph use before close.
All reactions