ifdd-be-core 26.10.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. ifdd/be/core/__init__.py +13 -0
  2. ifdd/be/core/app.py +134 -0
  3. ifdd/be/core/auth/__init__.py +21 -0
  4. ifdd/be/core/auth/oidc.py +273 -0
  5. ifdd/be/core/cache_meta.py +160 -0
  6. ifdd/be/core/config.py +184 -0
  7. ifdd/be/core/contexts.py +192 -0
  8. ifdd/be/core/db/__init__.py +12 -0
  9. ifdd/be/core/db/base.py +10 -0
  10. ifdd/be/core/db/session.py +163 -0
  11. ifdd/be/core/docs_assets/assets.json +34 -0
  12. ifdd/be/core/docs_assets/ifdd/docs.css +6 -0
  13. ifdd/be/core/docs_assets/ifdd/swagger-init.js +52 -0
  14. ifdd/be/core/docs_assets/redoc/LICENSE +22 -0
  15. ifdd/be/core/docs_assets/redoc/redoc.standalone.js +1851 -0
  16. ifdd/be/core/docs_assets/redoc/redoc.standalone.js.LICENSE.txt +102 -0
  17. ifdd/be/core/docs_assets/swagger-ui/LICENSE +202 -0
  18. ifdd/be/core/docs_assets/swagger-ui/NOTICE +2 -0
  19. ifdd/be/core/docs_assets/swagger-ui/oauth2-redirect.js +1 -0
  20. ifdd/be/core/docs_assets/swagger-ui/swagger-ui-bundle.js +2 -0
  21. ifdd/be/core/docs_assets/swagger-ui/swagger-ui-bundle.js.LICENSE.txt +129 -0
  22. ifdd/be/core/docs_assets/swagger-ui/swagger-ui.css +3 -0
  23. ifdd/be/core/docs_ui.py +194 -0
  24. ifdd/be/core/graph.py +124 -0
  25. ifdd/be/core/helper.py +20 -0
  26. ifdd/be/core/jsonld.py +65 -0
  27. ifdd/be/core/logging.py +42 -0
  28. ifdd/be/core/models.py +175 -0
  29. ifdd/be/core/openapi.py +417 -0
  30. ifdd/be/core/presentation.py +62 -0
  31. ifdd/be/core/repository.py +308 -0
  32. ifdd/be/core/routers/__init__.py +17 -0
  33. ifdd/be/core/routers/aspects.py +162 -0
  34. ifdd/be/core/routers/graph_data.py +99 -0
  35. ifdd/be/core/routers/node_types.py +81 -0
  36. ifdd/be/core/routers/nodes.py +363 -0
  37. ifdd/be/core/routers/params.py +123 -0
  38. ifdd/be/core/routers/scopes.py +81 -0
  39. ifdd/be/core/routers/versions.py +107 -0
  40. ifdd/be/core/schemas.py +93 -0
  41. ifdd/be/core/temporal.py +200 -0
  42. ifdd/be/core/tools/__init__.py +1 -0
  43. ifdd/be/core/tools/schema.py +108 -0
  44. ifdd/be/core/version.py +30 -0
  45. ifdd/be/core/writes.py +242 -0
  46. ifdd_be_core-26.10.2.dist-info/METADATA +539 -0
  47. ifdd_be_core-26.10.2.dist-info/RECORD +51 -0
  48. ifdd_be_core-26.10.2.dist-info/WHEEL +5 -0
  49. ifdd_be_core-26.10.2.dist-info/entry_points.txt +3 -0
  50. ifdd_be_core-26.10.2.dist-info/licenses/LICENSE +29 -0
  51. ifdd_be_core-26.10.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,13 @@
