Affordances¶
Some operations are impossible right now as a fact about the world rather than about the caller: an archived note cannot be renamed, refunds are closed while the books are. An affordance says so on the operation, once, so every transport reads the same rule. A call is refused with a stable code beside the sentence, and a transport listing operations before anyone calls them can leave out one that no call could pass.
seeds = DEFAULT_POOL_SEEDS.extend(
read_only=lambda: getattr(settings, "NOTES_READ_ONLY", False),
)
rename_spec = ServiceSpec(
service=rename_note,
permissions=[IsOwner()],
validator=DataclassValidator(Rename),
instance_selector_spec=rename_note_spec.instance_selector_spec,
presenter=DataclassPresenter(NoteOut),
affordances=[
Affordance( # a condition on nothing in particular: a callable over the seeds
code="notes_read_only",
reason="Notes are read-only during maintenance.",
when=lambda *, read_only: not read_only,
),
Affordance( # a condition on the row: an ORM expression, answered in SQL
code="note_archived",
reason="An archived note cannot be renamed. Restore it first.",
when=Q(archived=False),
),
],
idempotent=True, # renaming twice to one title leaves what renaming once did
)
ServiceSpec's
affordances takes a sequence of conditions, each an
Affordance
with three fields:
codenames the rule, never the state that tripped it, and does not change when the sentence is reworded. It is what a transport or a client branches on.reasonis the sentence people and models both read, and the message of the refusal. Say what is not possible and, where it helps, what would make it possible.whenis true when the operation is available.
Not a fact about the caller: that is permissions, which is always checked
first, so a principal who may not see a row is never told what state it is in.
A translated reason¶
A translated project declares its sentences at import time, before any request
has a language, so reason also takes a lazy string:
from django.utils.translation import gettext_lazy as _
Affordance(
code="note_archived",
reason=_("An archived note cannot be renamed. Restore it first."),
when=Q(archived=False),
)
It is kept unevaluated on the declaration and resolved wherever the kernel hands
an answer out - the answers for each row, the refusal a call raises, the
affordance unmet_operation_affordance returns - in the language active there,
so every reason a caller receives is a str and no transport translates.
code stays a plain string: it is what clients branch on, in every language.
A lazy reason that resolves to an empty string is refused with
ImproperlyConfigured where it is handed out, since it cannot be refused before
it has a language.
Two kinds of condition¶
when's type decides which kind it is. It is derived, never declared, so it
cannot drift from what it describes:
- An ORM boolean expression - a
Q, anExists, a lookup - is a condition on the row. It reads exactly asNote.objects.filter(when)does, relations included, and is answered in SQL: every condition on the row in one query, however many are declared. ANULLis not true. - A callable is a condition on nothing in particular. It is called with
the pool seeds it names -
user,progressand any registered pool seed, likeread_onlyabove - and never with the call's target, its validated values or a client's argument: the caller does not get to decide whether the operation is available. Its result is read for truth, so a callable that returns nothing means unavailable. It is sync-only and never awaited: an answer still to be awaited is refused withImproperlyConfiguredrather than read as met, since a coroutine is truthy.
A Python callable over the row is refused. A rule that has to run once per
row turns every list reporting availability into a query per row, and
prefetching does not fix it. A rule the ORM cannot express is not an
affordance: it stays in the service, which raises a
ServiceConflict
and advertises nothing.
Refused where it is written¶
Every mistake below raises ImproperlyConfigured when the spec is built, so it
fails at import rather than on the first call through a transport that never
asked:
- a
codethat is not a non-empty string, or areasonthat is neither a non-empty string nor a lazy one; - an ORM expression that is not boolean, such as
F("title"); - a callable naming
data,instance,collection,resultorqueryset, the names dispatch seeds per call; - a
whenthat is neither an expression nor a callable, or is an async callable - anasync def, an object whose__call__is one, or an async generator function; affordancesthat is not a sequence - a singleAffordance, a set whose order would decide which refusal a caller sees, a generator the first call would exhaust;- an entry that is not an
Affordance, or a code declared twice; - a condition on the row on an operation with a
collection_selector_spec, which has no single row to answer it against.
Offering an operation¶
A transport that lists operations before anyone calls them - an MCP server
building its tool list, an agent assembling its next toolset - asks
unmet_operation_affordance
for the first callable condition not met now, or None.
OPERATIONS = {"list_notes": list_notes_spec, "rename_note": rename_spec}
def tools_for(user: Any) -> dict[str, str | None]:
"""Each operation a transport could offer, with the code of what withholds it."""
pool = base_pool(user=user, seeds=seeds)
tools: dict[str, str | None] = {}
for name, spec in OPERATIONS.items():
unmet = unmet_operation_affordance(spec, pool, reserved=seeds.reserved)
tools[name] = None if unmet is None else unmet.code
return tools
Conditions on the row are skipped without a query, because at list time there
is no row; they go on being answered at the call. A
SelectorSpec
answers None.
operation_affordances
returns the conditions that would be asked, so a transport can skip building a
pool when there are none.
Build the pool the way the call's would be:
base_pool with the same
seeds=, and reserved=seeds.reserved beside it, which is required: a default
would ask a condition with none of the registered seeds, so one reading a
registered seed would fail at describe time though dispatch serves it. A condition that raises propagates: one
that cannot be answered is not a no.
The answer is advisory. An operation listed a moment before a condition flips is refused when it is called, with the code this would answer if asked again then. A condition driven by a clock has no event, so nothing announces the moment it flips.
On an event loop, await
aunmet_operation_affordance
instead. It gives the same answer, with every condition asked in one
sync_to_async hop, since a condition may query; a spec with nothing to ask at
list time costs no hop at all, and most declare nothing.
Enforcing at the call¶
dispatch and
adispatch answer a
service spec's affordances themselves, after object-level authorization and
the Validator and before the run's transaction opens. The first one not met
refuses the call with
ActionUnavailable,
carrying its reason as the message and its code, and the service never
runs. A callable condition sees every registered seed, and whatever a
transport seeds per call, such as progress. A selector spec's affordances refuse nothing: they are
answers about each row.
def rename(user: Any, pk: int, title: str) -> Note:
result = dispatch(
rename_spec, principal=user, arguments={"pk": pk, "title": title}, pool_seeds=seeds
)
return result.value
enforce_affordances
is that step, exported for a transport that runs a service itself. It calls it
after authorization and validation and before the service, with the pool
seeds' reserved set, which is required: a default would ask a condition with
none of the registered seeds, so one reading a registered seed would fail on a
transport running the service without dispatch though dispatch serves it. It
also takes the call's call_context=, so a condition naming it is
handed the dict the call's other stages share (the parameter, else one the
pool carries, else a fresh one; two different dicts are refused):
def rename_step(user: Any, note: Note, title: str) -> Note:
"""One step of a chain that resolved its row itself and runs the service in hand."""
grant = authorize(rename_spec, user)
authorize_target(rename_spec, user, note, grant=grant)
data = bind_arguments(rename_spec, {"pk": note.pk, "title": title}, principal=user, target=note)
pool = base_pool(user=user, seeds=seeds)
pool.update({**data, "data": data, "instance": note})
enforce_affordances(rename_spec, pool, instance=note, reserved=seeds.reserved)
return rename_spec.service(**resolve_callable_kwargs(rename_spec.service, pool))
rename_step is one step of a chain that resolved its row itself and runs the
service in hand: it builds the pool the service will receive, the call's
arguments included, and enforces the affordances against that pool.
A transport running a service from an event loop awaits
aenforce_affordances,
which refuses and lets through as enforce_affordances does, reserved=
required here too, answering every condition in one sync_to_async hop, and
none for a spec declaring none.
Declaration order decides which refusal a caller sees, and nothing after the
first unmet condition runs. A condition on the row is read from the table, not
from the instance in hand. Two other answers come from the row: one that
vanished since it was resolved is
ServiceNotFound,
and a condition on the row reached with no model instance to answer it for is
ImproperlyConfigured.
ActionUnavailable is a ServiceConflict, so a transport that has never heard
of it still answers a conflict. One that wants the code matches it before its
generic conflict and service-error handlers.
A transport answering over HTTP puts the code beside the detail a client
already reads, as django-spec-html's error_response does at 409:
Asking for one more value¶
A service that gets far enough to discover it needs something else - usually
because of what it found - raises
AdditionalInputRequired
with a message and a schema. It is not a validation error, because what was sent is not
wrong, and it is a
ServiceError, so
a transport that has never heard of it still reports why the operation did not
complete.
@dataclass
class Purge:
confirmed: bool = False # declared, so the second call may send it
def purge_archived(*, user: Any, confirmed: bool) -> int:
doomed = Note.objects.filter(owner=user, archived=True)
count = doomed.count()
if count > 1 and not confirmed:
raise AdditionalInputRequired(
f"{count} archived notes will be deleted. Confirm to proceed.",
schema={"confirmed": {"type": "boolean"}},
)
doomed.delete()
return count
purge_spec = ServiceSpec(
service=purge_archived,
permissions=[IsSignedIn()],
validator=DataclassValidator(Purge),
)
def purge(user: Any, arguments: dict[str, Any]) -> int:
return dispatch(purge_spec, principal=user, arguments=arguments).value
schema describes what is missing, keyed by the argument the service expects
it back under. The answer comes back as an ordinary argument on the next call,
so the operation declares it like any other, and there is no session to
resume. A transport answering over HTTP puts the schema beside the detail when
there is one, as django-spec-html's error_response does at 422:
{"detail": "2 archived notes will be deleted. Confirm to proceed.", "schema": {"confirmed": {"type": "boolean"}}}
A schema one transport cannot render is the raiser's error, not the caller's,
so a service asks the same question on every route or on none.
check_requested_input
is that rule, for a transport to call before it renders the question. It reads
the spec's top-level parameters and the schema, runs no query, and raises
ImproperlyConfigured naming the key for a key no top-level parameter
declares, for a fragment that is not a schema object, for a shape some
transport cannot render, and for a type the declared parameter does not
take. A declared key the server fills - one a provider is annotated to fill,
or a seed the call's pool_seeds registers - is refused too, because
dispatch drops the caller's value for it and the answer would never arrive.
Hand it the call_context= of the call whose service raised, and both are
read as the spec declares itself to that call, so a Validator that declares
the asked key only to a call can ask for it.
The narrowest renderer is an MCP elicitation form: a string, number,
integer or boolean, or an array whose items list enum values. On a
many spec the top level is the list and the spec's reads, so a
confirmation asked once for the whole call is a reads parameter.
def check_the_question() -> None:
check_requested_input(purge_spec, {"confirmed": {"type": "boolean"}})
Declaring idempotency¶
ServiceSpec(idempotent=True) states that repeating the call with the same
arguments leaves the state making it once did. Nothing in this package reads
it, because idempotency is a property of the service the author writes, not
something a dispatcher can arrange; it is stated once so that a retry policy, a
queue's redelivery handling and an agent tool annotation all read the same
answer. None, the default, means undeclared, so a transport can tell "nothing
was said" from a declared False. atomic answers a different question: a
single call is all-or-nothing, not that a second one is a no-op.
Answers for each row of a list¶
A SelectorSpec declares which operations' affordances each of its rows is
answered for, keyed by a name the caller chooses:
The values are the ServiceSpecs themselves rather than registry names, so a
read takes no registry dependency and the declaration is the one the operation
enforces. Each answer is named affordance__<name>__<code> - here
affordance__rename__notes_read_only and affordance__rename__note_archived.
A name colliding with a key of the selector's annotations, or two entries
generating one name, is refused when the spec is built, because a generated
answer silently replacing a project's own annotation is the worst way for this
to fail.
Dispatch answers them wherever the selector runs: a selector spec's own, or a
service spec's output selector. On a queryset, every answer joins the spec's
annotations in the one .annotate() call shaping makes, before
extend_queryset and before a transport pages the rows, so the list still
costs one query and a page's rows carry what the whole list would have. A
condition on the row is the same correlated EXISTS the call is refused by,
so the list and the call agree about every row; a callable condition is
answered once per call, against the seeds alone, as it is at the call. Rows a
selector returns directly are answered too: instances by one query per model
class, mappings with their callable answers only, because a mapping has no row
to find.
present then adds an
affordances object to every row it presents, and so does every response the
HTTP views serve and every payload
present_for_audience
hands an agent, reason included:
def list_notes(user: Any) -> list[dict[str, Any]]:
result = dispatch(list_notes_with_answers_spec, principal=user, arguments={}, pool_seeds=seeds)
return present(list_notes_with_answers_spec, result)
[
{"id": 1, "title": "Draft", "affordances": {"rename": {"available": true}}},
{
"id": 2,
"title": "Old",
"affordances": {
"rename": {
"available": false,
"code": "note_archived",
"reason": "An archived note cannot be renamed. Restore it first."
}
}
}
]
Each name answers with the first condition its row does not meet, in
declaration order, as the call would refuse. A row deleted between the selector
returning it and its answers being asked is {"available": false} with no
code and no reason, because no condition's sentence is true of a row that
no longer exists. A selector spec's affordances refuse nothing: the archived
note is still listed, and says why it cannot be renamed.
A page that lists rows holds them raw - a queryset's instances, a table's
records (a django-tables2 row's record, not the bound row) - and presents nothing.
row_affordance_answers
reads one row's answers for it, the same object present adds to the row:
def rename_offered(user: Any) -> dict[int, bool]:
result = dispatch(list_notes_with_answers_spec, principal=user, arguments={}, pool_seeds=seeds)
return {
note.pk: row_affordance_answers(list_notes_with_answers_spec, note)["rename"]["available"]
for note in result.value
}
It takes the spec the rows came through, whichever kind: a selector spec, a
service spec (which it reads through its output selector, as present does) or
anything that compiles to one. A spec that presents no affordances answers {},
as present leaves the affordances key out, so a name the answer lacks is a
name the spec does not declare, and a caller asking about one must treat it as
not declared. A service spec's own affordances are conditions it is checked
against and are never presented, so they count for nothing here; declare the
mapping on the selector that returns the rows. A row that carries no answer for
a name whose spec declares a condition is refused; a name with no conditions
reads no flag, so every row is available for it.
Links: what a row leads to, and how to call it¶
An answer says whether an operation is available for a row; a link also says
which row field fills which of its reads.
row_links reads one
row's links, here for the listing above, whose NoteRow marks id as a
HANDLE:
registry = SpecRegistry()
registry.register("list_notes", list_notes_with_answers_spec)
registry.register("rename_note", rename_spec)
def note_links(user: Any) -> list[dict[str, Any]]:
result = dispatch(list_notes_with_answers_spec, principal=user, arguments={}, pool_seeds=seeds)
return [
row_links(list_notes_with_answers_spec, item, registry=registry)["rename"]
for item in present(list_notes_with_answers_spec, result)
]
note_links(ada)
# [{"available": True, "spec": rename_spec, "arguments": {"pk": 1}, "required": ("pk",),
# "name": "rename_note"},
# {"available": False, "code": "note_archived", "reason": "...", "spec": rename_spec,
# "arguments": {"pk": 2}, "required": ("pk",), "name": "rename_note"}]
Each read of the target binds by inference: rename_spec requires pk, which
no field of NoteRow is named, and id is its one HANDLE field, so pk
binds to id. The reads a link binds are the target selector's and the spec's
own reads; a read the target's kwargs provider fills is the provider's, and
a Validator's field is never bound. A read is required when it names the
row: a target selector's required read the shape check demands of a caller,
less those a provider may fill
(provider_reached),
so a link and a call never disagree about the row. The spec's own reads are
the caller's input - a rename's new title - so they bind when a field carries
them and are never required of the row. Each read binds to the field a
SpecLink names, else to the
output field of its name, else, when one required read is left and the output
marks one field HANDLE, to that field. An optional read binds only by name or
by a SpecLink. A field marked HIDDEN is never bound, since a link's
arguments reach its caller. Name a binding by wrapping the value; here it
spells out what inference does, and an output whose key is another field names
that field instead:
A bare spec is SpecLink(spec): the answers, their annotations and the schema
are the bare spec's, so wrapping one changes nothing present serves.
row_links reads a presented item before any audience projection, or a raw row
as row_affordance_answers does, and agrees with it about availability. An
optional read's field the item does not carry is left out of arguments; a
required read's raises ImproperlyConfigured, since the link could not be
called. required names the link's required reads, each in arguments. A
transport that reverses a URL for the link reverses with those alone: an
optional read the row carries - a rename's current title - binds into
arguments as a default for the caller, and is no part of the route, so
reverse(name, kwargs=arguments) would find no match where
reverse(name, kwargs={r: arguments[r] for r in link["required"]}) does. A raw row is read by the output field's name, by attribute or key, so
where the output names a field by an alias or a serializer source, read the
presented item instead. name is the
target's name in the registry passed, matched by identity, and left out when
the registry holds none, so a transport that cannot name a target keeps the
answer.
SpecRegistry.name_of
answers it: a registered SpecSource matches the spec it compiles to, an
entry replace swapped matches the spec it displaced as well as its own, and a
spec registered under two names raises ValueError.
When the binding is checked. Construction refuses a SpecLink naming a
read the target does not take, and nothing more: binding reads the rows'
output, and a presenter may only answer it once the apps are loaded - a
dataclass naming a class defined further down its module, a serializer whose
fields need the app registry. The rest is checked against a built registry,
when the project chooses:
check_links
returns a Django check Error for each link leaving a required read unbound,
matching two HANDLE fields, or naming a field the output does not declare or
marks HIDDEN (django_service_specs.E001), and for each target the registry
holds under two names (django_service_specs.E002). The kernel registers no
check of its own, since a project may build one registry per app and merge
them: check the one the transports read, in one line,
link_bindings
answers the bindings themselves, {name: {read: field}}, and raises what the
check reports. A link no check saw is refused at its first use the same way:
row_links and link_bindings raise that message as ImproperlyConfigured,
and keep the refusal for the spec, so the output is read once.
Rows that wrap the instance¶
A tree node, a dataclass row or a table cell builder wraps the model instance
rather than being it, so its answers have nothing to be set on. The selector's
row_object says where the instance is: an attribute name, or a callable
taking the row and returning the instance.
@dataclass(frozen=True)
class NoteNode:
note: Note
children: tuple[NoteNode, ...] = ()
SelectorSpec(
kind=SelectorKind.LIST,
selector=note_tree,
permissions=[Unrestricted()],
affordances={"rename": rename_note},
row_object="note", # or row_object=lambda node: node.note
)
The answers are set on the instance as they are on a model row, one query per
model for the whole list, and each row comes back unchanged, so a frozen wrapper
works; present and row_affordance_answers read them through the same
row_object. Set, it applies to every row, model and mapping rows included. It
must find a saved instance, or None for a row with no object, which answers
{"available": false} for every name with a condition; anything else is refused
with ImproperlyConfigured naming row_object. A selector returning a
QuerySet beside it is refused, since a queryset's rows are answered in SQL as
the model itself. A row_object that is neither a non-empty string nor a sync
callable is refused when the spec is built.
spec_output_schema
describes the object on each item, with or without a projection, and with each
name's codes enumerated so a client can switch on them:
{
"type": "object",
"properties": {
"rename": {
"type": "object",
"properties": {
"available": {"type": "boolean"},
"code": {"type": "string", "enum": ["notes_read_only", "note_archived"]},
"reason": {"type": "string"}
},
"required": ["available"]
}
},
"required": ["rename"]
}
Presenting refuses what would lose or garble the answers: a spec declaring
affordances with no presenter, a presented row that is not an object or
already has an affordances key, and a row that did not come through the
selector declaring them. Dispatch refuses a condition on the row beside mapping
rows, and a row that is neither a model instance nor a mapping.
A target lookup - a service spec's instance_selector_spec or
collection_selector_spec - that declares affordances has its rows answered
too, as djangorestframework-services' dispatch answers them, and nothing
presents them: a service spec presents only its output selector's answers. The
declaration costs a subquery, or a query of its own when the lookup returns a
bare row, and buys nothing. Declare the answers on the read that lists the
rows, or on the output selector.
shape_queryset
answers none: a transport that shapes a selector's rows itself, rather than
through dispatch, hands present rows with no answers on them, and is refused.