Storages#

The contract between the server and the data of an application, and the storages that keep the resources in memory.

class scim2_server.storage.ScimStorage[source]#

Where a SCIM server reads and writes its resources.

Subclass it to connect the server to a data source, such as a SQL database or a directory. The server handles the SCIM protocol, and calls these methods to read, search, create, update and delete resources. Every method receives the ResourceType it applies to, so a single storage can serve several resource types.

A storage follows these rules, which ScimStorageContract checks:

  • Every resource it returns is a copy. Changing it does not change the stored resource, and the resources it receives are not changed either.

  • It fills id, meta.resourceType and meta.version. It fills meta.created and meta.lastModified when it stores them, and leaves them empty otherwise. It leaves meta.location to the server, which knows the URLs. For the same reason, a reference to another resource, such as members.$ref, can be relative to the SCIM root, such as Users/2819c223. The server returns its URL.

  • The version changes whenever the resource changes. An update that changes nothing may keep it.

  • A resource that does not exist raises NotFoundException.

  • A value already taken by an attribute whose uniqueness is server or global raises UniquenessException. This holds for sub-attributes too, such as emails.value. Each value of a multi-valued attribute counts on its own. The uniqueness holds within a resource type. A storage on a database relies on its unique constraints, and turns their violations into the exception. The constraint should find equal the values the filters find equal, and the storage documents the differences. A resource keeping its values, or swapping them between its entries, is written.

  • It supports what the ServiceProviderConfig of the server announces, such as sorting. The server refuses the rest before calling the storage.

supports_cursors: bool = False#

Whether search() pages the resources with cursors that give stable pages.

Set it to True once search() follows the rules of the cursors. The server refuses to start when its configuration announces cursor pagination and the storage does not support it.

abstractmethod get(resource_type: ResourceType, resource_id: str, *, response_parameters: ResponseParameters[Any] | None = None) → Resource[source]#

Return a resource.

The server passes response_parameters when it returns the resource to the client, for a GET request. The storage may then leave out the attributes the response does not keep, for instance to avoid loading the members of a group. It must return every attribute the response keeps. Path.iter_paths gives them. The server applies the parameters to the response anyway. Without response_parameters, the storage returns the whole resource.

The whole resource holds the write-only and never returned attributes, such as password, in the form the storage keeps them, a hash for instance. The server never returns them to the client (RFC 7643 §2.2). It needs them to keep a value that a PUT leaves out (RFC 7644 §3.5.1), and to clear one that a PATCH removes (RFC 7644 §3.5.2.2).

A get method without response_parameters is deprecated, and raises a DeprecationWarning. The server then does not pass the parameters. scim2-server 0.9 will require it.

Raises:

NotFoundException – When no resource of this type has this identifier.

abstractmethod search(resource_types: list[ResourceType], search_request: SearchRequest[Any], *, position: Any = None) → SearchPage[source]#

Return one page of the matching resources, and their number.

The search request is already validated, and its count is already bounded by the maxResults of the server. The storage filters, sorts and pages the resources of every given resource type as a single collection. Several resource types mean a search at the server root.

An attribute that a resource type does not declare matches none of its resources (RFC 7644 §3.4.2.1).

A start_index pages the resources by index. A cursor that is not None pages them with a cursor (RFC 9865), when the storage supports_cursors. The storage then returns the next and previous positions of the page, as values that JSON can hold. The server hides them in the cursors it gives the client, and passes them back as position. position is None on the first page.

The cursors give stable pages. A position holds the sort value and the identifier of the last resource of the page, or of the first one for the previous page. A resource that exists during the whole paging, and whose sort value does not change, is returned exactly once. A resource created or deleted meanwhile is returned or not, depending on where it sorts.

A search method without position is deprecated, and raises a DeprecationWarning. It returns the number of matching resources and the page, and pages by index only. scim2-server 0.9 will require position.

Raises:
abstractmethod create(resource_type: ResourceType, resource: Resource) → Resource[source]#

Store a new resource, and return the stored resource.

Raises:

UniquenessException – When a unique value is taken.

abstractmethod update(resource_type: ResourceType, resource: Resource, *, expected_version: str | None = None) → Resource[source]#

Replace the stored resource that has the identifier of resource, and return the stored resource.

The server calls it for PUT and PATCH requests. It applies the request to the stored resource first, so resource is the whole new state of the resource.

A write-only or never returned value that get() returned comes back unchanged when the request does not change it. The storage keeps it as it is, and does not hash it again. It clears the value when it comes back as None.

