API reference¶
Everything below is exported from django_service_specs directly, and from the
subpackage it is listed under. Import from the package root in application
code; the subpackage paths are where each name is defined.
The pydantic adapters are the one exception. pydantic is an optional extra,
so they are exported from django_service_specs.adapters.pydantic alone, and
importing the package root never imports pydantic.
Settings¶
One Django setting, read at the call rather than at import, so
override_settings reaches a spec built before it. The management command's
output format is SPEC_CLI_OUTPUT, read by
django-spec-cli.
SERVICE_SPECS_MAX_ARRAY_LENGTH: the most elements an array argument takes where its parameter declares nomax_length, and the most rows amanycall carries where its spec declares nomany_max_length.1000when unset;Nonebounds no array. Anything but a non-negativeintorNoneis refused asImproperlyConfiguredwhere it is read. See how long a list may be.flat_argumentsbounds a query string's lists by the same key.
Specs¶
ServiceSpec
dataclass
¶
Bases: AffordanceDeclarer
A write: what it takes, who may run it, what it acts on, what it returns.
Dispatch runs it in a fixed order, once a deactivated principal has been
refused: the shape check and the closed argument set, class-level
authorization, target resolution, object-level authorization, validation
with the target in the Validator's context, the affordances, the
preconditions, the service, then the output selector.
Attributes:
| Name | Type | Description |
|---|---|---|
service |
Callable[..., Any]
|
The operation. Called with the keywords it declares: the
principal ( |
permissions |
Sequence[PermissionCheck] | None
|
The checks a principal must pass. |
reads |
Parameters
|
The arguments the service, its providers and its preconditions
read with no Validator in front of them - the |
shapes |
Parameters
|
The arguments that shape what the presenter renders rather
than what the service does - which fields, a query over the
result - as a Parameters group of their own, as a selector spec's
|
partial |
bool
|
Whether a call may leave out any of the Validator's
parameters, as an HTTP |
many |
bool
|
Whether the call carries a list of rows, each validated by the
|
many_argument |
str
|
The argument a |
many_min_length |
int | None
|
The fewest rows a |
many_max_length |
int | None
|
The most rows a |
validator |
Validator | None
|
Validates the arguments its own |
instance_selector_spec |
SelectorSpec | None
|
A |
collection_selector_spec |
SelectorSpec | None
|
A |
output_selector_spec |
SelectorSpec | None
|
Re-reads what the service produced, with its
return value in the pool as both |
presenter |
Presenter | None
|
Renders the dispatch value. When |
allow_none |
bool
|
Declares that a service with no output selector may
present nothing: its return may be |
returns_many |
bool
|
Declares that the service's own return is a list of
rows, each presented by the |
affordances |
Sequence[Affordance] | None
|
What must be true for this operation to be possible right
now, as a sequence of |
atomic |
bool
|
Run the service inside |
idempotent |
bool | None
|
Whether repeating the call with the same arguments leaves
the same state as making it once. Declaration-only: 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
here so the fact is stated once, on the spec, and every transport
reads the same answer - a retry policy, a queue's redelivery
handling, an agent tool annotation. |
preconditions |
Sequence[Callable[..., None]] | None
|
Raise-to-abort rules, a sequence of callables each called
with the keywords it declares from the service's pool, after the
|
kwargs |
Callable[..., Mapping[str, Any]] | None
|
A provider of extra pool entries: called with the keywords it
declares from the call's pool, it returns a mapping merged into the
pool the service is called from after the caller's arguments, so a
key it answers is the author's value whatever the caller sent. A
value of |
input_data |
Callable[..., Mapping[str, Any]] | None
|
A provider of server-owned input: called with the keywords
it declares from the call's pool, the resolved target among them,
it returns a mapping merged onto the caller's arguments before the
Validator sees them, after the caller's, so its keys are the
author's values. A value of |
progress_reporter |
Callable[..., Any] | None
|
A provider of a
|
metadata |
Mapping[str, Any] | None
|
A project's own per-operation facts, stored as given. |
derive ¶
A new spec of this class with the named fields replaced, and every other one this spec's.
Built through the constructor, so every check a fresh declaration passes runs again on the result, the combinations included: a change that is valid alone and refused beside the fields it keeps is refused here. The spec it is called on is never changed, and the fields not named are the same objects, not copies.
A field is replaced, never extended: reads= is the new spec's whole
reads. Name the base's value to keep it and add to it,
reads=base.reads + Parameters.of(...).
The result is another spec, by identity: a
Grant minted for this
one does not cover it.
Raises:
| Type | Description |
|---|---|
TypeError
|
a name in |
ImproperlyConfigured
|
the result is refused as a fresh declaration with the same fields would be. |
target_selector_spec ¶
The selector resolving what the service acts on, if it declares one.
link_reads ¶
The reads a link to this spec from a row may bind.
The target selector's reads and this spec's own, less each read its
kwargs is annotated to fill. Which of them a caller must send is the
shape check's to say
(provider_reached).
Validator fields never bind: they may need the app registry.
as_kernel_spec ¶
This spec, as its own compiled form.
What makes a spec a
SpecSource like
any declaration of another library's, and how
kernel_spec
tells the two apart: a spec compiles to itself, and is never cached.
parameters ¶
Everything this spec takes: its target selector's reads, its own, its shapes, then its Validator's.
On a many spec the Validator's parameters are each row's, so the
top level is the spec's reads, its shapes and then the list itself: a
required array under many_argument whose rows are the Validator's
parameters. A row's field is no top-level argument, so it may share a
read's name.
Assembled on every call rather than at construction, because a Validator reading a model-backed declaration may need the app registry, and specs are commonly built at import time. A name two sources declare is refused here, as is one dispatch seeds itself; the three that need no Validator, the target's reads, the spec's and its shapes, were refused at construction already.
call_context is the call's dict when a call asks, and None
when a reader outside one does, unless a transport describing the spec
hands a stamped dict with no call under way; it is handed on to a
Validator whose parameters declares the keyword (see
Validator.parameters).
presenter_for_output ¶
The presenter the dispatch value renders with: this spec's or its output selector's.
SelectorSpec
dataclass
¶
A read: what it takes, who may run it, how its rows are shaped, what it returns.
Dispatched on its own, it is a list or a retrieve. Nested in a
ServiceSpec, it is how
that service resolves its target, its collection or its output.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
SelectorKind
|
|
selector |
Callable[..., Any]
|
The read itself. Called with the keywords it declares, from
the principal ( |
permissions |
Sequence[PermissionCheck] | None
|
The checks a principal must pass. |
reads |
Parameters
|
The arguments the selector reads with no Validator in front of
it - its filters, its ordering, the key of the row it retrieves.
With |
shapes |
Parameters
|
The arguments that shape what the presenter renders rather
than which rows are read - which fields, a query over each row -
as a Parameters group of their own. Part of |
presenter |
Presenter | None
|
Renders the rows. Not read on an instance or collection selector, whose rows the service consumes rather than returns. |
allow_none |
bool
|
On a |
select_related, |
(prefetch_related, annotations)
|
Applied to the queryset the selector returns, in that order. Declaring any of them when the selector returns something else is refused at dispatch. |
extend_queryset |
Callable[..., QuerySet[Any]] | None
|
Applied last, called with the keywords it declares from
the same pool plus |
filter_set |
Any
|
Applied after |
affordances |
Mapping[str, AffordanceDeclarer] | None
|
What can be done to each row right now. A mapping from a
name the caller chooses to the
|
row_object |
str | Callable[[Any], Any] | None
|
How to find the model instance in a row that wraps one - a
tree node, a dataclass row, a table cell builder - so its
|
kwargs |
Callable[..., Mapping[str, Any]] | None
|
A provider of extra pool entries: called with the keywords it
declares from the selector's pool, it returns a mapping merged into
that pool after the caller's arguments, so a key it answers is the
author's value whatever the caller sent - a tenant, a project scope.
A value of |
preconditions |
Sequence[Callable[..., None]] | None
|
Raise-to-abort rules, a sequence of callables each called
with the keywords it declares from the same pool once the selector
has resolved, the row as |
progress_reporter |
Callable[..., Any] | None
|
A provider of a
|
metadata |
Mapping[str, Any] | None
|
A project's own per-operation facts, stored as given and read back by its own checks or audit hooks. |
derive ¶
A new spec of this class with the named fields replaced, and every other one this spec's.
Built through the constructor, so every check a fresh declaration
passes runs again on the result, the combinations included: a change
that is valid alone and refused beside the fields it keeps is refused
here. The spec it is called on is never changed. The fields not named
are equal to its own, and the same objects except where the
constructor rebuilds one: a spec with a filter_set has its
reads assembled afresh, author's own and then the filters'.
A field is replaced, never extended: reads= is the new spec's whole
reads, and a filter_set's filters join after it as they join
after a declared one. Name the base's value to keep it and add to it,
reads=base.reads + Parameters.of(...).
The result is another spec, by identity: a
Grant minted for this
one does not cover it.
Raises:
| Type | Description |
|---|---|
TypeError
|
a name in |
ImproperlyConfigured
|
the result is refused as a fresh declaration with the same fields would be. |
as_kernel_spec ¶
This spec, as its own compiled form.
What makes a spec a
SpecSource like
any declaration of another library's, and how
kernel_spec
tells the two apart: a spec compiles to itself, and is never cached.
parameters ¶
Everything this spec takes: its reads, then its shapes.
call_context is taken and ignored, so a reader asking a
ServiceSpec or a SelectorSpec asks both alike: a selector spec
has no Validator to hand it to.
SpecSource ¶
Bases: Protocol
An object that compiles itself to a ServiceSpec or SelectorSpec.
The seam for a library that declares operations in its own vocabulary -
djangorestframework-services' spec, compiled from a serializer and
permission classes - so its declaration is handed to dispatch, the
registry, the schemas and the rest as it is, with no wrapper of this
package's around it.
ServiceSpec and SelectorSpec satisfy it too: each compiles to
itself, which is how
kernel_spec tells a
spec from a declaration by that mark rather than by its class.
as_kernel_spec() is called the first time any entry point reads the
object, and the compiled spec it answers is the one every later call
reads: the object is read as a declaration, and a change to it after that
first read is not seen. Two first reads that overlap - concurrent, or a
compile that reads its own object - may each compile, and both answer the
spec published first. One compiled spec per object is also what lets a
Grant, bound to a spec
by identity, carry from resolve_target to dispatch when both are
handed the same object.
as_kernel_spec ¶
This declaration as a spec of this package's.
kernel_spec ¶
spec as a spec of this package's: itself, or what it compiles to.
Everything it takes is a
SpecSource, and
as_kernel_spec() is what it asks. A ServiceSpec or SelectorSpec
compiles to itself, and is returned as it is. Anything else compiles to a
spec - an object that in turn compiles to itself - and the compiled spec
is cached per object, by identity: the same object
answers the same compiled spec on every call, and two objects that compare
equal are two declarations, each compiled on its own. The cache holds the
object weakly and its compiled spec for as long as the object lives, so a
compiled spec that refers back to its object keeps both for the life of
the process, as a declaration at module level is kept anyway.
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Parameters¶
Parameter
dataclass
¶
One thing an operation takes, as a declaration every transport reads.
JSON Schema, argv, the closed argument set and the shape check are all derived from it, so a transport describes itself from the declaration rather than from whichever validation library the spec happens to use.
name and type are positional because every declaration has both;
everything else is keyword-only.
items is an array's element: a JSON type name for a flat list, or the
Parameters of the object each element is. fields is the same for a
parameter whose own type is object. Nesting is what lets a relation
write declare its rows: an author with its books says what a book is, where
a flat items="object" would say nothing and let a malformed row through.
nullable is the parameter's own: whether the argument may be null.
items_nullable is its element's: whether a null may stand in the
array where an element would, as in list[int | None]. The two are
independent, because a list that may be absent and a list that may hold
gaps are different declarations, and an array with no declared items
admits a null element already.
type is a JSON type or file, which an array's items may name
too. A file is a Django File, an upload included, and has no
choices: it is matched by nothing a declaration could list.
type may also be any, for a parameter that declares no type, as an
unannotated argument does: 3 and "abc" are both one. Its value is
handed on exactly as it arrived, never read as a number or a boolean, so
a query string's "3" stays the string "3"; null is accepted
only where nullable says so, as for every other type. Having no type,
it describes nothing a type would - no choices, format, fields,
items or bound - and an array's items never name it, since an
array that declares no items takes any element already.
choice_labels names the choices for a reader: a mapping of a choice to
its label, or Django's choices spelling, pairs of the two, which keeps
apart the 1 and True a mapping's keys would merge. A choice may go
unlabelled. The labels constrain nothing, so the shape check reads only
choices; the schema carries them as titles. They are stored as a tuple
of pairs, and a label may be a lazy translation, rendered when the schema
is built.
default is UNSET when none is
declared, so a default of None stays a real default. It is reported, not
applied: whether an omitted argument arrives as the default, as None or
not at all is the validating library's behaviour, and each adapter reports
what its library does. It takes no part in the hash, so a declaration with
a list or dict default is as hashable as any other, while equality still
tells two defaults apart.
minimum and maximum bound a number, inclusively: an integer, a
number, or a decimal string, which is compared as the decimal it
spells, so "1E+999999999" is past a bound of 1e50 without ever
being built as the integer it names. Each is an int or a finite
float, a JSON number. The schema states them on an integer and a
number and not on a decimal string, where JSON Schema gives them no
meaning; the shape check enforces all three. They exist for the bound a
reader needs before any Validator runs: a filter whose form field has none
hands the value to the database's integer conversion, which builds every
digit. Any other bound - a string's length, a Validator's max_value -
is still the Validator's alone.
On an array, format, minimum and maximum describe
each element, as choices do: an array of integer or number
takes a bound, and an array of string takes format="decimal" and
then a bound too, which is what a django-filter CSV number filter
declares. A decimal is the one format an element takes: a number element
is read as a float on the way, which rounds a fraction past a float's
precision, where a decimal string is compared and handed on as it was
sent. Any other format on an array, and a format or a bound on an
element that cannot carry it, is refused. The list's own count is
min_length and max_length's, so an array may carry both pairs.
min_length and max_length bound how many elements an array
takes, inclusively, and are refused on anything else: each a
non-negative int. They are checked on the list whole, before any
element is read, so a list past its maximum costs no per-element work.
An array that declares no max_length is still bounded, by the
SERVICE_SPECS_MAX_ARRAY_LENGTH setting, 1000 unless the project sets
another count or None: a list a caller controls the length of is a
cost the caller controls, and the setting is read at the call, so it
applies to a declaration built before settings were configured. A
declared max_length outranks it either way, wider or narrower.
min_length has no default: an empty list is taken unless one says
otherwise.
json_schema_extra carries the JSON Schema keywords no field of a
Parameter spells - a pattern, a string's maxLength,
uniqueItems - as a mapping of keyword to value, held as a deep copy of
its own. It is how an adapter whose library declares more than a
Parameter carries keeps it on every route rather than on its own.
parameters_schema
adds its keys to this parameter's node. A keyword a field states there is
refused here, naming the field, whether or not this parameter sets it:
type, format (so a custom format is refused too: format is a
field), default, the choices' enum, anyOf and const, the
bounds, minItems and maxItems, items, description from
help, and properties, required and additionalProperties
from fields. Either side winning would advertise what the declaration
does not say or drop what was written, and refusing the keyword only when
one build stated it would make the same declaration valid until the array
cap came on or a spec moved to REJECT. A value JSON cannot carry - a
Decimal, a lazy translation, at any depth - is refused too, naming its
key. It is advertised, not enforced: the shape check never reads it, so
what it states holds only where the spec's Validator enforces it
(test_it_is_advertised_and_not_enforced_by_the_shape_check).
It takes no part in the hash, as default does not, and still in equality.
reflected says the parameter was read off a callable's signature
rather than written by an author, as djangorestframework-services reads a
selector's, a target lookup's or a spread service's parameters into
reads. It counts on a reads parameter alone - a selector spec's,
a target selector's or a service spec's - and only at dispatch: a
reflected read named like a seed the call's pool_seeds registers
leaves that call's argument set, and the seed fills it, where an unmarked
one is refused as a configuration error
(test_a_reflected_read_a_registered_seed_is_named_like_is_the_seed_s).
On a Validator field or a shape it changes nothing. No schema carries it,
since it describes where a declaration came from rather than what a caller
sends; it takes part in equality and the hash, because two declarations
that differ in it dispatch differently
(test_reflected_is_compared_and_hashed_and_never_in_the_schema).
nested
property
¶
The Parameters inside this one: an object's fields, or an array's rows.
Parameters
dataclass
¶
An ordered set of Parameter.
A spec's Parameters are assembled from several sources - its target
selector's reads, its Validator's parameters() - and + is how.
A name declared twice is refused, at construction and at + alike:
two sources claiming one argument is a spec bug, and a last-wins merge
would hide which of the two declarations a transport describes and which
one the argument reaches.
Any iterable of parameters is accepted and stored as a tuple, so the declaration stays hashable and ordered.
check_arguments ¶
check_arguments(
parameters: Parameters,
arguments: Mapping[str, Any],
*,
unknown_arguments: UnknownArguments = UnknownArguments.REJECT,
partial: bool = False,
) -> dict[str, Any]
The shape check: what a caller can get wrong that the declaration can see.
Presence, JSON type, format, bounds, length, choices and nullability, at every level of nesting, with no query. It is what runs at enqueue time and in front of an untrusted caller's Validator, so a malformed call is refused before it costs a row lookup, and it is no stricter than the libraries behind it, with three exceptions named below: ASCII digits, a declared bound, and the length of an array. So a decimal accepts a JSON number as well as a string, because every decimal validator does, and a check stricter than the worker refuses what would have run.
- A required parameter with a declared default is not refused when absent, because the Validator will supply the default. The default is not applied here: whether an omitted argument arrives as its default is the validating library's behaviour, not the shape check's.
- Under
partial=Trueno absent parameter is refused, at any depth: a partial update sends only what changes, and DRF skips an absent field anywhere below a partial serializer. A value that is present is checked as it would be otherwise, and an unknown key is still refused. - A string is read as the number it spells where an
integeror anumberis declared, wherever the declaration reaches, and the number is handed on:"3"is 3,"3.0"and" 3 "are 3 too, and a number's"1e3"is 1000.0. Django's forms and pydantic's lax mode both read these strings so, and the reading is the onecoerce_flatmakes, which this shares. Where the two differ it is Django's: an integer's"5."and"5 .0"are 5, which pydantic'sintrefuses, so this is looser than pydantic there. The exception is a string outside ASCII for anintegeror anumber, not adecimal: Django's fields read Arabic-Indic or fullwidth digits and Unicode spaces as Python'sintdoes, and this refuses them, as pydantic and JSON do. A string that spells no such number is refused as the type it is not. The number goes on rather than the string because a Validator stricter than those two, the dataclass adapter's, refuses"3"for anint. boolis neither anintegernor anumber, although Python makes it anint: a JSONtruesent for a count is a caller's mistake, not the number one.- A
fileis a DjangoFile, and nothing else is one: no JSON value can be, so a JSON caller's string for it is refused at its name. - An
anyis handed on as it arrived: no type is declared, so nothing is read as a number, and"3"stays the string"3". Anullis still refused unless it isnullable, and NaN and the infinities are still no JSON value. A container is not walked, as an undeclared array element's is not, and a value of no JSON type - a Python caller's, or a multipart upload sent under its name - is handed on too. - An integral float is an
integer, and is handed on as anintwherever the declaration reaches. JSON Schema counts5.0as an integer, so the{"type": "integer"}this kernel advertises admits it, and a Validator never sees5.0for an integer: its own type check and its bounds read theint.5.5is still refused, and so are NaN and the infinities, which no integer is. Anumberkeeps the float it was sent. DRF reads it differently at an exponent: itsIntegerFieldreadsstr(value), as Django's form field does, so given1e16raw, both read"1e+16"and refuse it, where this check follows JSON Schema and hands on10000000000000000, which either field then takes. - NaN and the infinities are refused wherever the declaration reaches.
JSON has no spelling for either, so they are outside the
numbertype, and this is a type rule rather than a stricter check - although pydantic'sfloatand the dataclass adapter's both take one. minimumandmaximumbound a number inclusively, in the words Django'sMinValueValidatorandMaxValueValidatoruse. The second exception: a bound is the declaration's, and may be stricter than the library behind it.filter_set_parametersdraws django-filter's1e50below zero and on a range's bounds too, where django-filter draws none, because past it an integer column's conversion builds every digit of the value. A decimal string is compared as the decimal it spells, which reads its exponent and builds none of its digits, so"1E+999999999"is refused as fast as"2"is taken. An array's bounds bound each element, refused at its index.- An array's length is read before any of its elements: within its
min_lengthandmax_length, and where it declares no maximum, within theSERVICE_SPECS_MAX_ARRAY_LENGTHsetting, 1000 unless the project says otherwise. The third exception, since that default is the kernel's and may be stricter than the library behind it: a list is a cost its caller controls the size of, one Validator run per row of amanycall and one query variable per value of aninfilter. The refusal is the list's own, at its name, in DRF's words. choicesconstrain the value, and an array's choices constrain each of its elements, since an array is never one of a list of scalars. So do an array'sformatand bounds: adecimalarray's elements are each read as a decimal is, and handed on as they were sent.- An
objectwith nofieldsis free-form: its type is checked and its contents are not, because nothing is declared inside it to check against. An array with noitemstakes any element, and each is still one of the array's values: its choices and the finiteness rule reach it, while an element that is itself an object or an array is not walked.
The closed argument set applies at every level, inside each row and
each nested object as well as at the top. Closed only at the top, an
unknown key in a row would reach the row's constructor and come back as a
TypeError naming no row. REJECT refuses the key where it appeared;
IGNORE drops it from the returned copy.
Returns a cleaned copy and never modifies arguments. The containers it
walks are new - the top-level mapping, each declared object, each array -
while a value it does not look inside, such as a free-form object, is
passed through as the caller's. The values it replaces are the two it
reads as numbers: an integral float declared an integer, and a numeric
string declared either.
Raises:
| Type | Description |
|---|---|
InvalidArguments
|
carrying every problem found as one tree
addressed by path, rather than the first; the tree's shape is
documented on |
NON_FIELD_ERRORS
module-attribute
¶
The key a message about a node itself sits under, beside its fields' messages.
A row that is not an object has no field to hang the message on, so it goes
here inside the row: {"books": {1: {"non_field_errors": ["..."]}}}. It is
Django's and DRF's spelling of the same idea, so a transport rendering either's
errors reads the kernel's without a translation table.
NON_FIELD_KEYS
module-attribute
¶
The keys a message about the whole input sits under: the kernel's, and Django's.
Django's is here because a service re-raising a model's message_dict as a
ServiceValidationError carries its form-wide messages under "__all__".
Neither adds a step to the path a message is placed or printed with. Both are
held by test_a_refusal_tree_is_read_as_paths_to_messages, which fails with
either left out.
coerce_flat ¶
Flat strings to the JSON-like primitives a typed caller would have sent.
Every flat-string transport - argv, a query string - needs this, and needs
it to agree, so it is the kernel's rather than each transport's: validation
libraries read strings differently from one another, and after this every
Validator sees an argv call exactly as it would see typed JSON. It is
directed by the declaration: an integer or a number is parsed, a
boolean is parsed from exactly four spellings, and everything else is
left as the string it arrived as. A decimal, a date-time, a date and a
UUID stay strings, for the Validator to decode, exactly as they would
arrive off a JSON wire, and the shape check reads each format after this:
"null" for a uuid is refused there, on every route alike.
So does an any: it declares no type to read the string as, so a
query string's "3" reaches the shape check and the Validator as
"3".
- An integer is read as Django's
IntegerFieldreads one:"5.0"and"5."are 5, and"5.5"is refused. An array's integer elements are read the same way, a repeated query-string key's included. A string outside ASCII spells no integer or number, Arabic-Indic or fullwidth digits included, although Django's fields read them: seeparse_number. - An array longer than it takes is refused whole, at its name, before any element is read: the shape check's own length rule, which this shares, so a flat list of a million malformed values costs one message.
- An array's elements are each coerced by its
itemstype, and a single value becomes a one-element list, since a flat transport sends a one-element list as a bare value.Noneis not wrapped: an option argparse never received is absent, not a list holding a null. - A parameter with nested Parameters is refused by name: an object, or an array of objects, has no flat spelling, and passing its strings through would leave the refusal to a type error that does not say why.
- A key the parameters do not declare passes through untouched, so the
closed argument set in
check_argumentsstays the one place that refuses it, under the caller's policy. - A
uuid.UUIDfor astringis spelled back, an element of astringarray's too: Django's<uuid:pk>path converter decodes one before the kernel sees it, and a string is what the declaration says, so the shape check reads it as it would read the same id off a JSON wire. - Any other value that is not a string passes through untouched: it has
already been decoded by someone, and this does not second-guess them. An
any, and an array declaring noitems, takes auuid.UUIDas it came, since neither says it is a string.
Raises:
| Type | Description |
|---|---|
InvalidArguments
|
every refusal at once, a parameter's at its name and
an array element's at its index: |
InvalidArguments ¶
Bases: DispatchError
The arguments were refused: their shape, or the Validator's verdict on them.
Parameters are declared and arguments are supplied, and this refuses the
arguments. It is raised by the shape check, the closed argument set,
coerce_flat, a Validator and the relation writes, so every refusal of
input reaches a transport as one type.
Not a service validation error, and not a subclass of one. A service
raising
ServiceValidationError
is stating a business rule about well-shaped input; this says the input was
not well-shaped, or did not validate. An MCP server answers the two
differently on purpose.
detail is a tree addressed by path, because nested arguments fail inside
rows:
- a field:
{"title": ["..."]} - a nested object:
{"author": {"name": ["..."]}} - rows, keyed by their
intindex, only the rows that failed:{"books": {1: {"title": ["..."]}}} - a message about a row itself, under
non_field_errorsinside the row - a message about a
manycall's list as a whole, undernon_field_errorsbeside the failing rows' indices, after them
Every leaf is a list of str, so the whole tree is JSON-serializable once
the integer keys are written as strings, which is what json.dumps does.
A many call's node that carries the list's own message mixes int
indices with non_field_errors, so json.dumps(..., sort_keys=True)
over it raises TypeError: it is already in reading order, and is
written as it stands.
missing names the arguments the call left out, read off the tree
rather than parsed from its words, so a transport wording "you did not
send title" has one reading to ask and not its own walk of detail.
after_authorize marks that
check_call raised
this after its class-level permission check passed, which it does for one
refusal only: the rows of a many call, raised after its fourth step. A
transport that called check_call before charging a rate limit reads it
to tell a refused row, where the call was admitted and only its rows are
wrong, from a refused call, which was not admitted; it need not ask the
checks again to find out. Every other refusal leaves it False,
dispatch's own refusal of the same rows included, though that one too
is raised after its authorization: the mark is check_call's statement
about its own order of steps, not a general account of where in a run the
error arose.
missing
property
¶
The top-level arguments the call left out, sorted: those with a message coded
"required".
Any refusal coded "required" counts - the shape check, a selector
refusing a read nothing filled, and the Validator adapters (dataclass,
pydantic, forms), which code it too - and it is the code DRF gives
the same mistake. An argument that was sent and was wrong is not here, nor is
one whose only messages carry another code or none (a Validator's own
plain str). Top level only: a nested object's field and a
many call's row field are not arguments of the call, so they are
never listed, and neither is non_field_errors, which is a message
about the call and not a name in it
(test_missing_is_not_the_node_s_own_message fails without that
exclusion). A nested node is a dict, whose iteration yields keys and
never a message with a code, which is why a row or a nested object
lists nothing (test_missing_does_not_reach_into_a_nested_object_or_a_row).
The code is read and not the words
(test_missing_reads_the_code_and_not_the_words fails if the words are).
CodedMessage ¶
Bases: str
A message in an
InvalidArguments tree,
carrying the code of the mistake it names.
The words are for a person and are translated; the code is for a
program and is not. Every refusal the kernel and its shipped adapters
make carries one - the shape check, coerce_flat,
a selector or extend_queryset refusing a read nothing filled, a
FilterSet refusing its data, a relation write refusing a row, and
DataclassValidator, FormValidator and PydanticValidator - and
the code is the one a
DRF field gives the same mistake ("required", "null",
"invalid", "not_a_list", "max_length" and the rest), so an
adapter building DRF's error details maps each one across unchanged.
Where Django or pydantic refused, their own code comes through: Django's
as it raised it, and pydantic's error type as DRF's code for the same
mistake. The arguments page lists them, refusal by refusal.
It is its message to everything that reads a string. Equality,
hashing, json.dumps, %-formatting and repr all see the plain
str, and the code takes no part in any of them: a tree with codes
compares equal to the same tree written with plain strings, the body a
transport writes is unchanged by them, and so is the text str makes of
a tree, which a log line or Django's BadRequest carries. That is the difference from DRF's
ErrorDetail,
whose equality reads the code too, and why this is not one. Read the code
with getattr(message, "code", None), since a Validator's own messages
reach the same tree as it raised them, a plain str among them.
A copy, a deep copy and a pickle each keep the code.
refusal_messages ¶
Every message in the refusal tree value, each with its path from the root:
books.1.title.
The tree InvalidArguments carries: a key is a step of the path, a
row's index included, and a NON_FIELD_KEYS key adds none. A list is
the tree's leaf, so its messages share the path, and only a list:
anything else is one message whatever its type, a lazy translation
(which is not a str) included, so it is never taken apart into
characters. Each message is rendered as a str, in the tree's order.
A message at the root has the empty path. Read by every transport that
prints or places a refusal, so each reads one tree one way.
expected_type_refusal ¶
The refusal of a value that is not of kind, as one sentence a translator sees whole.
kind is one of a closed set of eight keys: the six JSON types,
"string", "integer", "number", "boolean", "array" and
"object", and two that are not JSON types, "decimal" and
"file". A decimal arrives as a string or a number, so its refusal
names both, and a file is a parameter's type that no JSON value is.
Raises:
| Type | Description |
|---|---|
KeyError
|
|
One sentence per type rather than "Expected %(type)s", because an
interpolated JSON type name would reach a translated sentence
untranslated. The shape check and the Validators the adapters build share
this one table, so a caller reads the same refusal whichever of them
answered, and a transport refusing a value it read itself, such as a
query string's, says it in the same words. Built on each call, because a
translation looked up at import time needs configured settings before the
package can be imported at all.
Its code is the one DRF gives the same mistake: "not_a_list" for an
array, as its ListField and ListSerializer both do, and
"invalid" for everything else, as each of its scalar fields, its
FileField and a nested Serializer handed something other than a
mapping do. A free-form object is "invalid" too, where DRF's
DictField would say "not_a_dict": one type here stands for both of
its fields, and the nested serializer is the one a declared object becomes.
max_length_in_force ¶
The most elements the array param takes: its own max_length, or the setting's.
One reading for every place that bounds or describes a list - the shape
check, coerce_flat, the split of a flat value, a many call's rows
and the schema, and a transport reading a list itself - so the bound a
client is told is the bound it meets.
None where the setting is None and nothing is declared.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
a |
clean_held_to_their_columns ¶
Validate a bound form as its full_clean() does, refusing a number no integer column
holds.
Django's own validation hands such a number to the database driver in two
places, and SQLite's raises OverflowError for one past 64 bits: a
model choice field matching its key, and a ModelForm's uniqueness
checks and constraints querying with a value. Each is answered first, in
the words of the check Django would have made:
- a model choice field sent a key its column cannot hold is taken off the
form while it validates and given the field's own
invalid_choicerefusal after, so the form'sclean()and its other errors are found as Django finds them with the field refused; - a
ModelForm's value its integer column cannot hold is refused as the model's validation step starts, before its uniqueness checks and constraints query with it, with themin_valueormax_valuerefusal of Django's model integer field.
Shared by FormValidator, which validates its form so, and by
django-spec-html's add_argument_errors, which finds a form's own
errors so before it places a refusal beside them.
The form is left as it was found, whether its validation returned or
raised: every field it had, in its order, and its own _post_clean,
the class's or one the form carried itself. Only its errors and what it
cleaned are new.
Public so that a transport in a distribution of its own, validating a project's form, holds it to the same columns with the same words.
Flat sources¶
flat_arguments ¶
A flat source as strings and lists of strings, read by parameters, blanks read as absent.
A flat source is a query string or a form's fields: Django's QueryDict,
or any MultiValueDict, where every value is a string and a key may
repeat. A transport reading one calls this, merges its route's kwargs into
what comes back, and hands the result to
coerce_flat,
so every transport reading a flat wire reads it by the same rules. Nothing
is coerced here.
A flat source is read by the declaration. A parameter of type
array takes every value its key was sent with, and anything else takes
the last, as QueryDict reads a repeated key. An array of numbers,
integers, booleans or decimal strings also reads a value holding commas
as its elements, ?ids=1,2 as ["1", "2"] with the space around a
part trimmed, because a comma cannot be part of such a value and it is
the spelling a django-filter CSV filter advertises; repeated keys and
commas may mix. An empty part (?ids=1,,2) is not dropped as a blank
element is: it is kept, for coerce_flat to refuse at its index as any
malformed element is. A string array is split only where its choices
hold no comma, as an ordering's do, so ?o=title,-pk is
["title", "-pk"]; otherwise it is never split, since a comma is part
of a string. An array is read no further than one element past the
most it takes - its max_length, or the
SERVICE_SPECS_MAX_ARRAY_LENGTH setting's default - so coerce_flat
refuses a list over it at its name as a whole, without a million commas
becoming a million elements first; Django's
DATA_UPLOAD_MAX_NUMBER_FIELDS counts keys, and a comma list is one.
A blank value is absent unless "" is one the parameter can
take: a plain string can, and a number, a boolean, a date, a decimal,
or a string whose choices leave the blank out cannot. A flat wire has no
other spelling of "left blank", and an empty ?count= or ?since=
from a filter form is not a refusal to count or a malformed date. Each
blank element of an array is read by the same rule, the whole array
absent once nothing is left. Django's csrfmiddlewaretoken, the field
{% csrf_token %} renders into a form, is dropped: no Django transport
takes it as an argument. A key parameters do not declare is kept as
it is, so the closed argument set in dispatch stays the one place that
refuses it, under the caller's policy.
Validation¶
Validator ¶
Bases: ABC
The kernel's validation contract.
parameters() declares what the Validator takes, and validate()
turns JSON-like primitives into validated values or raises
InvalidArguments.
An adapter reads its library's own declaration into parameters(), and
must not query doing it: a transport describes a spec before any call.
Nominal on purpose. An adapter subclasses this, and subclassing is the
opt-in. A structural check on a method name is the gate that lets stock
classes through by accident: an is_valid protocol matches a Django form
and a DRF serializer, and a validate protocol matches a DRF serializer
and a pydantic model class, none of which was written to this contract.
No instance and no many keyword: the row a call acts on is target
resolution, and a many spec's list is handed to validated_many(),
a method of its own. partial arrives in the
ValidationContext
rather than as a keyword, because it is the spec's statement about the
call, not the Validator's: a partial call may leave out any field, and a
Validator returns only the fields the caller sent, or refuses a partial
call with ImproperlyConfigured when what it builds needs every field.
Ignoring the flag is the one wrong answer, since the omitted fields would
come back cleaned to blanks and an update would write them.
supports_partial says which of the two a Validator does, so a spec
learns it when it is declared rather than on its first call: a
ServiceSpec declaring partial=True over a Validator whose
supports_partial is False is refused when it is built. True
by default; DataclassValidator and PydanticValidator set it
False as a class attribute, since each builds every field, and a
subclass of either that does handle a partial call sets it back. An
adapter whose answer depends on what it was built over sets it on the
instance in __init__ instead, and the spec reads the instance. The
refusal at the call stays, for a Validator called directly.
unsendable names the fields the Validator requires that its
parameters() leaves out. No caller can send such a field, since a
transport offers only what parameters() declares, so a transport can
read it where it registers a spec and refuse the spec there rather than
on every call. Empty by default, which is the right answer for a Validator
that declares every field it requires, as the kernel's own adapters do. An
adapter whose library can require a field it does not declare, such as a
DRF serializer requiring one named like a seed, overrides it with a
property, which may read what the instance was built over. The default is
a property with no setter, so unlike supports_partial an instance of a
class that inherits it, or overrides it with a property, cannot assign it
(test_an_instance_cannot_assign_unsendable). A plain class attribute also
answers a reader, but the type checker does not hold its type, and an
instance can then assign it
(test_an_instance_can_assign_a_class_attribute_override).
Sync-only. A Validator may query - a uniqueness check does - so dispatch
runs it in the executor on the async path, and it must not be async def.
validate() receives only the arguments its own parameters()
declare: the caller's, through the shape check, with the spec's
input_data merged over them. Through dispatch every required field
is among them, whoever filled it, since one nobody filled is refused in
the shape check's words before validate() runs
(test_a_required_field_nobody_filled_is_refused_before_the_validator_runs).
bind_arguments runs no provider, so there a field input_data
fills or may fill can arrive absent, and is the Validator's to refuse
(test_a_field_input_data_fills_is_left_to_the_validator_which_runs_no_provider).
It returns the values the
operation receives, keyed by name; a nested row may come back as whatever
the library builds (a dataclass instance, a model instance), since the
mutation helpers read either.
validated() is the call's whole result, and what dispatch asks for: the
values, the call's data, and any value the Validator binds for the
call. An adapter overrides it where its data is not the mapping
validate() returns, as the dataclass and pydantic adapters' is the
instance they build, or where the library leaves an object the service
may want; the rest need not touch it.
validated_many() is what dispatch asks of a many spec instead: the
whole list at once. By default it is validated() on each row, which
serves a Validator whose library validates one row at a time. An adapter
whose library validates a list as one, running list-level checks and
binding one object for the call, overrides it.
unsendable
property
¶
The required fields parameters() leaves out, which no caller can send.
Empty by default. A transport can refuse a spec over a Validator that names any, where it registers the spec. An override is a property, which may read what the instance was built over, or a class attribute.
parameters
abstractmethod
¶
What this Validator takes, as a declaration. Never queries.
A Validator may opt into the call it is asked for by declaring
parameters(self, *, call_context=None): every ask inside one call
then hands it that call's call_context, the same dict its
ValidationContext carries, so a transport describing a serializer
under its own request can tell its own call from a dispatch the
service makes inside it. It is None outside a call - at
registration, for a schema handed no context, or for any other reader
describing the spec - and the declaration must hold there too. Opted
in or not, it never queries. A Validator declaring no keyword is asked
as before, as is one whose parameters takes only **kwargs or is
a functools.wraps wrapper that does not name the keyword itself:
the method's own signature decides. The helpers a transport calls
during a call - apply_server_arguments,
check_requested_input, server_owned_keys - take the call's
dict as call_context= and ask with it. So do those it describes a
spec with - spec_caller_input_schema, spec_input_schema,
provider_reached - which also take a transport's stamped dict with
no call under way, where request and view are None, so a
declaration read under one must hold without them.
validate
abstractmethod
¶
Validated values, or InvalidArguments. May query; never async def.
validated ¶
validate()'s values, as the call's data too, with nothing else bound.
One validate() call, so a Validator that queries queries once. An
override returns the same values its validate() would, and may
hand an object as data and bind values in pool.
validated_many ¶
validated_many(
rows: Mapping[int, Mapping[str, Any]],
context: ValidationContext,
*,
many_argument: str,
) -> Validated
A many call's rows, validated as one call: what dispatch asks of a many spec.
rows maps each row's index in the caller's list to its arguments,
already through the shape check, with the spec's input_data merged
over each and only the keys parameters() declares, as on a single
call. A row the shape check refused, or one dispatch refused for a
required field nobody filled, is not among them, so the indices
may have gaps: an override validating a list maps its library's
positions back through list(rows), and a list-level verdict it
reaches sees only the rows handed to it.
Returns the call's Validated: values holds the rows' values as
a list under many_argument and nothing else, since a row's fields
are never spread into the service's keywords; data is the list a
service declaring data receives; pool is what the Validator
binds once for the whole call.
Refuses with InvalidArguments whose detail is the list's own
node: each failing row's tree under its int index, and a message
about the list as a whole under non_field_errors. Dispatch puts
the shape check's refusals beside it and raises the whole under
many_argument, so every failing row is reported at once.
By default, validated() on each row in order, every refusal
collected before any is raised, and each row's data and values in
a list. A value a row binds is refused with ImproperlyConfigured:
the service runs once for every row, so a value bound for one has
nowhere to go. An override that binds for the call binds once.
Validated
dataclass
¶
The values a call's service is called with, its data, and what else it binds.
Validator.validated()
returns one, and dispatch builds the call's pool from it: values
spread by name, data under its own name, and pool beside both.
valuesis whatvalidate()returns: the validated values keyed by the name the service takes each under.datais the validated object as a whole, which a service declaringdatareceives. For a mapping Validator it isvaluesitself; forDataclassValidatorandPydanticValidatorit is the instance, whose fieldsvaluesholds.poolis any other value the Validator binds for this one call, such as the bound object a library validated through, so a service can ask for it by name. Empty unless the Validator says otherwise.
Three fields rather than one mapping, because data need not be a
mapping at all, and a value bound for the call is not one the caller sent:
neither belongs among the values a caller's argument names.
validator_parameters ¶
validator.parameters(), handed call_context where it declares the keyword.
Every ask inside one call passes that call's dict, the same object, so a
Validator keyed on the dict describes one call one way. Every ask outside a
call - registration, a schema, a describe-time reader - passes None,
unless a transport describing a spec hands a stamped dict with no call
under way. Handed None, the Validator is asked as it always was, with
no keyword at all
(test_an_opted_in_validator_asked_outside_a_call_is_handed_no_keyword).
Otherwise the keyword is passed only to a parameters naming
call_context itself (_declares), so a Validator that never
declared it is asked as before
(test_a_validator_declaring_no_call_context_is_asked_as_before).
Dispatch asks every Validator through this, and so should a transport
that asks one itself during a call - for the names of a many spec's
rows, say - handing it the call's dict, so a Validator that opted in is
described as dispatch describes it, whoever wrote it
(TestThePublicName.test_an_opted_in_validator_is_handed_the_call_s_dict_through_it).
ValidationContext
dataclass
¶
The principal, the target, whether the call is partial, its seeds, and the call's context.
target is here, rather than a constructor keyword the way DRF takes
instance=, because the kernel is what resolves it: target resolution
runs before validation, so an update's uniqueness check can exclude the
row being updated. It is the resolved row for a spec with an instance
selector, the resolved queryset for one with a collection selector, and
None for a create.
partial is true for a call that may leave out any parameter, an update
of only what it names: the shape check in front of the Validator has not
refused an absent required one. A Validator then returns only the fields
the caller sent, or refuses the call with ImproperlyConfigured if it
cannot. It trails the other two with a default, so a context built from a
principal and a target is a whole call.
ambient is the call's base pool as dispatch resolved it: user,
progress and every registered seed - an HTTP adapter's request,
a view it registers, a tenant - read-only at its top level. Its values
are the call's own live objects - the principal itself, for one - so a
Validator must not mutate them
(test_the_validator_reads_the_registered_seeds_and_the_user holds both
halves). A library whose validation
reads what its caller registered, as a serializer reads its context's
request, finds it here rather than in an argument. It never holds an
argument, a validated value or the target, which have seats of their
own. Empty for a context built by hand, and in bind_arguments handed
no pool_seeds; it trails the others, so neither changes.
resolved is the target under the pool name dispatch hands it to the
service as, read-only: {"instance": row} for a spec with an instance
selector - {"instance": None} when one that allows none finds no row
- {"collection": rows} for one with a collection selector, and empty
for a create. target is the same object with the role taken off, so a
callable a Validator resolves through the pool, as FormValidator's
form_kwargs is, names it as a selector or a service does. Dispatch
fills it from the target it resolved, and bind_arguments from the
target its caller passes and the spec's selectors, by the one rule
both share. Empty for a context built by hand; it trails the rest, so no
existing construction changes.
call_context is the call's context: one plain dict the transport
creates for its natural scope - a request, an agent run - and hands to
dispatch, which every stage that declares it receives as the same object.
A Validator reads it and writes to it directly, as a DRF serializer does
its context, and a later stage of the call reuses what it put there
rather than computing it again. Unlike ambient it is the transport's
and the stages' to change; the kernel writes nothing to it. A context
built by hand gets an empty dict of its own, never one shared with
another, so a Validator that writes to it needs no guard for a call that
was handed none. It trails every other field, so no existing
construction changes. One key is the family's rather than any one
transport's: "transport", where stamped, names the transport that built
the context, by convention only - dispatch neither writes nor reads it,
so read it with
call_transport.
Output¶
Presenter ¶
Bases: ABC
Turns one value an operation produced into JSON-like data.
output() declares the result and present() renders one value. They
are separate because describing the result is not optional where rendering
is: an HTML transport hands the object to a template and never renders it,
but its confirmation page still reads what the result declares.
present takes one value. A list result is handed to
presented_rows() whole, which by default presents it item by item, so a
Presenter never has to guess whether it was handed a row or a collection of
them.
presented() is what dispatch's present asks for a single value: one
value and the call's
PresentationContext.
By default it is present(value), so a Presenter that reads nothing of
the call overrides present() alone. One whose library renders under a
context - the principal, a request a transport registered as a seed -
overrides presented() and reads it there. A method of its own rather
than a keyword on present(), so every Presenter written against
present(value) is still one, and nothing reads a signature to decide
whether to pass the context.
presented_rows() is what it asks for a list: every row it presents at
once - a transport serving one page has already sliced the result, so the
page's rows - and the same context. By default it is presented() per
row, so only a Presenter that batches something over the rows overrides
it: one lookup for every row on the page rather than one per row, or a
library whose list rendering takes the collection.
Sync-only. Presenting a row that reads a relation is a query, and the
kernel cannot tell in advance whether the row was prefetched, so the async
path runs every Presenter in the executor. An async def present,
presented or presented_rows is refused when the spec is built, and
an answer from any of the three that is still to be awaited is refused
where it is read.
output
abstractmethod
¶
What present returns, as a declaration; None for no JSON shape. Never queries.
present
abstractmethod
¶
One value to JSON-like data. May query; never async def.
presented ¶
One value to JSON-like data, for the call context describes: present(value).
context is None for a result dispatch did not build, such as
a DispatchResult a transport constructed itself.
presented_rows ¶
Every row of a list to JSON-like data, in one call: presented() per row.
values is a tuple of the rows being presented, already evaluated,
so it can be walked as often as a batched lookup needs. Return a
list with one presented value per row, in the order given: a
selector spec's affordances are added to each presented row by its
position, so dispatch's present refuses an answer that is not a
list or whose length differs from values. context is the one
every row of the result shares, as presented() receives it.
PresentationContext
dataclass
¶
The principal a call ran for, its target, its seeds, its context and its shapes.
The output-side counterpart of
ValidationContext.
Dispatch builds one per call and carries it on the
DispatchResult,
and present hands it to
Presenter.presented()
with every value it presents, so a library that renders under a context -
a field defaulting to the current user, a link built from the request - can
read the call it is rendering for.
principalis who the call ran for.targetis the row or the queryset a service spec resolved,Nonefor a create and for a selector spec, whose rows are the value itself.ambientis the call's base pool, read-only at its top level:user,progressand every registered seed, such as an HTTP adapter'srequest. Its values are the call's own live objects, so a presenter must not mutate them (test_a_selector_spec_s_rows_are_each_presented_with_the_call_s_context holds both halves). Never an argument, a validated value or a provider's key.call_contextis the call's context, the one plaindictthe transport created for its scope and every stage that declares it received, as onValidationContext: the Validator, the service and the presenter share one object, so a presenter - and a nested one handed the same context - reuses what an earlier stage put there. It is the presenter's to read and write; the kernel writes nothing to it. A context built by hand gets an empty dict of its own. Its"transport"key, where stamped, names the transport that built the context: a family convention dispatch neither writes nor reads, so read it withcall_transport.shapesis what the caller sent for the spec's declaredshapes, the arguments that shape the output - which fields, a query over the rows - by name, read-only. An argument the caller left out is absent rather thanNone. Empty for a spec that declares none and for a context built by hand; no other argument is ever here. Under dispatch it is also the pool'sshapesseed, so a selector namingshapesreads what the presenter reads.
Output
dataclass
¶
The ordered fields of an operation's output, read without rendering anything.
Readers that never render: an agent tool's output schema, a capability manifest, a command's table header when there are no rows, a confirmation page's target display. Ordered, because a table's columns are, and the order is declaration order.
Paired with Parameters:
that is what goes in, this is what comes out.
OutputField
dataclass
¶
One field of an operation's output, declared without rendering anything.
The output-side counterpart of
Parameter,
carrying what a reader needs that names and types alone do not give:
label: a readable header. Libraries disagree here (one inventsIdfromid, others give nothing), so the adapter supplies what its library has andNonemeans it has none.choices: value-and-display pairs, because a table shows the display and a schema states it as a title, and a bare value list gives neither.always_present: whether the key is in every rendered row. A rendering rule rather than a type - one library drops a read-only key it cannot read where another always emits it - so the adapter supplies it, and a schema lists only always-present keys as required. The schema of a spec declaring shapes requires none of a row's keys, whatever this says.marking: how an agent audience is shown the field.
fields and items describe a nested object and an array's element,
and items_nullable whether a null may stand in for an element, as on
Parameter.
type is one of the JSON types, or any for a value whose JSON type
is open - a computed field, a JSON column - which a schema then describes
with no type at all rather than as a string it may not be. As on
Parameter, any lists no choices, since a list of values says what
type they are, and an array of any element declares no items rather
than items="any".
json_schema_extra carries the JSON Schema keywords no field of an
OutputField spells, as on Parameter: a mapping of keyword to value,
held as a deep copy of its own, which
output_schema
adds to this field's node. A keyword a field states there is refused
here, naming the field, whether or not this field sets it: type,
format, items, the choices' enum, oneOf and const,
title from label, and properties and required from
fields; so is a value JSON cannot carry. It describes what the
presenter renders and constrains nothing.
Out of the hash and in equality, as on Parameter.
FieldMarking
dataclass
¶
How one output field is presented to an agent audience.
Carried on the OutputField
it marks, so it belongs to the declaration of what an operation returns
rather than to whichever library rendered it. That is what lets a
transport's projection for an audience work over a dataclass, a pydantic
model and a DRF serializer alike: each adapter reads its own library's
declaration into Output, marking included, and the projection reads
only Output.
Applied only for a caller that names an audience:
audience_projection_for_spec
reads the markings into an
AudienceProjection,
which
present_for_audience
applies to the presented value and
spec_output_schema
to the schema. A caller that names none, which is every HTTP response, is
presented every field whatever its marking.
The marking lives on the field, not in a list beside the output. That is what lets it travel into a nested output with no hoisting rule, and what stops a rename from silently desyncing it from a name the parent maintains.
description
class-attribute
instance-attribute
¶
Audience-facing description, replacing the field's help text for this audience only.
Help text is shared with every human reader, so it cannot say "opaque handle, never read this out". This can, without changing a word of what a human reader sees.
formatter
class-attribute
instance-attribute
¶
How this field's value is rendered for an agent audience, if not verbatim.
A ValueFormatter
transforms the value and declares the JSON type it produces, so the
payload and the schema move together. Unset, the default, changes
nothing.
An explicit formatter wins over the substitution of a choice's display, which is a real collision: a status field can have choices and still be something an author wants spelled their own way. Only one transform can apply, and the one written by hand is the one that was asked for; a derived default losing to an explicit declaration is the ordinary direction.
HANDLE suppresses it, exactly as it suppresses choice
substitution: a handle is another tool's input, and a formatted machine
identifier is a broken one. Declaring both is honoured as HANDLE and
the formatter never runs. A field a second tool takes as input therefore
wants handle,
or that tool receives a display string its own input schema rejects.
handle
classmethod
¶
An opaque identifier: passed to other tools, never spoken to a user.
hidden
classmethod
¶
Plumbing: dropped from the projected payload and the projected schema.
label
classmethod
¶
The field that names this record for a human.
formatted
classmethod
¶
Ordinary content, rendered through formatter.
The generic constructor: any transform that declares what it produces.
timestamp
is one of these with the formatter filled in, and a field that is both
formatted and something else - a formatted label, say - is written as
FieldMarking(FieldAudience.LABEL, formatter=...).
timestamp
classmethod
¶
A date-time read as a formatted local string rather than raw ISO-8601.
The zone is Django's active one and cannot be passed here; fmt is a
strftime string and defaults to a day-first, 24-hour rendering.
ValueFormatter.timestamp
holds the transform and the reasoning behind both of those.
AudienceProjection
dataclass
¶
How one operation's output is shaped for an agent audience.
Read off the FieldMarkings
and the choices an Output
declares, by
audience_projection_for_spec.
Nothing here depends on the value being presented, so a transport builds
it once, where it registers the spec, and passes it to every
present_for_audience
and spec_output_schema
rather than reading the declaration again per call.
One projection drives both
project_payload
and
annotate_output_schema,
which is what keeps the advertised schema describing the payload sent.
fields
class-attribute
instance-attribute
¶
Every explicitly marked field, by name. Unmarked fields are absent.
label
class-attribute
instance-attribute
¶
The field naming this record for a human, if one is marked.
choice_labels
class-attribute
instance-attribute
¶
Per field with choices, the {value: display} pairs whose display
differs from the value. Absent for a field whose displays only repeat its
values.
nested
class-attribute
instance-attribute
¶
Child projections, by field name, for a nested object and for the objects of an array.
is_empty ¶
True when applying this projection would change nothing.
The fast path: an unmarked output with no labelled choices anywhere costs a caller one boolean rather than a walk of the payload.
A value formatter needs no term of its own: it is carried by a
marking, so an output that declares one has a non-empty fields
already. A term that can never be the deciding one goes stale without
failing.
One or-chain, so each term is held by its own case of
test_each_term_alone_makes_it_non_empty.
audience ¶
The audience declared for name, defaulting to CONTENT.
formatter ¶
The formatter that applies to name, or None.
None for a HANDLE however the two were declared together: a
handle is another tool's input and a formatted machine identifier is a
broken one. The suppression lives here rather than in each walk, so the
payload and the schema cannot end up formatting different fields,
which is the one failure the projection exists to make impossible.
audience_projection_for_spec ¶
audience_projection_for_spec(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
overrides: Mapping[str, FieldMarking] | None = None,
name: str | None = None,
) -> AudienceProjection
Resolve the markings on the Output spec
presents.
The output is spec.output(): a selector spec's presenter's, or a
service spec's own presenter's, or its output selector's when it declares
none. A transport that registers its tools up front calls this once per
spec and hands the result to
present_for_audience
and spec_output_schema,
so the payload it sends and the schema it advertises are projected by one
declaration.
Each OutputField
contributes its marking, its choices whose display differs from the
value, and, for an object's fields or an array's items declared as
an Output, a child projection when the child has anything to project.
A spec with no output yields an empty projection rather than an error:
there is nothing to mark up.
overrides layers a mount's own markings over the declaration's, for the
one case the declaration cannot express: a mount that needs what its
sibling hides. The declaration stays authoritative, and an override is the
exception rather than a second place to declare an audience. Only the
top-level markings and the label move; the choices and the children come
from the declaration. name identifies the mount in the refusals below,
the two-label one included: it replaces Output as what that message
calls the output, and without it the wording is unchanged.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
Two fields of one output
are both marked |
project_payload ¶
Drop plumbing, speak choice displays and format values, at any depth.
Three changes, each driven by the declaration that shapes the schema in
annotate_output_schema,
so the two cannot disagree:
- fields marked
HIDDENare removed. Removed rather than moved under some reserved key: a payload a model reads is read in full either way, so moving a field costs its keys again and hides nothing. What an agent must never use should not be there. - a field's choice value is replaced by its display, so a person is not
read
PENDING_REVIEW. Not on aHANDLE, which another tool takes as input. An array of choices is substituted member by member rather than looked up whole. - a field whose marking carries a
ValueFormatteris rendered through it: a date-time read as a local date-time rather than raw ISO-8601, an amount with its currency. It wins over the choice display, being the transform an author wrote by hand, and over a nested output's projection. Also not on aHANDLE, for the same reason, and a null is never formatted.
A payload that is neither an object nor a list of them is returned as it is, and so is every key the projection has nothing to say about, including one a transport added beside the declared fields.
Apply this where a payload becomes an agent's answer, not where it
feeds the next step of a chain, which still needs the handles. Returns a
new payload and never modifies payload.
annotate_output_schema ¶
annotate_output_schema(
schema: dict[str, Any] | None,
projection: AudienceProjection,
*,
handle_description: str | None = None,
) -> dict[str, Any] | None
Apply to a schema the projection
project_payload applies to the
payload.
Four changes, each the mirror of one the payload undergoes:
- hidden properties are removed, and dropped from
required, which is left out when nothing in it remains; - a marking's
descriptionbecomes the property's"description", so a handle says what it is for in the schema a model reads without that wording reaching any other reader; - a field with labelled choices is restated in its displays, because
that is what the projected payload carries: an
enum's values are replaced, and aoneOf'sconsts are, each losing thetitlethat annotated the value it now equals. A"type"stated beside them is restated as the types of the values now listed, so a display string is never described as the integer it replaced, with"null"named last where the stated type admitted it and a null is still served - not where the choices giveNonea display, which is served in its place - and left as written beside aoneOfentry that admits more than its constants. A display two values share is listed once, so a row served it matches oneoneOfentry rather than two, and an array of such choices no longer claimsuniqueItems. Not on aHANDLE, which keeps its values on both sides: a field another tool takes as input should be marked one. - a formatted field is restated as the type its
ValueFormattersays it produces, plus whatever that declaration adds about the shape of the produced value, in place of everything the property said about the value before, choices included. Itstitleanddescriptionare kept, and so is anullthe property admitted - however it stated one, as a type, ananyOfmember,Nonein anenumor aoneOfentry for a labelled choice - since a null is never formatted. The type is written fromproducesrather than taken from the fragment, so a renderer cannot contradict its own advertisement, and a fragment'senumlists the null too, and itsconstbecomes anenumof that value and a null, where the property admitted one. Not on aHANDLEeither.
Generating both sides from one declaration is the point: a schema that advertises a field the payload no longer carries is worse than either behaviour on its own.
handle_description is the wording for a HANDLE whose marking
declares none, and defaults to nothing. Telling a reader what to do
with an identifier is advice for one kind of reader, and the kernel does
not know which kind is reading. The transport that knows its audience
supplies the sentence.
Takes the item schema; an array's items are annotated and the
array kept. A caller wrapping items in an envelope of its own annotates the
item and wraps it afterwards, as
spec_output_schema
does. None, or a projection with nothing in it, returns schema
itself; anything else returns a new schema and never modifies schema.
Files¶
A spec whose result is a file, as presenting a file describes it.
FileResult
dataclass
¶
A file an operation produced: its content, its name, its type and its size.
content is bytes, a binary file object (a Django File, an open
IO[bytes]) or an iterable of bytes. A str is refused, since it
is text rather than a file, and so is an async iterable, which no
transport streams yet.
filename is shown to a caller and quoted into a header, never joined to
a path, so it is refused when it is empty, . or .., or holds a
path separator (/ or \), a NUL or any other control character.
content_type is the media type, or None for a
FilePresenter
to fill. size is the length in bytes, read from bytes or from any
object with an int size (a Django File) when it is not given,
and None when it cannot be known without reading.
The content is read once: a file object or a generator is consumed by
read(), and both read() and close() close it.
read ¶
The whole content, closing it; past max_bytes, closes it and raises FileTooLarge.
Raises:
| Type | Description |
|---|---|
FileTooLarge
|
The content is longer than |
TypeError
|
An iterable yielded something other than |
FileTooLarge ¶
Bases: Exception
A FileResult read past the ceiling a transport set; max_bytes names it.
Not a DispatchError: the operation ran and produced the file. Each
transport answers it in its own terms, as it answers a not-found.
FilePresenter ¶
Bases: Presenter
Declares that an operation's result is a file of content_type, and presents it.
present(value) hands a
FileResult on
as it is, with its content_type filled from this presenter's when it
has none. Any other value goes through render(value), or is the content
itself when there is no render, and is wrapped in a FileResult
named by filename: a str, or a callable of the value such as
lambda invoice: f"invoice-{invoice.pk}.pdf". A render that answers
with a FileResult is handed on the same way.
output() is None: a file has no JSON shape, so
spec_output_schema
describes none. A transport reads the declaration through
file_output when it
registers the spec.
file_output ¶
The FilePresenter
spec presents its result through, or None when its result is not a file.
What a transport asks when it registers a spec, so it serves a file, or
refuses to, before the first call. The presenter is a selector spec's own,
or a service spec's presenter_for_output(): its own, or its output
selector's.
allow_none is allowed: a None is answered as the transport answers
nothing for any other spec.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
The file would be one of
many: presented by a |
JSON Schema¶
spec_input_schema ¶
spec_input_schema(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
unknown_arguments: UnknownArguments = UnknownArguments.REJECT,
call_context: dict[str, Any] | None = None,
) -> dict[str, Any]
parameters_schema over
spec.parameters().
The whole argument set dispatch checks: a selector spec's reads and
shapes, or a service spec's target selector's reads, its own, its
shapes, then its Validator's parameters. A many service spec's is
its reads, its shapes and the one list its many_argument
names, each row an object of the Validator's parameters. A shape is an
argument like any other here, closed set included, though only the
presenter reads it. Pass the unknown_arguments the transport dispatches with,
because the schema closes the argument set exactly when dispatch does.
A partial spec's Validator parameters are required nowhere, at
any depth - an object's fields and an array's rows included - because
dispatch refuses none of them absent: a client reading required would
otherwise never send the partial call the spec exists for. Its reads
and its target selector's keep their required, as dispatch keeps
them, so the schema still says which row a partial update names. On a
many spec the list stays required and its rows' fields are not.
parameters() itself is unchanged and still says what a whole call
needs. Nothing else is relaxed: a read a kwargs provider fills or may
fill is listed as declared, required meaning the call needs the value
from someone - the caller, or a provider that may fill it. A
reflected read and a Validator field named like a registered seed are
listed as declared too, and so is anything a transport binds or
withholds: this takes no ServerArguments. The schema a transport
advertises, less what the server fills and with nothing a provider may
fill required, at the top and in each row of a many spec, is
spec_caller_input_schema.
Read on every call, as parameters() is, so a Validator reading a
model-backed declaration is asked only once the app registry is ready.
Describe-time unless handed a context: a schema describes the spec
outside any call, so with no call_context a Validator that declares it
is handed None (test_describe_time_readers_hand_none). A transport
describing the spec under a context of its own hands that dict, and the
Validator is asked with it, as spec.parameters(call_context=...) asks
(test_a_field_declared_only_to_a_call_is_listed_under_that_call_s_context_alone).
spec_caller_input_schema ¶
spec_caller_input_schema(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
server_arguments: ServerArguments | None = None,
unknown_arguments: UnknownArguments = UnknownArguments.REJECT,
call_context: dict[str, Any] | None = None,
) -> dict[str, Any]
What a caller is asked to send spec:
spec_input_schema less what
the server answers.
spec_input_schema lists every parameter as declared, required
meaning the call needs the value from someone. This is the schema a
transport advertises, so required means the caller, and it requires
exactly what dispatch refuses the caller for leaving out
(test_the_top_level_requires_exactly_what_check_call_refuses_absent):
- Withheld, from
propertiesandrequired: every nameserver_owned_keyslists forpool_seeds, the seeds the transport dispatches with (test_a_read_a_typed_kwargs_fills_is_not_offered, test_a_reflected_read_named_for_a_registered_seed_is_withheld_only_under_those_seeds), so a Validator field named like a registered seed is still offered (test_a_validator_field_named_for_a_registered_seed_is_offered); and thenames()of the transport'sserver_arguments, bound and withheld alike (test_bound_and_withheld_server_arguments_are_not_offered). This does not check that binding:check_server_argumentsdoes, once, when the transport is built. Amanyspec's list is the one nameserver_owned_keyslists that is not withheld: a provider annotated to fill it is refused when the spec is built, so it is listed only where a mount registers a seed of that name, which dispatch refuses (test_a_many_spec_s_list_is_offered_where_a_mount_registers_a_seed_of_its_name). - Offered and not required: a parameter a provider may fill,
provider_reached, the set the shape check relaxes, read seat by seat (test_a_read_a_provider_may_decline_is_offered_and_not_required, test_a_selector_spec_s_reads_beside_an_untyped_kwargs_are_offered_and_none_required, test_a_key_the_spec_s_kwargs_may_decline_leaves_the_target_s_read_required, test_a_validator_field_input_data_may_fill_is_offered_and_not_required). Not a read a provider requires itself: a provider is handed the caller's reads and the seeds, never another provider's answer, so dispatch demands it of the caller and it stays inrequired(test_a_read_a_provider_requires_itself_stays_required).
On a many spec each row is read the same way, by what
input_data reaches there: it runs once per call and is merged over
every row, so one items serves them all. A field it is annotated to
fill leaves the row's properties, since dispatch drops the caller's
value for one once checked
(test_a_row_field_a_typed_input_data_fills_is_not_offered_in_any_row),
and one it may fill is offered and not required
(test_a_row_field_a_typed_input_data_may_decline_is_offered_and_not_required,
test_beside_an_untyped_input_data_a_row_requires_nothing). The two levels
stay apart. A row's relaxing never reaches the top, where the list and
the reads stay as dispatch demands them
(test_a_row_s_relaxing_stays_out_of_the_top_level). Nor does the top's
withheld set reach a row: check_server_arguments refuses binding a
row field, a registered seed's name leaves a row field of that name the
caller's, and kwargs is merged into the service's pool, never a row
(test_a_read_bound_by_the_server_leaves_a_row_field_of_its_name_offered,
test_a_registered_seed_leaves_a_row_field_of_its_name_offered,
test_an_untyped_kwargs_leaves_every_row_as_declared). Dispatch agrees row
by row
(test_a_row_omitting_a_relaxed_field_is_dispatched_and_one_omitting_a_required_field_is_refused).
partial is spec_input_schema's, applied first, and a required
left empty, at either level, is dropped, as spec_input_schema writes
none for a spec requiring nothing
(test_a_partial_many_spec_withholds_a_filled_row_field_and_requires_nothing_in_a_row).
unknown_arguments closes both levels or neither, as dispatch does
(test_the_unknown_argument_policy_closes_both_levels_or_neither).
Off a many spec, the reading django-spec-mcp and django-spec-agents
made of spec_input_schema before this existed
(test_off_many_it_is_the_mcp_and_the_agents_reading), but for a read a
provider requires itself, which django-spec-agents' reading relaxed;
neither read a row
(test_on_a_many_spec_the_transports_readings_part_from_it_only_in_the_rows).
spec_input_schema itself is unchanged and still lists what the server
fills (test_spec_input_schema_still_lists_what_the_server_fills). A
SpecSource is
described as the spec it compiles to
(test_a_spec_source_is_described_as_the_spec_it_compiles_to). Read on
every call, as parameters() is
(test_the_declaration_is_read_on_every_call).
Describe-time unless handed a context. With no call_context a
Validator that declares it is handed None, and server_owned_keys and
provider_reached are read with no call's context
(test_describe_time_readers_hand_none), so a field declared only to a
transport is not offered
(test_with_no_call_context_the_schema_is_the_declaration_made_to_no_call).
A transport describing the spec under a context of its own, a stamped one
above all, hands that dict, and it is the object every ask of the Validator
is handed (test_a_reader_handed_a_context_hands_that_object_to_every_ask).
The field is then offered there and nowhere else
(test_a_field_declared_to_one_transport_is_offered_and_required_under_its_context,
test_a_field_declared_to_one_transport_is_not_offered_under_any_other_context),
and read as dispatch reads it under that dict: withheld, relaxed and
required at each level by what its context declares
(test_a_seed_named_field_declared_only_to_a_transport_is_the_caller_s_under_its_context,
test_a_field_declared_only_to_a_transport_input_data_may_fill_is_not_required,
test_a_row_field_declared_only_to_a_transport_input_data_fills_is_not_offered,
test_a_row_field_declared_only_to_a_transport_input_data_may_fill_is_not_required,
test_under_a_context_it_requires_exactly_what_check_call_refuses_absent_under_it).
A Validator declaring no call_context is asked as before
(test_a_validator_declaring_no_call_context_is_asked_as_before_under_one).
No call need be under way: where a transport has none, the dict of
build_call_context names it, with request and view None.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
a declaration that fails assembly, one a Validator
makes only under the handed |
spec_output_schema ¶
spec_output_schema(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
paginate: bool = False,
projection: AudienceProjection | None = None,
handle_description: str | None = None,
) -> dict[str, Any] | None
The JSON Schema of what present returns
for spec.
None when spec.output() is None: a spec with no presenter
declares nothing about what it returns, and a shape invented for it would
be a guess every client then trusts. So does a spec presenting a file
through a
FilePresenter,
which has no JSON shape to describe. A
SpecSource is
described as the spec it compiles to.
Otherwise the item's output_schema,
shaped by what dispatch returns for this kind of spec:
- A LIST selector spec, or a service spec whose output selector is a
LIST, presents every row:
{"type": "array", "items": <item>}. - A RETRIEVE selector spec with
allow_nonepresentsNonefor a missing row, so the item's type gains"null". Withoutallow_nonea missing row is not-found, which a transport answers in its own terms and never presents, so the item stays as it is. - A service spec whose output selector is a RETRIEVE gains
"null"whatever itsallow_nonesays: once the service has run, a re-read that finds nothing isNonerather than not-found, because reporting not-found would tell the caller a committed write did not happen. - A
manyservice spec with no output selector, or areturns_manyone, which never has one, presents the rows its service returned as{"type": "array", "items": <item>}, never paged, which gains"null"when the spec declaresallow_none. - A service spec with no output selector presents what the service
returned, described by its presenter as the item, which gains
"null"when the spec declaresallow_none. Undeclared, aNoneis not stated and the item stays strict: whether a service may return one is not otherwise in its declaration.
Where "null" is admitted is
can_present_nothing's
answer, which a transport writing a schema of its own asks too.
paginate describes a list served one page at a time, as
paginate_output
and OutputPage.envelope
shape it: {"items": [...], "page": n, "totalPages": n, "hasNext": b},
every key required. It changes only a list's schema, since one row has no
pages, so a transport may pass it for every spec it serves paged.
projection describes what
present_for_audience
hands back rather than what present does, through
annotate_output_schema:
hidden fields left out, labelled choices restated in their displays, and a
marking's wording as a field's "description". It lands on the
item, wherever the item sits, because the array and the paging
envelope are this function's own shapes and belong to no Output. Omit
it, as every caller naming no audience does, and the schema is the full
declaration. handle_description is the wording for a handle whose
marking declares none, and defaults to none: what a reader should do with
an identifier depends on the reader, and the transport is what knows.
A spec declaring shapes promises no field of a row. A shape
reaches the presenter alone, and a fields selection there leaves keys
out, which nothing in the presenter's declaration can say for every value
a caller may send. So the item lists no required at any depth, wherever
it sits, while the affordances object dispatch adds to each row and the
paging envelope keep theirs. A spec declaring none is described with the
required its presenter's always_present states.
parameters_schema ¶
parameters_schema(
parameters: Parameters,
*,
unknown_arguments: UnknownArguments = UnknownArguments.REJECT,
) -> dict[str, Any]
The JSON Schema object an argument set must satisfy, read from parameters.
One dialect whichever library declared the parameters, because every
adapter reads its library into
Parameters
and this reads only that. The policy is precise: never false, and not
incomplete where the declaration knows. What it still leaves out is what a
Parameter does not carry, and a decimal's bound, which JSON Schema has no
way to state on a string.
- An object is
{"type": "object", "properties": {...}}, with"required"listing, in declaration order, the names the shape check refuses when absent - a required parameter with no declared default, since one with a default is not refused - and left out when there are none. "additionalProperties": falseis emitted underREJECTonly, and at exactly the levelscheck_argumentscloses: the top, every object parameter that declaresfields, and every row of an array whoseitemsare Parameters - an empty declaration included, since it refuses every key. UnderIGNOREan undeclared key is accepted and dropped, so statingfalsethere would refuse a call that runs.- An object parameter with no
fieldsis{"type": "object"}: what is still known, constraining nothing a valid call could fail. It is also the node an adapter truncates a recursive declaration to. - An array is
{"type": "array", "items": ...}: a type name's{"type": t}, the object schema of its rows, or{}for an array that declares noitemsand accepts any element. The array'sformatand bounds describe each element, so they go onitems, as its choices do: a CSV number filter's are{"type": "string", "format": "decimal"}, and an array ofintegerbounded at 1 has{"type": "integer", "minimum": 1}. - A file is
{}. No JSON value is one, so any JSON type stated here would be false, and JSON Schema has no keyword for a multipart part. What is still known is the rest: whether it is required, its"description". An array of files has{}for its items. - An
anyis{}too, since every JSON value is one; its"default"and"description"are stated as on any other node. - A scalar is
{"type": t}with its"format"when it declares one. A decimal is therefore{"type": "string", "format": "decimal"}: the form every decimal validator reads without a binary float's rounding. The shape check also accepts a JSON number, which this does not advertise. An identifier is{"type": "string", "format": "uuid"}, JSON Schema's own format name, and the shape check refuses a string that spells no UUID. - An array's length is
"minItems"as declared, and"maxItems"as in force: the declaredmax_length, or where none is declared theSERVICE_SPECS_MAX_ARRAY_LENGTHsetting's, 1000 unless the project sets another. The shape check refuses past it either way, so a client told nothing would send a call that cannot run; under a setting ofNonean array that declares no maximum states none. - Bounds are
"minimum"and"maximum", inclusive, as declared, on anintegerand anumber. A decimal string states neither: JSON Schema applies them to a number instance only, so on a string a validating client ignores both and a strict one may flag them. The shape check still enforces them, as it does for every bound. - Nullable makes the type
[t, "null"], on objects and arrays too, anditems_nullabledoes the same to an array'sitems. A file's node and anany's state no type, so they admit null already and gain nothing; a non-nullable one'snullis refused by the shape check alone. - Choices are an
"enum"beside the"type"the parameter declares. On an array they go onitems, because the shape check applies them to each element. A nullable parameter's enum gainsNonewhen its choices do not list it, since an enum claims the whole set of accepted values. An array's items do so byitems_nullablealone, whether or not the array itself may be null. - Labelled choices are an
"anyOf"of{"const": value, "title": label}in its place, where some label says more than its value does; labels that only repeat their values keep the"enum". A choice with no label is a bare{"const": value}. ANoneis{"type": "null"}instead, titled when it is labelled, and so is theNonea nullable parameter gains. A choice declared twice is listed once, so the entries are disjoint and each value has one title;Trueand1are two values to JSON, although Python finds them equal.anyOfrather thanoneOf, which admits the same values over disjoint entries: an OpenAI strict schema refusesoneOf, and Gemini refuses it too, where pydantic-ai rewrites it only on a node with no"type". And{"type": "null"}rather than{"const": null}, which Google's transform empties into{}, a schema every value matches. A title isstr()of the label, so a lazy one is rendered in the language active now, and it constrains nothing. - A default is emitted when one is declared and survives JSON encoding;
a
Decimal, a date or a callable is left out rather than misstated. So is a choice set holding such a value, since listing only some of the accepted values would be false. helpbecomes"description".json_schema_extrajoins the parameter's node last, at any depth: the keywords the declaration has no field for, such as apatternor a string'smaxLength. The Parameter refused every keyword a field states here when it was declared, a customformatincluded, so the extra never restates or contradicts the declaration. What it states is advertised and not enforced by the shape check; it holds where the spec's Validator enforces it.
Nothing else, deliberately. No title on a property, because a Parameter
has no label of its own; a title is only ever a choice's.
No $defs or $ref ever: most MCP clients refuse a schema with a
reference in it, so every schema is flat and self-contained, however deep
the declaration nests. No $schema key, which a transport adds if its
wire wants one. And no bound the shape check does not enforce
(maxLength, a Validator's max_value) unless a json_schema_extra
states it, for a Validator that enforces it.
The one stated without being declared is an array's default maximum,
because the shape check enforces it. The one enforced without being
stated is a decimal's bound, because a string has no keyword for it.
Every call builds a new schema, so a transport may add its own keys to the
result without reaching the declaration or another transport's copy.
Defaults, choice values and json_schema_extra values are placed in it
as declared, not copied.
unknown_arguments accepts the policy's plain value as well, and a value
that is neither, or the kept PASSTHROUGH member, raises ValueError
here rather than quietly describing one policy or the other.
output_schema ¶
The JSON Schema object of one presented item, read from output.
One item: whether the operation returns a list of them, or may return
None instead, is the spec's to say, and
spec_output_schema
wraps this accordingly. The dialect is the input side's, with the
differences a description of what came back needs:
- An object is
{"type": "object", "properties": {...}}, with"required"listing the fields whosealways_presentis true, in declaration order, and left out when there are none.requiredsays the key is there, not that its value is non-null. - No
additionalProperties. Output is not a closed set a caller can get wrong, and a transport may add keys of its own to what it sends. - A field states its type,
[t, "null"]when nullable, its"format"when it declares one, and"title"from itslabelwhen it has one. Adapters set a label only where the author wrote one, so a title is never a field name restated in worse English. Itsjson_schema_extrajoins the node last, holding only keywords no field states, since the field refused the rest when it was declared. Ananyfield states no type, nullable or not, since{}admits every value and the null with it. - Nesting is as on input:
fieldsmake an object schema, an object with none is{"type": "object"}, and an array'sitemsare{"type": t}, a nested item's object schema, or{}when undeclared.items_nullablemakes the item's type[t, "null"]. - Choices are
(value, display)pairs. When every display is juststr(value)they are an"enum"of the values, since a title restating the constant teaches nothing. Otherwise they are a"oneOf"of{"const": value, "title": display}, so the human phrasing travels with each value;titleconstrains nothing, and the accepted set stays exactly the constants. The"type"is stated either way. A nullable field addsNone({"const": None}in aoneOf) when its choices do not list it, because both forms claim the whole set of values. On an array the choices describe each element and go onitems, widened byitems_nullablerather than the array's own nullability. A choice set holding a value JSON cannot carry is left out whole.
marking is not emitted, and a HIDDEN field is described here
like any other: this is the whole declaration, which is what a caller
naming no audience is presented. Showing a field to an agent audience, or
leaving it out, is a projection over this schema, which
annotate_output_schema
applies and
spec_output_schema
composes for a caller that passes one.
As on input: no $defs or $ref, no $schema key, and a new
schema on every call.
can_present_nothing ¶
Whether a successful dispatch of spec may present None as its result.
The question an output schema answers before it admits "null", asked in
one place so that
spec_output_schema
and every transport advertising an output schema of its own give the same
answer:
- A
SelectorSpec: aRETRIEVEdeclaringallow_none, which presentsNonefor a missing row. Withoutallow_nonea missing row is not-found, which a transport answers in its own terms and never presents. ALISTpresents its rows,[]for none, and neverNone, whateverallow_nonesays. - A
ServiceSpecwith anoutput_selector_spec: aRETRIEVEre-read, whateverallow_nonesays, because once the service has run a re-read that finds nothing isNonerather than not-found, and reporting not-found would tell the caller a committed write did not happen. ALISTre-read presents rows and neverNone. - Any other
ServiceSpecpresents the service's own return, and answers its ownallow_none. That is a declaration rather than an observation: an undeclaredNoneis still presented, against a schema that does not admit it.
many and returns_many are not read. Each decides whether the result
is a list of what the service returned, not whether it may be None: a
None return from either is presented as None too, so its
allow_none answers as any other service's, and a many spec's
re-read answers by its kind as above. returns_many is refused beside a
re-read, so it never has one.
It answers whether None may come back, not whether a schema exists: a
spec with no presenter has no output schema to widen, whatever this says.
A SpecSource answers
as the spec it compiles to, never by attributes of its own that share these
names: its kinds are another library's, and none of them is this one's
RETRIEVE.
Dataclass adapters¶
DataclassValidator ¶
Bases: Validator
A Validator whose declaration is a standard-library dataclass.
The reference adapter: what any adapter owes the kernel, done with nothing
but the standard library and Django. parameters() reads the fields and
their annotations; validate() decodes JSON-like arguments into those
types and builds the instance, nested dataclasses included.
The annotations it reads, and what each declares:
str,int,float,bool: their JSON types.floattakes an integer as well, since JSON writes2.0as2; nothing else crosses types, sotrueis not anint. An integer past a float's range is refused as no number, in the words the shape check refuses a non-finite one in, since no finite float stands for it.Decimal,datetime,date: a string, with the format it decodes from. A decimal takes a JSON number too, as every decimal validator does, and an integer exactly, whatever its digits.X | None: nullable. Inside a list,list[X | None], it is the element that is, declared asitems_nullableand not as the array's own nullability.Literal[...]and anEnum(Django'sTextChoicesandIntegerChoicesincluded): choices, of the JSON type the values share. AnEnumdecodes to the member.list[X]: an array;list[SomeDataclass]is an array of rows, each declared as nested Parameters. For any other element,Parameter.itemsholds its JSON type, and what else describes the element is declared on the array, where it constrains each element: a list of choices declares them there, andlist[Decimal]thedecimalformat, so each element is read as a scalar decimal is, a JSON number included, and a query string's?prices=1.5,2.25is two of them. A list of dates or date-times is an array of strings, since an element takes no other format, and is decoded here.- A list declares no length, since a dataclass has no way to state one,
so the shape check in front of this Validator holds it to the
SERVICE_SPECS_MAX_ARRAY_LENGTHsetting, 1000 by default. A list a caller may send more of is declared with a Validator that states its length, such as a pydantic model'sField(max_length=...), or under a larger setting. - a dataclass: an object, with its own fields as nested Parameters.
dict[str, X], for anyXabove: an object with no declared fields, as the pydantic adapter declares one, since Parameters cannot say "every value is an X". Each value is decoded asX, and refused under its own key. Only a str key, because a JSON object has no other.X | UnsetType: the argument may be left out, with or without a default, and the field then holdsUNSETrather than a value a service would act on. It adds no JSON type, since no wire can send it.
A field with a default, or a default_factory, is optional, and one with
neither is required. Only a plain default is reported as the Parameter's
default: a factory's value is computed per instance, so it is not a
declaration a transport could print. A field declared init=False is
the dataclass's to compute, so it is neither taken nor returned.
Annotated is looked through, and an annotation outside this list is
refused with ImproperlyConfigured naming the field, never read as a
string.
A row that updates must declare its key. A relation write matches an
incoming row to an existing one by its primary key, so a row dataclass used
for an update needs pk: int | None = None: present for a row that
exists, absent for a new one. Without it no incoming row matches an
existing one, and every update replaces every row. Nothing fails when that
happens, which is why it is written down here.
Time zones follow Django's forms, not pydantic: an offset-less
date-time is made aware in the current time zone when USE_TZ is on,
so a date-time means the same thing whichever library validated it.
Every failure is reported, not the first, as one InvalidArguments
whose detail is addressed by path: {"books": {1: {"title": [...]}}}
for a field inside the second row, only the rows that failed, and a message
about a row itself under non_field_errors inside it. A ValueError
or Django ValidationError raised by the dataclass's own
__post_init__ is a message about that object, and lands there too.
It is correct without the shape check in front of it, for a caller that uses it directly: a wrong JSON type is a refusal, not a crash, and an argument no field declares is refused as the dataclass's own constructor would refuse it.
The annotations are read on first use rather than at construction, for the reason a spec's parameters are: specs are built at import time, and an annotation may name a class its module cannot resolve yet.
parameters ¶
The dataclass's __init__ fields, as Parameters. Never queries.
validate ¶
The built instance's __init__ fields, by name, or InvalidArguments.
Nested values stay dataclass instances, which is what the mutation
helpers read a row from. A partial call is refused: see validated().
validated ¶
The built instance as the call's data, and its __init__ fields as the values.
A service declaring data receives the instance, typed as the
dataclass; one declaring the fields by name receives them. The values
are the instance's own attributes, so data.title and title are
one object.
A partial call is refused with ImproperlyConfigured, because a
dataclass instance holds every field and a partial call may leave any
out. Building one anyway would mean a value the field's annotation does
not admit standing in for each field not sent, or no instance and no
__post_init__ at all. A field an update may leave out is declared
X | UnsetType, which every call honours; a spec whose calls are
partial uses a Validator that can return only what was sent.
supports_partial is False, so a ServiceSpec declaring
partial=True over this Validator is refused when it is built, and
this refusal answers only a caller using it directly.
DataclassPresenter ¶
Bases: Presenter
An operation's output declared as a dataclass, rendered from any object.
output() reads the fields and annotations the way
DataclassValidator
does, so one dataclass declares the same types going in and coming out.
present(value) reads each declared field by attribute, so the value
may be an instance of the dataclass or anything carrying the same names: a
model row is the case this is for, and it is never converted into the
dataclass first. A nested dataclass field is read the same way off the
attribute's value, and a list field may be a related manager, read
through .all() so a prefetch is used when there is one. Encoding is
JSON's: a Decimal as its string, a datetime or date in ISO
8601, an Enum as its value.
A field whose value is UNSET is left out of the rendered object, and
only a field whose annotation admits UnsetType is declared as possibly
absent (always_present=False). Labels are None: a dataclass has no
label of its own, and a reader can title-case a name as well as an adapter.
Choices are (value, display) pairs. A Django Choices enum supplies its
label, translated when output() is called; a plain Enum or a
Literal has no display of its own, so the value's str stands in.
A FieldMarking is declared on the field it marks, in its annotation:
id: Annotated[int, FieldMarking.handle()].
Forms adapter¶
FormValidator ¶
Bases: Validator
A Validator whose declaration is a Django form class.
parameters() reads the form's class-level fields, base_fields, in
declaration order; validate() binds the arguments to a new form and
returns what it cleaned. Every rule the form states stays the form's to
enforce - its fields' validators, clean_<field>(), clean() and, on
a ModelForm, the model's own validation and uniqueness checks - and the
shape check in front of it enforces what the declaration can see.
The fields it reads, and what each declares, the first match winning:
BooleanFieldandNullBooleanField: aboolean.DecimalField: astringin thedecimalformat, which takes a JSON number as well, and an integer whatever its digits.FloatField: anumber, and an integer past a float's range is refused as the field refuses an infinity,invalidin its own words.IntegerField: aninteger. On aModelForm, a value the form cleans to an integer past the range of the model's integer column is refused in the words and with the code of the validator Django's model field carries from 5.0,max_valueormin_value, before a uniqueness check or a constraint queries with it: Django 4.2 states no range for SQLite, whose driver raisesOverflowErrorfor one. It is judged where Django 5.0 and later judge it, after the field, itsclean_<field>()and the form'sclean(), so each of those answers first, and a value aclean_<field>()brings inside the range is taken. Only a column Django validates is judged: a valueclean()sets for a column the form has no field for, and a field declared over a columnMeta.fieldsleaves out orMeta.excludenames, are the form's, as Django never writes them onto the row.DateTimeFieldandDateField: astringin thedate-timeordateformat.TimeFieldandDurationField: astring.ChoiceField: choices, with the empty choice dropped and option groups flattened. A plain one cleans withstrand matches the string against each choice'sstr, so it takes astringand its choices are declared as strings, whatever type they were written in. ATypedChoiceFieldtakes the JSON type all of its values share. A choice set given as a callable is computed per form and may query, so it is not read: the field is astringwith no choices, which every choice field accepts, and the form checks the choice.MultipleChoiceFieldandTypedMultipleChoiceField: an array of that, whose choices constrain each element.ModelChoiceField: the JSON type of the model field it matches rows on - itsto_field_name, or the primary key - and no choices, since they are rows and reading them would query.ModelMultipleChoiceField: an array of that, so one matching rows on aDecimalFieldtakes an array ofdecimalstrings, and a query string's?rows=12.50,9.99is two of them. Django matches each against the column's own spelling, so"12.50"names a row a two-place column holds and12.5names none. A date or a date-time key is an array of strings, since an element takes no other format. They validate to the row, and to a queryset of rows. A key past the range of the integer column rows are matched on names no row, and is refused as the field refuses a key no row holds,invalid_choicein its own words, before the form queries: Django hands aModelMultipleChoiceField's keys to the database driver, which raisesOverflowErrorfor one, and so does aModelChoiceField's on Django 4.2.- No choice field declares a length, since Django's have none, so the
shape check in front of this Validator holds a list to the
SERVICE_SPECS_MAX_ARRAY_LENGTHsetting, 1000 by default. - any other
CharField(email, URL, slug, UUID, regex, IP address): astring. - every
CharField, those above included, declares the limit of aMaxLengthValidatoron it asjson_schema_extra'smaxLength, and a required one aMinLengthValidator's asminLength, so a schema advertises them: the validatormax_lengthandmin_lengthappend, or one a project appends by hand, the tightest winning; aModelForm's carries its column's, which Django puts on the field. Only those two are read, by exact type, so aSimpleArrayField, whosemax_lengthcounts its items with subclasses of them, declares no length, and neither does a callable limit. The shape check enforces neither, and the form refuses a string past one in its own words, beside its other refusals. An optional field's minimum is not declared, since the form takes""whatever it says, and a length counts on the value the form cleans: stripped unlessstrip=False, and aURLField's with the scheme it adds. - No
IntegerFieldorFloatFielddeclares itsmin_valueormax_value. The shape check enforces a declaredminimumormaximumbefore the form runs, in its own words, so declaring them would replace a field'serror_messagesfor the bound and keep the form's other refusals from coming back beside it. FileFieldandImageField: afile, which no JSON caller can send. A multipart request carries one, and a Python caller hands a DjangoFile; the form is bound with it as itsfiles, where a file field reads, and the form's own checks run on it. AContentFilebuilt with no name is refused by the form, which needs one.- an optional file field whose widget is a
ClearableFileInput, as aFileField's and anImageField's are by default, declares its clear checkbox as well: abooleannamed as the widget names it,<name>-clear, right after the file. Checked with no upload, the form cleans the field toFalse, its own value for a cleared file, whichvalidate()returns under the field's name and aModelFormwrites as no file through the model field'ssave_form_data; checked beside an upload, the form refuses the pair. It is the only way to clear one, sincenullkeeps the file a row holds andfalseis not a file. A required file field, or one whose widget has no checkbox, declares none, and a field named as a checkbox is refused.
Every choice field's choices carry their labels, as choice_labels,
for a schema to show beside each value: the label Django displays, keyed
by the value as the caller sends it, so a plain ChoiceField's are
keyed by the string. A lazy label stays lazy until a schema renders it.
Refused with ImproperlyConfigured, naming the form, the field and its
class: a JSONField, a
MultiValueField such as SplitDateTimeField, a ComboField, any
field the list does not cover, and a ModelChoiceField with no queryset
or matching rows on a model field with no JSON type. The declaration is read at
construction, so a form that cannot be described fails where the spec is
written; nothing in it queries or needs a translation, so building a spec
at import time is safe. help is the exception, and is read from
help_text on each parameters() call, in the language active then.
What the Parameters say about presence is what the form does:
requiredis the field's ownrequired. For aBooleanFieldthat is a statement about presence too: an absent checkbox cleans toFalse, which a required one refuses, as it refusesfalse. ANullBooleanFieldis never required, whatever it says, because its validation is empty and it takes an absent value asNone.nullableisnot required, and always true for aNullBooleanField. A form readsNoneas an empty value for every field, so an optional field takesnulland cleans it to its empty value, and a required one refuses it. A clear checkbox is no field: it is optional and nevernull, since unchecked and absent are the one answer the widget reads.defaultis alwaysUNSET: a field'sinitialis what an unbound form displays, and a bound form cleans an absent optional field to its empty value, never to its initial.
The types are JSON's, and do not cross. A form reads its data as an
HTML post's strings, so it also takes a value of another type through
str - a number for a CharField, 1 for the choice "1" -
and the shape check refuses one, as it does for every declaration: a
caller sends the declared type. The empty choice is the other case: an
optional choice field reads "" as no value, and a caller sends
null for that instead.
The form is bound to a post. Its data is an immutable
QueryDict holding each argument as the strings a browser would post
for it, so a form or widget written for HTML reads it as it reads
request.POST: getlist on a list, .isdigit() on an id. A list
is one string per element, a boolean "True" or "False", a date,
time or datetime its ISO spelling, a duration Django's own, and null
an absent key; any other value is its str. A file stays in files.
An argument is in its wire form, which no locale touches. A
localized number field reads its post through the active locale, and
under one whose thousands separator is a dot reads "1.500" as fifteen
hundred. So a number, or a string spelling one, for a localized
IntegerField, FloatField or DecimalField is posted as its
widget renders it in that locale, which the field reads back as the
number it is.
Declare the fields on the class. A field a form adds or changes in its
own __init__ is not in base_fields, so it is not described, and
under UnknownArguments.REJECT the closed argument set refuses its key
before the form is built. A field declared disabled is not a
parameter either: the form ignores what a caller sends for it and cleans
its initial, which validate() returns with the rest on a whole
call.
A partial call binds only the fields the caller sent. When the
ValidationContext
says partial, every field the arguments do not name is taken off the
bound form before it validates, so it is neither required nor cleaned,
and validate() returns no key for it: an absent BooleanField does
not come back False, nor an absent CharField '', which an
update would write over the row. A value that is sent is checked exactly
as on a whole call, so a required field may be left out but not sent
empty. A checked clear checkbox sends its file field, and an unchecked
one is what an absent one is. On a ModelForm the fields left out keep the target's values,
and each one's own model check skips them, as Django skips any model
field a form does not have. Its uniqueness checks and constraints do
not: they run over the row as it would be saved, what was sent on top
of the target's values, leaving out only the model fields the form never
declares, as a whole call does. So an update that sends one field of a
unique_together pair or a UniqueConstraint and collides is refused
as the whole call would be, under non_field_errors, rather than
failing with an IntegrityError when the row is saved. That needs a
target row: a partial call bound as a create checks only what was sent,
since the rest would be the model's defaults, which nothing writes.
clean()
sees only what was sent, so it
reads cleaned_data with get, as Django advises for a field that
failed. parameters() is the same for both calls: required says
what a whole call needs.
A ModelForm is bound to a copy of the target. When the
ValidationContext
carries a row of the form's model, the form is built with
instance= a shallow copy of it, so its uniqueness checks exclude the
row being updated. It is a copy because a ModelForm writes the cleaned
values onto its instance while it validates: handed the target itself, it
would change the row the service receives before the service runs, and a
helper that saves only what changed, such as
update_from_input,
would find nothing to save. Any other target - the queryset a collection
selector resolves, or none - binds the form as a create.
A plain form that declares instance is handed the target. When a
plain form's __init__ names a parameter instance (a bare
**kwargs does not count), the form is built with instance= the
context's target itself, whatever it is and never a copy (a collection
selector's queryset too), None when there is none; a plain
form that declares none is built from data and files alone.
A form whose __init__ takes more is handed it by form_kwargs.
It is a callable returning a mapping of extra constructor keywords, such
as a queryset scoped by the caller's tenant, and it binds through the
pool as a selector or a service does, naming what it wants: user,
progress, every registered seed, and the target under the name the
service receives it by, from the context's resolved: instance
for a spec with an instance selector, None when one that allows none
finds no row, collection for one with a collection selector, and
neither for a create. It is the target itself, never the copy the form
edits. user is the context's principal on every path, and
progress is null_progress wherever the context carries no
reporter. In bind_arguments handed pool_seeds, it is handed
every seed of the registry, as on dispatch. In bind_arguments handed
none, or with a
ValidationContext
built by hand, the context holds no seeds, so a callable naming one
gives it a default or meets Python's own TypeError;
form_keywords
is the path off dispatch for building the form itself, and resolves the
seeds it names. It is called on
every validate(), on the thread the call runs on, which under
adispatch is the one its synchronous phases share, so it may query;
on a many call that is once per row, or once for the call under a
formset_class, so a query belongs in a seed, which resolves once per
call.
What it returns is passed beside data, files and instance,
and returning one of those three, for a plain form as for a
ModelForm, is refused with ImproperlyConfigured naming it, as is
returning anything but a mapping. parameters() still reads only the
class: a field __init__ adds from those keywords is not a parameter.
The callable is kept as form_kwargs. A transport building the form
itself, for a page, builds it the same way with
form_keywords,
which calls it from the pool dispatch would, the seeds it names included.
A many call is one formset under formset_class. Without one,
validated_many() binds each row to a form of its own. Given a
BaseFormSet subclass whose form is form_class (anything else
is refused, as are an inline formset, which needs a parent row, and
can_order, whose field is no parameter), it binds every row into one
formset, spelled <prefix>-<i>-<field> as a post spells it, runs each
form and the formset's clean(), and refuses with each form's errors
under the caller's index for its row and non_form_errors() under
non_field_errors. Every row sent is validated: none is skipped as an
unchanged extra form, so a row equal to the fields' initials is still
checked. form_kwargs is called once and handed to every form, and may
not return prefix or empty_permitted, which the formset sets per
form. The bound formset is in the call's pool as formset. A
formset validates whole rows, so the validator's supports_partial is
False. Under can_delete, parameters() declares DELETE, a
boolean (not for a plain formset with can_delete_extra=False,
whose forms are all extra ones and carry none): a row sent with it
true skips its form's errors, as Django's formset skips them, and
reaches the service with DELETE true and only the fields that
cleaned. A row left out is left alone.
A BaseModelFormSet edits the call's collection target, a queryset of
its model, which a collection selector resolves; a call with none is
refused with ImproperlyConfigured. parameters() declares the
model's key before DELETE: optional, of the JSON type its column
takes, as a ModelChoiceField's. A row sending a key is an existing
row, bound first among the formset's initial forms, its errors still
answered under its own index, and its form is bound to its row from a
fresh copy of the collection, so its uniqueness checks exclude it and
the rows the service receives are not changed. A row with no key is a
new one. A key outside the collection is refused under the row's key
field as invalid_choice, deleted or not: Django's own key field takes
any row of the model, and is held to the collection here. Two rows
naming one key are refused under non_field_errors, where Django's
formset would let the last one win. Each row comes back as its form's
cleaned_data, the key cleaned to its row, or None for a new one.
A form field named as one of these additions is refused.
A refusal is one
InvalidArguments
carrying the form's own errors and messages, {field: [messages]}, with
the form-wide ones Django keeps under "__all__" moved to
non_field_errors, the key every other refusal uses. An argument no
field declares is ignored by the form, as Django ignores any key it has
no field for: the closed argument set in front of it is what refuses one.
parameters ¶
The form's class-level fields, in declaration order, as Parameters.
validate ¶
The form's cleaned_data, or InvalidArguments carrying its errors.
A ModelChoiceField cleans to the row and a
ModelMultipleChoiceField to a queryset, which is what the service
receives. On a partial call, only the fields the caller sent are
bound, and so only those are returned; a ModelForm's uniqueness
checks still read the whole row, as the class docstring says. Under a
formset_class it raises ImproperlyConfigured: a formset
validates a many call's rows, and one call is not that.
validated_many ¶
validated_many(
rows: Mapping[int, Mapping[str, Any]],
context: ValidationContext,
*,
many_argument: str,
) -> Validated
The rows bound into one formset_class formset, or each its own form without one.
form_keywords ¶
form_keywords(
spec: ServiceSpec | SelectorSpec | SpecSource,
principal: Any,
*,
pool_seeds: PoolSeeds | None = None,
target: Any = None,
call_context: dict[str, Any] | None = None,
) -> Mapping[str, Any]
What spec's FormValidator's form_kwargs returns, for a transport building the form.
A page shows the form before the call runs, so it builds the form itself,
and a form whose __init__ takes a keyword of its own needs what
dispatch would hand it. This calls form_kwargs from the pool dispatch
binds it from, through the same code
FormValidator
calls it with, so the returned mapping is checked as there: one that is
not a mapping, or that returns data, files or instance, which
only the bind may set, is refused with ImproperlyConfigured. Spread it
beside those three: form_class(data=..., **form_keywords(...)).
The pool holds:
user, the principal;progress, the no-op reporter, since no call is running;- the registered seeds of
pool_seedsthatform_kwargswould be handed, resolved once for the principal, and no other: the seeds it names, or every seed for one taking**kwargs, as on dispatch; call_context, the dict handed here, or a fresh one; a page hands the dict it will hand dispatch, so what the two calls write is shared;requestandview, read off that context,Nonefor a key it lacks, as in every pool dispatch builds, unlesspool_seedsregisters the name, whose seed is the value then; and a seed's resolver may declare either;targetunder the name dispatch hands it by:instancefor a spec with an instance selector,collectionfor one with a collection selector, and nothing for a create.
A deactivated principal resolves no seed, as on dispatch, which refuses one
before any resolver runs: where a seed would be resolved for one, this raises
PrincipalUnavailable first. A call that resolves none - no pool_seeds,
or a form_kwargs naming no registered seed - is asked as ever.
A spec whose Validator is not a FormValidator is refused with
TypeError, as resolve_target refuses a spec it cannot answer for:
a page wired to a spec it cannot build a form for is the caller's mistake,
and an empty answer would hide it. A FormValidator with no
form_kwargs returns {}, resolving nothing.
It neither authorizes nor resolves the target: a page admits the
principal with
authorize and
finds the row with
resolve_target
first. It is sync, and form_kwargs may query, so an async caller hops
once with sync_to_async.
Filters adapter¶
filter_set_parameters ¶
The arguments a FilterSet reads, as the Parameters a caller sends.
This is what lets a filter be a read like any other: the schema describes
it, the closed argument set admits it, the shape check judges it and each
transport accepts it, all from the declaration rather than from
django-filter. SelectorSpec puts these after its own reads.
Named as django-filter reads them, because a Parameter describes what a
caller sends and the FilterSet is what receives it. A range filter
(RangeFilter, DateFromToRangeFilter and the rest) reads one key per
bound - price_min and price_max, joined_after and
joined_before - so it is one Parameter per bound, never an object
called price that no FilterSet reads. A CSV filter (BaseInFilter,
BaseRangeFilter) reads one key holding several values, and is an array;
its widget takes a list as it takes "1,2". A choice filter offers its
values, flattened out of any group, as integer when every value is an
int and otherwise as the strings Django's ChoiceField compares, each
with the label it was declared with as its choice_labels, so the schema
names it for a reader; a choice set built by a callable, and a related row's
key, offer only string. Every other filter is its scalar: boolean, a date or
date-time string, and string for the rest. A number filter, and
each bound of a numeric range, is a decimal string, because its
form field is a DecimalField and reads one exactly, where a float read
on the way loses a key past 2**53; a JSON number is still taken. So
is each value of a CSV number filter: an array whose format and
bounds describe each element, as its choices would, so a fraction keeps
every digit it was sent with and ?pks=1,2 still splits over HTTP,
since no decimal holds a comma. Each decimal is bounded,
minimum=-1e50 and maximum=1e50, a CSV filter's values each: the
line django-filter's number filter draws above, drawn below too and on a
range's bounds, which it leaves open. A value past it is refused by the
shape check, at its index in a CSV filter's list, before it reaches the
database's integer conversion, which builds every digit of
"1E+999999999".
Every one is optional, because a filter narrows a read and never
stands between a caller and it. help is the author's help_text when
there is one; otherwise it says what the filter matches when the
argument's name does not (min_pk is pk with gte), and for a
bound, which bound of which field it is.
Two filters that read one key - a range joined and a filter called
joined_after - are refused, as any two Parameters of one name are,
because django-filter would hand one value to both.
An object whose base_filters is missing, empty or None declares
nothing, and is read without django-filter. A
SelectorSpec
refuses one as its filter_set unless it is a django-filter
FilterSet class, since none of the caller's data would be handed to
it. Reading any filter needs the [filter] extra.
Pydantic adapters¶
Installed with the pydantic extra and imported from
django_service_specs.adapters.pydantic.
PydanticValidator ¶
Bases: Validator
A Validator whose declaration is a pydantic model.
parameters() reads the model's fields into Parameters, and
validate() hands the arguments to the model: pydantic builds the
instance, nested models included, and its own validators run as they would
for any other caller.
The annotations are read as
DataclassValidator
reads them, from one shared table, so a model and a dataclass declaring
the same field declare the same parameter: str, int, float,
bool; Decimal, datetime and date as strings with their
format; X | None as nullable; Literal[...] and an Enum as
choices; Annotated looked through; and list[X] of any of these,
where list[X | None] makes the element nullable and not the array
and list[Decimal] declares each element a decimal. On top of
those:
-
a list's length, however the model states it -
Field(min_length=, max_length=),conlist,annotated_types'Len,MinLenandMaxLen- is the parameter'smin_lengthandmax_length, so a list the model allows more of thanSERVICE_SPECS_MAX_ARRAY_LENGTHis not held to it. Where a field states one twice, the last pydantic applies is the one declared, as it is the one pydantic enforces. A number's bounds are not declared:gtandltare exclusive, which a parameter cannot state, and the model keeps every bound in its own words rather than some in the kernel's; -
a nested model is an object with its own fields as nested Parameters, and
list[SomeModel]an array of rows; dict[str, X]is an object with no declared fields, whose values are pydantic's to validate;- a model that contains itself is described four times on one path
(
MAX_APPEARANCESin the adapter'sutils), and deeper levels as an object with no fields. pydantic still validates every level.
Any, a union of two types, UnsetType, a RootModel and anything
else without one JSON type is refused with ImproperlyConfigured naming
the model and the field, never read as a string.
Names. A parameter is named for the key pydantic validates by: the
field's validation_alias when it is a string, else its alias, else
its name (the name alone when the model sets validate_by_alias=False).
An AliasPath or AliasChoices is not one name, and is refused.
validate() returns the values keyed by the field name whatever the
wire called them, because that is the keyword the service is called with.
required is pydantic's own is_required(). The default is reported
when JSON carries it as itself; a default_factory, or a default such
as a Decimal or a date, is not reported, and the field is optional
all the same. help is the field's description.
A row that updates must declare its key, as with the dataclass
adapter: pk: int | None = None on the row's model, or no incoming row
matches an existing one and every update replaces every row.
Refusals keep pydantic's words, addressed by path into the kernel's
tree: {"books": {1: {"title": ["..."]}}}, with a row's index as an
int. A message about a model itself - its model_validator refusing
- sits under non_field_errors inside that model, or at the top for the
model being validated. The kernel's shape check runs first and refuses a
wrong JSON type, and a list past its declared length, in the kernel's
words, under the code pydantic's would carry; pydantic's are what a
caller reads for the model's other rules: bounds, patterns, validators.
Each message carries a code, the one a DRF field gives the same
mistake where pydantic's error type has one: missing is
"required", a None refused by a type is "null", a string or a
list too long or too short "max_length" or "min_length", a number
past a bound "max_value" or "min_value" (an exclusive bound too,
which no DRF field has), a Literal or an Enum "invalid_choice",
a list's type "not_a_list", a decimal's digits "max_digits",
"max_decimal_places" and "max_whole_digits", and a forbidden extra
key the kernel's "unknown". Any other of pydantic's own types is
"invalid", DRF's code for a value it cannot take, and a
ValueError or an assert in a validator is too, as DRF says for a
message raised with no code. A PydanticCustomError's type is the
author's code, and is kept, as a Django ValidationError's is.
Time zones are pydantic's: an offset-less date-time stays naive, where
DataclassValidator makes it aware as Django's forms do. Declare the
offset, or convert in the service.
The declaration is read at construction, so an unmappable field fails where the spec is written. A model whose annotations named a class not yet defined when it was built is completed first, as pydantic completes it on first use.
parameters ¶
The model's fields as Parameters, named as pydantic validates them. Never queries.
validate ¶
Every field's validated value, keyed by field name, or InvalidArguments.
The context reaches pydantic's validators as info.context, a dict
with "principal", "target" and "call_context", the call's
context as the very dict the transport passed, so a validator can check
a value against the caller or the row being updated, and read or write
what the call's other stages share. Nested values stay
model instances, which is what the mutation helpers read a row from.
A partial call is refused with ImproperlyConfigured. pydantic
validates a model whole: a required field not sent is missing, and a
model_validator is written against every field being there, so
there is no partial validation to hand the call to. Validating only
the fields sent, one by one, would skip the model's own rules; a spec
whose calls are partial uses a Validator that can return only what was
sent. supports_partial is False, so a ServiceSpec
declaring partial=True over this Validator is refused when it is
built, and this refusal answers only a caller using it directly.
validated ¶
The validated instance as the call's data, and its fields as the values.
A service declaring data receives the model instance, as it
receives the dataclass instance from DataclassValidator, so a
service written for data.title reads the same whichever of the two
validated it. One declaring the fields by name receives them, as
validate() returns them; they are the instance's own attributes,
so data.title and title are one object.
PydanticPresenter ¶
Bases: Presenter
An operation's output declared as a pydantic model, rendered by that model.
output() reads the fields as
PydanticValidator
does, so one model declares the same types going in and coming out, and
adds what only the output side has:
- each field is named for the key
model_dump(by_alias=True)emits: itsserialization_alias, else itsalias, else its name; - fields declared
exclude=Trueare not output, and eachcomputed_fieldis, after the fields, typed by its return annotation; - every field is
always_present, becausemodel_dumpemits every key, except one with anexclude_if, which may be dropped; labelis the field'stitlewhen the author set one, andNoneotherwise: pydantic invents no label, and a reader can title-case a name as well as an adapter;- choices are (value, display) pairs: a Django
Choicesenum supplies its label, translated whenoutput()is called, and a plainEnumor aLiteralhas no display of its own, so the value'sstrstands in; - a
FieldMarkingis declared in the field'sAnnotatedmetadata:id: Annotated[int, FieldMarking.handle()].
present(value) renders with the model itself, so its serializers and
its JSON encoding are what a caller receives. The value may be an instance
of the model, a model row, any object carrying the same names, or a
mapping keyed by field name. Anything but an instance is read one declared
field at a time, by attribute or by key, and the model validates what was
read: a related collection may be a manager, read through .all() so a
prefetch is used when there is one, where pydantic's own
from_attributes would fail on it. A field the value does not carry is
left to the model's default.
A value that does not fit the model raises pydantic's ValidationError
as it is. What is presented is the operation's own value rather than a
caller's, so a mismatch is a defect in the operation, not a refusal to
report.
The declaration is read at construction, as the validator's is.
Dispatch¶
dispatch ¶
dispatch(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
principal: Any,
arguments: Mapping[str, Any],
grant: Grant | None = None,
seeds: CallSeeds | None = None,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
unknown_arguments: UnknownArguments = UnknownArguments.REJECT,
progress: ProgressReporter | None = None,
target: Any = UNSET,
extra_kwargs: Mapping[str, Any] | None = None,
call_context: dict[str, Any] | None = None,
) -> DispatchResult
Run spec for principal with arguments, in a fixed order.
First, a deactivated principal is refused as PrincipalUnavailable: an
authenticated one whose is_active is false, with or without a
grant. One with no is_active reads as active, and anonymous goes on
to the permission check, which decides whether anonymous may act. It is
the rule resolve_principal applies and is_deactivated exports for
a transport's own entry points, so a principal is refused alike whichever
way it reached dispatch.
Then the same seven steps for both kinds of spec, and for adispatch:
check_argumentsoverspec.parameters()underunknown_arguments: the closed argument set and the shape check. It refuses no absent Validator field under a service spec'spartial, at any depth, while areadsargument and the target's read stay required; nor a parameter a provider fills or may fill - a read thekwargsof the spec declaring it reaches, a Validator fieldinput_datareaches, where the provider is annotated to fill the key, may decline it, or names no keys at all, less a read a provider requires itself, which stays demanded of the caller. A parameter so relaxed is still required of the call: once the provider has answered, a read declared required that nobody filled is refused where the answer is merged, in the shape check's words (step three for a selector's read, before the affordances for a service spec's), and a Validator field by the Validator. A value the caller sends for a key a typed provider is annotated to fill is checked, then dropped, so it never stands in for the provider's; one for a key the provider may fill is kept beneath its answer. Before that, a parameter a registered seed inpool_seedsis named like is answered by where it is declared: areflectedread leaves the argument set and the seed fills it; a top-level Validator field stays the caller's, and reaches the service indatawhile the seed keeps the parameter of its name; anything else is refused as a configuration error.authorize, honouringgrantif it covers this spec and principal. Before anything is resolved, so a refused principal learns nothing about which rows exist.- Resolution: a selector spec's own selector, or a service spec's instance
or collection selector, called with the base pool plus the arguments its
readsdeclare and what itskwargsprovider returns, then shaped, and a RETRIEVE collapsed to its row. A missing row isDispatchResult(kind="not_found"), returned rather than raised, unless the selector saysallow_none. A RETRIEVE's missing row isNone, aDoesNotExistor anHttp404alike; a LIST raisingHttp404, asget_object_or_404does of a parent row, is not found whateverallow_nonesays, while aDoesNotExistescaping a LIST is a fault and raises. authorize_targeton a retrieved row, andauthorize_scopewhere no row is: on a list, a collection target's set, empty or not, a create'sNone, and theNonea service spec's instance selector lets through under itsallow_none. A selector spec's ownNoneunderallow_noneis asked of neither.- A service spec's Validator, on only the arguments it declares, with
its
input_dataprovider's values merged over the caller's, and the resolved target andpartialin its context. Itsvalidated()result is the call's: the values,data, and what it binds. - A service spec's
affordances, throughenforce_affordances: the first one not met refuses the call asActionUnavailablecarrying itscode. After the object-level check, so a principal who may not see the row is never told what state it is in, and before the run's transaction opens, so a refusal never opens one. Then itspreconditions, in declaration order, from the same pool: the first to raise aborts the call, and what it raises reaches the caller as it is. - The run: the service, called with the principal,
data(the Validator'sdata),instanceorcollection, each validated value by name, what the Validator binds, the spec'sreads, what itskwargsprovider returns,progressand every registered seed, throughrun_servicesospec.atomicholds and anasync defservice is bridged. Then the output selector, if declared, with the service's return asresult.
A selector spec stops after step four and its preconditions: its
selector is its run, and they run on what it found, never on a missing
row. Its affordances are answers about each row, for a list to
report, and nothing about reading is refused by them.
A many service spec takes a list of rows under its
many_argument, beside its reads and nothing else, and runs the
service once for all of them, inside one transaction under atomic. Its
steps differ in three places:
- Step one checks the top level - the list, and the
reads- and each row, but raises only the top level's refusal there. A row's refusal is raised in step five, beside the Validator's refusals of the other rows, so a principal refused in step two learns nothing about the rows it sent. - Steps three and four resolve nothing: the scope check is asked of
None, as for a create, never of the caller's rows. - Step five runs the Validator once per row, each with the
input_dataprovider's values merged over it; the provider is called once for the call. Every row is checked and validated before the service runs, and every failing row is refused in oneInvalidArguments, addressed by the row'sintindex undermany_argument: a field as{"items": {2: {"title": [...]}}}, a message about the row itself undernon_field_errorsinside the row, and the list's own refusal as{"items": [...]}. The service receives the rows'dataas a list underdata, and their values as a list undermany_argument; neither is spread by field. Theaffordances- conditions on no row, since one on the row is refused when the spec is declared - and thepreconditionsare answered once.
kind is "list" for it, unless an output selector says otherwise
or the service returned None, which is presented as None.
progress is the transport's own progress reporter, seeded under the
reserved name progress into the pool of whatever is this call's run -
the service, or a selector spec's own selector - and into that spec's
callable affordance conditions'. With none, the pool carries
null_progress, so a callable that declares the parameter runs on every
transport. A target or output selector, and its affordance conditions,
always get null_progress: a lookup has nothing to
report, and one reporting after the service finished would read as the
work restarting. The run alone also reports to the spec's
progress_reporter, and only a run that takes progress: called on
the run's first report, or before an async def run once nothing before
the run can refuse the call; either way a call refused before its run
never calls it. A selector spec's run is its selector, and its step four
and preconditions answer after it, so a selector spec refused there
may already have called it: by the selector's first report, or, for an
async def selector, before the await.
target is a service spec's target resolved by the caller - the row
an HTTP view's get_object() found, or what resolve_target
returned - and stands in for step three: no lookup runs, and the call's
instance or collection is target. Step four still runs on it,
unless grant says target_checked, so with that grant
has_object_permission is asked once across both. Without target
step four runs whatever the grant says: the grant vouches for the target
the caller found, not for what the arguments make the lookup find. So a
selector spec, which takes no target, runs it on the row or the list
its selector found, whatever the grant says. None is a missing
row, not-found unless the instance selector says allow_none; a create
takes None and refuses anything else. Dispatch trusts it: the
target's reads are still checked as declared, and keeping them and
target in agreement is the caller's. A selector spec refuses it.
extra_kwargs is the transport's per-call overlay for the spec's
kwargs provider - what an HTTP view's per-request hook adds - merged
beneath it, so the spec's own provider wins on a clash. It is treated
as the provider's own return is: an UNSET entry is dropped, a key the
provider is annotated to fill is the server's and the overlay's value for
it is dropped too, so an overlay never fills a key the provider declined
to, and a key naming a registered seed is refused. So, before step one,
is a key naming a parameter the spec declares - a read, a Validator
field, a target read, a many spec's list - unless its value is
UNSET or the spec's typed kwargs provider fills it: the caller's
value for a parameter is what steps two and three read, so an overlay
standing in for it would run the call on a value they never saw. That is
the only refusal of a key the spec could own, because it is static: it
turns on the spec alone, never on what a request sent. The overlay is the
lowest of three tiers: beneath the spec's provider, and beneath what the
Validator computed or bound in step five, so a key among those is left
to the Validator's value and the overlay's entry is dropped for that
call - a Validator computing a key only from some requests makes it the
overlay's on the others, and an error on none. It
reaches a selector spec's own selector and a service spec's service,
never a target or output selector. There is no overlay for the
Validator's input: a transport merges such values into arguments,
where the checks and the Validator read one value.
call_context is the call's context: one plain dict, created and
owned by the transport for its natural scope - an HTTP request, an agent
run - and handed to every stage that declares it as the same object,
never a copy. A kwargs or input_data provider, a selector of any
role, an affordance condition, a precondition, the service and the run's
progress_reporter declare it as a parameter named call_context, a
name reserved as every seed's is, so no argument may take it. It reaches
them by that name alone: one taking **kwargs for the rest of the pool
is never handed it, so a catch-all forwarding what it gets runs as it did
before the name was reserved
(TestACatchAllIsNeverHandedTheCallContext). A permission
check's method declares it as a keyword, as it declares arguments;
the Validator reads it as ValidationContext.call_context and the
presenter, every row of a list and any presenter it hands its context on
to, as PresentationContext.call_context. So a later stage reads what
an earlier one put there rather than computing it again. With none, a
fresh empty dict for this call alone, so a stage writing to it runs
unchanged on a transport with nothing to put in it. The kernel writes
nothing to it and keeps nothing across calls. Stages of one call run in
sequence; calls sharing one dict across threads should write to it by
compute-if-absent - get, and on a miss compute the value and store it
with call_context.setdefault(key, value) - for a value any of them
would compute the same.
A permission check's method may also name a registered seed in
pool_seeds as a keyword, and is handed its value at whichever of the
three questions declares it. The seeds the checks name, and only those,
are resolved before step two, so the class-level check can read them, and
every pool after takes those values as they are: each resolves once for
the call, and the check, the selectors and the service see one object.
A transport that ran the prelude first, with
check_call or
resolve_target,
makes that once span the prelude too by handing on its .seeds with
its grant, and one that admits the call with authorize before it
finds the row hands on the carrier
resolve_seeds
returned, which it handed authorize too: seeds is a
CallSeeds, and its
values stand in for resolving those seeds here, so the prelude's checks
and this call's run see one value of each. Without seeds, each is
resolved once by the prelude and once more here. A carrier is bound to
the spec, the principal, the call_context dict and the pool_seeds
registry its prelude ran with, each by identity, and one that does not
cover this call is refused before step two, before any seed resolves.
So pass the same call_context dict to both: a prelude handed none ran
with a dict of its own, readable as seeds.call_context, and its carrier
covers only a call handed that same dict, so a call that passes none, or a
fresh one, is refused.
Every other seed resolves as before, once per pool and each after step
two, as every seed does for a spec whose checks name none. A seed named
arguments is never named this way: a check declaring arguments
is handed the call's. A parameter a check's method fills by position -
principal, spec and the target or scope, whatever it calls them -
is never read as an opt-in.
The presenter's context also carries shapes: what the caller sent
for the spec's declared shapes, read-only, a shape left out absent.
No shape reaches a pool under its own name, nor the Validator at all; the
same mapping is in the pool of every callable but a service spec's target
selector as the shapes seed, for a callable that names it (the target
selector is handed an empty mapping, as under resolve_target; see
RESERVED_POOL_SEEDS).
kind is "list" for a LIST selector spec, a service whose output
selector is a LIST, or a many or returns_many service with no
output selector that returned something that is a set of rows, and
"instance" otherwise. Nothing is presented here;
present does that, so a
transport that hands the object to a template never pays for rendering it.
Raises:
| Type | Description |
|---|---|
PrincipalUnavailable
|
a deactivated principal, before step one. |
InvalidArguments
|
step one, or the Validator, or a parameter of a
selector, its |
NotPermitted
|
step two or step four, or |
TypeError
|
|
ActionUnavailable
|
step six, an affordance not met. |
ServiceNotFound
|
step six, a condition on the row reached after the row was deleted. |
ImproperlyConfigured
|
a spec that declares no permissions, a parameter,
a validated, bound or provided value named after a seed, a bound
value named after a validated one, any value bound for a row of a
|
adispatch
async
¶
adispatch(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
principal: Any = None,
principal_id: Any = None,
arguments: Mapping[str, Any],
grant: Grant | None = None,
seeds: CallSeeds | None = None,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
unknown_arguments: UnknownArguments = UnknownArguments.REJECT,
progress: ProgressReporter | None = None,
target: Any = UNSET,
extra_kwargs: Mapping[str, Any] | None = None,
call_context: dict[str, Any] | None = None,
) -> DispatchResult
Run spec from async code: dispatch's steps, order and refusals.
Every concept is sync-only, and so is every spec-carried callable but
one. A permission check, a Validator, a selector nested in a service spec,
extend_queryset, a seed's resolver, a spec's providers and its
preconditions may each query, so each runs in
Django's thread-sensitive executor, never on the event loop. Only the run
may be async def - the service, or a selector spec's own selector -
because it is the one callable no phase shares: a spec is written once for
both entry points, and a concept written async def could not be called
from dispatch.
So the phases run in one sync_to_async(thread_sensitive=True) hop,
and the run's shape decides only what else joins it:
Every refusal before the run is made inside that hop, an affordance and
a service spec's precondition included: a condition on the row is a
query. A selector spec's preconditions run on what its selector found,
so after an async def one they join the hop that shapes its return.
- A sync run joins the hop, so a sync spec costs exactly one.
- An atomic
async defservice joins it too, through the bridge inrun_service:transaction.atomicis sync-only, so the transaction is opened on the executor thread and the coroutine is driven from inside it, where its own thread-sensitive ORM calls come back to the connection holding it. - A non-atomic
async defrun is awaited on the loop after the hop. Holding the executor thread while it awaits - a network call, say - would stall every thread-sensitive call queued behind it. What follows it (an output selector; a selector spec's shaping, row and object-level check) takes a second hop, and only when there is such a thing to do.
Exactly one of principal and principal_id. principal_id is
resolved with
resolve_principal
inside the hop, because resolving it is itself a query; taking only the
row would push that query into a hop of the caller's. A grant never
covers a principal resolved here, since a grant is bound to the principal
object it was minted for. A deactivated row is refused there, with its
identifier in the message; a deactivated principal is refused by
dispatch's own check, which reads the same rule, so the two cannot
disagree about who may act.
progress reaches the run as it does under dispatch, including an
async def one awaited on the loop, so a reporter must be safe to call
from either: the executor thread for a sync run, and an event loop for an
async def one, atomic or not. A spec's progress_reporter is never
called on the loop: for an async def run it is resolved inside the
hop, once nothing before the run can refuse the call.
target is dispatch's: a service spec's target the caller resolved,
standing in for the lookup inside the one hop, and checked there unless
grant says target_checked; without target, checked whatever
the grant says. A selector spec and a many spec
refuse it before any hop, and a selector spec's row or list is checked
whatever the grant says, as dispatch's is.
extra_kwargs is dispatch's overlay, copied on entry, merged
beneath the spec's kwargs provider inside the hop, on every path, and
refused there where it names a declared parameter; beneath the
Validator's computed and bound values too, as in dispatch, on both
hops (test_a_value_the_validator_computed_outranks_the_overlay_on_both_hops).
That refusal and the read of whether a check declares arguments both run off the loop
(test_the_overlay_refusal_and_a_check_s_signature_are_read_off_the_loop).
call_context is dispatch's: the transport's dict, handed to every
stage that declares it as the same object, on every path and across
every hop; with none, one fresh dict for the call, made here on entry, so
the stages of each hop share it.
seeds is dispatch's, handed on with the grant from check_call,
resolve_target or authorize (after resolve_seeds) and taken
on every route, and refused as dispatch refuses it, the wrong type or no
grant on the loop before any hop. Like a grant, a carrier never covers a principal resolved
here
from principal_id, which is not the object its prelude was handed, so
such a call is a TypeError on the loop too, before any hop; pass the
principal the prelude was handed.
A many spec checks, validates and writes its rows as dispatch
does, every row inside the one hop.
Raises:
| Type | Description |
|---|---|
TypeError
|
both or neither of |
PrincipalUnavailable
|
|
(InvalidArguments, NotPermitted, ImproperlyConfigured)
|
as |
(ActionUnavailable, ServiceNotFound)
|
as |
DispatchResult
dataclass
¶
The value an operation produced, and how to read it.
Not-found is reported, not raised: a required row that does not exist
comes back as kind="not_found" and the transport decides what that
means on its wire - a 404, an exit code, a tool error. Nothing here is a
status code, because most transports have none.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
Literal['instance', 'list', 'not_found']
|
|
value |
Any
|
What to present: the selector's rows, or the service's return, or what its output selector re-read. |
service_result |
Any
|
The service's own return, before any output selector. |
instance |
Any
|
The resolved target - the row, or the collection's queryset. |
data |
Any
|
The Validator's |
context |
PresentationContext | None
|
The call a presenter renders for: its principal, its target,
its resolved seeds, the call's context and the arguments sent for
the spec's |
present ¶
Render result.value as JSON-like data, the way spec declares it.
The presenter is a selector spec's own, or a service spec's
presenter_for_output(): its own, or its output selector's when it
declares none.
kind="list": every item through the presenter'spresented_rows()in one call, which presents each in turn unless the presenter batches over them. To serve a page, handpresenta result holding the page's rows, and those are the rows it receives. With no presenter the items are returned as they are, but still in a list: a queryset is evaluated here rather than handed back lazily, becauseapresent's caller is on the event loop, where the first iteration of an unevaluated queryset is a query Django refuses to run.kind="instance": the value through the presenter. With no presenter, or a value ofNone- anallow_noneretrieve that found nothing, a service that returned nothing - the value as it is.Noneis not a row, and asking a presenter to render one produces either a crash or an object of blank fields indistinguishable from a real row.
Affordances. When the selector spec presented through declares
affordances - a selector spec's own, or a service spec's output
selector's, never a service spec's own, which are what its call is checked
against - each presented object gains an affordances key: per declared
name, {"available": true}, or {"available": false, "code": ...,
"reason": ...} naming the first condition the row does not meet, or a
bare {"available": false} for a row deleted before its answers were
asked, which fails no condition and so has no sentence to report. None
is not a row and carries none. The answers are read off the rows as the
selector's dispatch left them - annotations on a queryset's rows, or the
answers it attached to rows a selector returned directly - so presenting
them costs no query. A spec declaring none presents what its presenter
answers, untouched.
The call's context. Each value is handed to the presenter's
presented(), or a list's to its presented_rows(), with
result.context, the
PresentationContext
dispatch built for the call, or None on a result it did not build.
presented() is present() unless overridden, so a Presenter that
reads nothing of the call needs only present(). Every value of one
result is handed the same context, so a list's rows, and a nested
presenter a presenter hands it on to, share its call_context - the
dict the transport created for the call - and read the arguments that
shape the output from its shapes. A spec declaring no shapes and
a presenter reading neither present exactly as before.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
ImproperlyConfigured
|
The spec declares |
apresent
async
¶
present in one executor hop.
A presenter is sync-only and may query - reading a relation off a row the
selector did not prefetch, or evaluating a list's queryset - and the kernel
cannot tell in advance which, so the whole of present runs on Django's
thread-sensitive executor rather than on the event loop. What comes back is
plain data, safe to use on the loop.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
present_for_audience ¶
present_for_audience(
spec: ServiceSpec | SelectorSpec | SpecSource,
result: DispatchResult,
*,
projection: AudienceProjection | None = None,
) -> Any
present plus the agent projection.
The one call an agent transport makes instead of present, so an MCP
server, an in-process toolset and anything added later shape payloads
identically rather than each growing its own post-processor. spec and
result mean exactly what they mean to present, which this calls
first: the projection applies to the presented value and never to the
value it was presented from.
djangorestframework-services' render_for_audience is the same
composition over its serializer render, and takes the view,
request and many that render reads. This is named apart so that
neither package's name means two signatures.
projection is the output's resolved markings. Omit it and one is read
off the spec; a transport that registers its tools up front builds it
once with
audience_projection_for_spec,
a mount's overrides included, and passes it in. None is therefore not
a way out of projecting: a caller naming no audience calls present,
which is what every HTTP response is.
To serve one page, page the result's value first and present the page's
rows: present_for_audience(spec, replace(result, value=page.items)),
then envelope
what comes back. The presenter's presented_rows() is then called once,
with the page's rows and no others, so a lookup it batches over them
costs the same whatever the size of the whole set. The envelope's keys
belong to no Output, so the projection must never walk them. Whether to page is read off the
spec,
never off the result's kind: a LIST selector spec, or a service spec
whose output selector is a LIST, is paged, while a many or
returns_many service spec's kind="list" is every row its service
returned, which its output schema describes as a bare array.
A selector spec's declared affordances pass through whole: the
affordances object present adds to each row is a key no Output
declares, so the projection has nothing to say about it, and an agent
reads available, the code a client branches on, and the reason
- the sentence a model relays when it explains why an action is not
possible, written for exactly that reader.
Render an agent's answer with this. A pipeline that feeds one spec's
output into the next keeps presenting with present, or the handles the
next step reads by will have been projected away.
From async code, project what
apresent returns:
project_payload(await apresent(spec, result), projection). Presenting
may query and runs in the executor; projecting reads only the presented
data and the declaration, so it is safe on the event loop.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
resolve_target ¶
resolve_target(
spec: ServiceSpec | SpecSource,
*,
principal: Any,
arguments: Mapping[str, Any],
grant: Grant | None = None,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
call_context: dict[str, Any] | None = None,
seeds: CallSeeds | None = None,
) -> ResolvedTarget | DispatchResult
Find and check spec's target as dispatch would, without running anything else.
For a page that shows the row before the call acts on it - the form in
front of an update, the confirmation in front of a delete - and so must
show the row dispatch would find, refused where dispatch would refuse.
It runs dispatch's own steps, in dispatch's order, and the walk after
them is the very function dispatch runs:
- A deactivated principal is refused, as
PrincipalUnavailable. - The shape check over the target selector's parameters alone, on
only the arguments they name. A Validator field is neither required
nor an unknown key here, so a GET carrying the route's arguments and a
POST carrying the whole form both resolve; the target's own reads are
required as declared, except one its
kwargsprovider fills or may fill, which the lookup's pool must then hold once the provider has answered, as at dispatch. Areflectedtarget read a registered seed is named like is no argument, and the seed fills it. - Class-level authorization, honouring
grantas dispatch does. Like the two steps before it, before any query. - The lookup, and the checks on what it finds:
has_object_permissionon a row, andhas_scope_permissionon a collection target's set, empty or not, and onNone- a create, which resolves nothing, and a missing row the instance selector'sallow_nonelets through.
Returns (target, grant), a
ResolvedTarget:
the row, the set, or None, and a grant
covering spec and principal with target_checked set, which
is what dispatch(spec, ..., target=target, grant=grant) takes. So a
call resolved here looks nothing up again and asks no object-level or
scope check twice. Its .seeds are the values every check here was
offered of each registered seed one names; handed on as
dispatch(..., seeds=found.seeds), the run takes them as they are and
resolves none of them again
(test_resolve_target_then_dispatch_resolves_it_once). Like the grant they
are bound to this call, call_context included: pass dispatch the dict
passed here. The grant vouches for that target alone: handed to
dispatch without target=, it covers the class-level check and nothing
else, and dispatch checks the row its own lookup finds. A
target_checked grant handed in here is read the same way, since
this function looks its target up itself. A missing row allow_none does not let through
returns DispatchResult(kind="not_found"), dispatch's own answer, so it
is never mistaken for the None it lets through.
seeds is a carrier of values already resolved for this call: the
CallSeeds that
resolve_seeds
returns, for a page that ran authorize(seeds=) before it resolved the
row, or check_call's .seeds. Its values stand in for resolving
the seeds a check names, so the class-level check, the object or scope
check and the .seeds handed back carry one value of each, resolved
nowhere here (test_a_carrier_s_seeds_are_taken_and_resolved_nowhere_else).
It needs no grant: without one the class-level check is asked on its
values. One that does not cover this spec, principal, call_context
dict and pool_seeds registry is refused as NotPermitted before any
resolver runs and before any check is asked; pass the dict the carrier
was bound to, seeds.call_context.
call_context is the call's context, as dispatch takes it: the
transport's dict, handed as the same object to the target selector and to
every permission check method naming it, or a fresh dict of their own when
none is passed. A check naming a registered seed is offered it here as at
dispatch, at the class-level check and at the checks on what the lookup
finds. A page resolving its row ahead of the call passes the dict it will
hand that call, so the two read and write one context.
It is sync, as dispatch's steps are; an async caller hops once, with
sync_to_async(resolve_target, thread_sensitive=True).
Raises:
| Type | Description |
|---|---|
PrincipalUnavailable
|
a deactivated principal. |
InvalidArguments
|
a target read the arguments leave out or get wrong. |
NotPermitted
|
the class-level, object-level or scope check, or
|
ImproperlyConfigured
|
as |
ImproperlyConfigured
|
also a |
TypeError
|
a |
TypeError
|
|
ResolvedTarget ¶
Bases: tuple[Any, Grant]
(target, grant), as resolve_target has always returned, carrying the call's seeds.
Still a 2-tuple, so target, grant = resolve_target(...) reads as it
did. seeds is the
CallSeeds the
class-level check and the checks on the target were offered, for
dispatch(target=target, grant=grant, seeds=found.seeds).
seeds
property
¶
The values of the seeds a check names, as this call's checks were offered them.
resolve_seeds ¶
resolve_seeds(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
principal: Any,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
call_context: dict[str, Any] | None = None,
) -> CallSeeds
The registered seeds spec's checks name, resolved for principal, as a carrier.
For a transport that admits a call before it resolves the row - a page
asking the class-level check before it shows a form, then finding the
row, then running the call. Handed the
CallSeeds this
returns as seeds=,
authorize,
authorize_scope,
authorize_target,
resolve_target
and dispatch all take these values as they are, so the class-level
check, the object or scope check and the run see one value of each,
resolved here once (test_one_resolution_from_resolve_seeds_to_dispatch,
test_one_resolution_on_the_many_path).
The seeds resolved are those a check of the spec names at any of its
three questions - has_permission, has_object_permission and
has_scope_permission - as dispatch resolves them before its
class-level check, and as check_call hands them back. That is wider
than authorize(pool_seeds=), which resolves only the seeds the
class-level question names. A seed no check names stays unresolved: it
resolves in each of dispatch's pools as it always does
(test_it_resolves_what_check_call_resolves). Resolved from a base pool
with principal as user and no live reporter; a resolver raising -
PrincipalUnavailable for one - ends the call here. A spec declaring
no permissions resolves nothing, and authorize refuses it next.
A deactivated principal is refused first, as PrincipalUnavailable,
before any seed resolves, as dispatch refuses one
(test_a_deactivated_principal_resolves_no_seed).
The carrier is bound by identity to spec as handed (compared as
compiled, so a carrier for a
SpecSource covers
the spec it compiles to), to principal, to the call_context dict
and to the pool_seeds registry, and every function that takes it
refuses one that does not cover its call as NotPermitted. Handed no
call_context, it is bound to a fresh dict, readable as
.call_context
(test_a_call_handed_no_context_gets_a_dict_readable_on_the_carrier).
The common mistake is then to hand authorize(seeds=carrier) no
call_context either: None is not that dict, so the call is
refused. Pass call_context=carrier.call_context to every step, or
hand this the dict the call will use
(test_authorize_without_the_carrier_s_context_is_refused).
Like a grant, the carrier cannot be pickled.
Raises:
| Type | Description |
|---|---|
PrincipalUnavailable
|
a deactivated principal, or a resolver raising it. |
paginate_output ¶
paginate_output(
rows: Any,
*,
page: int | None = None,
limit: int | None = None,
max_page_size: int | None = None,
) -> OutputPage
Slice rows into the page a transport serves.
A function a transport calls on a paged spec's result value before
presenting it, not a paging scheme: the names a caller pages by, and the
ceiling a mount allows, are the transport's. A transport takes them off the
call before the spec's closed argument set sees them, and bounds
legitimately differ between two mounts of one spec.
Whether to page is read off the spec, never off the result's kind: a
LIST selector spec, or a service spec whose output selector is a
LIST, is paged, and
spec_output_schema
describes it as the envelope under paginate=True. A many or
returns_many service spec's result is kind="list" too, and is never
paged: it is every row the service returned, which its output schema
describes as a bare array whatever paginate says.
page and limit default to 1 and
DEFAULT_PAGE_SIZE.
Out-of-range values clamp at both ends - limit down to
max_page_size and up to 1, page up to 1 and down to the last page
that exists - and the clamps are not silent the way truncating an unpaged
result would be: totalPages and hasNext are computed from the
clamped limit, and the returned page is the one actually served. A
caller that asked for 500 rows and got 100, or for page 10 of 3, is told
what it received.
Both values are taken already parsed. Turning an untyped argument into an integer is where transports legitimately differ - a public endpoint clamps a malformed value and answers, an in-process toolset can hand a model its mistake back and ask again - and that is a policy about bad input, not about what a page is.
The upper clamp on page is why total is counted before the
slice: (page - 1) * limit on an unclamped page is an arbitrarily large
SQL OFFSET, which a backend either scans towards or refuses outright
with a DatabaseError this does not catch. No slice is longer than
total for the same reason, so a limit past any integer a database
holds, which no max_page_size bounded, still serves every row; the
page reports the limit asked for.
A queryset is counted with COUNT and sliced lazily, so the page's
items is still a queryset: present them, as
present does a list,
and the page is read once. A manager - any BaseManager, so one built
with BaseManager.from_queryset too - is paged as its .all(), since
it counts and cannot be sliced.
Raises:
| Type | Description |
|---|---|
TypeError
|
|
DEFAULT_PAGE_SIZE
module-attribute
¶
Rows per page when the caller asks for a page and names no size.
bind_arguments ¶
bind_arguments(
spec: ServiceSpec | SelectorSpec | SpecSource,
arguments: Mapping[str, Any],
*,
principal: Any,
target: Any = None,
unknown_arguments: UnknownArguments = UnknownArguments.REJECT,
call_context: dict[str, Any] | None = None,
pool_seeds: PoolSeeds | None = None,
) -> dict[str, Any]
Check arguments against the spec's parameters, then validate them.
The bind a transport calls when it binds input itself rather than through
dispatch - an MCP server answering a malformed call before it opens a
transaction, a queue validating a task in the worker. It is the same two
steps dispatch takes, so a transport that binds for itself cannot drift
from the gate dispatch applies. spec may be a
SpecSource, bound as
the spec it compiles to:
check_argumentsoverspec.parameters(), underunknown_arguments: the closed argument set and the shape check, at every level, relaxing what dispatch relaxes: an absent Validator field when the service spec ispartial, one itsinput_dataprovider fills or may fill, and a read thekwargsprovider of the spec declaring it fills or may fill - a typed provider's filled and declinable keys, and every parameter an untyped provider's values reach - less a read a provider requires itself, which stays demanded (test_a_read_its_own_untyped_provider_requires_is_demanded_of_the_caller).- For a
ServiceSpecwith a Validator,validated()on only the arguments the Validator's ownparameters()declare - never a selector's or the spec'sreads- withValidationContext(principal, target, partial), whoseresolvednamestargetas dispatch would:instancefor a spec with an instance selector,collectionfor one with a collection selector, nothing for a create, and whosecall_contextiscall_context, the very dict passed, or a fresh one.
Returns the Validator's values. A service spec with no Validator returns
{}, because every argument it takes is a read and none is validated. A
SelectorSpec
has no Validator and returns the checked arguments, which are what its
selector is called with.
It runs no provider. The spec's input_data, which dispatch merges
over the caller's arguments before the Validator, is not called here: it
reads the resolved target and the call's seeds, which this function is
not handed. A spec declaring one is bound on the caller's arguments alone,
so a field the provider fills or may fill passes the shape check and is
the Validator's to refuse: left out, or sent, since a value the caller
sends for a field the server owns is checked and then dropped, as in
dispatch. The presence check dispatch makes of such a field before the
Validator, once the provider has answered, is not made here
(test_a_field_input_data_fills_is_left_to_the_validator_which_runs_no_provider).
No kwargs provider is called either: a read one fills or
may fill passes the shape check absent, unless a provider requires it
itself, and the presence check dispatch
makes once the provider has answered is not made here
(test_bind_arguments_relaxes_a_may_fill_read). A read one is annotated to
fill is absent from a selector spec's checked arguments whether or not
the caller sent it.
Given pool_seeds, it binds as dispatch binds with them. A
reflected read a registered seed fills is no argument of the call, so
it is not demanded of the caller
(test_a_reflected_read_a_registered_seed_fills_is_not_demanded), and the
caller's value for it is refused as an unknown argument under REJECT
and dropped under IGNORE
(test_the_caller_s_value_for_it_is_refused_under_reject_as_dispatch_refuses_it,
test_the_caller_s_value_for_it_is_dropped_under_ignore). A parameter
dispatch refuses for sharing a seed's name is refused here too, with
ImproperlyConfigured
(test_an_unmarked_read_named_like_a_registered_seed_is_refused_only_with_the_seeds).
The Validator's ambient is the pool dispatch hands it: user,
progress as the no-op reporter, since no call is running, and every
registered seed, each resolved once for the principal against
call_context, so a FormValidator's form_kwargs naming a seed
is handed it
(test_a_form_kwargs_naming_a_registered_seed_is_handed_it). A Validator
field named like a registered seed is validated and returned among the
values, as any field is, and the seed keeps its own value in ambient
(test_a_validator_field_named_like_a_registered_seed_is_validated_and_returned).
Every seed resolves on each bind of a spec with a Validator, as on
dispatch, whether or not the Validator reads one, so a caller binding
often, a page re-checking a form on each edit, pays each resolver per bind.
A spec with no Validator resolves none, since nothing it binds reads one
(test_a_service_spec_with_no_validator_resolves_no_seed).
A deactivated principal is refused with PrincipalUnavailable first,
as dispatch refuses one: before the seat refusal and the shape check, for
every kind of spec and any registry, so no seed resolves for it
(test_given_seeds_a_deactivated_principal_is_refused_first_as_dispatch_refuses_it,
test_given_seeds_a_deactivated_principal_is_refused_before_the_seat_refusal,
test_a_deactivated_principal_resolves_no_seed). Which values a service's
pool spreads is dispatch's question.
Any registry is dispatch's, an empty one too, so the call's
request and view are seeds of the bind as of every pool dispatch
builds: a reflected read of either name is filled rather than
demanded (test_a_reflected_read_named_request_is_the_call_s_with_any_registry).
Without pool_seeds it is the function it was before it took
them: a reflected read is checked as declared, so a required one is
demanded of the caller
(test_bind_arguments_still_demands_a_required_reflected_read), no seed is
resolved, no principal is refused for being deactivated, and the
Validator's ambient is empty
(test_the_validator_s_ambient_is_dispatch_s_with_any_registry).
It does not resolve or authorize. Dispatch runs class-level
authorization, target resolution and object-level authorization between
these two steps, so the Validator sees the resolved row and a refused
principal learns nothing about which rows exist. A caller of this function
owns both: it authorizes before binding, and passes the row it resolved as
target, or None for a create.
It is the complement of
check_call: this
validates and does not authorize, and check_call authorizes and does
not validate.
Raises:
| Type | Description |
|---|---|
InvalidArguments
|
from either step. The shape check's tree carries every
problem at once, and a Validator is only reached with well-shaped
arguments. A |
check_requested_input ¶
check_requested_input(
spec: ServiceSpec | SelectorSpec | SpecSource,
schema: Mapping[str, Any] | None,
*,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
call_context: dict[str, Any] | None = None,
) -> None
Refuse an AdditionalInputRequired.schema some route could not ask, or could not hear
answered.
schema is what a service raised
AdditionalInputRequired
with, read against spec: a transport calls this before it renders the
question, so a service asks the same question on every route or on none.
None, a raise that carries no schema, asks nothing and passes.
It reads the spec's top-level parameters() and the schema, runs no
query and returns nothing. Each key is refused, by name, with
ImproperlyConfigured, in this order:
- A key no top-level parameter declares. The answer comes back as an
ordinary argument, so a key the closed argument set refuses could never
carry it. On a
manyspec the top level is the list and the spec'sreads, so a value asked once for the whole call is areadsparameter, and a key declared only inside a row is refused. - A key the server fills: one a provider the dispatch runs is
annotated to fill, or a seed
pool_seedsregisters - areflectedread the seed fills among them - asserver_owned_keysreads them. Dispatch drops the caller's value for such a key, so the answer would never reach the service.pool_seedsis the call's, asdispatchtakes it. A top-level Validator field named like a registered seed may be asked for, since the answer reaches the Validator anddata(test_server_owned_keys_leaves_such_a_field_out_and_a_service_may_ask_for_it), and so may a key a provider may decline or one an untyped provider's values reach, whose caller's value stands when the provider declines. - A fragment that is not a schema object: a
dict, as JSON carries one. - A shape some transport cannot render. The narrowest is an MCP
elicitation form, which takes a
string,number,integerorboolean, or anarraywhoseitemslist enum values, untitled (enum) or titled (anyOf). Atypelist, anobject, a fragment naming no type and an array of anything else are refused. - A
typethe declared parameter does not take, since the answering call would fail the shape check whatever was answered. The answer must be of a type the parameter takes: anintegerquestion may fill anumberparameter and not the reverse, any question may fill anany, and a number may fill adecimalstring, ascheck_argumentsreads one. An array question fills anarraywhose element takes its values, which are strings unless itsitemsname a type, as both of MCP's multi-select shapes are; the rows of amanylist are objects, which no list of values fills. Thetypeis compared and nothing finer: aformat,choicesor a bound the parameter declares still checks the answer when it arrives.
call_context is the dict of the call whose service raised: the spec's
parameters and the keys the server owns are read as the spec declares
itself to that call, so a Validator declaring an asked key only to a call
can ask for it
(test_handed_the_call_s_context_the_key_is_answerable, and
test_the_server_owned_keys_are_read_with_the_call_s_context_too for the
keys owned). Left None, both are read as the spec declares itself to
no call.
A SpecSource is
read as the spec it compiles to.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
naming the first key refused, or for a
|
check_call ¶
check_call(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
principal: Any,
arguments: Mapping[str, Any],
grant: Grant | None = None,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
unknown_arguments: UnknownArguments = UnknownArguments.REJECT,
call_context: dict[str, Any] | None = None,
) -> CheckedCall
dispatch's prelude, run alone: the checked arguments and the grant, or its refusal.
For a transport that answers a call before it runs - a task queue
refusing at enqueue what the worker's dispatch would refuse before it
resolves anything. Only that: no lookup runs, so no object or scope
check, no Validator, no affordance and no precondition, and a call this
passes may still be refused by dispatch at any of those
(test_a_scope_check_is_left_to_dispatch). The steps are
dispatch's own, in
its order, and the same function runs them for both, so the two cannot
drift apart:
- A deactivated principal is refused as
PrincipalUnavailable, with or without agrant. - A parameter a registered seed in
pool_seedsis named like, or one namedrequestorviewon any mount, is answered as dispatch answers it: areflectedread leaves the argument set, a top-level Validator field stays in it, and anything else is refused asImproperlyConfigured. check_argumentsunderunknown_arguments, relaxed exactly as dispatch relaxes it: a parameter a provider fills or may fill - a typed provider's filled and declinable keys, and every parameter an untyped provider's values reach, less a read a provider requires itself (test_a_read_its_own_untyped_provider_requires_is_demanded_of_the_caller) - and a Validator field underpartial. No provider runs here, so a call this passes without such a value may still be refused bydispatchwhere the provider's answer is merged (test_check_call_relaxes_a_may_fill_read).authorize, honouringgrantif it covers this spec and principal.
The keywords are dispatch's, less what only a run reads. The kernel's
own steps run no query; a project's PermissionCheck may.
It returns the checked arguments and the grant the call ran under, which
dispatch honours for the same spec and principal, so the
class-level check is not asked twice: a
CheckedCall,
still the 2-tuple (arguments, grant). Its .seeds are the values the
checks were offered of each registered seed one of them names, which
dispatch(grant=grant, seeds=checked.seeds) takes as they are, so the
checks here and the run there see one value of each, resolved once
(test_check_call_then_dispatch_resolves_a_check_named_seed_once). The
carrier is bound to this call's call_context dict, so a transport
passes dispatch the dict it passed here; a carrier from a call
handed no call_context is bound to a dict only this function held,
readable as checked.seeds.call_context, and covers only a call handed
that same dict: a later call that passes none, or a fresh one, is refused.
A many spec's rows come
back as a list of checked rows under many_argument, and a refused row
is raised here, after step four, in the tree dispatch raises it in -
though dispatch reports it beside the Validator's refusals of the
other rows, and this runs no Validator.
That refusal is marked: its after_authorize is True, and it is
False on every refusal of steps one to three and on dispatch's own
(test_a_refused_row_is_marked_as_raised_after_the_class_level_check,
test_a_failed_shape_is_not_marked_as_raised_after_the_class_level_check).
A transport that calls this before charging a rate limit reads it to tell
a refused row, which was refused after the class-level check passed, so the
call is admitted and only its rows are wrong, from a refused call, which
was not admitted. The checks are not asked again to find out.
It is the complement of
bind_arguments:
this authorizes and does not validate, and bind_arguments validates
and does not authorize. Neither resolves a target; for a service spec
that acts on a row,
resolve_target
finds and checks it.
spec may be a declaration with as_kernel_spec(), read as the spec
it compiles to, and the grant is for that compiled spec, which the same
object answers on every later call.
call_context is offered to the checks as dispatch offers it, the
very dict passed, or a fresh one; a check naming a registered seed is
handed it, resolved as dispatch resolves it before the class-level check.
Raises:
| Type | Description |
|---|---|
PrincipalUnavailable
|
step one. |
ImproperlyConfigured
|
step two, or a spec that declares no permissions. |
InvalidArguments
|
step three, or a refused row of a |
NotPermitted
|
step four. |
ValueError
|
|
CheckedCall ¶
Bases: tuple[dict[str, Any], Grant]
(arguments, grant), as check_call has always returned, carrying the call's seeds.
Still a 2-tuple, so arguments, grant = check_call(...) reads as it
did. seeds is the
CallSeeds the
checks were offered, for dispatch(grant=grant, seeds=checked.seeds).
seeds
property
¶
The values of the seeds a check names, as this call's checks were offered them.
check_seeds ¶
check_seeds(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
) -> None
Refuse a declaration that cannot hold as written on a mount registering pool_seeds.
Five of them, below: a parameter a seed or the call's own value would
meet, a positional-only parameter dispatch cannot pass, a keyword nothing
fills, an optional read over a keyword that requires it, and an array
read with no items over a keyword annotated with its element. The
first fails every call, the second and third every call that reaches the
callable, the fourth every call leaving the read out, which the
declaration says a caller may, and the fifth hands the callable any
element a caller sends. Each is decided by the spec and the
mount's registered seeds alone, so a transport registering a kernel spec
can refuse it where it registers it rather than list a tool or a route
whose calls fail in a way the declaration already settled. The spec does
not refuse these itself when it is built because the seeds are the
mount's, and a keyword one mount fills is unfilled on another. Nothing
runs: no seed resolves, no provider is called and no query is made.
Every refusal it finds is named in one ImproperlyConfigured, each
offender in a sorted list such as ['tenant'].
- A parameter a registered seed is named like, or
requestorview, that dispatch refuses on every call: a read nobody markedreflected, a shape, amanyspec's list (seed_named_parameters's second set), in the words dispatch refuses it in. A selector spec's own read or shape of either call name is one, refused here and by dispatch rather than when it is built. - A positional-only parameter with no default, of the service, the
selector or the target selector, and of each callable the third reads
below: a precondition, a callable condition, the output selector, an
extend_queryset, akwargsorinput_dataprovider and aprogress_reporter. Dispatch calls each by keyword, so nothing fills one, a read of its name included. - A keyword the callable requires that nothing fills: by name, with no default, and in none of the places dispatch fills a keyword from
-
what every pool carries (
user,progress,call_context,shapes,request,view), a seedpool_seedsregisters, a read of the callable's own seat, a key the seat's typedkwargsprovider names, and for a servicedata, andinstanceorcollectionwhere a target selector resolves one. The kernel seedsdatafor a service only, so a selector requiring it is refused as any unfilled keyword is. A service is handed its spec's reads, never its target selector's or its shapes, which reach it asshapes. It reads these callables, each against what dispatch hands that one: -
the service, the selector and the target selector, as above;
- a service spec's
preconditions, handed the service's pool, and a selector spec's, handed the selector's with the rows ascollection(a LIST) or the row asinstance(a RETRIEVE); - each callable
Affordancecondition, the spec's own and those a selector'saffordancesmap to, handed only the call's seeds:user,progress,call_context,request,viewand a seedpool_seedsregisters, never an argument (ambient_pool); a condition on the row binds nothing; - the output selector, handed the service's return as
instanceandresultand what every pool carries, never an argument nor its own reads; - each selector's
extend_queryset, handed its selector's pool with thequeryset; - each
kwargsprovider - the spec's own and its target selector's - and a service spec'sinput_data, handed what every pool carries, a seedpool_seedsregisters and its seat's reads less those the seat's typedkwargsprovider fills, whose caller's value dispatch drops; for a service,instanceorcollectionwhere a target selector resolves one. Neverdata, a Validator's value or a provider's answer:input_dataruns before the Validator, andkwargsis called from the same pool. A provider's own keys fill nothing it is handed, so its seat is read whether it is typed or not, and beside a Validator too; - a spec's
progress_reporter, where its run takesprogressby name or through**kwargs, which is where dispatch may call it: before anasync defrun, or on a sync run's first report. It is refused either way, though a sync run that never reports never calls it. It is handed only what every pool carries and a seedpool_seedsregisters. A run taking noprogressnever calls it, so it is not read there.
Each is named as the spec names it, such as
ServiceSpec.affordances[0] ('frozen').when,
SelectorSpec.preconditions[0] (owns_it) or
ServiceSpec.instance_selector_spec.kwargs, in the order a call
reaches it.
4. A keyword the callable requires that only an optional read fills:
a read the shape check does not demand - declared required=False,
or declaring a default, which is reported and never applied - over
a keyword with no default, that no seed and no provider fills. A call
sending it runs, and one leaving it out is refused as missing
(call_keywords), or on a provider fails with its own
TypeError, so a caller reading the declaration is told the read
is optional and refused for omitting it. It reads every callable the
third does that sees reads: a precondition, an extend_queryset
and a kwargs or input_data provider as well as the service,
the selector and the target selector. A condition, the output
selector and a progress_reporter are handed none of their spec's
reads, so it finds nothing on them.
5. An array read with no items over a keyword annotated with its
element: a read of type="array" declaring no items, over
the keyword it fills on its own seat, annotated list[X],
tuple[X, ...] or Sequence[X], or one of those | None,
where X is neither Any, object nor a type variable. Such
a read takes any
element, so a callable annotated pks: list[int] is handed a
query string's strings, and the message says to declare items.
It derives none from the annotation: a signature is not a
declaration. As with the third and fourth, it never guesses: a
keyword a provider fills or may fill is not one - a typed
provider's key, declinable or not, and any keyword of a seat whose
provider is untyped - and nor is a keyword a seed fills, as a
reflected read's.
A callable whose signature cannot be read is refused too, ahead of
these for its seat: any callable the third reads, such as a builtin type
like dict, which dispatch cannot bind a keyword to and so fails on
for every call reaching it. The second to fifth need that signature, so
such a seat is answered by this refusal alone, and the other seats are
still checked.
A Validator field the service never receives is not among them, because
such a spec runs and may mean to:
unreceived_fields
answers it, and the transport decides.
What it cannot see, and so never refuses. A provider whose return says
nothing about its keys may fill any keyword of the callable it provides
for, so that callable's keywords are left to dispatch (the third and
fourth); the provider's own are read as any seat's. An annotation that
does not resolve, as a forward reference to a name not importable where the
callable was defined, is not read, and leaves alone only its own keyword
(the fifth); so is a bare list, an element of Any or object, a
fixed-length tuple, a union of two sequences and an unannotated
keyword. A Validator may return a value it does not declare, or bind one,
so a service beside a Validator is not judged by the third and fourth
either (test_a_service_beside_a_validator_is_left_to_dispatch). A transport
handing dispatch an extra_kwargs overlay fills keywords this cannot
see, and should not call it for such a spec. Only the fifth refusal is not
run on a precondition, a condition, the output selector, an
extend_queryset, a provider or a progress_reporter. A precondition beside a Validator,
or one or an
extend_queryset beside an untyped provider, is left to dispatch by the
third and fourth as the callable beside it is, never by the second. A
callable taking **kwargs requires nothing, so one forwarding into a
stricter callable is not judged by what that callable requires. Nor is the
pool a transport builds itself to answer a condition at describe time
(unmet_operation_affordance): this reads the pool dispatch builds. Nor
does it read a filter_set, a form's form_kwargs or a seed's
resolver: dispatch binds each by keyword, and this is not asked of any.
Describe-time: run where a transport registers the spec, it reads
the spec as it declares itself to no call, handing a Validator that
declares call_context None
(test_describe_time_readers_hand_none).
It takes no call_context, unlike the input schemas, because none of
its five refusals reads a Validator's field: what it refuses is a read, a
shape, a many spec's list and a callable's keywords, a top-level
Validator field is in neither of seed_named_parameters' sets, and a
service beside a Validator is left to dispatch
(test_a_validator_field_is_the_caller_s_and_fills_the_service_s_keyword).
Assembling spec.parameters() still refuses a seat dispatch seeds
itself, a name two sources declare and a field a typed kwargs fills.
So a field declared only to one transport with such a shape is not refused
here, and raises at the first ask under that stamp, a schema's as well as
dispatch's
(test_a_declaration_only_a_transport_makes_is_refused_when_that_transport_asks).
spec may be a declaration with as_kernel_spec(), read as the spec
it compiles to.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
any of the five, or a callable whose signature cannot be read, every one found. |
seed_named_parameters ¶
seed_named_parameters(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
) -> tuple[frozenset[str], frozenset[str]]
Of spec's parameters named like a seed pool_seeds registers or the call's own: those
filled, and those refused.
The answer dispatch gives before it reads a call's arguments, read
alone, so a transport can give it when it registers the spec rather than
on every call. A parameter shares a name when a seed pool_seeds
registers is named so, or it is request or view, which dispatch
hands every callable from the call's context. Of those names:
- the first set is the
reflectedreads - a selector spec's, a target selector's or a service spec's - which the seed, or the call's own value, fills: no caller sends one, so a transport's schema leaves it out; - the second set is what dispatch refuses as
ImproperlyConfiguredon every call: a read nobody marked, a shape, amanyspec's list. A service spec's read, its target selector's or its shape namedrequestorviewis refused when the spec is built, so of those two names only a selector spec's own read or shape, or amanyspec's list, ever reaches this set; - a top-level Validator field is the caller's, validated into
data, and in neither set.
The same reader dispatch answers by
(test_it_is_the_answer_dispatch_gives), so the two cannot drift.
check_seeds
refuses the second set, beside the other declarations no call can run.
Describe-time: it reads the spec as it declares itself to no call,
handing a Validator that declares call_context None
(test_describe_time_readers_hand_none). Dispatch answers each call over
the parameters it assembles for that call, so a Validator field declared
only to a call is answered there and not here; since such a field is in
neither set, the two answers agree.
spec may be a declaration with as_kernel_spec(), read as the spec
it compiles to.
provider_reached ¶
provider_reached(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
call_context: dict[str, Any] | None = None,
) -> frozenset[str]
Every top-level parameter of spec a provider fills or may fill: what the shape check
relaxes.
Each provider's values reach one seat, and relax the parameters there: a
kwargs provider its spec's reads, a service spec's target
selector's kwargs that selector's reads, and, on a service spec
that is not many, input_data the Validator's fields. In its seat
a typed provider reaches the keys its TypedDict names, filled and
declinable alike, and one whose return says nothing about its keys
reaches every parameter there
(provider_keys).
Less a read a provider requires itself, by name with no default: a
provider is handed the caller's reads and the seeds, never another
provider's answer, so the shape check demands it of the caller
(test_a_read_its_provider_requires_is_not_reached).
The shape check does not demand a parameter this names, and a transport
reading it leaves such a parameter out of the arguments its schema
requires; one a provider is annotated to fill, and may not decline, is
in server_owned_keys
too, which leaves it out of the schema altogether.
The same reader the shape check relaxes by, so a transport's schema and
dispatch cannot disagree about which parameter a caller must send
(test_it_is_the_set_check_call_relaxes).
check_server_arguments reads it, so a parameter the shape check does
not demand may be withheld. One arc to coverage, each conjunct held by
its own test: a selector spec has no Validator
(test_check_server_arguments_lets_a_read_an_untyped_provider_reaches_be_withheld),
a service spec may have none
(test_a_service_spec_s_read_is_judged_by_its_service), and a many
spec's row fields are no top-level parameter, though one may share a
read's name
(test_check_server_arguments_still_refuses_withholding_a_many_read_a_row_field_shares).
Describe-time unless handed a context: for a schema or a check made
where a transport is built, it reads the Validator's fields as it declares
them to no call, handing one that declares call_context None
(test_describe_time_readers_hand_none). The shape check relaxes each call
by the parameters that call declares, so a transport describing the spec
under a context of its own hands that dict here, and reads the set the
shape check relaxes under it
(test_a_field_declared_only_to_a_call_is_reached_under_that_call_s_context_alone,
test_under_a_context_it_is_the_set_check_call_relaxes_under_it).
spec may be a declaration with as_kernel_spec(), read as the spec
it compiles to.
unreceived_fields ¶
unreceived_fields(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
) -> frozenset[str]
The Validator fields of spec its service takes neither by name, nor through data, nor
through **kwargs.
A value a caller sends for one is validated and then reaches the service
by no route, on a mount registering pool_seeds. A top-level field
named like a registered seed or the call's request or view
reaches the service through data alone, since the name in the pool
is the seed's, so a service taking it by name only never receives it. A
many spec's rows reach the service as the list under
many_argument, or in data, so its one field is that list. A
service taking **kwargs is handed data with the rest, and so
receives every field.
An answer, not a refusal, because such a spec runs, and may be meant
to: a Validator checking that password and confirm agree returns
password alone, and its service never takes confirm on purpose.
A transport decides what a non-empty answer means for it - refusing the
spec where it registers it, warning, or advertising the field anyway.
What it cannot see, and so never answers. A Validator may return a
field under a name other than its parameter's - a pydantic field
validated by its alias comes back under its own name - so a service
taking a keyword nothing declared explains is answered for none of its
fields
(test_a_field_validated_under_its_alias_reaches_its_own_name_and_is_not).
A kwargs provider whose return says nothing about its keys explains
every keyword the same way. Nothing runs: no seed resolves and no
provider is called.
Describe-time: for a transport registering the spec, it reads the
Validator's fields as it declares them to no call, handing one that
declares call_context None
(test_describe_time_readers_hand_none), so a field declared only to a
call is not answered.
spec may be a declaration with as_kernel_spec(), read as the spec
it compiles to; a selector spec, and a service spec with no Validator,
have no fields, and are answered with none.
check_server_arguments ¶
check_server_arguments(
spec: ServiceSpec | SelectorSpec | SpecSource,
server: ServerArguments,
*,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
) -> None
Refuse a ServerArguments
that cannot mean what it says for spec.
For a transport to call once, when it is built, with the pool_seeds it
dispatches with, so a binding that would do nothing or break every call
fails at startup rather than on the first call that reaches it. Pure and
synchronous, and it runs no query. The checks run in this order, and the
first that finds anything raises, naming the spec's kind and callable and
every name it found, in order:
- A name that is no top-level parameter of the spec, read as
django-spec-html's
route_argumentsreads a route's kwargs:spec.parameters().names(). So a field inside amanyspec's rows cannot be bound; a read beside the list can. Held by test_every_undeclared_name_is_refused_in_order and test_a_field_inside_a_many_row_is_not_a_top_level_parameter. - A name both bound and withheld, which asks for a value and for none. Held by test_a_name_both_bound_and_withheld_is_refused.
-
A name a registered seed occupies, as dispatch reads one. Only a registered seed can reach here, since
parameters()refuses the dispatcher's names as it assembles. Two refusals, in this order, each naming only its own: -
a parameter dispatch refuses as a configuration error - a read nobody marked
reflected, a shape. Held by test_a_parameter_a_registered_seed_occupies_is_refused and test_an_unmarked_read_is_still_refused_as_dispatch_refuses_it; - a
reflectedread, which the seed fills on every call, so a binding or a withholding would do nothing. Held by test_binding_or_withholding_it_is_refused_as_doing_nothing.
A top-level Validator field named like a registered seed is not
refused: it is the caller's argument, so a bound value reaches the
Validator and data while the seed keeps the service's parameter of
its name (test_check_server_arguments_binds_such_a_field), and
withholding it meets rule 5 as any field does.
4. A name a typed provider fills or may fill: the spec's kwargs
and, on a service spec, its input_data and its target selector's
kwargs, the providers
server_owned_keys
walks. A key a provider fills is dropped from the caller's arguments
and answered by the provider alone, so a binding would do nothing; one
it may decline with UNSET is the provider's on every call where it
answers, so a binding would hold only when the provider happens not
to. Each half is held by its own test:
test_a_name_a_typed_provider_fills_is_refused (the filled keys) and
test_a_name_a_provider_may_decline_is_refused_too (the declinable ones),
and each provider past the spec's own kwargs too:
test_a_validator_field_input_data_fills_is_refused (input_data) and
test_a_read_the_target_selector_s_provider_fills_is_refused (the
target's kwargs). A provider whose return names no keys may fill
any name and so names none, as for server_owned_keys.
5. A withheld name no call could then do without. Withheld, the
parameter is absent, so it is refused if the shape check demands it -
required and declaring no default, read as dispatch relaxes a
partial spec, whose Validator parameters it never demands - or, for
a read, if the callable that receives it declares it with no default of
its own: the selector of a selector spec or of a service spec's target,
and the service for a service spec's reads. Dispatch applies no
declared default, so the callable's is the only one that answers, and
a call without one is refused as missing, a client error no caller can
fix. A Validator parameter is the shape check's alone. Each conjunct
is held by its own test, named beside the guard. A parameter an
untyped provider's values reach is not refused here: that
provider may fill it on any call, so a call may do without the
caller's value, and dispatch refuses one nobody filled where the
provider's answer is merged
(test_check_server_arguments_lets_a_read_an_untyped_provider_reaches_be_withheld,
test_check_server_arguments_lets_a_field_an_untyped_input_data_reaches_be_withheld).
Less a read a provider requires itself, by name with no default: no
provider is handed another's answer, so only the caller can send it,
and withholding it is refused
(test_check_server_arguments_refuses_withholding_a_read_a_provider_requires).
A typed provider's keys, filled or declinable, were refused by rule 4.
6. A bound value its parameter refuses, checked as the shape check
checks it, so a server value in its Python form - a uuid.UUID, a
date, a Decimal - for a parameter that takes the wire's string
fails here rather than on every call. Held by
test_a_bound_value_its_parameter_refuses_fails_at_construction.
Describe-time: wherever it is called - where a transport is built,
or where one checks a binding again against the seeds a single call
adds - it reads the spec as it declares itself to no call, handing a
Validator that declares call_context None
(test_describe_time_readers_hand_none). So a name such a Validator
declares only to a call is refused here by rule 1
(test_a_name_a_validator_declares_only_to_a_call_is_undeclared): declare
the field to no call too, and each call's
apply_server_arguments,
handed that call's dict, checks the value against what the call declares.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
the first check that finds anything. |
apply_server_arguments ¶
apply_server_arguments(
spec: ServiceSpec | SelectorSpec | SpecSource,
arguments: Mapping[str, Any],
server: ServerArguments,
*,
call_context: dict[str, Any] | None = None,
) -> dict[str, Any]
arguments as dispatch should receive them under server: a new dict, the input
untouched.
For a transport to call on every call, before
dispatch or
adispatch, which
take the result as their arguments; both run the same prelude over
it, so one applied mapping answers the same through either. Dispatch
takes no binding of its own: this is the whole of the rule, and a
transport path that does not call it is unbound.
- The caller's value for every bound or withheld name is dropped,
before anything reads it. A value the caller sends for a name it was
never offered -
"null"for an integer it could not see - therefore never reaches the shape check and cannot refuse the call. Held by test_a_malformed_value_for_a_withheld_name_never_reaches_the_shape_check. - The bound values are laid over what is left, so a bound name holds the server's value whatever the caller sent, and a withheld one is absent. Held by test_a_bound_value_outranks_the_caller_s, which fails if the two steps swap.
Every other key is left as sent, for the shape check to read under the
transport's unknown_arguments, so a name nobody declared is still
refused under REJECT.
The bound values are checked against their own parameters, as
check_server_arguments checked them when the transport was built, and
handed on as the shape check reads them: a uuid in its canonical
spelling, an integral float declared an integer as the int. One that fails is the server's
mistake,
raised as ImproperlyConfigured with the refusal as its cause, never
as InvalidArguments: a client refusal would ask the caller to fix a
value it neither sent nor can see. This is where the rule parts from
django-spec-html's
route_arguments,
whose bad value is a client's 400, because a client chose the URL and
nobody but the server chose a bound value. A bound name the spec does not
declare, which
check_server_arguments
refuses when the transport is built, is refused here the same way.
Every refusal names the spec's kind and its callable, so a transport binding many tools can say which one is misconfigured.
call_context is the call's dict, the one the transport hands
dispatch: the bound values are checked against what the spec declares
to that call, so a Validator declaring a bound key only to a call binds it
(test_handed_the_call_s_context_the_key_is_bound), and a value its
declaration to no call takes is refused where the call's does not
(test_a_bound_value_is_checked_against_the_call_s_own_declaration). Left None, they are
checked against the declaration the spec makes to no call, as
check_server_arguments reads it.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
a bound value that fails its declaration, or a bound name the spec does not declare. |
REFUSALS
module-attribute
¶
REFUSALS: tuple[type[DispatchError] | type[ServiceError], ...] = (
DispatchError,
InvalidArguments,
NotPermitted,
PermissionCheckDenied,
PrincipalUnavailable,
ServiceError,
ServiceNotFound,
ServiceConflict,
ActionUnavailable,
AdditionalInputRequired,
ServiceValidationError,
)
Every refusal the kernel defines, family by family, each base before what is under it.
Two families: a DispatchError
refuses the call before the operation runs, and a
ServiceError is the
operation's own refusal. Both bases are listed, because either may be raised
bare, and so is ServiceConflict, the base of ActionUnavailable.
A refusal a transport defines - django-spec-html's UnsupportedMediaType is
one - is not here: that transport maps it and tests it. Read by
unanswered_refusals;
a test walking the class tree holds it equal to the package's own refusals,
so one a later release adds fails there until it is listed.
unanswered_refusals ¶
unanswered_refusals(
answers: Callable[[DispatchError | ServiceError], object]
| Sequence[tuple[type[BaseException], object]],
*,
unanswered: object = None,
) -> tuple[RefusalFinding, ...]
What a transport's map from the kernel's refusals to its outcomes leaves unanswered.
A RefusalFinding
per finding, and none for a map that answers every one of
REFUSALS, so a transport
holds its map from its own test suite with
assert unanswered_refusals(...) == (); pytest's failure shows the
first finding, and -v lists them all. A transport that leaves a gap on purpose
filters the findings by refusal or kind, never by their words,
which str() gives and which are free to change. Each transport keeps
its own vocabulary - an exit code, a status, a run state - and this checks
only that the vocabulary is total.
answers is the map in one of two shapes:
- An ordered table of
(refusal class, outcome)rows, read top to bottom byisinstancewith the first match winning, which is how the kernel's own maps are written. A refusal is answered with the outcome of the first row whose class it is an instance of, so a row for a base answers every refusal under it, and a catch-all row ofExceptionanswers them all. A row whose outcome isunansweredis no answer: a refusal it catches first stays unanswered whatever a later row says, as for the callable below. Pass the table itself. - A callable, given one instance of each refusal and answering with its
outcome, for a map written as branches. A refusal is unanswered when the
callable returns
unanswered(compared with==, so a falsy outcome such as0is still an answer). Whatever it raises propagates: a map that cannot answer a refusal without raising is broken in a way this should not hide. A mapping looked up by the error's exact class passeslambda error: table.get(type(error)), since reading it as ordered rows would let a base's key answer for a subclass the lookup never reaches.
Three kinds of finding, each a
RefusalFindingKind,
shown here as str() words them:
UNANSWERED,nothing in the map answers NotPermitted: a refusal no row, or no call, answers.BARE_BASE,nothing in the map answers DispatchError itself, though it answers every refusal under it, and DispatchError may be raised bare: the map looks complete and is not. Either family base may be raised bare: the kernel raises neither itself, but a project's own code may, andServiceConflictis a base too.SHADOWED_ROW,the row for ServiceConflict never answers: the row for ServiceError above it answers every ServiceConflict first: the precedence trap of an ordered table, a subclass's row below its base's. Itsrefusalis the dead row's class and itsshadowed_bythe earlier row's. Reported for every row, a transport's own refusal's included, since a row nothing reaches is dead whoever's refusal it names.
The precedence trap is reported for a table only. A callable written as branches orders them in code, and a branch for a subclass below its base's is a body that never runs, which the transport's own branch coverage reports; a table's order is data, which coverage reads as one expression.
relax_partial ¶
parameters as a call of spec is checked under partial: every Validator parameter
optional.
The one reading of what a partial call may leave out, for the shape check
and for spec_input_schema's required, so the schema never asks for
a field dispatch would not refuse absent, nor leaves one out that it
would. Made optional at every depth - an object's fields and an array's
rows included - as djangorestframework-services relaxes only its
serializer. The spec's reads and its target selector's keep their
required: a partial update still names the row it updates
(test_a_partial_call_omitting_the_target_s_pk_is_refused_at_the_shape_check).
So do its shapes, which say what is presented rather than what is
written, as on a many spec, where only the list's rows are walked.
On a many spec the Validator's parameters are each row's, so the list
stays required and only its rows are walked, since a read may share a
row field's name
(test_a_partial_many_spec_requires_the_list_and_its_reads_and_nothing_in_a_row).
parameters as they are for a selector spec, which has no partial,
and for a service spec that is not partial. One branch to coverage, so
each condition is held by its own test:
test_a_selector_specs_schema_is_its_reads (the type: without it, a
selector spec's missing attribute raises) and
test_a_spec_that_is_not_partial_requires_every_required_parameter (the
flag). The Validator's are told apart by what they are not, the spec's
reads and its target's, so the Validator is not asked for its parameters
again; a read and a Validator parameter of one name are refused when
parameters() is assembled. Of the names kept, the spec's reads are
held by test_a_partial_spec_with_no_target_keeps_its_reads_required, the
shapes by test_a_partial_spec_keeps_a_required_shape_required, and the
target's by
test_a_partial_spec_requires_none_of_its_validators_parameters_at_any_depth.
A copy, so the declaration every other reader sees - parameters()
itself, which still says what a whole call needs - is untouched.
Public so that a transport building an input surface of its own - a command's options, a form - asks a partial call for what dispatch asks, rather than restating the rule and drifting from it.
Affordances¶
enforce_affordances ¶
enforce_affordances(
spec: ServiceSpec | SpecSource,
pool: dict[str, Any],
*,
instance: Any,
reserved: frozenset[str],
call_context: dict[str, Any] | None = None,
) -> None
Refuse the call if one of the spec's affordances is not met.
dispatch and
adispatch call this
themselves for a service spec, with the pool the service is about to
receive and the pool seeds' reserved set. A transport that runs a
service without them - a chain that owns the transaction and hands each
step its own pool, say - must call it too, exactly as it calls
authorize, or a
condition the direct path refuses is skipped on that one. Neither entry
point calls it for a selector spec, whose affordances are answers about
each row rather than a refusal of the read.
pool is the keyword pool the service is about to receive and
instance its resolved target, None for an operation with none. It
raises
ActionUnavailable
carrying the unmet affordance's reason and code.
Callers must invoke this after object-level authorization and validation, and before the service: class-level authorization -> target resolution -> object-level authorization -> validation -> affordances -> service. After access because a refusal describes the row's state, and telling a caller who may not see the row what state it is in is a disclosure. Dispatch calls it before an atomic service's transaction opens, so a refusal never opens one.
Declaration order decides which refusal a caller sees, and nothing past the
first unmet condition runs. Every condition on the row is answered together
by one query the first time one is reached. A callable condition sees the
seeds of pool - never the call's target, input or client arguments - so
a **kwargs catch-all is held to the same rule the declaration enforces on
a named parameter. reserved is this call's seed set, registered seeds
included: seeds.reserved for the
PoolSeeds the pool was
built with, the mount's pool_seeds.reserved. It is required, with no
default, because a default would ask a condition with none of the registered
seeds, and one reading a registered seed (a tenant, a frozen flag) would fail
on a transport running a service without dispatch though dispatch serves it.
A callable's result is read for truth, so one that returns
nothing refuses rather than allows.
spec may be a declaration with as_kernel_spec(), read as the
service spec it compiles to.
call_context is the call's context, handed to a callable condition
that names it and never to one taking **kwargs for the rest: the dict
passed, else the one pool carries, else a fresh one the conditions of
this call share. A call_context passed beside a different one in
pool raises ImproperlyConfigured (with_call_context).
Raises:
| Type | Description |
|---|---|
ActionUnavailable
|
An affordance is not met. |
ServiceNotFound
|
A condition on the row was reached and the row is gone: resolved a moment ago, and there is now nothing to do it to. |
ImproperlyConfigured
|
A condition on the row was reached and
|
TypeError
|
|
unmet_operation_affordance ¶
unmet_operation_affordance(
spec: ServiceSpec | SelectorSpec | SpecSource,
pool: dict[str, Any],
*,
reserved: frozenset[str],
call_context: dict[str, Any] | None = None,
) -> Affordance | None
The first of the spec's operation-scope affordances not met now, or None.
For a transport deciding whether to offer an operation at all, before anyone
attempts it: an MCP server building its tool list, an agent assembling the
toolset for its next step. An operation whose answer is an
Affordance cannot be
called right now whatever it is called with, so offering it only invites a
refusal.
Only the callable conditions are asked - the ones answered without a row. A
condition on the row is skipped without being evaluated, because at list
time there is no row: it runs no query and needs no instance, and it goes on
being answered per object where it always is, at the call. The callables are
asked in declaration order and the first unmet one is returned, which is the
one a call would be refused with when no row condition before it answers
first. A callable's result is read for truth, so one that returns nothing is
unmet here as it is refused at the call. An exception it raises propagates:
this answers the question, and a condition that cannot be answered is not a
no.
Build pool the way the call's would be. A condition sees the seeds of
it, never a client argument, through the same definition the call is
refused by, so the two see the same names only if they are handed the same
seeds:
base_pool with the same
seeds=, and reserved=seeds.reserved here. reserved is the names a
condition may be handed from the pool: the mount's pool_seeds.reserved,
the kernel's reserved names plus the seeds it registers. It is required, with
no default, because a default would ask a condition with none of the
registered seeds, and one reading a registered seed would fail at describe
time though dispatch serves it.
The answer is advisory. Enforcement at the call
(enforce_affordances)
remains the authority, so a list built a moment before a condition flips is
answered, when the stale entry is called, by an
ActionUnavailable
carrying the code this would return if asked again then (or a row
condition's, where one declared earlier refuses first). A condition driven by
a clock has no event: it is answered when asked, and nothing announces the
moment it flips. A transport that can push list changes to its client needs
something else to tell it when to ask again.
A SelectorSpec is accepted and answers None: its affordances maps
names to other operations, to be answered for its rows, and is never a
condition on the selector itself - so a transport passes whatever spec it
holds rather than branching on its type and risking reading that mapping as
the selector's own.
call_context is the call's context, handed to a callable condition
that names it and never to one taking **kwargs for the rest: the dict
passed, else the one pool carries, else a fresh one the conditions of
this call share. A call_context passed beside a different one in
pool raises ImproperlyConfigured (with_call_context).
A lazy reason is answered as text in the language active at the call,
on a copy of the declared affordance; one declared as text is returned as
declared.
operation_affordances ¶
The operation-scope affordances spec declares, in declaration order.
The callable ones: the conditions answered without a row. A condition on the
row is left out, and so is anything on a SelectorSpec, which answers
(): its affordances maps names to other operations, to be answered
for its rows, and reading that mapping as the selector's own conditions
would answer a question about some other operation. A spec declaring none
answers () too.
A transport uses this to decide cheaply whether there is anything to ask at
list time before it builds a pool: most operations declare nothing, and an
empty answer means
unmet_operation_affordance
would return None without running anything. That function selects its
conditions here, so a transport's shortcut and the answer it skips cannot
disagree about which conditions there are.
aenforce_affordances
async
¶
aenforce_affordances(
spec: ServiceSpec | SpecSource,
pool: dict[str, Any],
*,
instance: Any,
reserved: frozenset[str],
call_context: dict[str, Any] | None = None,
) -> None
Same as
enforce_affordances,
for an async caller.
For a transport that runs a service without
adispatch, which
answers a spec's affordances inside its own hop. It refuses and lets through
exactly as the sync function does, with the same arguments, and
reserved= is required here as there: pass the mount's
pool_seeds.reserved.
A condition on the row is a query and a callable condition is user code
that may query, and neither can run on the event loop. So every condition
is answered in one sync_to_async(thread_sensitive=True) hop, as
dispatch's async path runs every sync concept: not one hop per condition.
A spec declaring none returns before the hop, so declaring nothing costs
the async path nothing. spec may be a
SpecSource, read as
the spec it compiles to, and a SelectorSpec is refused with the sync
function's TypeError whatever it declares.
Raises:
| Type | Description |
|---|---|
ActionUnavailable
|
An affordance is not met. |
TypeError
|
|
ServiceNotFound
|
A condition on the row was reached and the row is gone. |
ImproperlyConfigured
|
A condition on the row was reached and
|
aunmet_operation_affordance
async
¶
aunmet_operation_affordance(
spec: ServiceSpec | SelectorSpec | SpecSource,
pool: dict[str, Any],
*,
reserved: frozenset[str],
call_context: dict[str, Any] | None = None,
) -> Affordance | None
Same as
unmet_operation_affordance,
for an async caller.
For a transport building its list of operations on an event loop: an MCP
server answering a tool list, an agent assembling its next step's tools.
It gives the sync function's answer for the same arguments, and reserved=
is required here as there: pass the mount's pool_seeds.reserved.
A callable condition is user code and may query, so the conditions are
answered in one sync_to_async(thread_sensitive=True) hop, as
dispatch's async path runs every sync concept. A spec with nothing to ask
at list time - nothing in
operation_affordances,
which is every SelectorSpec and every spec declaring only conditions on
the row - returns None before the hop: a transport asks this for every
operation it lists, and most declare nothing. spec may be a
SpecSource, read as
the spec it compiles to.
A caller that must release a connection a condition opens - a long-lived
agent run, a worker with its own event loop - makes its own hop instead,
calls unmet_operation_affordance inside it, and releases the connection
in that same hop.
row_affordance_answers ¶
row_affordance_answers(
spec: ServiceSpec | SelectorSpec | SpecSource, row: Any
) -> dict[str, dict[str, Any]]
Each declared name's answer for row: the object present puts on it.
dispatch answers a selector's affordances for every row it returns, as
affordance__<name>__<code> values on the row. A page that holds those
rows rather than presented dicts - a queryset's instances, a table's records -
reads them here, whichever kind of spec it holds: a SelectorSpec, a
ServiceSpec (read through its output selector, whose affordances
are the ones presented), or a
SpecSource.
The result maps each name to {"available": bool}, plus code and
reason when it is False. Each name reports the first condition the
row does not meet, in declaration order, as the call would refuse. A
None answer is a condition on the row asked of a row that no longer
exists: {"available": False} with no code and no reason, and the walk
stops there. It is the same reading present and with_affordances
make of a row, because they call the same function.
A row that wraps its model instance is read through the presenting
selector's row_object, as dispatch answered it; a row whose
row_object is None answers {"available": False} for every name
with a condition, there being no object to have met it.
A spec that presents no affordances answers {}, as present leaves
the affordances key out of what it presents. A caller asking about a name
the answer does not hold must treat it as not declared; the answer cannot
tell a name the spec never declared from a spec that declares none.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
|
AFFORDANCES_KEY
module-attribute
¶
The key each presented object carries its affordance answers under.
row_links ¶
row_links(
spec: ServiceSpec | SelectorSpec | SpecSource,
item: Any,
*,
registry: SpecRegistry | None = None,
) -> dict[str, dict[str, Any]]
Each presented affordance of item, as a link: whether, what and how to call it.
The answer for each name is
row_affordance_answers's
(available, and code and reason when it is not), plus spec,
the operation the link leads to, and arguments, each read bound by
link_bindings
with the item's value for its field; an optional read's field the item
does not carry is left out. required names the reads the row must fill, each
in arguments: a transport reverses a URL with those alone, since an
optional read is the caller's input. With a registry, name is the
target's name there, and absent when it holds none, so a transport that
cannot name a target still has the answer.
item is what present returned, before any audience projection,
whose answers are read off its affordances key; or a row as dispatch
handed it over, answered as row_affordance_answers answers it and its
fields read by attribute or key. A spec that presents no affordances
answers {}.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
as |
ValueError
|
|
link_bindings ¶
Each presented affordance's {read: output field}: which row field fills which read.
Read off the selector spec presents through, as
row_affordance_answers
reads it, against what spec outputs. A read binds to the field its
SpecLink names, else to
the visible output field of its name, else, when one required read is
left and one field is marked HANDLE, to that field. A spec with no
output binds only what its links name. A required read is one the shape
check demands of a caller
(provider_reached).
Answered once per spec and kept, refusal and all, since an output never
changes; so a link no check_links saw is refused at its first use,
with the same message. An exception output() raises is not kept, so a
presenter that answers once the apps are loaded binds then.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
a link leaves a required read unbound, matches
more than one |
check_links ¶
check_links(
registry: SpecRegistry,
app_configs: Sequence[AppConfig] | None = None,
**kwargs: Any,
) -> list[CheckMessage]
The registry checked against itself: an error for each link it cannot bind or name.
Each entry's presented affordances are bound by
link_bindings,
which reads the rows' output, and so may need the apps loaded: hence a
check run when the project chooses, never when a spec is built. Each
target the registry holds is named through name_of; one it does not
hold is no error, since a link to it keeps its answer. The kernel
registers nothing: a project checks the registry its transports read,
such as the one its per-app registries merge into, and makes it a Django
system check in one line,
checks.register(functools.partial(check_links, registry)).
app_configs and kwargs are the system check's, and unread.
Authorization¶
PermissionCheck ¶
Bases: ABC
Whether a principal may run a spec, and whether they may act on a row.
A principal and a spec, and nothing else: no request and no view, because most transports have neither. Instances rather than classes, so a check can carry its own configuration (a codename, a group) and a spec reads as the list of checks it applies.
has_permission is the class-level check, run before any row is resolved,
so a principal refused here learns nothing about which rows exist.
has_object_permission runs against the resolved target of a retrieve or
an update; it allows by default, because most checks are class-level only.
has_scope_permission is the same question for a call that resolves no
single row: it is asked of the set a bulk call acts on or a collection
reads, and of None where the call acts on no existing row (a create).
It is a separate method rather than has_object_permission handed a set
or None, because a check written for a row would read an attribute off
it and fail on neither; it allows by default for the same reason.
A method may ask for the call's arguments by declaring a keyword
arguments: dispatch then hands it the call's shape-checked arguments,
as a read-only mapping, at each of the three questions - a route's captured pk, a
filter the caller sent - and a method that does not declare it is asked
without them. The base methods do not declare it, so every check
written without it stays a valid override; a many call's rows are
not among them, as they are validated after every check. Opt-in is by
name, read layer by layer down the __wrapped__ chain
functools.wraps leaves: a layer spreading **kwargs passes the
keyword to the one beneath, so it is handed only where a layer names it
before any layer without **kwargs, and a forwarding decorator keeps a
check opted in. arguments is None where a transport calls
authorize() without them, and a check that needs them decides for
itself what that means; reading it as an allow fails open. Only the mapping
is read-only: its values are the call's own objects, the ones the run
receives, so a check must not mutate them.
A method may ask for the call's context and for a registered seed the
same way: a keyword call_context is handed the one dict every stage
of the call shares, a fresh one where the transport passed none, and a
keyword named after a seed in the call's PoolSeeds is handed that
seed's value. Only the seeds a spec's checks name are resolved before the
class-level check, and the run reuses those values, so each resolves once
per call and the check and the service see one object; a seed raising
PrincipalUnavailable there ends the call as a refusal does. A
parameter the call fills by position - the principal, the spec, the
target or scope, whatever a method calls them - is never read as an
opt-in, so a DRF-style has_permission(self, request, spec) under a
transport registering a request seed is asked as before. A seed named
arguments is never handed this way: arguments is always the
call's arguments.
message is what
NotPermitted
says when this check refuses; None keeps the generic wording.
Sync-only, like every concept: a check may query, so the async path runs
it in the executor. An async def method would answer with a coroutine,
which is truthy and would allow every call, so a spec refuses a check
declaring one when it is built, with ImproperlyConfigured naming the
method; and an answer that is still to be awaited - from a plain def
wrapping an async def - is refused where it is read, failing closed.
spec is typed Any in each method, and is always the ServiceSpec
or SelectorSpec being run. The spec modules import this one to declare
their permissions field, so naming either class here would make the
package that declares specs and the one that judges them import each
other. A subclass may annotate it ServiceSpec | SelectorSpec.
has_permission
abstractmethod
¶
Whether principal may run spec at all.
spec is the ServiceSpec or SelectorSpec being run.
has_object_permission ¶
Whether principal may act on target. Allows unless overridden.
spec is the ServiceSpec or SelectorSpec being run.
has_scope_permission ¶
Whether principal may act on scope. Allows unless overridden.
spec is the ServiceSpec or SelectorSpec being run.
scope is the resolved set of a bulk or collection call, or None
for a call that acts on no existing row.
check_permissions ¶
check_permissions(
permissions: Sequence[PermissionCheck] | None, *, label: str
) -> tuple[PermissionCheck, ...] | None
Normalize permissions to a tuple, refusing anything that is not a check instance, and
an empty one.
Called by ServiceSpec and SelectorSpec on their permissions=,
and by a transport that accepts PermissionChecks on something other
than a spec - a prompt, a view - so that it normalizes and refuses them by
the rules a spec's permissions= gets, rather than by a copy of its
own. None comes back as None, for the caller to refuse or allow as
its own default says. A refusal is ImproperlyConfigured, and label
names the declaration it is raised for, as Class.permissions.
An empty sequence is refused, as None is refused at dispatch and
at registration: every check passing is vacuously true of no checks, so
permissions=[] would let anyone run the operation, and an empty list
is as often computed by accident as decided. Unrestricted() is the
decision, by name (test_an_empty_permissions_sequence_is_refused).
Each check is held to refuse_unusable_check: an instance of
PermissionCheck, never its class, with three sync methods. A
combinator is one such check, whose methods are sync, so its children are
not walked here: it held them to the same rule when it was built.
Unrestricted ¶
Bases: PermissionCheck
Anyone may run this spec: permissions=[Unrestricted()].
A spec that declares no permissions is refused at registration and at dispatch, because off HTTP there is no view whose policy it could inherit, and running it anyway is how an off-HTTP runner skips authorization with nothing warning. An operation that is genuinely open says so with this.
A named class rather than an empty list, so every open operation in a project is one search away, and an empty list computed by accident is not read as a decision: a spec handed one is refused when it is built.
AllOf ¶
Bases: _Combinator
Passes when every check passes: AllOf(IsStaff(), InTenant(), message=...).
What a spec's permissions= list already means, as one check, so it can
stand inside AnyOf or NoneOf. Each of the three questions asks
every check the same question, in order, and stops at the first that
fails (test_all_of_does_not_ask_past_the_first_refusal). message is
what NotPermitted says when it refuses; None keeps the generic
wording.
AnyOf ¶
Bases: _Combinator
Passes when one of its checks passes: AnyOf(IsOwner(), IsStaff(), message=...).
has_permission asks each check in order and stops at the first that
passes (test_any_of_does_not_ask_past_the_first_pass).
At the row and scope questions a check counts only where it passes the class-level question too, asked again, and then that question: an owner rule that allows any row by default must not let through a principal it refused at class level because another check admitted them there. Two questions asked of each check in turn, the first failing skipping the second, and each has a test that fails without it: dropping the class-level one fails test_any_of_row_question_skips_a_child_refused_at_class_level and test_any_of_scope_question_skips_a_child_refused_at_class_level, and dropping the row or scope one fails the same two tests, whose other check passes at class level and refuses the row or the scope. The class-level question is asked again rather than remembered from the class-level call, so the answer holds under a grant that covered that call and asked nothing (test_any_of_under_a_covering_grant_still_judges_the_row), and nothing is written to the call's context (test_any_of_writes_nothing_to_the_call_s_context). A check that opts into a seed or the arguments at the class-level question is handed them at the row and scope questions too, since it is asked there.
message is what NotPermitted says when it refuses; None keeps
the generic wording.
NoneOf ¶
Bases: _Combinator
Passes when none of its checks passes has_permission: NoneOf(IsSuspended(),
message=...).
It inverts the class-level question alone, asking each check in order
and refusing at the first that passes; its row and scope questions allow,
as a PermissionCheck's do by default. So a check judging rows or a
scope has no place inside it - the opposite of "may act on this row" is
no rule a call can be refused by - and one whose has_object_permission
or has_scope_permission is its own, at any depth, is refused when
this is built (test_none_of_refuses_a_row_level_child).
message is what NotPermitted says when it refuses; None keeps
the generic wording.
Grant
dataclass
¶
Proof that the class-level check already ran, for one spec and one principal.
Dispatch enforces permissions by default. A transport that authorized through its own machinery first - an HTTP view running its framework's permission classes - passes a grant instead, rather than skipping the check by omission, and pays one class-level evaluation per call instead of two.
Bound to one spec and one principal, by identity: a grant carried to another operation or another user covers nothing, and dispatch refuses it.
target_checked says the target-level checks ran too -
has_object_permission on a row, has_scope_permission on a set or
on nothing - which a transport can only claim once it has resolved the
target itself. It covers the target handed to dispatch as
target=, and nothing else: dispatch skips the checks only on that
target. When dispatch looks the target up itself, from the arguments, it
runs them whatever the grant says, since the row it finds may not be the
one the grant was minted for. resolve_target mints such a grant for
the target it returns, to be handed on with it. A selector spec takes no
target=, so on one the flag covers nothing: its selector finds the
row or the list from the arguments, and the checks run on what it
found.
Without it, dispatch runs those checks on what it resolves.
Not serializable. Pickling one raises TypeError, so a grant cannot
ride a queue into a worker: a task runs minutes later against state that
may have moved, and it re-authorizes by construction.
covers ¶
Whether this grant is for exactly this spec and this principal.
The spec is compared as compiled: a grant minted for a
SpecSource
covers that object and the spec it compiles to, and a grant minted for
the compiled spec covers the object, since each compiles once. Any
other object is covered exactly when it compiles to that very spec:
objects are compiled each on its own, so where a library compiles
each declaration afresh, as djangorestframework-services does, a grant
covers one declaration and not another that compares equal to it.
CallSeeds
dataclass
¶
The values of the registered seeds a check names, as one call's prelude resolved them.
check_call and
resolve_target
hand one back on .seeds, beside their grant, for dispatch(seeds=)
and adispatch(seeds=).
resolve_seeds
makes one ahead of authorize, for a transport that admits a call before
it resolves the row: authorize, authorize_scope,
authorize_target and resolve_target take it as seeds= too.
Each then takes these values as they are,
resolving none of those seeds again, so the checks the prelude asked and
the run that follows - the object-level check, the selectors, the service
and the presenter - see one value of each. Without it, each seed a check
names is resolved once by the prelude and once more by dispatch.
values holds only the seeds a check of the spec names, at any of its
three questions; every other seed resolves in each pool as it always does.
It is a read-only copy, taken when the carrier is built, so nothing the
prelude's dict meets afterwards reaches it.
Bound to one call, by identity: the spec (compared as compiled, as a
Grant compares it), the
principal, the call_context dict and the pool_seeds registry.
Where a grant can be reused across calls, a carrier is for the call whose
context it was minted with, and its names are that registry's. Dispatch
refuses one that does not cover its call as NotPermitted, and so does
every function that takes one, through
values_for.
Not serializable, as a grant is not: pickling one raises TypeError.
covers ¶
covers(
spec: ServiceSpec | SelectorSpec | SpecSource,
principal: Any,
call_context: dict[str, Any] | None,
pool_seeds: PoolSeeds,
) -> bool
Whether these values are this call's: its spec, its principal, its context and registry.
Each by identity, the spec as compiled, as
Grant.covers
compares it: a carrier minted for a SpecSource covers that object
and the spec it compiles to. A carrier is always bound to a dict, so a
call handed no call_context (None) is covered by none.
values_for ¶
values_for(
spec: ServiceSpec | SelectorSpec | SpecSource,
principal: Any,
call_context: dict[str, Any] | None,
pool_seeds: PoolSeeds,
) -> Mapping[str, Any]
These values, for a call they
cover; NotPermitted
otherwise.
The one place a carrier for another spec, principal, call context or
registry is refused, for every function that takes one: dispatch
and adispatch, resolve_target, and the three authorize
functions. Values resolved for another call are never read as this
one's, and never quietly replaced by fresh ones either
(test_values_for_returns_the_values_of_a_covered_call_and_refuses_any_other).
Raises:
| Type | Description |
|---|---|
NotPermitted
|
the carrier does not cover this call. |
authorize ¶
authorize(
spec: ServiceSpec | SelectorSpec | SpecSource,
principal: Any,
*,
grant: Grant | None = None,
arguments: Mapping[str, Any] | None = None,
call_context: dict[str, Any] | None = None,
seeds: Mapping[str, Any] | CallSeeds | None = None,
pool_seeds: PoolSeeds | None = None,
) -> Grant
Run spec's class-level permission checks for principal.
Dispatch enforces this by default. A transport that already authorized
through its own machinery - an HTTP view running its framework's
permission classes - passes the Grant it produced instead of paying for
a second evaluation; the grant is honoured only if it
covers this exact
spec and principal, by identity, so a grant carried over from another
operation or another user is refused rather than trusted.
spec may be a
SpecSource: each
check is asked about the spec it compiles to, the object dispatch hands
it for the same declaration, and the grant returned covers both.
Without a grant, spec.permissions is None is a configuration error, not
the principal's fault: off HTTP there is no view whose policy an
undeclared spec could inherit, so an operation that means to be open says
so with permissions=[Unrestricted()].
Otherwise every check's has_permission must pass, in order; the first
refusal raises
PermissionCheckDenied,
a NotPermitted naming the check and the spec, with that check's own message, or the generic
one when it declares none.
An answer still to be awaited - a coroutine from a check that is not
sync - raises ImproperlyConfigured rather than being read as a pass.
arguments is handed to each check's method that declares a keyword
of that name, and to no other, so a check that declares none is asked
without it. Dispatch passes the call's
shape-checked arguments as a read-only mapping, whose values are the
call's own and must not be mutated; None when the caller has none to
hand.
call_context and seeds are offered the same way, by name: a
method declaring call_context is handed the call's context - the dict
the transport handed dispatch, a fresh one when it handed none or this is
called without one - and a method naming a registered seed is handed that
seed's value from seeds, which dispatch resolves for the call only
when one of the spec's checks names one. A parameter the call fills by
position is never read as an opt-in, whatever its name.
pool_seeds is for a transport that calls this itself and has the
registry rather than the values: the
PoolSeeds it would
hand dispatch. Only the registered seeds a check's has_permission names
are resolved, once, for principal as user, and offered as
seeds would be; a seed only another question names, or one no check
names, is never resolved, and nothing is when a covering grant answers
first. A resolver raising - PrincipalUnavailable for one - ends the
call before any check is asked, as in dispatch. Handing seeds too
raises TypeError, since one would silently outrank the other, even when
the call is answered before a check is asked.
A deactivated principal handed with pool_seeds raises
PrincipalUnavailable before any seed is resolved, as dispatch refuses
one before anything else - grant or no grant, so a covering grant does not
stand in for it. Without pool_seeds nothing is resolved, and the call
is asked exactly as before the keyword existed.
seeds may instead be a carrier: the
CallSeeds that
resolve_seeds
returns, or check_call's or resolve_target's .seeds. Its values
are offered as they are and nothing is resolved here, so every step of a
call admitted before its row is found sees one value of each seed. It is
taken only for the call it
covers:
this spec, principal, the very call_context dict it was bound to
(None is never that dict: pass seeds.call_context) and its
registry, which is pool_seeds when handed and DEFAULT_POOL_SEEDS
otherwise; beside a carrier, pool_seeds is only the registry it is
matched against. One that does not cover the call raises NotPermitted,
and a deactivated principal PrincipalUnavailable, first of all,
before a covering grant can answer and before any check is asked.
Returns:
| Type | Description |
|---|---|
Grant
|
The grant that was honoured, or a freshly minted one covering this |
Grant
|
spec and principal. |
authorize_scope ¶
authorize_scope(
spec: ServiceSpec | SelectorSpec | SpecSource,
principal: Any,
scope: Any,
*,
grant: Grant,
arguments: Mapping[str, Any] | None = None,
call_context: dict[str, Any] | None = None,
seeds: Mapping[str, Any] | CallSeeds | None = None,
pool_seeds: PoolSeeds | None = None,
) -> None
Run spec's scope-level permission checks against scope.
The counterpart of
authorize_target
for a call that resolves no single row: scope is the resolved set of a
bulk or collection call, or None for a create. Every check's
has_scope_permission must pass, in order, and the first refusal raises
PermissionCheckDenied,
a NotPermitted naming the check and the spec, with that check's own message. An answer still
to be awaited raises
ImproperlyConfigured rather than being read as a pass. A
SpecSource is
checked as the spec it compiles to.
grant.target_checked skips the checks here as it does there: a
transport that already ran the target-level checks has claimed them.
Dispatch honours it, as there, only for a service spec's target handed
in as target=, so never on the list a selector spec reads.
arguments is handed to each check's method that declares a keyword
of that name, and to no other, so a check that declares none is asked
without it. Dispatch passes the call's
shape-checked arguments as a read-only mapping, whose values are the
call's own and must not be mutated; None when the caller has none to
hand.
call_context and seeds are offered the same way, by name: a
method declaring call_context is handed the call's context - the dict
the transport handed dispatch, a fresh one when it handed none or this is
called without one - and a method naming a registered seed is handed that
seed's value from seeds, which dispatch resolves for the call only
when one of the spec's checks names one. A parameter the call fills by
position is never read as an opt-in, whatever its name.
pool_seeds is for a transport that calls this itself and has the
registry rather than the values: the
PoolSeeds it would
hand dispatch. Only the registered seeds a check's has_scope_permission names
are resolved, once, for principal as user, and offered as
seeds would be; a seed only another question names, or one no check
names, is never resolved, and nothing is when grant.target_checked answers
first. A resolver raising - PrincipalUnavailable for one - ends the
call before any check is asked, as in dispatch. Handing seeds too
raises TypeError, since one would silently outrank the other, even when
the call is answered before a check is asked.
A deactivated principal handed with pool_seeds raises
PrincipalUnavailable before any seed is resolved, as dispatch refuses
one before anything else - grant or no grant, so a grant that checked the target
does not stand in for it. Without pool_seeds nothing is resolved, and the call
is asked exactly as before the keyword existed.
seeds may instead be a carrier: the
CallSeeds that
resolve_seeds
returns, or check_call's or resolve_target's .seeds. Its values
are offered as they are and nothing is resolved here, so every step of a
call admitted before its row is found sees one value of each seed. It is
taken only for the call it
covers:
this spec, principal, the very call_context dict it was bound to
(None is never that dict: pass seeds.call_context) and its
registry, which is pool_seeds when handed and DEFAULT_POOL_SEEDS
otherwise; beside a carrier, pool_seeds is only the registry it is
matched against. One that does not cover the call raises NotPermitted,
and a deactivated principal PrincipalUnavailable, first of all,
before grant.target_checked can answer and before any check is asked.
checks_read_arguments ¶
Whether one of spec's permission checks declares arguments on a question asked before
any row is resolved.
A transport that lists the operations a principal may run has no
arguments to hand a check, and one that declares arguments is written
to be given them. This answers, without calling any check, whether one
does, so the transport can decide first: list the operation, hide it, or
leave it to the call. It answers what a check declares, not what it
does with None: a check declaring arguments=None reads True
though it answers when handed nothing
(test_a_check_declaring_arguments_with_a_default_still_declares_them).
The questions are the two
authorize and a
create's
authorize_scope
of nothing ask before the call's arguments name anything: every check's
has_permission, and, for a ServiceSpec with no target selector,
its has_scope_permission too. A service spec with a target selector
asks the scope question of the row or set that selector resolves, and a
check's has_object_permission is asked of a resolved row; neither
exists without the arguments, so neither is read here. The declaration is
read as authorize hands it: a check declares arguments by name,
through the same reading (declared_keywords) that decides whether it
is handed them, so the two cannot disagree.
spec may be a declaration with as_kernel_spec(), read as the spec
it compiles to. A spec declaring no permissions has no checks and answers
False; dispatch refuses it at the call.
Each part of the rule has a test that fails without it: the class-level
question (test_a_check_declaring_arguments_on_the_class_question_reads_them),
a create's scope question
(test_a_check_declaring_arguments_only_on_the_scope_question_reads_them_in_a_create),
and the scope question left out beside a target selector or on a selector
spec, the predicate asks_scope_of_nothing that
authorize_without_arguments
reads too, one arc to coverage with two conjuncts
(test_the_scope_question_is_not_asked_where_a_target_or_a_selector_stands
holds the target selector's; the selector spec's, which has no
target_selector_spec, is held by every _listing case).
authorize_without_arguments ¶
authorize_without_arguments(
spec: ServiceSpec | SelectorSpec | SpecSource,
principal: Any,
*,
grant: Grant | None = None,
call_context: dict[str, Any] | None = None,
pool_seeds: PoolSeeds | None = None,
) -> Grant
Ask spec's permission checks for principal as a call with no arguments would.
For a transport that has to answer before it has a call's arguments, or
without them: a listing filtered by permission, an OPTIONS answer, a
completion, a call whose arguments failed their shape. Two questions, the
two dispatch asks before the arguments name a row or a set:
authorize, the
class-level one, and, for a ServiceSpec with no target selector (a
create),
authorize_scope
of None. Any other spec's scope question is of a row or a set only the
arguments name, and stays unasked. The rule is the one
checks_read_arguments
reads a spec's declarations by, so a check it says declares arguments
is a check this asks. Each question is handed arguments=None, the
kernel's word for a call with none to hand.
Nothing is caught. What either question raises reaches the caller as
it was raised: a refusal (NotPermitted, a check's own exception), a
configuration error (ImproperlyConfigured: a spec declaring no
permissions and no grant, a check left awaiting its answer), and a
check that cannot answer without the arguments it reads
(arguments["owner"] on None raises TypeError). Which of those
is a refusal, which hides an operation and which waits for the call is the
transport's policy, so the transport wraps this in its own try.
grant, call_context and pool_seeds are handed to both questions
as authorize takes them: a covering grant answers the class-level
question and a grant for another spec or principal is refused; both
questions are handed the one call_context dict, a fresh one where none
is handed, so what a check writes to it the next question reads; and each
question resolves from pool_seeds the seeds its own checks name. A deactivated
principal handed with pool_seeds raises PrincipalUnavailable before
any check is asked, as dispatch refuses one; without pool_seeds it is
asked exactly as authorize asks it. A grant's target_checked does
not answer the scope question here: it covers a target handed to dispatch
as target=, and a call with no arguments hands none, so dispatch would
ask it.
spec may be a
SpecSource, asked as
the spec it compiles to.
Returns:
| Type | Description |
|---|---|
Grant
|
The grant |
Grant
|
unchanged, or a fresh one for the spec and |
Grant
|
no target, so a |
authorize_target ¶
authorize_target(
spec: ServiceSpec | SelectorSpec | SpecSource,
principal: Any,
target: Any,
*,
grant: Grant,
arguments: Mapping[str, Any] | None = None,
call_context: dict[str, Any] | None = None,
seeds: Mapping[str, Any] | CallSeeds | None = None,
pool_seeds: PoolSeeds | None = None,
) -> None
Run spec's object-level permission checks against a resolved target.
Dispatch calls this on a retrieved row, never on a list: a collection has no single object to check against, and a member-level rule belongs to the presenter or the query that shaped it.
grant.target_checked lets a transport that resolved the row itself and
already ran the object-level check claim it once, so dispatch does not pay
for it twice; dispatch honours it only for a service spec's target
handed in as target=, and never on a selector spec's row (see
Grant); otherwise every check's has_object_permission must pass,
in order, and the first refusal raises
PermissionCheckDenied,
a NotPermitted naming the check and the spec, with that check's own message. An answer still
to be awaited raises
ImproperlyConfigured rather than being read as a pass. A
SpecSource is
checked as the spec it compiles to.
spec.permissions is None means nothing to check here rather than a
configuration error: authorize
already refused an undeclared spec before any target could be resolved, so
this function is never reached with one - iterating an empty tuple in its
place is simpler than asserting an invariant this module cannot enforce.
arguments is handed to each check's method that declares a keyword
of that name, and to no other, so a check that declares none is asked
without it. Dispatch passes the call's
shape-checked arguments as a read-only mapping, whose values are the
call's own and must not be mutated; None when the caller has none to
hand.
call_context and seeds are offered the same way, by name: a
method declaring call_context is handed the call's context - the dict
the transport handed dispatch, a fresh one when it handed none or this is
called without one - and a method naming a registered seed is handed that
seed's value from seeds, which dispatch resolves for the call only
when one of the spec's checks names one. A parameter the call fills by
position is never read as an opt-in, whatever its name.
pool_seeds is for a transport that calls this itself and has the
registry rather than the values: the
PoolSeeds it would
hand dispatch. Only the registered seeds a check's has_object_permission names
are resolved, once, for principal as user, and offered as
seeds would be; a seed only another question names, or one no check
names, is never resolved, and nothing is when grant.target_checked answers
first. A resolver raising - PrincipalUnavailable for one - ends the
call before any check is asked, as in dispatch. Handing seeds too
raises TypeError, since one would silently outrank the other, even when
the call is answered before a check is asked.
A deactivated principal handed with pool_seeds raises
PrincipalUnavailable before any seed is resolved, as dispatch refuses
one before anything else - grant or no grant, so a grant that checked the target
does not stand in for it. Without pool_seeds nothing is resolved, and the call
is asked exactly as before the keyword existed.
seeds may instead be a carrier: the
CallSeeds that
resolve_seeds
returns, or check_call's or resolve_target's .seeds. Its values
are offered as they are and nothing is resolved here, so every step of a
call admitted before its row is found sees one value of each seed. It is
taken only for the call it
covers:
this spec, principal, the very call_context dict it was bound to
(None is never that dict: pass seeds.call_context) and its
registry, which is pool_seeds when handed and DEFAULT_POOL_SEEDS
otherwise; beside a carrier, pool_seeds is only the registry it is
matched against. One that does not cover the call raises NotPermitted,
and a deactivated principal PrincipalUnavailable, first of all,
before grant.target_checked can answer and before any check is asked.
resolve_principal ¶
Look up the user who is to act, from an identifier a transport carries.
HTTP has a session or a token to resolve a principal from; most transports this kernel dispatches for do not, so a caller hands the primary key it already has (a queue payload, a management command argument, an agent's own notion of who is asking) and this is the one place that becomes a user row.
Every way an identifier can fail to name someone who may act becomes
PrincipalUnavailable,
terminal and never a fallback:
- no row with that primary key (
DoesNotExist), including a key past the range of an integer key's column, an infinite one among them, which no row can hold; - a malformed primary key (
ValueError,TypeError, or Django's ownValidationError- a non-UUID string against a UUID primary key raises that one instead ofValueError); - the row is deactivated, by the rule dispatch applies to a principal it
is handed (
is_activefalse, and a model with no such field reads as active). Soadispatch(principal_id=...)refuses here, with the identifier in the message, and dispatch's own check never disagrees.
Never AnonymousUser: an operation dispatched with no resolvable
principal has no principal, not an anonymous one.
is_deactivated ¶
True for an authenticated principal whose is_active is false.
ModelBackend never logs a deactivated account in, but
AllowAllUsersModelBackend and a project's own backend may, and a
transport that holds a user object of its own may hand one over long after
it was deactivated. The kernel's rule is that a deactivated principal never
acts, whichever way it arrived.
The kernel reads the rule where a principal first acts: dispatch, refusing
the principal it was handed, first and whether or not a Grant came with
it; resolve_principal, refusing the row an identifier named; and, ahead
of the first seed resolver, the authorize functions handed
pool_seeds and form_keywords, which refuse as dispatch does; and
bind_arguments handed pool_seeds, first, as dispatch. Those four
read it through refuse_deactivated in authorization/utils.py.
It is public
so that a transport in a distribution of its own refuses exactly the
principals dispatch refuses, by calling this rather than restating it, as
django-spec-html's entry points do with request.user before the
request is read.
It imports nothing that imports dispatch, so each reader can read it
without a cycle.
Both attributes are read with getattr rather than assumed, because a
principal is whatever a transport hands over:
- No
is_activereads as active, asModelBackendreads it: a custom user model is not required to declare the field. - Anonymous is not deactivated.
AnonymousUser.is_activeis false, so the rule asks about authenticated principals alone, and anonymous goes on to the permission check, which is what decides whether anonymous may act. A principal with nois_authenticatedis not anonymous, so it is read as authenticated and refused only when it says it is inactive.
Each condition is held by its own test in
tests/authorization/test_is_deactivated.py:
test_anonymous_is_not_deactivated fails without the first and
test_an_active_user_is_not_deactivated without the second.
sync_answer ¶
Return a permission check's answer, refusing one that is still to be awaited.
Read by the three authorize functions, so the class-level,
object-level and scope-level checks cannot disagree about an answer that
is not one, and by a transport that asks a check itself rather than
through them: it reads the answer through this, so a coroutine fails
closed there as it does in dispatch. A check is sync-only and its answer
is read for truth. An async def method returns a coroutine, which is
truthy, so read as it stands it would allow every call whatever the check
meant. The spec refuses an async def method when it is built, but a
method that hands back a coroutine from a plain def - a decorated
async def, a partial over one - looks sync until it answers, so the
answer is checked here, where it is read. It fails closed: the call is
refused with ImproperlyConfigured and never read as a pass. Any other
answer comes back as it is. asked names the method, as
Class.method.
A coroutine is closed first, so it is not left behind to warn that it was
never awaited. Two disjuncts, each held in
tests/authorization/test_sync_answer.py:
test_an_awaitable_that_is_not_a_coroutine_is_refused fails without the
first and test_an_async_generator_is_refused without the second, since
an async generator is not awaitable and is truthy too.
NotPermitted ¶
Bases: DispatchError
A permission check refused the principal, or a grant did not cover the call.
Named for what a failed has_permission means, literally. Not
PermissionDenied, which Django and DRF both own for their own
exceptions, and not a service error: a model that reads a denial as a
refusal to route around keeps trying, where a denial should end the attempt.
A declared check answering False raises
PermissionCheckDenied,
a subclass naming the check and the spec; every other refusal is this.
PermissionCheckDenied ¶
Bases: NotPermitted
A permission check the spec declares answered False.
Raised by authorize,
authorize_target
and authorize_scope
when one of the spec's checks answers False, and by nothing else. Every
other NotPermitted stays bare: a grant or a seeds carrier that does not
cover the call, a service's own refusal, and a check that raises
NotPermitted itself, which propagates as raised. So a transport can
answer a check's denial of an anonymous caller as an authentication
challenge, as DRF's permission_denied does, without turning any other
refusal into a sign-in prompt.
check is the check that answered: the combinator, for a check inside
AllOf,
AnyOf or
NoneOf, since that is
the rule the spec declares. The message is the check's message, or the
default wording when it has none.
spec is the spec the check was asked about, as a spec of this
package's: a declaration of another library's is named by what
kernel_spec compiles
it to. It is there because a denial inside a service's own dispatch
propagates out of the outer call as the same class, so the class alone
cannot say whose check refused: a transport treats a denial as its own
call's only where exc.spec is kernel_spec(spec) for the spec it
dispatched. Any, as PermissionCheck names it, because the spec
modules import this package.
PrincipalUnavailable ¶
Bases: DispatchError
The principal cannot act: an identifier naming nobody, or a deactivated account.
Raised by resolve_principal for an identifier that is missing,
malformed or names a deactivated row, and by dispatch for a deactivated
principal it was handed. Either way it comes
before any permission check, which is about what a principal may do, not
whether there is one.
Terminal. Never a fallback to AnonymousUser, which would run the
operation as somebody the caller did not name, and never a retry: a deleted
row does not come back, and a deactivated account is deactivated on purpose.
Services¶
run_service ¶
Call fn(**kwargs) from sync code, optionally inside transaction.atomic().
An async def service is bridged transparently via async_to_sync. The
bridge is not optional politeness: without it an async service returns its
coroutine object to the caller un-awaited — no exception, and under
atomic=True the transaction commits before the body would have run.
Async services under atomic=True route through
arun_service, which
owns the thread-sensitivity rule that keeps the ORM connection holding the open
transaction the same one the inner async DB calls use.
arun_service
async
¶
Await fn(**kwargs), optionally inside transaction.atomic().
ServiceError ¶
Bases: Exception
Raised by services to signal a business-rule failure.
Carries a message and nothing else, so a transport can surface it
without the service depending on that transport. A structured payload
belongs to a member that declares one:
ServiceValidationError
carries a field-keyed detail.
default_message is a msgid in the package's catalog, as each member's
is, and is looked up in the active language each time a refusal is built
with no message of its own, so it reads in the language of the request
that raised it. A message the caller passes is used as given.
ServiceValidationError ¶
Bases: ServiceError
Raised by services to signal invalid input or invalid state.
Distinct from
ServiceError so
a transport can tell "the arguments were fine but the business rule refused"
from "the input itself is invalid" and map the two differently. detail
may be a string, a dict (field → error(s)), or a list of errors.
ServiceConflict ¶
Bases: ServiceError
The operation collides with the resource's current state.
A slot already taken, a row someone else moved first, a name already used. The
resource is there and the request is well-formed; the two are simply
incompatible right now, and a caller can often resolve it by re-reading and
trying again — distinct from a plain
ServiceError,
which says "understood, and still not doing it" with no such implication.
def slot_is_free(*, user, data):
if Event.objects.filter(owner=user, day=data["day"], hour=data["hour"]).exists():
raise ServiceConflict(f"{data['day']} at {data['hour']}:00 is taken.")
A transport that has never heard of this type still handles a
ServiceError, and one that wants to do better matches on the class. It
must match before its generic ServiceError handler, or the subclass
check swallows it.
ServiceNotFound ¶
Bases: ServiceError
The operation's target does not exist, or is not this caller's to see.
The distinction from a plain
ServiceError
is which thing is wrong: the resource is absent rather than in the wrong
state, so a client should stop asking rather than try again differently.
def move_event(*, user, data):
event = Event.objects.filter(owner=user, pk=data["event_id"]).first()
if event is None:
raise ServiceNotFound(f"No event {data['event_id']}.")
Say the same thing for "absent" and "not yours." Answering a permission refusal for a row the caller cannot see confirms that it exists, which is why the owner-scoped lookup above raises this either way.
A transport that has never heard of this type still handles a
ServiceError, and one that wants to do better matches on the class. It
must match before its generic ServiceError handler, or the subclass
check swallows it.
ActionUnavailable ¶
Bases: ServiceConflict
The operation is not possible right now, for a reason with a stable name.
Raised when one of a spec's
Affordance conditions
is not met, carrying that affordance's code and its reason as the
message. django-spec-html's error_response answers it over HTTP as a
409 whose body is {"detail": <reason>, "code": <code>}.
A ServiceConflict
subclass rather than a code= argument on its parent, for three reasons. The
409 answer needs no new status, because a subclass is matched by its
parent's arm. A transport that wants the code matches this class ahead of its
generic conflict handler, and one that has never heard of it still reports a
conflict. And a ServiceConflict a service raises by hand genuinely has no
code and never will, so a nullable code on the parent would be a field
that lies at every other call site.
code names the rule and is what a transport or client branches on; the
message is the affordance's reason, the sentence a person or a model is
shown when the call is refused. A transport serving an agent should pass on
both: the model can say the sentence, and the code is what stays stable when
the sentence is reworded.
Like every member, it must be matched before a generic ServiceConflict
or ServiceError handler, or the subclass check swallows it.
AdditionalInputRequired ¶
Bases: ServiceError
A service cannot proceed without a value it was not given.
Not "what you sent is wrong" - that is
ServiceValidationError
- but "I got far enough to discover I need something else", usually
conditional on what the service found, so it cannot be expressed as a
required parameter:
def delete_rows(*, data, confirmed: bool = False):
doomed = rows_matching(data)
if len(doomed) > 100 and not confirmed:
raise AdditionalInputRequired(
f"{len(doomed)} rows match. Confirm to proceed.",
schema={"confirmed": {"type": "boolean"}},
)
...
schema describes what is missing, keyed by the argument name the service
expects it back under: a transport that can ask renders it, one that cannot
still has a message worth showing. The answer comes back as an ordinary
argument on every transport - an HTTP client re-submits with confirmed
in the body, an MCP client is asked and its answer is merged into the tool
arguments before dispatch - so raising is the whole of the service's
involvement; there is no callback to hold and no session to resume. The
operation declares that argument like any other, so the closed argument set
admits it on the second call.
A ServiceError
subclass deliberately, so a transport that has never heard of it still
reports that the operation could not be completed and why. One that wants to
do better must catch it before its generic ServiceError handler.
CreateService ¶
Bases: Protocol[InputT, ResultT]
The structural shape of a service that takes validated input and no target.
data is what the spec's
Validator returned,
under the pool's reserved data seed. **extras absorbs whatever else
the keyword pool delivers - user, a registered seed, the spec's
kwargs - without the service declaring each key. It is typed Any so
a service conforms under every type checker.
Nothing reads the Protocol at run time: dispatch binds a service from the
keywords it declares whatever it is annotated with, so conforming is a
claim checked by a type checker, through
implements.
Strictly typed extras stay possible on the service's own signature: declare
them as a TypedDict whose keys are all NotRequired and annotate
**extras: Unpack[YourExtras], so extras["tenant"] is typed in the
body. NotRequired because the Protocol's caller may not supply them.
The Protocol carries no type argument for the extras, since that
cross-check is not portable across type checkers.
UpdateService ¶
Bases: Protocol[InputT, InstanceT, ResultT]
The structural shape of a service that acts on a resolved row with validated input.
instance is the row the spec's instance_selector_spec resolved, under
the pool's reserved instance seed, and data what the spec's
Validator returned.
See CreateService
for **extras and strictly typed extras.
DeleteService ¶
Bases: Protocol[InputT, InstanceT, ResultT]
The structural shape of a service that acts on a resolved row, input optional.
instance is the row the spec's instance_selector_spec resolved. Most
deletes return None.
data has a default in the Protocol, so a service that reads no input
conforms without declaring it: bind InputT to
NoInput and leave data
out. A delete that does take input - a reason, a confirmation - binds
InputT to its input type and declares data with a default of its
own, data: ReasonInput | None = None: declared without one it does not
conform, since the Protocol's caller may leave data out.
See CreateService
for **extras and strictly typed extras.
implements ¶
Return the decorated callable unchanged, typed as conforming to proto.
proto is a parameterised service or selector Protocol:
@implements(CreateService[NoteInput, Note])
def create_note(*, data: NoteInput, **extras: Any) -> Note: ...
A type checker reports a callable that does not conform - a keyword the Protocol passes and the callable does not take, a return of the wrong type - at the decorator line, as ty does.
It lives in services/ beside the service Protocols, and decorates a
selector the same way, with
ListSelector
or RetrieveSelector.
Nothing changes at run time: dispatch binds a callable from the keywords it
declares, annotated or not.
Pool¶
PoolSeeds
dataclass
¶
Names a project adds to every dispatched callable's kwargs pool.
The names in RESERVED_POOL_SEEDS are the dispatcher's own. Everything
else a service legitimately needs — a tenant, a correlation id, a locale, a
clock, a feature-flag reader — has no channel, because off HTTP there is no
request for it to hang off. This is that channel. Where there is one,
a resolver declaring request reads it (CALL_SEEDS), and a
transport may still register request or view itself, as the ones
released before dispatch supplied them do; such a mount keeps its own.
A registration contributes two things:
- the value, resolved into every pool
base_poolbuilds; - reservation: dispatch refuses a spec whose Parameters declare the
name, and a Validator that returns a value under it, so an argument never
meets a seed in one pool. A caller sending the name is then refused as an
unknown argument, or dropped under
UnknownArguments.IGNORE, like any other name the spec does not declare.
The reason the two travel together is that either alone is a trap. A seed
with a value and no reservation shares the pool with an argument of the
same name, and which of the two a callable receives would depend on
spreading order; a reserved name with no value makes a callable that
declares it fail with a TypeError instead.
A reserved name, or one registered twice, is refused with ValueError
whichever way the registry is built: extend and the constructor run the
same check, so a registry written out as PoolSeeds(seeds=(...,)) cannot
shadow the dispatcher's own value either.
Immutable, and extend returns a new registry rather than mutating, so
there is no shared global state to leak between mounts or across tests. Pass
one per dispatch rather than installing it process-wide: a project that
mounts two operations with different ambient context needs them to differ,
and a module-level default cannot.
seeds = DEFAULT_POOL_SEEDS.extend(tenant=lambda *, user: user.tenant)
dispatch(spec, principal=user, arguments=arguments, pool_seeds=seeds)
A resolver is called through the same declare-to-receive rule as every other
spec callable: it names the pool entries it wants (user, an adapter's own
entry) and receives only those, or takes **kwargs for all of them.
A resolver is sync-only. A seed is a resolver - a callable whose
return is the value - and resolvers are called from sync code and never
awaited. An async def
one would seed a coroutine, which is truthy, so an affordance condition or
a precondition reading the seed would read an answer nobody computed. One
is refused when the registry is built, with ImproperlyConfigured; a
plain def handing back an awaitable is refused where it is resolved,
by base_pool.
Attributes:
| Name | Type | Description |
|---|---|---|
seeds |
tuple[_Seed, ...]
|
The registrations, in registration order. |
reserved
property
¶
Every name an argument may not occupy: the dispatcher's plus these.
Dispatch reads this rather than RESERVED_POOL_SEEDS directly, which
is what makes a registered seed as protected as a built-in one.
extend ¶
Return a new registry with seeds appended.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
A resolver is async - an |
ValueError
|
A name is one of the dispatcher's own, or is already
registered here (the same holds for a registry built directly:
a name reserved, or given twice in |
DEFAULT_POOL_SEEDS
module-attribute
¶
The empty registry every dispatch entry point falls back to.
A project that registers nothing gets the pool dispatch builds on its own: the
principal as user, a reporter as progress, and each step's own values
(data, instance, collection, result, queryset) where that
step has them.
RESERVED_POOL_SEEDS
module-attribute
¶
RESERVED_POOL_SEEDS: Final[frozenset[str]] = frozenset(
{
"user",
"data",
"instance",
"collection",
"result",
"queryset",
"progress",
"call_context",
"shapes",
}
)
The names dispatch seeds into a callable's keyword pool, which no argument may use.
user is the principal, progress the caller's progress reporter,
data the validated values, instance and collection the resolved
target, result the service's return (in an output selector's pool, where
instance is that return too, as djangorestframework-services binds it) and
queryset what extend_queryset shapes. call_context is the call's
context: the one plain dict the transport handed dispatch, or a fresh
one per call when it handed none, which every callable dispatch resolves -
a kwargs or input_data provider, a selector and its
extend_queryset, an affordance condition,
a precondition, the service, the run's progress_reporter - receives as
the same object by naming it, and never through **kwargs. Never a copy,
and the kernel writes nothing to it. Seed resolvers do not see it: a seed resolves before
anything the call adds. shapes is what the caller sent for the spec's declared
shapes, keyed by shape name and read-only: the mapping
PresentationContext.shapes holds, so a selector that eager-loads by the
query its presenter renders reads the value the presenter reads. It is in
the pools dispatch builds for a spec's callables: a selector and its
extend_queryset, a kwargs or input_data provider, a
precondition, the service, the run's progress_reporter, and a service
spec's output selector. A service spec's target selector is handed an empty
mapping instead, on every route, because resolve_target checks only the
target's own parameters and the lookup must find the same row either way
(test_a_target_selector_is_handed_no_shapes_on_any_route). It is an empty
mapping on a spec declaring no shapes, and, like call_context, it is handed only to a
callable naming it, never through **kwargs. Unlike call_context it
is not in an affordance condition's pool, the Validator's (a
FormValidator's form_kwargs included) or a mutation helper's nested
row services', and like it, not in a seed resolver's or a filter_set's
(test_form_kwargs_naming_the_shapes_is_handed_no_seed,
test_a_seed_resolver_naming_the_shapes_is_handed_none,
test_a_filter_naming_the_shapes_is_handed_none; a helper's row services
are handed its **kwargs, which
test_a_catch_all_is_never_handed_the_shapes keeps free of the seed). The seven besides those two
are the names djangorestframework-services seeds for the same values, so a callable
written for it runs under this kernel unchanged.
progress is in every pool, and live only where there is work to report on:
a service's run, and a selector spec's own selector. In a target or output
selector's pool it is null_progress, because a lookup has nothing to
report, and one reporting after the service finished would read to a watching
client as the work restarting.
A parameter declaring one of these names is refused, because a spread argument
must never be able to outrank the value dispatch seeded - a caller naming
itself user is the case that matters. request and view are not here:
they are CALL_SEEDS, the call's own, which dispatch hands a callable naming
one off the call's context. A transport may still register either through
PoolSeeds, which reserves it the same way, and dispatch refuses a spec
parameter of either name on every mount.
CALL_SEEDS
module-attribute
¶
The names dispatch reads off the call's context for every callable naming one.
request is the Django HttpRequest the call arrived on and view the
view serving it, each the very object the transport put in call_context
under that key, and None where it put none: off HTTP there is no request,
and code reading one learns that from the None
(test_with_neither_key_in_the_context_every_stage_is_handed_none). A spec
callable written for HTTP declares both, so a spec serves unchanged from every
transport only if every stage can be handed them.
Handed by name only. Every stage dispatch resolves - a seed's resolver, the
selectors, the target selector on every route included, the providers, a
FormValidator's form_kwargs, the affordance conditions, an
extend_queryset, the preconditions, the run's progress_reporter, the
service and the output selector - is handed either name it declares, and so is
every permission check that declares one. A **kwargs catch-all is handed
neither, and neither is a pool entry, so the Validator's ambient holds
neither, as the call's context itself is handled
(test_a_catch_all_is_handed_neither,
test_the_validator_s_ambient_holds_neither).
Outside RESERVED_POOL_SEEDS, so PoolSeeds.extend and the
constructor both accept a registration under either name, as the transports
released before the kernel supplied them make one. Such a mount keeps its own:
the registered seed is a pool entry, the value at every stage and every check,
and reaches a catch-all as any seed does
(test_the_registered_seed_supplies_the_name,
test_a_registered_view_still_reaches_a_catch_all).
Outside PoolSeeds.reserved as well, which keeps its published answer
for the transports that read it. Dispatch refuses a spec parameter of either
name on every mount all the same (test_a_parameter_named_either_is_refused),
and a kwargs provider's or an extra_kwargs key of either name
(test_a_provider_returning_request_is_refused,
test_an_overlay_key_named_either_is_refused). Two are not refused. A read
reflected off a selector's signature is filled with the call's value, as one
named like a registered seed is filled with the seed's
(test_a_reflected_read_named_either_is_the_call_s). A top-level Validator
field of either name is the caller's: it validates into data and never
reaches the service under the name, as a field named like a registered seed
(test_a_validator_field_named_request_takes_the_seat). A value of either name
that a Validator returns without declaring it, or binds for the call, is
refused, as a provider's is, since it would outrank the context's
(test_a_validator_returning_either_is_refused,
test_a_validator_binding_either_is_refused). A transport refusing a
caller's argument by these names reads this set.
base_pool ¶
base_pool(
*,
user: Any,
progress: ProgressReporter | None = None,
seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
**extra: Any,
) -> dict[str, Any]
The seeds a dispatched callable's kwargs pool carries, on every transport.
Every pool dispatch and adispatch build routes through here, so a
spec callable that declares a seed behaves the same whichever entry point
resolved it.
That is a property of the pools built here, not a rule the kernel can
enforce on its callers: this is a builder, not a gate. A transport adapter
that assembles a pool as a dict literal of its own carries exactly the keys
it wrote there, because resolve_callable_kwargs forwards only keys the
pool actually has. A callable declaring a seed the literal omitted then
raises TypeError at call time rather than running - progress most
often, since it is the seed with a default and so the one nobody remembers.
There is no request or view entry here (CALL_SEEDS): a
resolver declaring either is handed the one in the pool's
call_context where the pool carries one, None where the context
holds none, and a catch-all never is
(test_a_resolver_reads_the_request_off_the_pool_s_call_context). Dispatch
passes the call's context in for its resolvers and keeps it out of the
pool it hands on. A transport that registers either name as its own seed
keeps it, as before.
A seed resolving to an awaitable is refused with ImproperlyConfigured
and never enters the pool. PoolSeeds refuses an async def
resolver when it is registered, but a plain def handing back a
coroutine - a decorated async def, a partial over one - looks sync
until it answers. Nothing awaits a pool entry, and a coroutine is truthy,
so a condition reading it would read an unmet condition as met.
progress is the caller's reporter, and defaults to null_progress
rather than to None, so a declared reporter is always callable - see
ProgressReporter. Only None is replaced: a reporter that happens to
be falsy, such as a list-backed recorder that is empty until its first
report, is seeded as it is, where djangorestframework-services' or
would swap it for null_progress and drop every report. A seed's
resolver sees it like any other entry.
An adapter that dispatches callables through this package must build its
pool from this function, with its own entries spread in —
base_pool(user=…, **own_entries) — rather than restating the seeds.
Routing those entries through **extra is also what makes a name
collision loud: an entry called user raises TypeError here, where in
a dict literal it would quietly outrank the value the transport
authenticated.
seeds is the project's own registry
(PoolSeeds), resolved
into every pool this builds. It is the supported way to add an entry,
and the difference from spreading one through **extra is not
convenience: a registered name is also reserved, so dispatch refuses a spec
that declares an argument by that name rather than letting the two meet in
one pool. An **extra entry has no such protection. Spread an entry that
is genuinely per-call; register one that is ambient.
seeded_pool ¶
seeded_pool(
*,
user: Any,
seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
call_context: Mapping[str, Any],
progress: ProgressReporter | None = None,
) -> dict[str, Any]
The seeds of base_pool, resolved under a
call's context.
A transport with a call context builds its pool here, rather than
spreading its own request beside a registered seed: base_pool refuses
that pair, and it should, since a seed cannot silently outrank what the caller
spread in. Here nothing is spread. A resolver declaring request or view
reads the context's, and a seed registered under either name is the value.
call_context is what the resolvers bind against and no entry of what comes
back: it is no seed, and a Validator's ambient is a pool built here. A
transport that binds a callable against the context adds it back by name.
user, seeds and progress are as base_pool takes them.
null_progress ¶
null_progress(
progress: float,
*,
total: float | None = None,
message: str | None = None,
meta: Mapping[str, Any] | None = None,
) -> None
The
ProgressReporter
a transport with nowhere to send progress uses.
Seeded by base_pool
whenever the caller supplied no reporter, which is every dispatch from a
transport with no progress channel of its own, every HTTP request, and every
test.
The default is what makes the seed usable. Without it, a service
declaring progress would work over one transport and raise a
TypeError over the others, so nobody could declare it in code meant to
be shared - which is the entire premise of writing a service once.
Discarding the report is the honest behaviour for a caller that cannot
forward it; refusing the call is not.
combine_progress ¶
One ProgressReporter
forwarding to all of reporters.
For a transport with more than one sink of its own to hand dispatch's
progress=: the channel back to its client - MCP notifications, a
websocket - beside a task record, an audit trail or metrics. Neither
displaces the other; each report reaches every sink, in the order given.
Each sink is isolated. A sink that raises neither skips the sinks after it nor reaches the service that reported, because telemetry failing must not take down the run it describes. The failure is swallowed, not logged: a sink that cares about its own errors handles them inside itself, where the context to act on them is. No sink may depend on the order, since none can observe whether an earlier one succeeded.
This is not how dispatch joins a spec's own progress_reporter to the
transport's reporter: there, a sink's failure reaches the service, as the
transport's own reporter failing does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*reporters
|
ProgressReporter | None
|
The sinks, in call order. |
()
|
Returns:
| Type | Description |
|---|---|
ProgressReporter
|
|
ProgressReporter
|
when no sink is left, so the result is always callable; the one sink |
ProgressReporter
|
itself, unwrapped, when one is left; otherwise a reporter handing each |
ProgressReporter
|
report to every sink. |
provider_keys ¶
The names provider fills and those it may decline, or None if it does not say.
The static half of the kwargs= provider contract, whose runtime half is
how dispatch calls the provider. ServiceSpec.kwargs and
SelectorSpec.kwargs return a mapping, and one annotated to return a
TypedDict says, before it runs, which names it fills. A
transport reads that here to build a schema that does not ask the caller
for them, and to know which calls to refuse before dispatch, rather than
keeping a copy of this reader.
Returns a
ProviderKeys,
(filled, declinable): two disjoint sets that together are every key of
the TypedDict, the keys the provider always answers for and the keys
whose value admits UnsetType, which it may decline with UNSET. It
unpacks as a pair and names each set, so keys.filled reads as well as
filled, declinable = keys.
ProviderKeys(frozenset(), frozenset()) for provider=None: a spec with
no provider fills nothing. None when the provider says nothing about its
keys -- no return annotation, a plain dict, a lambda, or a return
annotation that does not resolve -- so it may fill any name, and a transport
requires none of them for lacking a default. Held by
test_a_spec_without_a_provider_fills_nothing and
test_a_provider_whose_return_says_nothing_is_untyped.
Each annotation costs only what it says. The return annotation is
resolved on its own, in the globals of the function a decorator wrapped
rather than the wrapper's (decorated-elsewhere in
test_a_generic_typed_dicts_arguments_decide_which_keys_may_be_declined),
so a parameter annotation naming a type imported only under
TYPE_CHECKING leaves the keys readable
(test_a_parameter_type_imported_only_for_type_checking_leaves_the_keys_readable).
The keys are read off the TypedDict without hints, and each value is
resolved on its own, so one that does not resolve makes only its own key
declinable: whether the provider may decline it cannot be read, and
declinable is the reading that neither hides the name from the caller nor
requires it (test_a_value_type_that_does_not_resolve_makes_only_its_key_declinable).
Python 3.14's lazily evaluated annotations are read the same way, in the
format that leaves an unresolvable name as a forward reference rather than
raising (test_lazily_evaluated_annotations_are_read_one_at_a_time).
That format is why typing-extensions is floored at 4.14: on 3.14, 4.13
hands the standard library's annotationlib a format number it reserves
for internal use, which raises, and every typed provider would read as
untyped.
A generic TypedDict is read with whatever binds its parameters.
Scope[str | UnsetType] does not relay __required_keys__, so the keys
come off Scope, where a value annotated T is the bare type variable.
What T stands for is substituted wherever it appears in a value, a union
included, whether an alias's arguments bind it
(test_a_generic_typed_dicts_arguments_decide_which_keys_may_be_declined)
or a class statement does, as class Declining(Scope[str | UnsetType])
does, and a subclass handing its own parameter on to Scope
(test_a_subclass_binding_decides_which_keys_may_be_declined). An
argument that does not admit UNSET still fills the key
(test_a_parameterised_typed_dict_is_read_off_its_origin), and one
wrapped in Annotated is read as what it wraps
(test_annotated_around_a_binding_is_read_as_what_it_annotates). A PEP 695
class Scope[T](TypedDict) is read the same way under postponed
annotations, where the "T" a value leaves resolves only beside the
class's __type_params__
(test_a_pep_695_type_parameter_is_read_as_the_class_declares_it).
Each key is read with the bindings of the class that declared it, so
one T reused at every level reads as each class binds it:
class Shadow(Scope[list[T]], Generic[T]) with extra: T, returned
as Shadow[str | UnsetType], fills tenant with a list and may
decline extra
(test_each_key_is_read_with_the_bindings_of_the_class_that_declared_it).
A key reached through two bases that bind it differently is filled if
either reading fills it.
A type variable nothing binds counts as filled, as in a bare
-> Scope (test_a_type_variable_nothing_binds_is_filled). Whether it
may be UNSET is written nowhere, and filled keeps the decision with the
provider by hiding the key from the caller. Declinable would let a
transport whose caller's value wins put that value in a key the provider
was meant to decide, such as a tenant.
Three readings stay as they are, each held by a test:
- A PEP 696 default on a type variable is not consulted
(
test_a_type_variables_default_is_not_consulted). - A base that cannot be substituted makes the provider read as untyped
(
test_a_base_that_cannot_be_substituted_leaves_the_provider_untyped). - A key a subclass redeclares is read with its base's bindings, since no
runtime record says which class wrote it
(
test_a_key_a_subclass_redeclares_is_read_with_its_bases_bindings).
Duck-typed on the keys a TypedDict class carries rather than
is_typeddict, because the standard library's answers False for a
typing_extensions.TypedDict on the older Pythons this package supports.
server_owned_keys ¶
server_owned_keys(
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS,
call_context: dict[str, Any] | None = None,
) -> frozenset[str]
Every name spec's dispatch fills from the server, whatever the caller sends.
For a transport building an input schema of its own, beside the one
parameters() describes: subtract this set from what it lists, so it
asks the caller for no key the server answers anyway. The union of:
- the names the pool seeds carry: the dispatcher's own (
user,data,instanceand the rest) and every seedpool_seedsregisters, but a registered seed's name that the spec's Validator declares as a top-level field. Such a field is the caller's to send: dispatch validates it intodataand leaves the service's parameter of its name to the seed, so a transport subtracting this set still asks for it (test_server_owned_keys_leaves_such_a_field_out_and_a_service_may_ask_for_it). A read markedreflectedand named like a registered seed is here, since the seed fills it and the call takes no argument of its name; - a read marked
reflectedand namedrequestorview, on any mount: dispatch fills it from the call's context and refuses a caller's argument of its name (test_server_owned_keys_owns_a_reflected_read_named_either); - the keys each provider the dispatch runs is annotated to fill, as
provider_keysreads them: the spec'skwargsand, on a service spec, itsinput_dataand its target selector'skwargs. Dispatch drops the caller's value for a key a provider fills once it has been checked, so the key holds the author's value whatever the caller sent. When the provider leaves it out or returnsUNSET, a parameter declared required is refused where the provider's answer is merged, and one that is not is absent.
No name here is a parameter dispatch demands of the caller, so a key
a provider fills is the server's for the whole call. Each provider's
values reach one seat - a selector's kwargs that selector's reads, a
service spec's kwargs its reads, input_data its Validator's
fields - and dispatch does not demand a parameter there that the provider
fills. A filled key that a parameter in any other seat declares is
refused when the spec is built, or, for a Validator field, when
parameters() is assembled. A many spec's list, named by
many_argument, is such a seat for every provider, since dispatch
always demands it of the caller: a key naming it is refused, filled or
declinable, even beside a Validator field of that name. A key no
parameter declares is the server's alone.
A key a provider may decline with UNSET is not here, nor is any key
of a provider whose return says nothing about its keys, which may fill
any name and so names none. Dispatch does not demand either of the
caller, since the provider may fill it, and keeps the caller's value
beneath the provider's answer, so the caller's is the one the callable
receives when the provider declines. Less a read a provider requires
itself, by name with no default, which only the caller can send and
dispatch demands. A transport that asks the caller for neither reads
them off provider_reached,
which leaves such a read out, or
spec_caller_input_schema,
which keeps it in required.
Static per spec, but for the Validator's fields. Those are read as
the Validator declares them to call_context: a transport subtracting
this set during a call hands the call's dict, so a seed-named field the
Validator declares only to that call is still asked for
(test_a_seed_named_field_declared_only_to_a_call_is_the_caller_s_in_that_call),
and a reader describing the spec outside any call leaves it None. A
transport that also answers some declared
parameters itself, per mount or per toolset, describes them with a
ServerArguments
and subtracts its names() beside this set: those are parameters the
spec declares and the caller is still not asked for.
A SpecSource owns
what the spec it compiles to owns. djangorestframework-services' own
reading adds the keys its reflected
input markers hide, which this package does not read.
resolve_callable_kwargs ¶
Pick the subset of pool matching fn's declared parameters.
Every pool-resolved callable in the kernel — a seed's resolver, a spec's
selector, extend_queryset, a service — binds through this one rule,
so a callable written for one entry point runs unchanged on another: it
names what it wants and gets exactly that, or takes **kwargs for the
rest of the pool, which is every entry but the call's context.
If fn declares **kwargs, the entire pool is passed, except a name
handed by name only (BY_NAME_ONLY_POOL_NAMES, the call's context),
which reaches a catch-all only where it also names it. Otherwise only
parameters present in the signature are forwarded.
Mutations¶
create_from_input ¶
create_from_input(
model: type[ModelT],
data: Any,
*,
field_map: dict[str, str] | None = None,
exclude_fields: list[str] | None = None,
m2m: dict[str, Any] | None = None,
relations: Mapping[str, RelationSpec] | None = None,
context: Mapping[str, Any] | None = None,
) -> ChangeResult[ModelT]
Build, save(), and return a fresh instance of model.
Regular fields come from data (a dataclass, dict, or object with __dict__).
A file field is written as a ModelForm writes it, through the model
field's save_form_data: a file is stored, None leaves the field to the model, and
False,
a form's value for a cleared file, stores no file.
m2m maps a many-to-many attribute to the rows it should hold — instances or
primary keys of rows that already exist — and set()s them after the save;
it creates nothing. A
ManyToManySpec
in relations does the other job: it writes the target rows from the payload,
creating or updating each, and then links them. A relation named by both is
refused, since it would be written twice and keep whichever ran last.
relations maps a relation name to the spec for its kind, and is the one map for
every kind — a reverse-FK
ChildSpec included. The
nested payload is read from data[relation] and written in the order the kind
dictates, not the order the map is spelled in (see
RelationPhase).
Keep the whole call inside the service's atomic block.
context is an opaque mapping forwarded verbatim down the tree, into the pool
of every row service a relation spec declares and of every scope callable. This
helper never reads it — it exists so per-row work downstream can see the acting
caller. A service opts in by handing on the pool it was called with,
context=kwargs. A catch-all is never handed the call's context, so a
service whose nested callables should see it names call_context and
hands it on beside the pool, as create_model's service does.
acreate_from_input
async
¶
acreate_from_input(
model: type[ModelT],
data: Any,
*,
field_map: dict[str, str] | None = None,
exclude_fields: list[str] | None = None,
m2m: dict[str, Any] | None = None,
relations: Mapping[str, RelationSpec] | None = None,
context: Mapping[str, Any] | None = None,
) -> ChangeResult[ModelT]
Async sibling of
create_from_input
using asave()/aset().
update_from_input ¶
update_from_input(
instance: ModelT,
data: Any,
*,
field_map: dict[str, str] | None = None,
exclude_fields: list[str] | None = None,
m2m: dict[str, Any] | None = None,
update_fields: bool | list[str] = True,
relations: Mapping[str, RelationSpec] | None = None,
context: Mapping[str, Any] | None = None,
) -> ChangeResult[ModelT]
Update instance with values from data, persisting only deltas.
By default (update_fields=True), the save call uses
update_fields=<changed> to write the minimal set of columns.
auto_now=True fields (e.g. updated_at) are automatically added to
that list so they are refreshed alongside the mutation, and so are a
changed ImageField's width_field and height_field, which
setting the image wrote on the instance. Pass False to
perform a full save, or an explicit list to control exactly which columns
are written (no auto-injection in that case).
A file field is written as a ModelForm writes it, through the model
field's save_form_data: a file replaces the one the row holds, None keeps it, and
False,
a form's value for a cleared file, leaves no file, reported as a change to "".
An upload, or any File that is not one a row holds, is always written and reported,
even under the name of the file it replaces, since a name says nothing of the content;
the held file handed back as itself is no change.
m2m assigns many-to-many rows that already exist, and only where the set
of primary keys differs from the current one;
ManyToManySpec
in relations writes the target rows from the payload instead. A relation named
by both is refused rather than written twice.
relations maps a relation name to the spec for its kind, one map for
every kind. The nested payload from data[relation] is
reconciled with what is already there — create / update / orphan-remove per
the spec — and a relation the input omits is left untouched. Kinds are
written in the order their class dictates, so a forward foreign key is
resolved before this instance is saved and the assignment rides the same
diff and update_fields path as any other column. Keep the call inside
the service's atomic block.
A relation that was written stays readable off the returned instance. The one-row kinds resolve their row by re-querying, so the parent's cached related object is replaced with the row that was written — and dropped where the write removed it — rather than left holding pre-write values.
context is an opaque mapping forwarded verbatim into the pool of every
row service and scope callable the relation specs declare; this
helper never reads it. See
create_from_input.
aupdate_from_input
async
¶
aupdate_from_input(
instance: ModelT,
data: Any,
*,
field_map: dict[str, str] | None = None,
exclude_fields: list[str] | None = None,
m2m: dict[str, Any] | None = None,
update_fields: bool | list[str] = True,
relations: Mapping[str, RelationSpec] | None = None,
context: Mapping[str, Any] | None = None,
) -> ChangeResult[ModelT]
Async sibling of
update_from_input
using asave()/aset().
apply_input ¶
apply_input(
instance: Model,
data: Any,
*,
field_map: dict[str, str] | None = None,
exclude_fields: list[str] | None = None,
) -> ChangeResult
Set attributes from data onto instance without saving.
Returns a ChangeResult
describing fields whose value actually changed. Useful when a service wants to
inspect what the input would change before deciding whether to persist.
A file field is set as update_from_input writes it: None keeps the
file, and False leaves none.
delete_relations ¶
delete_relations(
instance: ModelT,
*,
relations: Mapping[str, RelationSpec],
context: Mapping[str, Any] | None = None,
) -> ChangeResult[ModelT]
Remove the rows instance owns, deepest first, and leave instance.
The cascade for a delete service to run where the database will not: a
PROTECT foreign key, a relation whose row services must see each
removal, or a soft delete, which Django never cascades through because no
row is deleted. The service deletes (or retires) instance itself
afterwards, inside the same atomic block.
relations is the same map the write helpers take, so one declaration
describes both how a payload is written and what goes when the row does.
One rule covers every kind: the rows the instance owns are disposed of,
and the rows it merely points at are not.
- A
ChildSpecorGenericRelationSpeccollection, and aReverseOneToOneSpecrow, is disposed of after its own declared relations, so a non-nullable grandchild goes first. Each row is deleted, unlinked or handed to the spec'sdelete_serviceby the rule a write removing it follows: the spec'sorphansetting, or the service when one is declared. - A
ManyToManySpecloses its membership, and its target rows survive. - A
ForwardRelationSpecis reported untouched rather than refused: its row is not the instance's, and refusing it would make a map that is right for writing impossible to cascade.
The returned ChangeResult
reports the collections under children and the one-row kinds under
relations, as a write does, with no field changes. The instance's
cached relations are brought in line with the removal, so an instance
that outlives its cascade renders without the rows it lost.
context is an opaque mapping forwarded verbatim into the pool of
every row service the specs declare; this helper never reads it.
adelete_relations
async
¶
adelete_relations(
instance: ModelT,
*,
relations: Mapping[str, RelationSpec],
context: Mapping[str, Any] | None = None,
) -> ChangeResult[ModelT]
Async variant of
delete_relations.
The same rule, the same order and the same report, through Django's async
ORM. A row service a spec declares must be async def here, as in every
async helper: one the loop cannot await is refused, naming its slot.
register_row_error ¶
Re-root error_class under the row that raised it, as the kernel's own refusals are.
A relation write re-addresses a refusal raised inside one row - by a row service, or by the write of a row further down - under that row's place in the arguments, so the caller learns which row was refused. It does that for the two refusals this package raises and for Django's own write failures. A refusal from a library this package cannot name - a framework's validation error, raised by a row service written for that framework - would otherwise escape naming no row. Registering its class puts it in the same tree:
read_detailis handed the exception and returns its detail: a mapping of field names to messages, or the row's own messages as a list or a string. It is placed at the row's address as the kernel's refusals are - a collection's row under itsintindex, a list or string undernon_field_errorsinside the row - and the messages are kept as they are, codes and all.- The re-rooted tree is handed to
error_classas its one argument, and that is what is raised. The class is kept because the class says who refused and decides how each transport answers. A subclass raised by a row is caught as the registered class and rebuilt as it, so register the narrowest class whose constructor takes a detail this way.
A grandchild's refusal is re-rooted at each row it passes, so it arrives carrying both addresses. A list form - a list as long as the incoming one, empty against the rows that passed - is a rendering of this tree, and the transport answering in it renders it.
Registering the same class with the same reader again does nothing, so a
registration that runs at import or in an AppConfig.ready() may run
twice. Pass a module-level function rather than a lambda built per call,
which would be a second reader. Raises ImproperlyConfigured for:
- something that is not an exception class;
- a class already registered with a different reader, which keeps the first;
- a class the kernel already re-roots, or one wider than such a class: a
ServiceValidationErrororInvalidArguments, or Django'sValidationError,ValueErrororTypeError. A narrower one would never be asked, and a wider one,Exceptionat its widest, would read the caller's own bug in a row service as a refusal of the arguments. Each of the five is refused by its own case oftest_a_class_the_kernel_already_reads_is_refused, and the wider direction bytest_a_class_wider_than_one_the_kernel_reads_is_refused.
Registrations are process-wide, as the relation specs that read them are, and there is no removal: an adapter registers for the life of the process.
ChangeResult
dataclass
¶
Bases: Generic[ModelT]
Outcome of a mutation helper call.
instance is the model instance after the mutation. created is True iff this
came from
create_from_input
/
acreate_from_input.
changes records every field whose value actually differed from its prior value
(or from UNSET for creates).
Every relation declared in relations= reports in one of two fields, chosen by
the relation's shape. children carries one
ChildCollectionChange
per collection: a reverse-FK
ChildSpec, a
GenericRelationSpec
and a
ManyToManySpec.
relations carries one
RelatedObjectChange
per one-row relation: a
ForwardRelationSpec
and a
ReverseOneToOneSpec.
A collection reports tuples of pks and a one-row relation reports an outcome, so
they are different carriers. Both are empty when no relation is declared, and a
declared relation the input omits still gets its entry, reporting nothing.
A forward relation shows up twice and means two different things — here as
what happened to the row it points at, and in changes as the parent's
foreign-key column, which only appears if it actually changed.
The class is generic over the concrete model type: callers that pass
Author into a mutation helper get back a ChangeResult[Author]
whose .instance is typed as Author. The bare name
ChangeResult (no parameter) resolves to ChangeResult[Model] and
keeps working for callers that don't care.
get_field_change ¶
Return the
FieldChange for
field_name, or None.
get_child_change ¶
Return the
ChildCollectionChange
for relation, or None.
get_relation_change ¶
Return the
RelatedObjectChange
for relation, or None.
FieldChange
dataclass
¶
One field's before/after pair from a mutation.
old will be UNSET for fields populated as part of a create
(no prior value existed).
ChildCollectionChange
dataclass
¶
What a nested write did to one relation that holds a collection.
Carried in ChangeResult.children, one entry per collection declared in
relations=: a reverse-FK
ChildSpec, a
GenericRelationSpec
or a
ManyToManySpec.
A relation holding one row reports a
RelatedObjectChange
instead. The tuples hold row primary keys:
created— rows inserted.updated— rows that already existed, matched by the spec'smatch_keyand written: among the parent's own rows for a child or generic collection, insidescopefor a many-to-many.deleted— rows the relation let go and deleted.unlinked— rows the relation let go and kept, with their link to the parent set toNone.removed— rows handed to the spec'sdelete_service. Deliberately a fifth tuple rather than a reuse ofdeleted: once a service owns the row, the loop no longer knows whether it was deleted, archived, unlinked or left standing, and folding those intodeletedwould report a guess as fact. What the loop does know is that the row left the relation and a service decided the rest.
Whether a row let go is deleted or unlinked is the spec's orphan
(RelationOrphan),
not the column alone: "delete" always deletes; "unlink" always unlinks,
and is refused where the link cannot hold NULL; "auto", the default,
unlinks when it can — both columns, for a generic relation — and deletes when
it cannot. A many-to-many target is shared, so a member "replace" drops
only loses its membership and is always unlinked; that kind has no
orphan and no delete_service, and its deleted and removed stay
empty.
updated records every matched row the write ran through
update_from_input or the spec's update_service, whether or not that
row's own columns actually changed.
RelatedObjectChange
dataclass
¶
The delta for a relation that holds one row, not a collection.
Carried in ChangeResult.relations, one entry per singular relation declared in
relations= — a forward foreign key / one-to-one, or a reverse one-to-one.
ChildCollectionChange's
five pk tuples cannot report a one-row relation honestly: every one of them would
be either empty or a one-tuple, and "which of the five is non-empty" is a worse way
to say "what happened" than saying it. So a singular relation reports one
outcome and one pk.
outcome is a RelationOutcome,
which documents what each value means.
pk is the primary key of the row the outcome is about, read
before any delete (Django clears instance.pk afterwards), and
None when no row was touched ("untouched" / "cleared").
create_model ¶
create_model(
model: type[ModelT],
*,
field_map: dict[str, str] | None = None,
exclude_fields: list[str] | None = None,
m2m: Mapping[str, Any] | Callable[[Any], Mapping[str, Any]] | None = None,
relations: Mapping[str, RelationSpec] | None = None,
) -> Callable[..., ModelT]
A service that builds a row of model from its validated data, and returns the row.
The service a create operation would otherwise write by hand:
def create_author(*, data: AuthorIn, **_: Any) -> Author:
return create_from_input(Author, data).instance
field_map, exclude_fields and relations are handed to
create_from_input
as they are, so one relations map writes every nested kind, a reverse
foreign key's
ChildSpec among
them. m2m is a static mapping, or a callable handed the validated
data that returns one, which is the usual case when the rows to link
arrive in the arguments:
create_model(Post, m2m=lambda data: {"tags": data.tags})
The service returns the row, not the
ChangeResult,
since the row is what a create's output presents. It opens no transaction:
dispatch runs a service inside one, which covers the row and every nested
write. It takes **kwargs, so the rest of the pool - the user and
any registered seed - is absorbed rather than refused. It names
call_context, which a catch-all is never handed, and the same pool
with the call's context beside it is handed on as the helper's
context, so a row service a relation spec declares can see who is
calling and, by naming call_context, the very dict the call's other
stages share.
acreate_model ¶
acreate_model(
model: type[ModelT],
*,
field_map: dict[str, str] | None = None,
exclude_fields: list[str] | None = None,
m2m: Mapping[str, Any] | Callable[[Any], Mapping[str, Any]] | None = None,
relations: Mapping[str, RelationSpec] | None = None,
) -> Callable[..., Awaitable[ModelT]]
The async twin of create_model.
An async def service over
acreate_from_input,
so adispatch awaits it
rather than bridging it. Every row service its relations declare is an
async def too, which the async helpers check.
update_model ¶
update_model(
model: type[ModelT],
*,
field_map: dict[str, str] | None = None,
exclude_fields: list[str] | None = None,
m2m: Mapping[str, Any] | Callable[[Any], Mapping[str, Any]] | None = None,
update_fields: bool | list[str] = True,
relations: Mapping[str, RelationSpec] | None = None,
) -> Callable[..., ModelT]
A service that writes the validated data onto the resolved row, and returns the row.
The service an update operation would otherwise write by hand:
def update_author(*, instance: Author, data: AuthorIn, **_: Any) -> Author:
return update_from_input(instance, data).instance
model is not read: it is taken for symmetry with
create_model and
to bind the row's type for a type checker, since the row is the
instance the spec's instance selector resolved. field_map,
exclude_fields, update_fields and relations are handed to
update_from_input
as they are, and m2m is read as create_model reads it.
The service returns the row rather than the
ChangeResult,
opens no transaction of its own, absorbs the rest of the pool and hands it
on as context with the call's context beside it, as create_model's
does.
aupdate_model ¶
aupdate_model(
model: type[ModelT],
*,
field_map: dict[str, str] | None = None,
exclude_fields: list[str] | None = None,
m2m: Mapping[str, Any] | Callable[[Any], Mapping[str, Any]] | None = None,
update_fields: bool | list[str] = True,
relations: Mapping[str, RelationSpec] | None = None,
) -> Callable[..., Awaitable[ModelT]]
The async twin of update_model.
An async def service over
aupdate_from_input.
delete_model ¶
delete_model(
model: type[ModelT],
*,
soft_delete: Callable[[ModelT], None] | None = None,
relations: Mapping[str, RelationSpec] | None = None,
) -> Callable[..., None]
A service that deletes the resolved row, after the rows it owns, and returns None.
The service a delete operation would otherwise write by hand:
def delete_author(*, instance: Author, **_: Any) -> None:
instance.delete()
model is not read, as in
update_model:
the row is the instance the spec's instance selector resolved.
soft_delete is called with the row instead of instance.delete(),
for a row that is retired rather than removed:
def archive(instance: Author) -> None:
instance.is_archived = True
instance.save(update_fields=["is_archived"])
delete_model(Author, soft_delete=archive)
So no row is deleted and Django sends no pre_delete or post_delete
for it.
relations is the map the writes take, and what it declares goes
before the row, deepest first, through
delete_relations:
the rows the instance owns are disposed of, a many-to-many loses its
membership, and a forward relation is left alone. It is the cascade a
database will not run - a PROTECT foreign key, or a soft delete, which
removes no row for Django to cascade from - and the one a declared
delete_service sees row by row. A value that is not a relation spec is
refused with ImproperlyConfigured here, when the service is built,
rather than at its first call. With no map, or an empty one, nothing but
the row is touched.
The service opens no transaction: dispatch runs it inside one, so a refused
cascade leaves every row in place. It absorbs the rest of the pool and
hands it on, with the call's context it names, as the cascade's
context, so a row's delete_service can see who is calling and,
by naming call_context, the very dict the call's other stages share.
adelete_model ¶
adelete_model(
model: type[ModelT],
*,
soft_delete: Callable[[ModelT], Awaitable[None]] | None = None,
relations: Mapping[str, RelationSpec] | None = None,
) -> Callable[..., Awaitable[None]]
The async twin of delete_model.
Deletes with await instance.adelete(), after the cascade
adelete_relations
runs by the rule delete_model states. soft_delete is an
async def called with the row in place of adelete().
delete_collection ¶
delete_collection(
model: type[ModelT], *, soft_delete: Callable[[Any], None] | None = None
) -> Callable[..., None]
A service that deletes the resolved collection in one bulk delete, and returns None.
Pairs with a spec's collection_selector_spec, whose rows dispatch
seeds into the pool as collection. The service a bulk delete would
otherwise write by hand:
def delete_books(*, collection: QuerySet[Book], **_: Any) -> None:
collection.delete()
collection.delete() is Django's bulk delete, which runs each foreign
key's on_delete and sends pre_delete and post_delete for every
row, as a single row's delete does. An empty collection deletes nothing, so
running the operation twice is harmless. model is not read,
as in delete_model.
soft_delete is called with the collection instead of delete(),
as in lambda rows: rows.update(is_archived=True). The service opens no
transaction, since dispatch runs it inside one, and absorbs the rest of
the pool.
adelete_collection ¶
adelete_collection(
model: type[ModelT], *, soft_delete: Callable[[Any], Awaitable[None]] | None = None
) -> Callable[..., Awaitable[None]]
The async twin of
delete_collection.
Deletes with await collection.adelete(). soft_delete is an
async def called with the collection in its place.
Relations¶
RelationSpec ¶
What the nested-write driver needs from a relation spec: its phase.
The relations={name: spec} mapping of the mutation helpers takes one
spec per relation, and the kinds differ in almost everything — a forward
foreign key has no orphans, a reverse one-to-one has no collection, a
child collection has both. What they share is that the driver must know
when to write each one, and that answer belongs to the class rather than
to the instance: every forward foreign key is written before the parent's
save() because it is a forward foreign key, not because a particular
spec asked to be.
So each concrete spec declares write_phase as a class attribute and the driver
orders by it (see
RelationPhase for
the sequence). A spec author never sets it per-instance, and the mapping's insertion
order cannot reorder the phases — only the relations within one.
Subclasses are frozen dataclasses; this base deliberately declares no
fields, so each kind spells out its own and no kind inherits a knob that
means nothing for it. Each takes its required fields positionally and every
option by keyword only, so ChildSpec(Book, "author", mode="merge") names
what it sets and an option added to a kind moves no other argument.
ChildSpec
dataclass
¶
Bases: RelationSpec
How to persist one reverse-FK ("one-to-many") child collection.
The reverse-FK member of the relation taxonomy: it writes rows whose
foreign key points back at the parent, so it belongs to
RelationPhase.REVERSE and is written after
the parent's save().
Passed in the relations={relation_name: ChildSpec(...)} map of
create_from_input
/
update_from_input
(and their async siblings). The incoming child rows are read from
data[relation_name]; each child is persisted by running it back through
the same mutation helpers, so scalar / m2m / nested semantics compose
recursively. The whole parent + children write runs inside
the service's atomic block; validating the arguments stays with the spec's Validator,
which dispatch runs before the service — the helper owns persistence only.
Pluggable services — the spec owns reconciliation, the service owns the row.
Matching, mode and orphan handling never move into your code; a slot is called
once per row the loop has already decided about. Each is invoked through
run_service /
arun_service with
atomic=False, because the surrounding service's atomic block already wraps the
whole tree and letting each row open its own would mean a savepoint per row. Each
receives only the pool keys it declares (the library's usual signature-filtering
idiom), drawn from the mutation helpers' opaque context= plus the loop's own
seeds. Those seeds — data / instance / parent — are applied after
the context, so a context key of the same name cannot outrank them, the precedence
form of the rule RESERVED_POOL_SEEDS states for dispatch's pools. In the
async loops the slot must be an async def: the async path is awaited end to end,
so a sync one is refused with ImproperlyConfigured, naming the relation and the
slot, before it runs.
A declared slot owns that row entirely: field_map,
exclude_fields, m2m and the nested relations map configure the
default mutation-helper call, so a create_service / update_service
standing in for it makes them dead configuration.
Declaring both raises
ImproperlyConfigured at construction rather
than dropping them quietly. delete_service is exempt — it replaces the
unlink-or-delete rule, not the helper call, so the cascade still removes a
row's grandchildren before handing the row over. The spec keeps only what
it never delegates — which rows exist, which incoming row matches which
existing one, and what happens to the ones left over.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
type[Model]
|
The child model class. |
fk |
str
|
Name of the child's forward foreign-key field pointing at the
parent ( |
match_key |
str
|
Field used to pair an incoming row with an existing child.
An incoming row whose |
mode |
RelationMode | str
|
|
orphan |
RelationOrphan | str
|
What removing an orphan does, where |
field_map |
dict[str, str] | None
|
Forwarded to the per-child |
exclude_fields |
list[str] | None
|
Forwarded to the per-child call, as |
m2m |
Mapping[str, Any] | Callable[[Any], Mapping[str, Any]] | None
|
The child's own many-to-many assignments — the per-child analogue
of the helpers' |
relations |
Mapping[str, RelationSpec] | None
|
The child's own relations, of any kind — a
|
create_service |
Callable[..., Any] | None
|
Per-row service replacing the default mutation-helper
call, for a child whose write has real behaviour (side effects,
derived columns, events, an external call). Called as
|
update_service |
Callable[..., Any] | None
|
The same for updates, called as
|
delete_service |
Callable[..., Any] | None
|
Called as
|
ForwardRelationSpec
dataclass
¶
Bases: RelationSpec
How to persist a forward relation — a ForeignKey or a
OneToOneField declared on the parent itself.
One spec covers both: OneToOneField subclasses ForeignKey, and the
column being unique changes nothing about how it is written.
Declared in relations={field_name: ForwardRelationSpec(...)} on the
mutation helpers, where the name is the parent's own field
(relations={"author": ...} for Post.author). The nested payload is
read from data[field_name] and the resolved row is assigned to that
field before the parent is saved
(RelationPhase.FORWARD) — an ordinary
column assignment, reported by diff_attrs and persisted by the same
minimal update_fields save as any other field.
The resolved row is assigned onto the parent in memory whether or not the
column moved, so a caller who read the relation before the write does not
read the pre-write row back off the returned instance. A row re-matched
against scope is a different Python object from the one the parent had
cached, and two rows sharing a primary key are equal, so the diff correctly
reports no column change and would otherwise leave the stale object behind.
The value reads three ways. Omitted leaves the relation untouched.
None sets the parent's foreign key to None without removing the
row it used to point at — a forward target is not owned by the parent and
may be shared, so removing rows is the reverse kinds' job. A mapping
writes the target row: without a match_key it creates one, with a
match_key it names one, matched against scope.
A spec writes a row. To merely point the column at a row that already exists, don't declare a relation at all — pass the pk or the instance as the plain field it is.
There is no mode and no delete_service: a forward relation has no
collection to reconcile and no orphans to dispose of. Clearing it is the
None case, and it clears the column.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
type[Model]
|
The target model class. |
match_key |
str
|
The field pairing an incoming payload with an existing row
(default |
scope |
QuerySet[Any] | Callable[..., QuerySet[Any]] | None
|
The rows this caller may update — a queryset, or a callable
resolved from the caller's |
field_map |
dict[str, str] | None
|
Forwarded to the target row's own |
exclude_fields |
list[str] | None
|
Forwarded likewise. Excluding the |
m2m |
Mapping[str, Any] | Callable[[Any], Mapping[str, Any]] | None
|
Forwarded likewise — the target's own many-to-many assignments. |
relations |
Mapping[str, RelationSpec] | None
|
Forwarded likewise — the target's own relations, of any kind. |
create_service |
Callable[..., Any] | None
|
Optional service replacing that call, for a target whose
write has behaviour of its own. It receives |
update_service |
Callable[..., Any] | None
|
The same, and additionally receives |
ReverseOneToOneSpec
dataclass
¶
Bases: RelationSpec
How to persist a reverse one-to-one — the row that points back.
The other side of a OneToOneField: the column lives on the related row
(Profile.author) and the parent (Author) reaches at most one of them through
the reverse accessor. So it is the
ChildSpec loop minus the
collection, written in RelationPhase.REVERSE once the parent has a primary key
to point at.
Declared in relations={accessor_name: ReverseOneToOneSpec(...)}, where
the name is the parent's reverse accessor (relations={"profile": ...}
for Author.profile). The value at data[accessor_name] reads three
ways. Omitted leaves the relation untouched. None removes the
existing row, if any, by the orphan rule below — unlike a forward
relation, this row is the parent's, so clearing the relation has to do
something about it. A mapping updates the row when the parent already
has one, and creates and links one when it does not.
The existing row is found by querying fk rather than through the reverse
accessor, so whatever the accessor had cached is a different Python object
from the one that gets written. Each of the three cases leaves the parent
agreeing with the write — pointed at the written row, or cleared where the
row was removed — so the returned instance does not read a pre-write row.
There is no match_key and no scope — the parent owns at most one row
here, so the relation itself is the match — and no mode: a one-row
relation has no orphans beyond the None case, which is explicit.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
type[Model]
|
The related model class. |
fk |
str
|
The name of that model's field pointing at the parent ( |
orphan |
RelationOrphan | str
|
What removing the row does, by
|
field_map |
dict[str, str] | None
|
Forwarded to the row's own |
exclude_fields |
list[str] | None
|
Forwarded likewise. Shaping configures the row's
write only; the row itself is found through |
m2m |
Mapping[str, Any] | Callable[[Any], Mapping[str, Any]] | None
|
Forwarded likewise. |
relations |
Mapping[str, RelationSpec] | None
|
Forwarded likewise — the row's own relations, of any kind. |
create_service |
Callable[..., Any] | None
|
Optional service replacing that call for the row, with
the contract |
update_service |
Callable[..., Any] | None
|
The same; returning |
delete_service |
Callable[..., Any] | None
|
Replaces the unlink-or-delete rule above, so the outcome
is reported as |
ManyToManySpec
dataclass
¶
Bases: RelationSpec
How to persist a many-to-many from nested rows rather than from keys.
Declared in relations={accessor_name: ManyToManySpec(...)}, where the
name is whichever side the parent reaches the relation through — the field
it declares (Post.tags) or the reverse accessor of a field declared on
the other model (Tag.posts). Either works; Django hands back the same
related manager.
Each row in data[accessor_name] is a payload, not a key: the target
row is created or updated first, and only then is the membership written
(RelationPhase.M2M, after the parent has a
primary key). That is the difference from the mutation helpers' m2m=
argument, which assigns rows that already exist and creates nothing. A
relation named by both is refused: it would be written twice and keep
whichever ran last.
An omitted relation is untouched; an explicit [] empties the membership
in "replace" mode; a list of mappings writes every target and then sets
the membership (or adds to it, in "merge" mode).
There is no delete_service: the row is shared, so a target dropped from
the relation loses only its membership and is reported under
ChildCollectionChange.unlinked, leaving
deleted empty for this kind.
A many-to-many with an explicit through model is not covered. The
loop writes target rows and lets Django write the through row, which cannot
carry the extra columns a custom through model exists for.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
type[Model]
|
The target model class. |
match_key |
str
|
The field pairing an incoming payload with an existing target
row (default |
scope |
QuerySet[Any] | Callable[..., QuerySet[Any]] | None
|
The rows this caller may update, on the terms
|
mode |
RelationMode | str
|
|
field_map |
dict[str, str] | None
|
Forwarded to the target row's own |
exclude_fields |
list[str] | None
|
Forwarded likewise. Excluding the |
m2m |
Mapping[str, Any] | Callable[[Any], Mapping[str, Any]] | None
|
Forwarded likewise — the target's own many-to-many assignments, not this relation. |
relations |
Mapping[str, RelationSpec] | None
|
Forwarded likewise — the target's own relations, of any kind. |
create_service |
Callable[..., Any] | None
|
Optional service replacing that call for a target whose
write has behaviour of its own. It receives |
update_service |
Callable[..., Any] | None
|
The same, and additionally receives |
GenericRelationSpec
dataclass
¶
Bases: RelationSpec
How to persist a GenericRelation — a collection linked by content type.
The reverse-FK collection with the foreign key replaced by a pair of columns: a
ForeignKey to ContentType saying which model the row belongs to, and an id
column saying which row. It reconciles exactly as
ChildSpec does — matched
inside the parent's own accessor, so no scope= is needed or accepted — and is
written in RelationPhase.GENERIC, once the parent's save() has given it both
a content type and a primary key.
Declared in relations={accessor_name: GenericRelationSpec(...)}, where
the name is the GenericRelation declared on the parent
(relations={"attachments": ...} for Catalog.attachments). A
relation the input omits is untouched; an explicit [] in "replace"
mode empties it.
This kind needs django.contrib.contenttypes in INSTALLED_APPS,
and nothing else in the library does. Declaring the spec is always safe;
writing one without the app installed raises
ImproperlyConfigured naming the remedy.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
type[Model]
|
The related model class — the one carrying the content-type and
id columns, e.g. |
content_type_field |
str
|
Name of the content-type column, defaulting to
Django's own |
object_id_field |
str
|
Name of the id column, defaulting to |
match_key |
str
|
The field pairing an incoming row with an existing one
(default |
mode |
RelationMode | str
|
|
orphan |
RelationOrphan | str
|
What removing a row does —
|
field_map |
dict[str, str] | None
|
Forwarded to the row's own |
exclude_fields |
list[str] | None
|
Forwarded likewise. Excluding the |
m2m |
Mapping[str, Any] | Callable[[Any], Mapping[str, Any]] | None
|
Forwarded likewise. |
relations |
Mapping[str, RelationSpec] | None
|
Forwarded likewise — the row's own relations, of any kind. |
create_service |
Callable[..., Any] | None
|
Optional service replacing that call, with the contract
|
update_service |
Callable[..., Any] | None
|
The same; returning |
delete_service |
Callable[..., Any] | None
|
Replaces the unlink-or-delete rule above, so the outcome
is reported as |
Registry¶
SpecRegistry ¶
A name -> spec map with tags, stable ordering, and filtered views.
One declaration site for the operations a project exposes over more than one transport, so the transports read one source instead of each enumerating specs and drifting. It holds only the invariant part of an operation - which spec, its canonical name, its tags; per-transport configuration stays at the binding that owns it. Adapters read a registry at configuration time to build their binding tables; nothing consults one per dispatch.
registry = SpecRegistry()
registry.register("list_orders", orders_spec, tags=("read", "public"))
registry.register("refund_order", refund_spec, tags=("write", "admin"))
public = registry.by_tag("public") # a new registry - a snapshot
There is no global registry: a consumer holds as many of its own
instances as it likes, with no shared state between them. Registries are
mutable - register adds - but every derivation (by_tag,
subset, merge, replace) returns a new registry holding a
snapshot of the selected entries, sharing the spec objects rather than
copying them.
A derived view never mutates its source, and a later register() on the
source does not appear in a view derived earlier.
register ¶
register(
name: str,
spec: ServiceSpec | SelectorSpec | SpecSource,
*,
tags: Iterable[str] = (),
) -> None
Add a spec under name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The canonical name. Must be unused in this registry - a duplicate raises rather than overwriting, so a copy-pasted declaration fails at import time instead of silently shadowing an operation. |
required |
spec
|
ServiceSpec | SelectorSpec | SpecSource
|
A |
required |
tags
|
Iterable[str]
|
Free-form labels, deduplicated into a frozen set. |
()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
TypeError
|
|
ImproperlyConfigured
|
the spec, or what it compiles to, has
|
all ¶
Every entry, in registration order, so a transport's listing is stable.
mutations ¶
The ServiceSpec entries, in registration order.
by_tag ¶
A new registry holding the entries carrying any of tags.
Union, not intersection - chain calls for an intersection
(reg.by_tag("read").by_tag("public")). No tags matches nothing.
subset ¶
A new registry holding the named entries, in the order given.
Raises:
| Type | Description |
|---|---|
KeyError
|
A name is not registered here - a typo is a configuration error, not a quietly smaller surface. |
merge ¶
A new registry combining this one with others, in order.
Names are unique per registry, so independent registries may reuse one; merging is the single place that reuse becomes a conflict.
Raises:
| Type | Description |
|---|---|
ValueError
|
The same name appears in more than one input. |
replace ¶
A new registry with spec under name in place of the spec registered there.
The entry keeps its tags and its place in the order, and every other
entry is shared, as in any view. The usual replacement is the
registered spec's own derive(...): a variant shaped for one
transport goes to the registry that transport is handed, while the
source keeps serving the base. The replacement is checked as
register checks a spec, and the entry records the spec it displaced,
so name_of answers this name for either.
Raises:
| Type | Description |
|---|---|
KeyError
|
|
TypeError
|
|
ImproperlyConfigured
|
|
name_of ¶
The name spec is registered under here, or None.
Matched by identity, never by equality: two equal declarations are two
operations. An entry matches when it holds spec or a spec it
displaced (see replace), compared as compiled, so a registered
SpecSource
matches the spec it compiles to, which is what an affordance names.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
specs ¶
A fresh name -> spec dict - the shape adapters already accept.
Each spec as registered, so an object with as_kernel_spec() is
handed back as itself; every entry point here takes it as it is.
Pass registry.specs() wherever a dict[str, spec] goes today.
Mutating the returned dict does not affect the registry.
RegisteredSpec
dataclass
¶
A spec under its canonical name, with free-form tags.
The value type held by
SpecRegistry. It
carries only the part of an operation that is invariant across
transports - which spec, what it is called, and how it is grouped.
Per-transport configuration (an HTTP view's URL kwargs, an MCP tool's
annotations, an agent adapter's own metadata) stays at the binding that
configures it, not here.
Fields:
name- the canonical name for this operation. Unique within the registry that holds it; two independent registries are separate namespaces and may reuse a name.spec- aServiceSpec(a write) or aSelectorSpec(a read), or aSpecSourcethat compiles to one, kept as registered: a transport reads the spec it runs throughkernel_spec, and the object itself is still there to be asked what only it knows. The kind is deliberately not stored as its own field: it is derived byisinstanceon the compiled spec wherever it is needed, so a stored discriminator can never drift from the object it describes.tags- a frozen set of free-form labels used to derive filtered views (registry.by_tag("public")). Tags carry boolean-ish facts -"read","admin","destructive"- that every transport can interpret in its own vocabulary.displaced- the specsSpecRegistry.replaceput this one in place of, oldest first, soname_ofstill finds the operation by the spec an affordance names when a transport's registry holds a variant.
unguarded_specs ¶
The entries of registry that any principal may run, in registry order.
Each entry is judged by the spec it compiles to, through
kernel_spec: that
is the object dispatch hands its permission checks, so a source object
declaring checks of its own is judged by what runs rather than by what it
says.
authorize runs every check in order, and the first refusal stops the
call, so a spec is unguarded only when every check it declares is an
Unrestricted - one real check beside one guards it
(test_a_real_check_beside_unrestricted_is_guarded). A subclass of
Unrestricted counts as one: it is a project's own name for the same
decision. Nothing else can leave a registered spec open, since a registry
refuses permissions=None and a spec refuses an empty sequence when it
is built; the report reads only what a registry can hold.
This says what the declaration allows, not whether a call succeeds: dispatch still refuses a deactivated principal, whatever the checks say.
The function is the one report behind the system check and the command's own listing, so the two cannot disagree.
UnguardedSpec
dataclass
¶
A registry entry whose spec any principal may run.
Fields:
name- the name the spec is registered under, which is the subcommand an operator types.reason- theUnguardedReasonits declaration falls under.
Selectors¶
shape_queryset ¶
shape_queryset(
queryset: Any,
spec: SelectorSpec | SpecSource,
pool: Mapping[str, Any],
*,
source_label: str,
) -> Any
Apply spec's shaping fields to queryset, in the fixed order.
select_related, prefetch_related and annotations run first, in
declaration order, so extend_queryset always sees the fully
declaratively-shaped queryset. extend_queryset is resolved from
{**pool, "queryset": queryset} through the same declare-to-receive rule
as every other pool-resolved callable, and its return is the shaped
queryset from here on.
It answers no affordances. Dispatch answers a selector spec's in the
same .annotate() call, with the call's registered seeds, which this is
not handed; a transport that shapes rows here and then presents them
through a spec declaring affordances is refused at present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_label
|
str
|
Named in the misconfiguration error to point at the
offending spec ( |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The shaped queryset, or |
Any
|
configured. |
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
Shaping is configured but |
TypeError
|
|
run_selector ¶
Call a selector from sync code, transparently bridging an async one.
A selector is the one callable a SelectorSpec may make async def;
every other concept in the spec is sync-only and runs in the executor. The
bridge keeps sync code from ever seeing an un-awaited coroutine.
kwargs is what the selector is called with, already bound: resolve it
from a pool first, as dispatch does.
arun_selector
async
¶
arun_selector(
fn: Callable[..., Any] | Callable[..., Awaitable[Any]], kwargs: Mapping[str, Any]
) -> Any
Call a selector from async code: an async def one is awaited, a sync one called inline.
Inline rather than in the executor, because a selector returns a queryset nobody has evaluated yet and building one runs no query. A sync selector that does query when called has to be run in the executor by its caller, as dispatch runs everything but the selector.
materialize_retrieve ¶
Collapse a RETRIEVE selector's return to the single instance, or None.
The one definition of what kind=RETRIEVE means once the selector has
run: a queryset materializes through .first() - so an author can write
selector=lambda *, pk: Model.objects.filter(pk=pk) and still get the
spec's shaping applied first - and anything else passes through as the
resolved object. What each caller does with a None differs; how the
value is arrived at does not.
Exported for a transport that runs a RETRIEVE selector without
dispatch, so the row it checks or presents is the row dispatch would
have resolved. Blocks on the query, so call amaterialize_retrieve
from a coroutine.
amaterialize_retrieve
async
¶
Async twin of materialize_retrieve, awaiting .afirst().
Separate because the materialization is the query: .first() would
block the event loop, and raises SynchronousOnlyOperation there. The
same rule otherwise; keep the two in step.
is_queryset ¶
True for Django QuerySet objects and Manager instances.
The one definition of a queryset-shaping target: what the shaping fields
may be applied to, what a RETRIEVE selector materializes from, and what
paginate_output pages by counting. Tested by type rather than by
hasattr(…, "first"), which would also match a domain object that
happens to expose first. QuerySet subclasses all pass, and every
BaseManager, so one built with BaseManager.from_queryset does too.
Selector ¶
Bases: Protocol
Any callable returning a queryset, a list or one object.
The loosest description of a SelectorSpec's selector: dispatch binds
it from the keywords it declares, drawn from the keyword pool and the reads
the spec declares, so no signature is imposed and conforming is optional.
For a typed result, use
ListSelector
or RetrieveSelector.
Runtime-checkable, and an isinstance check asks only whether the object
is callable: an async def passes it too, so it cannot tell the two
kinds apart.
AsyncSelector ¶
Bases: Protocol
The async def sibling of Selector.
A SelectorSpec's selector may be async def, and
adispatch awaits it.
To a type checker the two Protocols differ in the return, an awaitable
here. An isinstance check cannot tell them apart, since both ask only
whether the object is callable;
is_async is the run-time
question.
ListSelector ¶
Bases: Protocol[ResultT]
The structural shape of the selector of a LIST SelectorSpec.
It returns the rows, a queryset or any other iterable; a queryset is what
the spec's shaping (extend_queryset and its peers) can act on. Every
keyword arrives through **extras.
See CreateService
for **extras and strictly typed extras.
RetrieveSelector ¶
Bases: Protocol[ResultT]
The structural shape of the selector of a RETRIEVE SelectorSpec.
It returns the one row, or None for a row that is not there, which
dispatch answers as not-found unless the spec declares allow_none. A
selector returning a queryset, which dispatch collapses to its one row,
binds ResultT to the queryset's type. The lookup the spec reads -
typically pk - arrives through **extras with every other keyword.
See CreateService
for **extras and strictly typed extras.
Types¶
DispatchError ¶
Bases: Exception
A refusal made by dispatch rather than by the operation.
Deliberately not a subclass of
ServiceError, and
none of its children is one. Every consumer's exception ladder reads a
service error as a refusal the caller adapts to: an agent transport turns
one into a result the model reads and routes around while its run goes on.
A denial declared that way becomes something the model retries, and an
invalid argument set declared as a service validation error moves an MCP
server's answer from "invalid arguments" to a business-rule failure, which
is exactly the distinction that server draws by type.
So the pair says who refused: dispatch, before the operation ran, or the operation itself.
default_message is a msgid in the package's catalog, as each child's
is, and is looked up in the active language each time a refusal is built
with no message of its own. A message the caller passes is used as
given.
UnsetType ¶
Singleton sentinel type. Always falsy; identity-equal to itself only.
Don't instantiate this directly — use the module-level UNSET singleton.
UnsetType() returns that same instance, but the sentinel is the value
you compare against and UnsetType is only useful as a type annotation.
is_supplied ¶
Return True if value is anything but UNSET, None included.
A type checker narrows value to T where this returns True: a
str | None | UnsetType becomes str | None, an attribute read
(patch.bio) included. Where it returns False the value is UNSET.
supplied_fields ¶
Return data's fields whose value is not UNSET, in their order.
data is a dataclass instance or a mapping. A dataclass gives its
__init__ fields only, as the mutation helpers read it: a field declared
init=False is the dataclass's to compute, never the caller's to send.
None is a supplied value and is kept.
Shallow: a value is returned as it is, so a nested dataclass, a list of
rows or a model instance is the caller's own object, its UNSET fields
untouched. The values are typed Any because each is its own field's
type, which no dict annotation can spell per key.
Raises:
| Type | Description |
|---|---|
TypeError
|
|
TRANSPORT_KEY
module-attribute
¶
The call_context key that names the transport which built the call's context.
The transport stamps it last, over anything already there, as the plain string,
so call_context["transport"] == "agent" holds with nothing imported. Dispatch
neither writes nor reads it, and it is not a reserved name: a seed or an argument
may be called transport. A missing key means an in-process caller, or a
transport on a release that has not adopted the key yet. See
reading which transport is calling.
call_transport ¶
Return what the call's transport stamped under TRANSPORT_KEY, or None.
None means nothing stamped this context: an in-process caller, whose dict
has no such key, a transport on a release that has not adopted the key yet, or
a Validator's parameters() asked outside a call, which is handed no dict at
all, unless a transport describing a spec hands a stamped dict with no call
under way.
The stamp comes back as it was written, whatever string the transport chose,
so compare it to a plain string: call_transport(call_context) == "rest".
build_call_context ¶
build_call_context(
transport: str,
*,
base: Mapping[str, Any] | None = None,
request: Any = None,
view: Any = None,
format: str | None = None,
action: str | None = None,
) -> dict[str, Any]
Return a new call_context for one call, stamped with transport.
The dict holds every entry of base and the four standard entries,
request, view, format and action, each None where
neither base nor an argument gave one, so a stage reading
call_context["action"] gets None rather than a KeyError on any
transport that builds through this
(test_every_standard_entry_is_there_and_none_where_nothing_gave_one).
Dispatch hands a callable declaring request or view None for a
None entry, exactly as for a missing one, so filling them changes no
binding (test_with_every_standard_key_none_every_stage_is_handed_none).
Each layer wins over the one before it: the None defaults, then
base, then each argument that is not None, then transport,
written last so it replaces a transport entry base carried. An
argument left at None is not given, so it leaves base's entry
(test_a_none_argument_leaves_base_s_entry); to clear one, edit the result.
base is copied, shallowly and never mutated: its values are the very
objects it held, so a request is the request. The result is a plain dict,
a fresh one on every call and the caller's to keep: a transport that hands
one dict to every callable of a request builds it once and passes the same
object each time.
Affordance
dataclass
¶
What can be done to this object right now, declared once on the operation.
A condition on a
ServiceSpec saying
whether the operation is possible as a fact about the world: an order
that shipped cannot be cancelled, a draft with no title cannot be published,
refunds are closed while the books are. Not a fact about the caller - that is
permissions, which refuses with
NotPermitted
and is always checked first. An affordance refuses with
ActionUnavailable,
a conflict.
ServiceSpec(
service=cancel_order,
affordances=[
Affordance(
code="order_shipped",
reason="A shipped order cannot be cancelled.",
when=~Q(status="shipped"),
),
],
)
when is true when the action is available, and its type decides what
kind of condition 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 asModel.objects.filter(when)does, relations included, and is evaluated in SQL: one query for a single object, however many conditions it declares. A row is available only when the condition is true; aNULLis not true. - A callable is a condition on nothing in particular - "refunds are
closed during month-end". It is resolved through the keyword pool like any
other spec callable and returns a
bool. It is sync-only, declared withdef: it is never awaited, so anasync defone is refused when the affordance is declared. It sees the pool's seeds only:user,progressand any registered pool seed, an HTTP adapter'srequestamong them. Never the call's target or input, and never a client argument - the caller does not get to decide whether the operation is available.
A Python callable over the row is refused, and that refusal is the design. A predicate the ORM cannot read has to run once per row, which turns every list that reports availability into one query per row, and prefetching does not fix it: a prefetched relation answers some reads from its cache and silently re-queries for others. A rule that cannot be computed for fifty rows in one query is not an affordance - it stays in the service, where it is enforced and never advertised.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
str
|
Stable and machine-readable: it names the rule, never the state that tripped it, and it does not change when the sentence is reworded. What a transport or a client branches on. |
reason |
str | Promise
|
The sentence people and models both read - in a rendered
answer, and as the message of the |
when |
Any
|
The condition, as above. |
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
|
SpecLink
dataclass
¶
Bases: AffordanceDeclarer
A SelectorSpec.affordances value naming which row field fills which read of its target.
A bare ServiceSpec in the mapping means SpecLink(spec): its reads
bind by inference. A read binds to the field arguments names, else to
the output field of the same name, else, when one required read is left
and the output marks one field HANDLE, to that field (id to
pk). Optional reads bind only by name or by arguments.
affordances is the target's, so the answers, their annotations and
the schema are those of the bare spec. The inference reads the rows'
output, which a presenter may only answer once the apps are loaded, so it
is checked against a built registry by
check_links,
never here.
Attributes:
| Name | Type | Description |
|---|---|---|
spec |
AffordanceDeclarer
|
The operation the link leads to, a |
arguments |
Mapping[str, str]
|
|
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
|
ProgressReporter ¶
Bases: Protocol
How a long-running service reports how far it has got.
A dispatched callable receives one under the reserved pool seed
progress, exactly as it receives user - declare the parameter and it
arrives:
def export_invoices(*, data, progress: ProgressReporter):
rows = list(build_rows(data))
for index, row in enumerate(rows):
write(row)
progress(index + 1, total=len(rows), message="writing rows")
Reporting is always safe and never required. A transport with somewhere
to send progress passes its reporter to dispatch(progress=...); one with
nowhere to send it passes nothing, and the pool carries
null_progress
instead. So a service that declares the parameter runs unchanged on every
transport and in tests. The call takes four arguments:
progress- how far along, in whatever unit the service chose. It must increase across calls within one dispatch; a transport that forwards it is entitled to treat a decrease as a bug.total- the denominator, when it is known. Omit it rather than guessing: a receiver renders an indeterminate bar for a missing total and a wrong percentage for a wrong one.message- a short human-readable status. For a person watching, not for a machine to parse.meta- structured detail about this update (which stage, which file, how many rows have failed), so that structure need not be stringified intomessageand parsed back out at the far end.
meta is the part a receiver may not understand, and each decides
for itself: a websocket consumer forwards it into the frame the UI renders;
a receiver with nowhere to put it drops it. Never encode something the
operation's correctness depends on - it is telemetry, not a channel. And
namespace the keys if the far end might be MCP: a progress notification
carries the structure under the protocol's _meta, whose key-naming
rules reserve unprefixed names and anything under a
modelcontextprotocol / mcp prefix, so {"com.example/stage": ...}
is safe and {"stage": ...} is not portable.
Implementations must not raise. A reporter is called from inside domain code that has no reason to defend against it, and dispatch hands the caller's reporter over as it is, so a transport failing mid-report would take the service run down with it.
ProviderKeys ¶
Bases: NamedTuple
What
provider_keys
read off a kwargs= provider, before it runs.
Two disjoint sets of key names that together are every key of the
TypedDict the provider is annotated to return.
A NamedTuple so that it reads both ways its consumers read it. It still
unpacks as filled, declinable = provider_keys(spec.kwargs), which is how
the MCP server's call site reads it, and it answers .filled and
.declinable, which is what the Pydantic-AI toolset's private dataclass
offered before this replaced it. Both are held by
test_the_answer_names_its_two_sets_and_still_unpacks.
Attributes:
| Name | Type | Description |
|---|---|---|
filled |
frozenset[str]
|
The keys the provider always answers for, |
declinable |
frozenset[str]
|
The keys whose value admits |
ServerArguments
dataclass
¶
Values a transport supplies for a spec's declared parameters, and names it takes from no one.
For a mount or a toolset that knows something the caller must not choose:
the project an agent's run is scoped to, a sibling capture the caller may
not reach for instead. Each name is a parameter the spec declares, so every
reader of the call - the permission check, the selector, a kwargs
provider - sees one value, the server's.
valuesare supplied for the call and outrank the caller: whatever the caller sent under one of these names is dropped and the value here takes its place. A bound value satisfies arequiredparameter and replaces a declared default.withheldnames are neither offered nor taken: the caller's value is dropped and nothing takes its place, so the parameter is absent and the callable's own default answers, as for any argument nobody sent.
It is a value and does nothing on its own. A transport calls
check_server_arguments
once, when it is built, so a binding that cannot mean what it says fails
at startup;
apply_server_arguments
on each call, before dispatch; and subtracts
names
from the input schema it builds, beside
server_owned_keys,
so the caller is never asked for a name the server answers.
values is copied into a read-only mapping of its own when the value is
built, because the check runs once and the binding is applied on every
call after: a key added later, to the mapping a caller passed in or to the
binding's own, would reach the call unchecked. It still copies and pickles
like any other value a transport holds, rebuilt through the constructor.
It takes no part in the hash, as Parameter.default does not, so a binding is hashable
whatever its values are while equality
still compares them. withheld is held as a frozenset, a set
included, and a bare str is refused, since frozenset("pk") is a set
of characters rather than one name.
names ¶
Every name the binding takes from the caller: the bound and the withheld together.
What a transport subtracts from the properties and the required
of the input schema it advertises, so the caller is offered none of them.
OutputPage
dataclass
¶
One page of rows, plus what a caller needs to know to ask for the next.
What paginate_output
returns, and the payload
spec_output_schema(paginate=True)
describes. The schema and the shaper are one mechanism in two places, so
they are kept beside each other: a transport that wraps its pages and one
that returns a bare list, against a schema claiming the envelope for both,
is the drift this exists to prevent.
items is the slice itself, unpresented: presenting needs the spec and
belongs to the caller. Hand the presented result back to
envelope
to get the wire shape.
total_pages
property
¶
How many pages exist at this limit. At least one, even for no rows.
An empty result is one empty page rather than zero pages: page is
1-based and the page served for an empty result is 1, so reporting 0
would describe a page the caller was just handed as not existing.
envelope ¶
Wrap already-presented rows in the published paging envelope.
rendered rather than items because an audience projection lands
on the rows and never on the envelope: page, totalPages and
hasNext are this shape's own keys and belong to no Output, so a
projection walking them would look for markings that cannot exist.
ValueFormatter
dataclass
¶
One field's value, transformed for an agent audience, plus what that yields.
Attached to a
FieldMarking
and applied by the same walk that drops hidden fields and speaks choice
displays, on both sides at once:
project_payload
gives the payload render's result, and
annotate_output_schema
gives the schema produces and schema, from this one declaration.
This is generic on purpose. A formatted local timestamp is the case
that asked for it, and building that alone would have left two hard-coded,
type-specific value transforms where there was one. Money with its
currency, a duration, a percentage and a quantity with its unit are all
visible from this same spot; adding them one at a time is how a small
marking type becomes a switch statement.
timestamp
is a named constructor over the mechanism rather than a branch inside it.
money = ValueFormatter(
lambda amount: f"EUR {amount}",
produces="string",
schema={"examples": ["EUR 1240.00"]},
)
The declaration carries what it produces, and the kernel writes that
into the schema. Choice substitution cannot lie, because both sides are
derived from the same choices; a caller-supplied render can, so the
type is declared next to it rather than inferred or left to a fragment.
schema merges over the written type for description,
examples or format, and is refused if it names type: a
formatter that could contradict its own advertisement would put the
divergence between schema and payload that the projection exists to
prevent back inside a single declaration.
Naming the type without describing the string it produces was the other rejected shape: what a formatted field looks like is most of what makes it discoverable, so both halves are here.
Nothing checks render's result when it runs. produces is a
promise the author makes once, not a per-value assertion: the guarantee is
that a renderer cannot advertise one thing and declare another, not that a
misdeclared renderer is caught mid-call.
Raises:
| Type | Description |
|---|---|
ImproperlyConfigured
|
|
render
instance-attribute
¶
The transform, applied to the presented value.
Called with what the presenter returned, not with a model attribute: the
projection runs after presenting, so a date-time a
DataclassPresenter
presented arrives as its ISO-8601 string, and a decimal as its string.
Never called with None; see
apply.
produces
instance-attribute
¶
The JSON type render returns. Written into the schema by the kernel.
schema
class-attribute
instance-attribute
¶
Extra JSON Schema keywords, merged over the written type.
For saying what the produced value looks like: description,
examples, format. May not contain type.
apply ¶
render(value), except that None passes straight through.
A null is the absence of the value the formatter formats, and every
transform would otherwise have to repeat the same guard: a nullable
field is ordinary, and strftime on None raises. The schema
keeps the null on its side as well, so a nullable field stays nullable
once formatted.
json_schema ¶
The declared type, with schema merged over it.
type is written last on purpose. __post_init__ already
refuses a fragment that names it, so this can never be the thing that
decides, and that is the point: the guarantee is structural as well as
validated, rather than resting on a check somebody may one day relax.
timestamp
classmethod
¶
A date-time as a formatted local string, with an example of the shape.
OutputField(
"due_at",
"string",
format="date-time",
marking=FieldMarking(formatter=ValueFormatter.timestamp()),
)
The zone is Django's active one, and there is no way to pass
another. It is what a per-tenant middleware calling
timezone.activate() is already for, and a worker serving an agent
activates the zone itself.
A callable zone is not merely unsupported, it is impossible. A
projection is built once, where a transport registers the spec, by
audience_projection_for_spec,
and the schema it advertises is described then, before any request
exists to describe. A per-request callable would therefore resolve
differently on the two sides, which is the divergence between schema
and payload that the projection exists to prevent. The schema says a
formatted string and never names a zone, and that is what keeps it
honest.
fmt is a strftime format string and defaults to a day-first,
24-hour rendering. The example in the schema is rendered from it, so
it cannot drift from what the field actually carries.
A bare date string is read as midnight, so a date can be formatted
too: give it a fmt without a time, or the rendering invents one. A
naive date-time, as a project with USE_TZ = False has, is already
local and is formatted as it is. A value that is not a date-time, and a
string that does not read as one, passes through unchanged, for the
same reason an unrecognised choice value does: a stale or oddly-typed
row should still be reported rather than fail the call. So is a string
shaped like a date-time that names no real moment, the thirtieth of
February say, which Django's parser refuses with a ValueError: paging
would otherwise turn one row's bad data into a failed page. Declaring this on a field that
never carries a date is a
misdeclaration nothing here can detect.
NoInput ¶
Binds a Protocol's InputT for a service that reads no input.
Pair it with DeleteService,
whose data has a default, so the service leaves data out:
@implements(DeleteService[NoInput, Note, None])
def delete_note(*, instance: Note, **extras: Any) -> None: ...
Never instantiated. It exists to fill the type variable with a name that
says why it is empty, which None or Any would not.
UnguardedReason ¶
Bases: str, Enum
The declaration that leaves a spec open to every principal.
Read from authorize: every check in spec.permissions must pass, in
order, so one real check beside an Unrestricted() guards the spec, and
a spec authorizes nothing only when every check it declares is
Unrestricted. That is UNRESTRICTED, a decision somebody wrote down.
No other declaration reaches a registry unguarded. permissions=None is
refused when the spec is registered, and an empty permissions - which
every check would pass vacuously - is refused when the spec is built, so
there is no member for either.
Inheriting from str keeps the value JSON-serializable while still
behaving as a proper enum for is / ==.
RefusalFinding
dataclass
¶
One finding of
unanswered_refusals:
the refusal it is about, which kind of finding it is, and for a shadowed
row, the row that shadows it.
A value, so a transport holds its map with == () and allows a gap it
means by filtering on refusal or kind, never on the words, which
str() gives and which are free to change.
The classes are typed as any exception rather than as the kernel's two
families, because a shadowed row may name a transport's own refusal, or a
catch-all Exception above it.
RefusalFindingKind ¶
Bases: str, Enum
What a RefusalFinding found.
The thing a transport filters by when it allows a gap on purpose, beside the refusal's class, rather than by a finding's words, which stay free to change.
Inheriting from str keeps the value JSON-serializable and lets a caller
compare against the plain string, matching
SelectorKind.
UNANSWERED
class-attribute
instance-attribute
¶
Nothing in the map answers the refusal: no row, or no call.
BARE_BASE
class-attribute
instance-attribute
¶
The map answers every refusal under a base and not the base itself.
It looks complete and is not, since either family base may be raised bare: the kernel raises neither itself, but a project's own code may.
SHADOWED_ROW
class-attribute
instance-attribute
¶
A table's row never answers, because an earlier row of its own base, or of its own class, answers every refusal it names first.
Reported for a table only: a callable's branch order is code, which the transport's own branch coverage reads.
SelectorKind ¶
Bases: str, Enum
The shape a selector spec returns.
LIST returns a collection, a queryset when it can be shaped. RETRIEVE
returns one row: a queryset is materialized with .first(), and a missing
row is reported as not found unless the spec allows None.
Inheriting from str keeps the value JSON-serializable while still
behaving as a proper enum for is / ==.
FieldAudience ¶
Bases: str, Enum
Whether an output field is content, a name, a handle, or plumbing.
An operation's output is often read by more than one kind of consumer: a frontend or a command that decides its own presentation, and a model that will read the payload aloud unless told otherwise. The two want different subsets of the same fields, and the difference is not a transport difference - an MCP server and an in-process toolset want the same thing as each other and something different from a browser.
So the axis this names is audience, not protocol. Declared per field
through FieldMarking,
on the field's OutputField,
and applied only for a caller that names an audience; one that names none
keeps presenting every field.
Inheriting from str keeps the value JSON-serializable and print-friendly
while still behaving as a proper enum for is / ==.
CONTENT
class-attribute
instance-attribute
¶
The default: ordinary data, shown to every consumer.
LABEL
class-attribute
instance-attribute
¶
The field that names this record for a human. At most one per output, and two are refused when the output is read into a projection.
HANDLE
class-attribute
instance-attribute
¶
An opaque identifier. Passed to other tools, never read out to a user, and never re-spelled by a choice's display - a handle is somebody else's input.
HIDDEN
class-attribute
instance-attribute
¶
Plumbing. Dropped from the projected payload and from the projected schema.
UnknownArguments ¶
Bases: str, Enum
The closed argument set's policy, applied at every level of nesting.
REJECT is the default everywhere. An untrusted caller's undeclared key
is refused before it costs a query, and a trusted one's typo - a command's
misspelt option, a task enqueued with last month's argument name - fails
where the caller can see it rather than being dropped on the floor.
There is no pass-through policy. An undeclared argument reaching a
callable is exactly what the closed set exists to prevent: on a selector,
with no Validator in front of it, it would let a caller supply a keyword
the operation's author never offered. PASSTHROUGH is a member and not
a policy, and every function taking one refuses it.
REJECT
class-attribute
instance-attribute
¶
Refuse the undeclared key with InvalidArguments, at the level it appeared.
PASSTHROUGH
class-attribute
instance-attribute
¶
Kept as a name, and refused as a policy.
It is here for the current release of djangorestframework-services, whose
published transports compare a policy against it by identity: with the
member, that comparison is false for either policy, where its absence
would raise AttributeError. It is never run.
check_arguments
and
parameters_schema
raise ValueError for it where they read the policy, so dispatch,
adispatch, check_call, bind_arguments and spec_input_schema
refuse it too, rather than running it as IGNORE.
RelationMode ¶
Bases: str, Enum
How a relation reconciles the rows the payload leaves out.
Shared by every kind that reconciles a collection, so the two words mean the same thing on all of them. What "dispose of" means is the kind's own business — a child row is unlinked or deleted, a many-to-many target is only dropped from the relation — but when it happens is this one flag.
Inheriting from str keeps the value JSON-serializable and means a plain
string works wherever the member does, in a comparison and as an argument.
RelationOrphan ¶
Bases: str, Enum
How a relation disposes of a row it no longer holds.
Shared by the kinds that own their rows — a reverse-FK collection, a
generic relation, a reverse one-to-one — so the word means the same thing on
all three. It answers what happens to a row that is let go;
RelationMode answers when a row is let go at all, and the two are
independent knobs on purpose.
The default derives the answer from the schema. The other two exist because
a derived answer is not a stated one: whether the link can hold NULL is
a fact about a column, and a migration adding null=True later would
silently turn a replace that deleted into one that unlinks, with nothing
in the spec — or in its tests — changing to say so. A spec that means to
delete says so.
Inheriting from str keeps the value JSON-serializable and means a plain
string works wherever the member does, matching RelationMode and
RelationOutcome.
AUTO
class-attribute
instance-attribute
¶
Derive it from the link: unlink when it can hold NULL, else delete.
Mirroring on_delete=SET_NULL versus CASCADE, which is the better
default because it honours what the model already declares.
UNLINK
class-attribute
instance-attribute
¶
Always blank the row's link to the parent and leave the row standing.
Refused when the link cannot hold NULL — there is nothing to blank, and
deleting the row instead would be the opposite of what was asked.
DELETE
class-attribute
instance-attribute
¶
Always delete the row, whether or not its link could have been blanked.
RelationPhase ¶
Bases: IntEnum
The slot in the write sequence a relation kind belongs to.
A nested write cannot honour the order the relations= mapping happens
to be spelled in: a forward foreign key has to be resolved before the
parent row exists, and a many-to-many has to be assigned after it does.
So the order is a property of the relation kind — each spec class
declares its phase as a write_phase class attribute (see
RelationSpec) and the
driver walks the phases in this enum's order, never the mapping's:
FORWARD— the FK column lives on the parent, so the target row must exist before the parent is saved. Writing it first also means the assignment is an ordinary column change, picked up by the same diff andupdate_fieldsmachinery as any other field.- the parent's
save()— not a phase; the boundary the phases are named around. REVERSE— the FK column lives on the other row (reverse FK collections and reverse one-to-ones), so the parent must have a primary key to point at.GENERIC— generic relations, which need the saved parent's content type and primary key.M2M— through-table writes, which need both rows saved.
Declaration order still decides everything the phases leave open: two relations in the same phase are written in the order they were declared.
The member values order the phases and nothing else; compare and sort by the members, never by the numbers.
RelationOutcome ¶
Bases: str, Enum
The single fact a
RelatedObjectChange
reports.
A collection reports five tuples of primary keys, which is the honest shape for many rows and a poor one for a relation that holds exactly one: every tuple would be empty or a one-tuple, and "which of the five is non-empty" is a worse way to say what happened than saying it. So only the one-row kinds report an outcome — a forward relation and a reverse one-to-one — and a collection, many-to-many included, reports its tuples.
Inheriting from str keeps the value JSON-serializable and lets a caller
compare against the plain string, matching
SelectorKind.
UNTOUCHED
class-attribute
instance-attribute
¶
Nothing was written to the relation.
The input omitted it, or set a reverse one-to-one that holds no row to
None. It is the one outcome for which a
RelatedObjectChange
is falsy.
UPDATED
class-attribute
instance-attribute
¶
An existing row was matched and written.
CLEARED
class-attribute
instance-attribute
¶
A forward relation was set to None.
The parent's foreign-key column is assigned None and the row it pointed
at, if any, is not touched, because a forward target is not owned by the
parent and may be shared. The change carries no primary key: nothing
happened to a row. It is reported whether or not the column held a value;
whether the column moved is ChangeResult.changes' to say.
UNLINKED
class-attribute
instance-attribute
¶
A reverse one-to-one row was kept and its foreign key set to None.
Mirroring on_delete=SET_NULL. The spec's orphan decides between this
and DELETED: "unlink" always, "auto" when the foreign key is
nullable. A member a many-to-many drops is not reported here: that kind is a
collection, so the member's pk lands in
ChildCollectionChange.unlinked.
DELETED
class-attribute
instance-attribute
¶
A reverse one-to-one row was deleted.
Mirroring on_delete=CASCADE. The spec's orphan decides between this
and UNLINKED: "delete" always, whether or not the foreign key could
have been blanked, and "auto" when it is not nullable.
REMOVED
class-attribute
instance-attribute
¶
A row was handed to the spec's delete_service.
Deliberately not DELETED. Once a service owns the row the loop no
longer knows whether it was deleted, archived, unlinked or left standing,
and reporting a guess as fact is worse than reporting the one thing that is
true: the loop removed the row from the relation and a service decided the
rest.
is_async ¶
Return True if calling fn(...) produces a coroutine.
Handles plain async def functions, functools.partial wrapping
one (via inspect.iscoroutinefunction's built-in unwrapping), and
any callable whose __call__ is a coroutine function.