Module scopes
- Comparing
- v1 to v2
- Current
- Read the document
Abstract
We I will make a resolution know which module's code it is
constructing. The container will hold keep a stack of module scopes, pushing a
binding's owner while that binding resolves and popping it afterwards,
so that everything constructed beneath it inherits the owner by recursion. The active scope , and it will be stamped onto each
Dependencystamp the scope in force onto
each dependency and Invocationinvocation as it is builtbuilds them, so that
factories and resolvers receive it without any signature changing. This
This design is the mechanism alone: what a module is is
then handed belongs to module resources.
Motivation
A module needs things that belong to it rather than to the engine,
such as its own logger channel, its own filesystem root, or a query builder bound to its own schema. Each of those needs
an answer to one question, asked question answered at the moment something is constructed: which module is this for?
Nothing can answer it today. A module's registrar is instantiated directly, before the
container exists, as RFC-0015 describes. The container is immutable cannot change once it is built. Nothing at
Nothing
at dispatch knows which module a class belongs to. There is no ambient current module held anywhere at runtime.
The binding is what carries the identity. A binding registered through a module's
EngineBuilder records the module identifier that registered it, as
RFC-0015 describes, so resolving that binding is the point at which the container can know
whose code it is about to construct.
Proposal
The container will hold the scope stack, push and pop it, and stamp the active
module scope onto what it builds. A Binding will carry the
module identifier that registered it, or none for the
engine's own bindings. A Dependency and an Invocation will each carry the scope they were
built under. The Scoped attribute will name another module's scope for one dependency.
The scope stack
The container will hold the scope stack itself, and will push onto it, pop from it, and
stamp what it builds with the module scope on top. It will be a stack rather than a a
single value, value because resolution nests: a
a scoped binding may may
depend on another module's scoped binding, and
and both scopes are live at once.
Push and pop Every push will be wrapped paired with its pop in a try/finally. A Otherwise a constructor throwing part way down a graph graph
would otherwise leave
leave the stack dirty for the remaining life rest of the worker's life. That is the same failure the The resolution stack in
stack
in RFC-0006 avoids the same failure by removing its entry however the resolution finishesends.
The Whatever state the stack is in, it will be emptied when a cycle closes, whatever state it is in, through the disposal in
the
disposal in RFC-0007. It will be emptied per cycle rather than than
per request because the vocabulary is
cycle is the container'ss own unit of work: HTTP opens one per for each request, a queue worker in a a
warm process opens one per for each job, and a scheduler opens
opens one per for each tick. A scope leaked in a long-lived process shows process
would show up as one module's channel appearing in another module's
s cycles, which is hard to trace back to its cause.
Ownership
A binding registered through a module-scoped EngineBuilder will have an owning
carry its
owner, the module identifier that registered it. A binding
the engine registers itself will carry none. That presence is will be the entire whole signal:: when the
container resolves a binding with an owner, it will push the owner for the length of the
resolution and pop it afterwards, and when it resolves one without, it will push nothing.
- A binding with an owner will push it for the duration of the resolution, and pop it afterwards.
- A binding with no owner, which is every binding the engine registers, will push nothing.
There will be no flag to opt a binding into being scope-aware. Such a flag would be true exactly when an owner exists, so it would carry no information. There will be no gate on reading a module scope either: the scope will be stamped unconditionally, so every resolver and factory will already have it.
There will be no flag to opt a binding into being aware of its scope. Such a flag would be true exactly when an owner exists, so it would carry no information. Nor will anything gate reading a module scope: the scope will be stamped unconditionally, so every resolver and factory will already have it.
The container will therefore have one behaviour rather than a set of modes: push when a binding has an owner, and pop when it is done.
Capturing a scope
A module scope will be captured when a Dependencydependency or an Invocationan
invocation is created, and
and held, rather than looked up when it is read. A nested nested
resolution moves will move the stack between a
a value being built and being consumedused, and several live live
values holding different scopes is will be the expected state, not an
state rather than an edge case.
The two will acquire it differently, because they are built differently:. A Dependency is constructed with all its
values, so it will take the scope as one more of them, alongside those
RFC-0001 gives it, and whoever builds it will supply the scope. An
Invocation is built by static factories that hold no reference to the container and so can read nothing; the container
will stamp the scope onto it afterwards, as it already does with the arguments supplied to it.
| How it acquires the scope | |
|---|---|
Dependency |
Constructed with its values, so it takes the scope as one more of them, alongside the parameter, type, name, qualifier, resolvable attribute, default and liminality of RFC-0001. Whoever builds it supplies the scope. |
Invocation |
Built by static factories that have no container reference and so can read nothing. The container stamps it after the fact, as it already does for the arguments supplied to it. |
Neither will inherit a scope from whatever caused it. A Dependency stamped X may resolve to a
binding owned by Y, at which point the container will push Y, and the Invocation that
constructs it will be stamped Y. Propagating from the parent would be wrong in exactly the case that matters.
Consuming a scope
A module scopefactory will receive an invocation , which will carry the scope. Most first-party scoped
services will be consumed along two pathsfactories, because whatever manages them will track their instances itself and neither changes a published
signature:the container will not
cache them.
- A factory will receive an
Invocation, which carries the scope. Most first-party scoped services will be factories, because whatever manages them will own their instance tracking and the container will not cache them. - A constructor parameter will become a
Dependency, which carries the scope, and be handed to aResolver.Resolver::resolve()is a contract third parties implement, as ADR-0002 records, and it will be untouched: the scope will arrive inside theDependencyit already receives.
Neither will inherit a scope from whatever caused it. A dependency stamped backups may resolve to a
binding owned by servers, at which point the container will push servers, and the
invocation that constructs it will be stamped servers. Propagating the scope from the parent would be wrong in exactly
the case that matters.
Using a scope
A module scope will reach the code that needs it along two paths, and neither will change a published signature.
A constructor parameter will become a dependency, which will carry the scope, and will be
handed to a resolver. Resolver::resolve() is a contract third parties implement, as
ADR-0002 records, and it will stay as
it is: the scope will arrive inside the dependency it already receives.
Scope and attributes
An attribute carries information about one use siteplace a dependency is used. A module scope
carries information
information about one module. Neither substitutes will stand in for the other, and both apply will apply
at once.
A logging channel attribute is will show how the worked exampletwo combine. Logging is not designed yet, and whatever designs it will will
ship the
the attribute and its resolver with no scope to compose againstcombine with, because modules do not exist yet. Once they do, the
resolver will compose the two, and read the name on the attribute will be read relative to the scope:
| Site | Attribute | Scope | Channel |
|---|---|---|---|
| Engine component | #[Channel('database')] |
none | database |
| Engine component | #[Channel] |
none | the engine's own |
| Module class | #[Channel] |
backups |
backups |
| Module class | #[Channel('audit')] |
backups |
backups.audit |
A module will never write its own module identifier at a consumption site. where it consumes something.
That is
will be the property this design protects: a module's code will not name the module.
Naming another module's scope
The attribute will give one #[Scoped]dependency parameter an explicit scope, resolving it under a named
a
named module scope rather than the ambient scope. It will exist
will
exist for a module that extends another module and needs that module's instance of something.,
such as the servers module's connection:
public function __construct(
#[Scoped(Servers::IDENT)] private Connection $servers,
) {}
This will open no hole. Modules are PHP running in one process with no isolationisolation between them, so a module wanting wanting
another module's
connection s connection can already construct one directly. The attribute will make explicit and
greppable an explicit, and searchable, an
intent that would otherwise be invisible.
It will stamp that one Dependencydependency and push nothing. A parameter attribute silently rescoping that silently
changed the scope of an arbitrarily deep
subtree is deep graph would be hard to reason about, and what this targets it will be meant for is leaf factories factories
at the leaves, with no onward dependenciesdependencies of their own, so the difference
difference rarely shows. If a binding
with an owner turns up during that
that resolution, ordinary ownership pushing it will apply push its
owner as usualany other would. Pushing can be added later; it
, where it could not be removedtaken away.
#[Scoped] The attribute will carry two constraints:
- It takes a constant, never a literal.
AThe constantinheritswill be covered by thedrift validationcheck under Rules below, so a typo will be fatal rather than a wrong instance. - The named scope must be a
declared dependency ofmodule dependency themodulemodule declares.Cross-module couplingCoupling between modules belongs inthethe manifest rather than buried in a constructor, anddeclaringdeclaring itmeanswill mean a missing targetwill beis found when the module boots rather than when something resolves.
There will be no attribute for the opposite case, a parameter opting out of the the
ambient scope. Unmodular is will be the name
name reserved for it, because every shorter word word
is already taken: . Unscoped already means something else for a #[Collect]
method in in
RFC-0015, Platform collides with the panel context of that
name, Core is ambiguous when
when core features are themselves modules, as as
ADR-0013 records, and Global
reads badly in PHP. It is named here so that
it is not renamed later, and will be added when a parameter actually needs it.
Where a scope is pushed
| Site | Identifier from |
|---|---|
| Resolving a binding with an owner | The binding. |
| Router and action dispatch | The owning identifier the collector handler recorded when it collected the route. |
| A queue worker | The job's payload, if it carries one. |
| Register and boot | The manifest, which whatever drives the module lifecycle already holds. |
Anything resolved outside these will run with no module scope. That residue will be accepted rather than closed.
A module scope will be pushed in four places, each taking the module identifier from what it already holds:
- resolving a binding with an owner, from the binding;
- dispatching a route to its action, from the owner the collecting handler recorded when it collected the route;
- a queue worker running a job, from the job's payload, where it carries one;
- the register and boot phases, from the manifest, which whatever drives the module lifecycle already holds.
Anything resolved outside these will run with no module scope. That gap will be accepted rather than closed.
An empty stack
Nothing will error throw when the stack scope stack is empty. Whether that an empty stack matters belongs will
belong to the service, not service rather than to the container,
, because services will differ:. A logger will tolerate it: no
module scope will mean the engine's own channel, and the loss
will be cosmetic. A query builder bound to a schema will not: no scope will mean querying the wrong tables, silently. So
the schema builder's factory will check the scope and throw, and the container will stay ignorant of which services care
about being unscoped.
- A logger tolerates it. No module scope means the engine's own channel, and the loss is cosmetic.
- A query builder bound to a schema does not. No scope means querying the wrong tables, silently.
So the schema builder's factory will check the scope and throw, and the container will stay ignorant of which services have opinions about being unscoped.
In debug, a class resolved under a module's autoload prefix with an empty stack will raise a warning, which surfaces a missing push site while developing at no cost in production.
In debug, a class under a module's autoload prefix resolved with an empty stack will raise a warning. That will show up a missing push site while a module is being developed, and will cost nothing in production.
Memoisation
Stamping a module scope will cost nothing, because a Dependencya
dependency is not memoised and
and there is no cached structure for a scope to invalidate, as
ADR-0020 records.
A cached resolution plan would change that. Every entry in one would be depend on the scope-dependent, so a plan could not be
shared be shared
between resolutions running under different scopes. Nothing proposes such a plan and the module lifecycle has
has no compile compile
step, so this is recorded as a conflict to be aware of rather than something given up.
Rules
- When one module
Yresolves a bindingregistered byanother moduleXregistered, the scope will beXthe registering module's. The binding's codeis Xwill be that module's code, soX'sits logger, its schema and its filesystemarewill be the rightanswersones. - A module's declared identifier constant will be
validatedchecked against its manifest at discovery.A moduleA module whosetwotwo disagree will fail to load. That will turn drift from a silentlywrongwrong schema into a module that refuses to start,and it is whatand willletbe what lets theattribute take a constant safely.#[Scoped] Cross-module accessAccess across modules will be policed by capabilities, in the components that care. Routing will do this withCrossRoutes, as RFC-0015 describes. The container will not be an enforcement layer.
Out of scope
- Module resources. What a module declares, what is provisioned for it and what it is
handed. This design will only
makesmake a resolution able to say whose code it is. - Enforcement. The container will not decide whether one module may reach another's things.
- The
attribute. Named above so that it is not renamed, and added when a parameter needs it.#[Unmodular] - Pushing from the
attribute.#[Scoped] - Logging. The channel attribute
is a workedwill be an example, not a design. - Thread safety. The open question below covers it.
Alternatives considered
The decisions this This design rests on are recorded separatelyADR-0002,
dependencies selecting their instance through parameter attributes, with the alternatives each one rejected:and
ADR-0020, resolution data not being memoised per
parameter.
A single current scope rather than flag marking a stackbinding as aware of its scope. We I rejected this because a scoped bindingthe flag would be true exactly when an
owner can
depend on another module's scoped bindingexists, and so would say nothing the value has to nestowner does not.
A flag marking Looking the scope up when a binding scope-awarevalue is read, rather than capturing it when the value is built. We I rejected this because the flag would be true exactly when an
ownerbecause
a nested resolution existsmoves the stack in between, and so would say nothing the answer read later is not the one
that was true when the owner does notvalue was created.
Looking the scope up when Inheriting a value is read, rather than capturing it when scope from the value is builtthat caused it. We I rejected this
this because a nested resolution moves dependency stamped with one module
resolving to a binding owned by another must produce the stack in betweensecond, so the answer read later which is not the
answer that was true when precisely the value was createdcase inheritance would get
wrong.
Inheriting Pushing a scope from the value that caused itScoped attribute. We I rejected this because a Dependency stamped X resolving
parameter attribute that silently changes the
scope of an arbitrarily deep graph is hard to reason about. Pushing can be added later if a binding owned by Y must produce Y, which is precisely the case inheritance would get wrongneeds it, and could not
be taken back.
Pushing a scope from #[Scoped]Throwing on an empty stack. We I rejected this because a parameter attribute that silently rescopes an
arbitrarily deep subtree services disagree about whether an empty stack is hard to reason about. Pushing can be added later if a case needs itproblem, and could not be
taken backso
the decision belongs to each service rather than to the container.
Erroring on an empty stack. We rejected this because services disagree about whether an empty stack is a problem, so the decision belongs to each service rather than to the container.
No other alternatives were weighed.
A single current scope rather than a stack. I rejected this because a scoped binding can depend on another module's scoped binding, so the value has to nest.
Backwards compatibility
Dependencywill take one more constructor argument, so everything that builds onesupplieswill supply the scope.Invocationwill carry a scope the container stamps, which its static factories do not supply.
Nothing else will change. Resolver::resolve() will be untouched, and no binding needs editing: a
binding with no owner will behave exactly as it does today.
Open questions
- Whether queue workers run as an in-process thread pool. A scope stack on a shared container is mutable state across concurrent resolutions, and interleaved pushes and pops would corrupt it. A container per thread makes the question moot; a shared container needs the stack to be thread-local. Nothing in the record says workers are threaded, and the only concurrency anywhere in it is concurrent fragment requests and concurrent index creation. It belongs to the bootstrap design, where the driver contract lives.
Whether queue workers run as an in-process thread pool
A scope stack on a shared container is mutable state across concurrent resolutions, and interleaved pushes and pops would corrupt it. A container per thread makes the question moot; a shared container needs the stack to be thread-local. Nothing in the record says workers are threaded, and the only concurrency anywhere in it is concurrent fragment requests and concurrent index creation. It belongs to the bootstrap design, where the driver contract lives.
Changelog
- : Reworded in the readable house style, and the project's own vocabulary linked to the glossary. The design is unchanged.
- : Rewrote the document in full, with no change to the design.
Sources
- Issue #70, Engine - Container - Module scopes, , edited three minutes later the same day: that
therethere isnono ambient current module and why, the binding being the identity carrier, the scope stack and why it isaa stack,,try/finallyand the dirty stack it prevents, emptying at the cycle boundary rather than therequestrequest boundaryandand the leak it avoids, ownership as the whole signal with no opt-in flag and no gate on reading,thethe emptystackstack belonging to the service with the logger and schema builder as the two cases, the debug warning,, capture atcreationcreation with the two values acquiring it differently and neither inheriting, consumptionthroughthrough factories and resolverswithwith no signature changed, scope and attributes being orthogonal with the channel table,,#[Scoped]with itstwotwo constraints and why it pushes nothing,Unmodularand the four names it was chosen over,, the push sites andthethe accepted residue, the three rules, the memoisation conflict, every boundary, andthethe thread-pool question. - Issue #39, Engine - Modules - Collectors, , with no edits:
Unscopedalready meaningsomething differentsomething different for a#[Collect]method, which is why the opposite case needs another name. - Issue #47, Engine - Container - Circular dependency detection, original text of
, with no edits:in its edit history: popping only onthethe success path leaving stale entries after any failure, which is the precedent for wrapping pushandand pop. - Issue #67, Engine - Sessions, , and issue #59, Engine - Database - Schema: tables, indexes and DDL
objects, : concurrent fragment requests and concurrent index creation, the only concurrency anywhere
in thein the record, which is why the thread-pool question is open rather than answered.
Source rfc/0016-module-scopes.md · commit 9444a99 · published