Parameters:

expected_version – The version the stored resource must still have, when given.

Raises:
abstractmethod delete(resource_type: ResourceType, resource_id: str, *, expected_version: str | None = None) → None[source]#

Delete a resource.

Parameters:

expected_version – The version the stored resource must still have, when given.

Raises:
operation() → AbstractContextManager[None][source]#

Enclose one SCIM operation: a single request, or one operation of a bulk request.

It does nothing by default. A SQL storage can open a savepoint here, so that a failed operation does not prevent the next ones of a bulk request (RFC 7644 §3.7). Committing the request is left to the application. The following storage opens a SQLAlchemy savepoint:

>>> class SQLStorage(ScimStorage):
...     def operation(self):
...         return self.session.begin_nested()

Write a storage describes the other methods.

class scim2_server.storage.AsyncScimStorage[source]#

The asynchronous variant of ScimStorage.

Its methods are coroutines, and follow the rules of ScimStorage, which AsyncScimStorageContract checks.

supports_cursors: bool = False#

Whether search() pages the resources with cursors that give stable pages. See ScimStorage.supports_cursors.

abstractmethod async get(resource_type: ResourceType, resource_id: str, *, response_parameters: ResponseParameters[Any] | None = None) → Resource[source]#

Return a resource. See ScimStorage.get().

abstractmethod async search(resource_types: list[ResourceType], search_request: SearchRequest[Any], *, position: Any = None) → SearchPage[source]#

Return one page of the matching resources, and their number. See ScimStorage.search().

abstractmethod async create(resource_type: ResourceType, resource: Resource) → Resource[source]#

Store a new resource. See ScimStorage.create().

abstractmethod async update(resource_type: ResourceType, resource: Resource, *, expected_version: str | None = None) → Resource[source]#

Replace a stored resource. See ScimStorage.update().

abstractmethod async delete(resource_type: ResourceType, resource_id: str, *, expected_version: str | None = None) → None[source]#

Delete a resource. See ScimStorage.delete().

operation() → AbstractAsyncContextManager[None][source]#

Enclose one SCIM operation. See ScimStorage.operation().

class scim2_server.storage.SearchPage(total: int | None, resources: list[Resource], next: Any = None, previous: Any = None)[source]#

A page of found resources, as ScimStorage.search() returns it.

total: int | None#

The number of matching resources, on every page.

It may be None when the resources are paged with a cursor (RFC 9865 §2).

resources: list[Resource]#

The resources of the page.

next: Any = None#

The position of the next page, or None on the last page.

previous: Any = None#

The position of the previous page, or None on the first page.

scim2_server.storage.uniqueness_conflict(attribute: AttributeBinding) → UniquenessException[source]#

Return the 409 refusing a value that another resource holds, for one of the unique_attributes().

The detail tells the attribute, but never the value. An attribute of the schema of the resource is told by its path, such as emails.value. An attribute of an extension is told by its URN.

>>> from scim2_models import Path, User
>>> uniqueness_conflict(Path[User]("emails.value").resolve()).detail
'Uniqueness conflict with attribute emails.value'
class scim2_server.memory.InMemoryStorage(clock: Callable[[], ~datetime.datetime]=<function utcnow>)[source]#

A storage keeping the resources in memory, for tests, debugging and demos.

It indexes the resources by identifier and the unique values. A unique value is unique within its resource type, as a database does with a unique constraint on a table. A search walks every resource of the searched types, unless it compares a single string attribute to a string with eq. A lock serializes every access, so it can serve a threaded server.

It indexes the values under the policy in effect when they were written, so it serves the resources of a single policy.

Parameters:

clock – Return the date of a write, for meta.created and meta.lastModified. Pass a fixed clock to get predictable dates.

generate_id(resource_type: ResourceType, resource: Resource) → str | None[source]#

Return the identifier of a new resource, or None to let the storage draw one.

Override this method to choose the identifiers. The following storage numbers the resources from 1:

>>> from itertools import count
>>> class NumberedStorage(InMemoryStorage):
...     def __init__(self):
...         super().__init__()
...         self.ids = count(1)
...
...     def generate_id(self, resource_type, resource):
...         return str(next(self.ids))
>>> storage = NumberedStorage()
>>> storage.generate_id(None, None), storage.generate_id(None, None)
('1', '2')

The storage calls it once for each new resource, after checking its unique values, so a refused resource gets no identifier. An identifier that another resource of the same resource type holds raises UniquenessException.

next_version() → str[source]#