1
+ """ifdd.be.core - shared runtime for IFDD JSON-LD micro services."""
2
+
3
+ from .app import create_app
4
+ from .config import CoreSettings, configure, get_settings
5
+ from .version import __version__
6
+
7
+ __all__ = [
8
+ "create_app",
9
+ "CoreSettings",
10
+ "configure",
11
+ "get_settings",
12
+ "__version__",
13
+ ]
ifdd/be/core/app.py ADDED
@@ -0,0 +1,134 @@
1
+ """Application factory.
2
+
3
+ An instance calls :func:`create_app` after registering its own settings. The
4
+ factory owns everything that was previously written out at module level in the
5
+ generated ``main.py``: middleware, CORS, the documentation pages, the OpenAPI
6
+ document and the router wiring.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from contextlib import asynccontextmanager
12
+ from typing import Iterable, Optional
13
+
14
+ from fastapi import FastAPI
15
+ from fastapi.middleware.cors import CORSMiddleware
16
+ from fastapi.routing import APIRouter
17
+ from slowapi import Limiter
18
+ from slowapi.errors import RateLimitExceeded
19
+ from slowapi.util import get_remote_address
20
+ from starlette.middleware.sessions import SessionMiddleware
21
+ from starlette.requests import Request
22
+ from starlette.responses import JSONResponse
23
+
24
+ from .config import CoreSettings, configure, get_settings
25
+ from .docs_ui import install_docs
26
+ from .jsonld import install_document_loader
27
+ from .logging import setup_logger
28
+ from .openapi import build_openapi
29
+ from .routers import (
30
+ build_aspect_router,
31
+ graph_data_router,
32
+ nodes_router,
33
+ scopes_router,
34
+ types_router,
35
+ versions_router,
36
+ )
37
+ from .version import __version__
38
+
39
+
40
+ def create_app(
41
+ settings: Optional[CoreSettings] = None,
42
+ extra_routers: Optional[Iterable[APIRouter]] = None,
43
+ ) -> FastAPI:
44
+ """Create and wire the FastAPI application.
45
+
46
+ Args:
47
+ settings: Settings of the instance. They are registered with
48
+ :func:`~ifdd.be.core.config.configure`; without them the settings
49
+ are read from the environment.
50
+ extra_routers: The extension point for instance-specific endpoints
51
+ that must not live in the shared core. They are included after
52
+ the generic routers and before the catch-all document routes.
53
+
54
+ Returns:
55
+ The application, ready for uvicorn (``uvicorn --factory
56
+ ifdd.be.core:create_app`` or an instance's ``app.main:app``).
57
+ """
58
+ if settings is not None:
59
+ configure(settings)
60
+ settings = get_settings()
61
+
62
+ logger = setup_logger(__name__)
63
+ install_document_loader()
64
+ logger.info(
65
+ f"Starting {settings.API_TITLE} {settings.IFDD_BE_VERSION} (ifdd-be-core {__version__})"
66
+ )
67
+
68
+ @asynccontextmanager
69
+ async def lifespan(_: FastAPI):
70
+ """Close the database engine when the application stops."""
71
+ yield
72
+ from .db.session import _session_manager
73
+
74
+ if _session_manager is not None:
75
+ await _session_manager.close()
76
+
77
+ # FastAPI's own /docs and /redoc pages use inline scripts and a CDN; the
78
+ # pages of docs_ui replace them (see that module).
79
+ app = FastAPI(
80
+ title=settings.API_TITLE,
81
+ version=settings.IFDD_BE_VERSION,
82
+ debug=settings.DEBUG,
83
+ lifespan=lifespan,
84
+ docs_url=None,
85
+ redoc_url=None,
86
+ swagger_ui_oauth2_redirect_url=None,
87
+ )
88
+
89
+ app.add_middleware(
90
+ SessionMiddleware,
91
+ https_only=settings.IFDD_BE_SSL_ENABLED,
92
+ secret_key=settings.FASTAPI_SECRET_KEY,
93
+ )
94
+
95
+ logger.debug(f"Allowed origins: {settings.IFDD_CORS_ORIGINS}")
96
+ app.add_middleware(
97
+ CORSMiddleware,
98
+ allow_origins=settings.IFDD_CORS_ORIGINS,
99
+ allow_credentials=True,
100
+ allow_methods=["*"],
101
+ allow_headers=["*"],
102
+ expose_headers=["X-Total-Count", "Content-Range"],
103
+ )
104
+
105
+ limiter = Limiter(key_func=get_remote_address)
106
+ app.state.limiter = limiter
107
+ app.add_exception_handler(RateLimitExceeded, _rate_limit_handler)
108
+
109
+ # Before every router: /docs/oauth2-redirect has two path segments and
110
+ # would otherwise be taken by GET /{node_aspect}/{node_id}.
111
+ install_docs(app, settings)
112
+
113
+ app.include_router(versions_router)
114
+ app.include_router(types_router)
115
+ app.include_router(scopes_router)
116
+ app.include_router(graph_data_router)
117
+ app.include_router(build_aspect_router(settings.IFDD_ASPECTS))
118
+ for router in extra_routers or ():
119
+ app.include_router(router)
120
+ # The catch-all /{node_aspect}/{node_id} routes are registered last so that
121
+ # they never shadow a more specific path.
122
+ app.include_router(nodes_router)
123
+
124
+ app.openapi = build_openapi(app, settings)
125
+ return app
126
+
127
+
128
+ def _rate_limit_handler(request: Request, exc: RateLimitExceeded) -> JSONResponse:
129
+ """Answer 429 when a slowapi limit is exceeded.
130
+
131
+ No route carries a limit at the moment; the handler is kept for instance
132
+ routers that add one.
133
+ """
134
+ return JSONResponse(status_code=429, content={"message": "Rate limit exceeded"})
@@ -0,0 +1,21 @@
1
+ """OIDC access-token validation and the role checks used as FastAPI dependencies."""
2
+
3
+ from .oidc import (
4
+ get_oauth2_scheme,
5
+ nodes_read_auth,
6
+ nodes_write_auth,
7
+ optional_auth,
8
+ public_auth,
9
+ require_roles,
10
+ valid_access_token,
11
+ )
12
+
13
+ __all__ = [
14
+ "get_oauth2_scheme",
15
+ "nodes_read_auth",
16
+ "nodes_write_auth",
17
+ "optional_auth",
18
+ "public_auth",
19
+ "require_roles",
20
+ "valid_access_token",
21
+ ]
@@ -0,0 +1,273 @@
1
+ """OIDC bearer-token validation.
2
+
3
+ Both the security scheme and the token cache are built on first use so that
4
+ importing this module never touches the settings. This keeps import order
5
+ irrelevant for instances that register their own settings subclass.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from functools import wraps
11
+ from typing import Annotated, Callable, List, Optional, Union
12
+
13
+ import jwt
14
+ from cachetools import TTLCache
15
+ from fastapi import Depends, HTTPException
16
+ from fastapi.security import OAuth2AuthorizationCodeBearer
17
+ from jwt import PyJWKClient
18
+ from starlette.requests import Request
19
+
20
+ from ..config import get_settings
21
+ from ..logging import setup_logger
22
+
23
+ logger = setup_logger(__name__)
24
+
25
+ RoleSpec = Union[List[str], Callable[["object"], List[str]]]
26
+
27
+ # Value of the claim "typ" in Keycloak access tokens.
28
+ ACCESS_TOKEN_TYPE = "Bearer"
29
+
30
+
31
+ def _resolve_roles(spec: Optional[RoleSpec], settings) -> List[str]:
32
+ """The role names of a role spec: a list, or a callable of the settings."""
33
+ if spec is None:
34
+ return []
35
+ if callable(spec):
36
+ return list(spec(settings))
37
+ return list(spec)
38
+
39
+
40
+ _scheme: Optional[OAuth2AuthorizationCodeBearer] = None
41
+ _token_cache: Optional[TTLCache] = None
42
+
43
+
44
+ def get_oauth2_scheme() -> OAuth2AuthorizationCodeBearer:
45
+ """The bearer-token extractor, built from the settings on first use.
46
+
47
+ It reads ``Authorization: Bearer <token>``. With auth enabled a missing
48
+ header answers 401; with auth off it returns None.
49
+ """
50
+ global _scheme
51
+ if _scheme is None:
52
+ settings = get_settings()
53
+ _scheme = OAuth2AuthorizationCodeBearer(
54
+ tokenUrl=settings.IFDD_OIDC_TOKEN_URL,
55
+ authorizationUrl=settings.IFDD_OIDC_AUTHORIZATION_URL,
56
+ refreshUrl=settings.IFDD_OIDC_REFRESH_URL,
57
+ auto_error=settings.IFDD_BE_AUTH_ENABLED,
58
+ )
59
+ return _scheme
60
+
61
+
62
+ class _LazyOAuth2Scheme:
63
+ """Dependency wrapper that defers scheme construction to request time."""
64
+
65
+ async def __call__(self, request: Request) -> Optional[str]:
66
+ """The bearer token of the request (see :func:`get_oauth2_scheme`)."""
67
+ return await get_oauth2_scheme()(request)
68
+
69
+
70
+ oauth_2_scheme = _LazyOAuth2Scheme()
71
+
72
+
73
+ def _get_token_cache() -> TTLCache:
74
+ """Validated tokens by their text.
75
+
76
+ Holds ``IFDD_TOKEN_CACHE_SIZE`` entries for ``IFDD_TOKEN_CACHE_TTL`` seconds.
77
+ """
78
+ global _token_cache
79
+ if _token_cache is None:
80
+ settings = get_settings()
81
+ _token_cache = TTLCache(
82
+ maxsize=settings.IFDD_TOKEN_CACHE_SIZE, ttl=settings.IFDD_TOKEN_CACHE_TTL
83
+ )
84
+ return _token_cache
85
+
86
+
87
+ def ttl_cache(func):
88
+ """Cache the result of an async token check per token text.
89
+
90
+ A token is checked against the JWKS once and then served from the cache
91
+ until the cache entry expires. The cache lifetime does not extend a
92
+ token: an expired token in the cache is still answered from it until the
93
+ entry ends, at most ``IFDD_TOKEN_CACHE_TTL`` seconds.
94
+ """
95
+
96
+ @wraps(func)
97
+ async def wrapper(access_token, *args, **kwargs):
98
+ """Answer from the cache, or check the token and remember the result."""
99
+ cache = _get_token_cache()
100
+ if access_token in cache:
101
+ logger.debug("Token cache hit")
102
+ return cache[access_token]
103
+ result = await func(access_token, *args, **kwargs)
104
+ cache[access_token] = result
105
+ logger.debug("Token cache miss")
106
+ return result
107
+
108
+ return wrapper
109
+
110
+
111
+ _issuer_warning_logged = False
112
+
113
+
114
+ def _warn_once_without_issuer(settings) -> None:
115
+ """Log once per process that the token issuer is not checked."""
116
+ global _issuer_warning_logged
117
+ if not settings.IFDD_OIDC_ISSUER and not _issuer_warning_logged:
118
+ logger.warning("IFDD_OIDC_ISSUER is not set: the token issuer is not checked")
119
+ _issuer_warning_logged = True
120
+
121
+
122
+ @ttl_cache
123
+ async def valid_access_token(access_token: Annotated[str, Depends(oauth_2_scheme)]):
124
+ """Validate an access token and return its claims.
125
+
126
+ Checks the signature against the realm's JWKS, the expiry, the audience
127
+ ``IFDD_OIDC_JWKS_AUDIENCE``, the issuer ``IFDD_OIDC_ISSUER`` (if set)
128
+ and that ``typ`` is ``Bearer`` (RFC 9068: ID tokens are refused).
129
+
130
+ Args:
131
+ access_token: The bearer token of the request.
132
+
133
+ Returns:
134
+ The decoded claims.
135
+
136
+ Raises:
137
+ HTTPException: 401 with the reason for any failed check.
138
+ """
139
+ settings = get_settings()
140
+ jwks_client = PyJWKClient(
141
+ settings.IFDD_OIDC_JWKS_URL, headers={"User-agent": "custom-user-agent"}
142
+ )
143
+
144
+ _warn_once_without_issuer(settings)
145
+
146
+ try:
147
+ signing_key = jwks_client.get_signing_key_from_jwt(access_token)
148
+ claims = jwt.decode(
149
+ access_token,
150
+ signing_key.key,
151
+ algorithms=settings.oidc_algorithms,
152
+ audience=settings.IFDD_OIDC_JWKS_AUDIENCE,
153
+ issuer=settings.IFDD_OIDC_ISSUER or None,
154
+ options={"verify_exp": True},
155
+ )
156
+ except jwt.exceptions.PyJWKClientError as e:
157
+ logger.info(f"JWKS client error: {e}")
158
+ raise HTTPException(
159
+ status_code=401,
160
+ detail=f"Token validation failed: Unable to verify token signature. {e}",
161
+ )
162
+ except jwt.exceptions.ExpiredSignatureError as e:
163
+ logger.info(f"Token expired: {e}")
164
+ raise HTTPException(status_code=401, detail="Token has expired")
165
+ except jwt.exceptions.InvalidAudienceError as e:
166
+ logger.info(f"Invalid audience: {e}")
167
+ raise HTTPException(
168
+ status_code=401,
169
+ detail=f"Invalid token audience. Expected: {settings.IFDD_OIDC_JWKS_AUDIENCE}",
170
+ )
171
+ except jwt.exceptions.InvalidTokenError as e:
172
+ logger.info(f"Invalid token error: {e}")
173
+ raise HTTPException(status_code=401, detail=f"Invalid token: {e}")
174
+ except Exception as e:
175
+ logger.info(f"Unexpected error during token validation: {e}")
176
+ raise HTTPException(status_code=401, detail=f"Authentication failed: {e}")
177
+
178
+ # An ID token of the same client has the same audience and signature;
179
+ # only the token type tells them apart (Keycloak: "Bearer" vs. "ID").
180
+ # RFC 9068, section 5: resource servers must not accept ID tokens.
181
+ if claims.get("typ") != ACCESS_TOKEN_TYPE:
182
+ logger.info(f"Rejected token of type {claims.get('typ')!r}")
183
+ raise HTTPException(status_code=401, detail="Invalid token: not an access token")
184
+ return claims
185
+
186
+
187
+ def require_roles(required_roles: List[str]):
188
+ """A dependency that needs a valid token with all of ``required_roles``.
189
+
190
+ Unlike :func:`optional_auth` it has no development stand-in; the routers
191
+ of the core use :func:`optional_auth` and its shortcuts.
192
+
193
+ Args:
194
+ required_roles: Client roles of ``IFDD_OIDC_JWKS_AUDIENCE``.
195
+
196
+ Returns:
197
+ The dependency; it answers 403 if a role is missing.
198
+ """
199
+
200
+ async def role_checker(token_data: dict = Depends(valid_access_token)):
201
+ """Return the claims, or answer 403 if a required role is missing."""
202
+ settings = get_settings()
203
+ client_id = settings.IFDD_OIDC_JWKS_AUDIENCE
204
+ resource_access = token_data.get("resource_access", {})
205
+ user_roles = resource_access.get(client_id, {}).get("roles", [])
206
+ for role in required_roles:
207
+ if role not in user_roles:
208
+ raise HTTPException(
209
+ status_code=403,
210
+ detail=f"Insufficient permissions. Role {role} required.",
211
+ )
212
+ return token_data
213
+
214
+ return role_checker
215
+
216
+
217
+ def optional_auth(required_roles: Optional[RoleSpec] = None):
218
+ """Return an auth dependency, or a development stand-in when auth is off.
219
+
220
+ ``required_roles`` may be a plain list or a callable that receives the
221
+ active settings and returns the list. The callable form keeps role names
222
+ that live in the configuration out of import-time evaluation.
223
+ """
224
+
225
+ async def dispatcher(request: Request):
226
+ """Return the claims of the token, or the development user when auth is off."""
227
+ settings = get_settings()
228
+ if not settings.IFDD_BE_AUTH_ENABLED:
229
+ return {
230
+ "preferred_username": "dev-user",
231
+ "resource_access": {
232
+ settings.IFDD_OIDC_JWKS_AUDIENCE: {
233
+ "roles": [
234
+ settings.IFDD_ROLE_PUBLIC,
235
+ settings.IFDD_ROLE_NODES_READ,
236
+ settings.IFDD_ROLE_NODES_WRITE,
237
+ # a context pattern: every domain context below the root
238
+ settings.IFDD_CONTEXT_ROOT,
239
+ ]
240
+ }
241
+ },
242
+ }
243
+ roles = _resolve_roles(required_roles, settings)
244
+ token = await oauth_2_scheme(request)
245
+ token_data = await valid_access_token(token)
246
+ client_id = settings.IFDD_OIDC_JWKS_AUDIENCE
247
+ user_roles = (
248
+ token_data.get("resource_access", {}).get(client_id, {}).get("roles", [])
249
+ )
250
+ for role in roles:
251
+ if role not in user_roles:
252
+ raise HTTPException(
253
+ status_code=403,
254
+ detail=f"Insufficient permissions. Role {role} required.",
255
+ )
256
+ return token_data
257
+
258
+ return dispatcher
259
+
260
+
261
+ def nodes_read_auth():
262
+ """Auth dependency requiring the configured node read role."""
263
+ return optional_auth(lambda settings: [settings.IFDD_ROLE_NODES_READ])
264
+
265
+
266
+ def nodes_write_auth():
267
+ """Auth dependency requiring the configured node write role."""
268
+ return optional_auth(lambda settings: [settings.IFDD_ROLE_NODES_WRITE])
269
+
270
+
271
+ def public_auth():
272
+ """Auth dependency requiring only a sign-in (the configured public role)."""
273
+ return optional_auth(lambda settings: [settings.IFDD_ROLE_PUBLIC])
@@ -0,0 +1,160 @@
1
+ """The c_* cache metadata of a JSON-LD document.
2
+
3
+ Every schema defines six terms with the prefix ``c_`` ("cache metadata"). The
4
+ backend never stores them inside the document: they are taken out of the
5
+ document before it is stored, their values live in table columns of the row
6
+ (see :mod:`ifdd.be.core.models`), and they are added to the document again
7
+ when it is read.
8
+
9
+ Two of them describe the stored copy and are always set by the backend; a
10
+ value sent by a client is discarded. The other four come from the source of
11
+ the document and are kept as sent:
12
+
13
+ ===================== ========= ===============================================
14
+ term origin column
15
+ ===================== ========= ===============================================
16
+ ``c_created`` source ``src_created``
17
+ ``c_modified`` source ``src_modified``
18
+ ``c_validNotBefore`` source ``valid_period``, lower bound (valid time)
19
+ ``c_validNotAfter`` source ``valid_period``, upper bound (valid time)
20
+ ``c_cacheCreated`` backend ``cache_created``: first stored
21
+ ``c_cacheUpdated`` backend ``cache_updated``: this version stored
22
+ ===================== ========= ===============================================
23
+
24
+ Only these six names are known; any other ``c_*`` term is rejected.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from dataclasses import dataclass
30
+ from datetime import datetime, timezone
31
+ from typing import Any, Mapping, Optional
32
+
33
+ from .helper import ensure_timezone_utc
34
+
35
+ CACHE_PREFIX = "c_"
36
+
37
+ SOURCE_TERMS = ("c_created", "c_modified", "c_validNotBefore", "c_validNotAfter")
38
+ BACKEND_TERMS = ("c_cacheCreated", "c_cacheUpdated")
39
+ CACHE_TERMS = SOURCE_TERMS + BACKEND_TERMS
40
+
41
+ XSD_DATETIME = "http://www.w3.org/2001/XMLSchema#dateTime"
42
+
43
+
44
+ class CacheMetaError(ValueError):
45
+ """A document carries c_* metadata the backend cannot accept (HTTP 422)."""
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class SourceMeta:
50
+ """The c_* values a source sent with a document; None means "not sent"."""
51
+
52
+ created: Optional[datetime] = None
53
+ modified: Optional[datetime] = None
54
+ valid_not_before: Optional[datetime] = None
55
+ valid_not_after: Optional[datetime] = None
56
+
57
+
58
+ def split_cache_meta(document: Mapping[str, Any]) -> tuple[dict, SourceMeta]:
59
+ """Separate a compacted document from its c_* metadata.
60
+
61
+ Returns a copy of the document without any c_* term and the source values
62
+ it carried. Backend values (``c_cacheCreated``, ``c_cacheUpdated``) are
63
+ dropped: the backend sets them itself. An unknown c_* term raises
64
+ :class:`CacheMetaError`.
65
+ """
66
+ content: dict = {}
67
+ sent: dict[str, datetime] = {}
68
+ for term, value in document.items():
69
+ if not term.startswith(CACHE_PREFIX):
70
+ content[term] = value
71
+ elif term in SOURCE_TERMS:
72
+ sent[term] = _parse_datetime(term, value)
73
+ elif term not in BACKEND_TERMS:
74
+ raise CacheMetaError(
75
+ f"unknown cache metadata term {term!r}; known: {', '.join(CACHE_TERMS)}"
76
+ )
77
+ meta = SourceMeta(
78
+ created=sent.get("c_created"),
79
+ modified=sent.get("c_modified"),
80
+ valid_not_before=sent.get("c_validNotBefore"),
81
+ valid_not_after=sent.get("c_validNotAfter"),
82
+ )
83
+ return content, meta
84
+
85
+
86
+ def cache_iris_in(expanded: Mapping[str, Any]) -> list[str]:
87
+ """Property IRIs of an expanded document that name a c_* term.
88
+
89
+ A client can bypass :func:`split_cache_meta` by writing a term as a
90
+ compact IRI (``"product:c_created"``). Such properties must not reach the
91
+ stored document either; the caller rejects them.
92
+ """
93
+ found = []
94
+ for iri in expanded:
95
+ local_name = iri.rstrip("/").rsplit("/", 1)[-1].rsplit("#", 1)[-1]
96
+ if local_name in CACHE_TERMS:
97
+ found.append(iri)
98
+ return found
99
+
100
+
101
+ def stored_values(
102
+ *,
103
+ created: Optional[datetime],
104
+ modified: Optional[datetime],
105
+ valid_not_before: datetime,
106
+ valid_not_after: Optional[datetime],
107
+ cache_created: datetime,
108
+ cache_updated: datetime,
109
+ ) -> dict[str, datetime]:
110
+ """The c_* values of a stored version, by term.
111
+
112
+ Terms without a value are left out: an open-ended valid time has no
113
+ ``c_validNotAfter``, an unsent ``c_created`` stays absent.
114
+ """
115
+ values = {
116
+ "c_created": created,
117
+ "c_modified": modified,
118
+ "c_validNotBefore": valid_not_before,
119
+ "c_validNotAfter": valid_not_after,
120
+ "c_cacheCreated": cache_created,
121
+ "c_cacheUpdated": cache_updated,
122
+ }
123
+ return {term: value for term, value in values.items() if value is not None}
124
+
125
+
126
+ def as_utc_text(value: datetime) -> str:
127
+ """ISO 8601 in UTC, whatever time zone the database session uses."""
128
+ return value.astimezone(timezone.utc).isoformat()
129
+
130
+
131
+ def add_to_compacted(document: dict, values: Mapping[str, datetime]) -> dict:
132
+ """Add c_* values to a compacted document (plain terms, ISO 8601, UTC)."""
133
+ for term, value in values.items():
134
+ document[term] = as_utc_text(value)
135
+ return document
136
+
137
+
138
+ def add_to_expanded(expanded: dict, values: Mapping[str, datetime], namespace: str) -> dict:
139
+ """Add c_* values to an expanded document.
140
+
141
+ ``namespace`` is the IRI of the schema namespace of the stored context,
142
+ e.g. ``https://type/v1/product/``; the property IRI is namespace + term,
143
+ exactly as the schema defines it (``product:c_created``).
144
+ """
145
+ for term, value in values.items():
146
+ expanded[f"{namespace}{term}"] = [{"@type": XSD_DATETIME, "@value": as_utc_text(value)}]
147
+ return expanded
148
+
149
+
150
+ def _parse_datetime(term: str, value: Any) -> datetime:
151
+ """An xsd:dateTime value as sent: a string or a JSON-LD value object."""
152
+ if isinstance(value, Mapping) and "@value" in value:
153
+ value = value["@value"]
154
+ if not isinstance(value, str):
155
+ raise CacheMetaError(f"{term}: expected an ISO 8601 date-time, got {value!r}")
156
+ try:
157
+ parsed = datetime.fromisoformat(value)
158
+ except ValueError as err:
159
+ raise CacheMetaError(f"{term}: not an ISO 8601 date-time: {value!r}") from err
160
+ return ensure_timezone_utc(parsed)