Return the version of a new write.

Versions come from a counter, so two writes never share a version, even within the same microsecond.

operation() → Generator[None][source]#

Hold the lock for the whole operation.

class scim2_server.memory.AsyncInMemoryStorage(storage: InMemoryStorage | None = None)[source]#

The asynchronous variant of InMemoryStorage.

It serves the resources of an InMemoryStorage. Every call runs without awaiting anything but generate_id(), so a call is never interrupted by another coroutine while it reads or writes the resources. operation() takes no lock: holding the lock of the storage across an await would block the event loop. Two concurrent updates of a resource are still told apart by expected_version.

Parameters:

storage – The storage to serve. Its generate_id() gives the identifiers, unless generate_id() is overridden. Its other methods serve the requests, except create: a new resource goes through generate_id() instead.

property resources: list[Resource]#

The stored resources.

async generate_id(resource_type: ResourceType, resource: Resource) → str | None[source]#

Return the identifier of a new resource, or None to let the storage draw one.

It returns what InMemoryStorage.generate_id() returns. Override it with an async def method to choose the identifiers. It can await, for instance to create the account in another service and take its identifier. The storage checks the unique values again once it returns. A write refused then, because another resource took a value in the meantime, does not undo what the method did.

Keyset pagination#

Helpers for a storage that pages with cursors by keyset.

A keyset storage orders the rows by the sort value, then by identifier. A position holds the sort value and the identifier of the row a page starts after, or ends before. These helpers read and write such positions, and build the pages around them. A storage may use its own positions instead.

scim2_server.keyset.encode_sort_value(value: Any) → Any[source]#

Return a sort value as a value JSON can hold.

None, booleans, numbers and strings are returned as they are. A datetime, a date, a Decimal or a UUID is returned as an object with a tag, such as {"date": "2026-10-09"}, so that decode_sort_value() gives it back in its own type.

Raises:

TypeError – if the value has another type.

scim2_server.keyset.decode_sort_value(value: Any) → Any[source]#

Return the sort value that encode_sort_value() gave.

Raises:

InvalidCursorException – if no sort value gives this value.

class scim2_server.keyset.Position(forward: bool, key: Any, id: str, type_index: int | None = None)[source]#

The row a cursor page starts after, or ends before.

The rows with the same sort value are ordered by identifier. In a search at the root, a storage may order them by the index of their resource type first, so that two resources of different types can share an identifier.

forward: bool#

Whether the page starts after the row, rather than ending before it.

key: Any#

The sort value of the row, or None when it has none, or when the search has no sort.

id: str#

The identifier of the resource of the row.

type_index: int | None = None#

The index of the resource type of the row, in a search at the root that orders the rows by resource type.

classmethod load(value: Any, *, has_sort: bool, type_count: int | None = None) → Position | None[source]#

Read a position that dump() wrote, or return None for the first page.

has_sort tells whether the search has a sort. Without one, the position holds no sort value.

type_count is the number of resource types that the storage orders the rows by. A storage that does not order the rows by resource type leaves it out. The position holds the index of a resource type when type_count is given, and holds none otherwise. dump() writes this index when type_index is not None.

Raises:

InvalidCursorException – if the value is not such a position.

dump() → dict[str, Any][source]#

Return the position as a value JSON can hold.

Raises:

TypeError – if encode_sort_value() cannot hold the sort value.

class scim2_server.keyset.Bound(key: Any, id: str, type_index: int | None = None)[source]#

The first or the last row of a page, as keyset_page() needs it.

key: Any#

The sort value of the row, or None when it has none, or when the search has no sort.

id: str#

The identifier of the resource of the row.

type_index: int | None = None#

The index of the resource type of the row, in a search at the root that orders the rows by resource type.

scim2_server.keyset.page_rows(rows: Sequence[Any], search_request: SearchRequest[Any], position: Position | None) → tuple[list[Any], bool][source]#

Return the rows of a page in the sort order, and whether more rows follow in the reading direction.

For a cursor page, the storage reads count + 1 rows, in the reverse order for a page that ends before the position. Without a cursor, the rows are returned as they are.

scim2_server.keyset.keyset_page(total: int | None, resources: Sequence[Resource], first: Bound | None, last: Bound | None, more: bool, position: Position | None) → SearchPage[source]#

Return a cursor page, with the positions of the pages around it.

first and last are the first and the last rows of the page, or None when the page is empty. more tells whether more rows follow in the reading direction, as page_rows() gives it. In the other direction, the page the client comes from is assumed to still exist.