pangloss-core 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026, Richard Hadden, Department of Digital Humanities, University of Graz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.4
2
+ Name: pangloss-core
3
+ Version: 0.1.0
4
+ Summary: Pangloss settings and the pieces shared by every Pangloss package
5
+ Author: Richard Hadden
6
+ Author-email: Richard Hadden <richard.hadden@oeaw.ac.at>
7
+ License-Expression: MIT
8
+ License-File: LICENCE.txt
9
+ Requires-Dist: pydantic-settings>=2.14.1
10
+ Requires-Python: >=3.15
11
+ Project-URL: Repository, https://github.com/richardhadden/pangloss-monorepo
12
+ Description-Content-Type: text/markdown
13
+
14
+ # pangloss-core
15
+
16
+ What every Pangloss package shares: the settings classes (`BaseSettings`, `ClientSettings`, `DatabaseSettings`), logging, and
17
+ `pangloss_core.backend`, through which add-on packages reach whichever database is configured.
18
+
19
+ Reference: [implementation_docs/settings.md](../../implementation_docs/settings.md), [implementation_docs/logging.md](../../implementation_docs/logging.md).
@@ -0,0 +1,6 @@
1
+ # pangloss-core
2
+
3
+ What every Pangloss package shares: the settings classes (`BaseSettings`, `ClientSettings`, `DatabaseSettings`), logging, and
4
+ `pangloss_core.backend`, through which add-on packages reach whichever database is configured.
5
+
6
+ Reference: [implementation_docs/settings.md](../../implementation_docs/settings.md), [implementation_docs/logging.md](../../implementation_docs/logging.md).
@@ -0,0 +1,20 @@
1
+ [project]
2
+ name = "pangloss-core"
3
+ version = "0.1.0"
4
+ description = "Pangloss settings and the pieces shared by every Pangloss package"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENCE.txt"]
8
+ requires-python = ">=3.15"
9
+ dependencies = ["pydantic-settings>=2.14.1"]
10
+
11
+ [[project.authors]]
12
+ name = "Richard Hadden"
13
+ email = "richard.hadden@oeaw.ac.at"
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/richardhadden/pangloss-monorepo"
17
+
18
+ [build-system]
19
+ requires = ["uv_build>=0.11.8,<0.12.0"]
20
+ build-backend = "uv_build"
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "pangloss-core"
3
+ version = "0.1.0"
4
+ description = "Pangloss settings and the pieces shared by every Pangloss package"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENCE.txt"]
8
+ authors = [
9
+ { name = "Richard Hadden", email = "richard.hadden@oeaw.ac.at" }
10
+ ]
11
+ requires-python = ">=3.15"
12
+ dependencies = [
13
+ "pydantic-settings>=2.14.1",
14
+ ]
15
+
16
+ [project.urls]
17
+ Repository = "https://github.com/richardhadden/pangloss-monorepo"
18
+
19
+ [build-system]
20
+ requires = ["uv_build>=0.11.8,<0.12.0"]
21
+ build-backend = "uv_build"
@@ -0,0 +1,34 @@
1
+ """What every Pangloss package shares: settings, logging, the storage a project names, and the backend for add-ons.
2
+
3
+ Imported from here (`from pangloss_core import BaseSettings`); the modules `settings`, `storage`, `backend` and `logs`
4
+ are there too. See implementation_docs/imports.md.
5
+ """
6
+
7
+ lazy from pangloss_core.backend import Backend, Transaction
8
+ lazy from pangloss_core.settings import (
9
+ BaseSettings,
10
+ ClientSettings,
11
+ DatabaseSettings,
12
+ get_settings,
13
+ )
14
+ lazy from pangloss_core.storage import (
15
+ Capabilities,
16
+ PanglossStorageError,
17
+ Storage,
18
+ check_requirements,
19
+ storage_of,
20
+ )
21
+
22
+ __all__ = [
23
+ "Backend",
24
+ "BaseSettings",
25
+ "Capabilities",
26
+ "check_requirements",
27
+ "ClientSettings",
28
+ "DatabaseSettings",
29
+ "get_settings",
30
+ "PanglossStorageError",
31
+ "Storage",
32
+ "storage_of",
33
+ "Transaction",
34
+ ]
@@ -0,0 +1,80 @@
1
+ """The database backend, for the packages that need to reach the graph and must not name one.
2
+
3
+ A backend that runs Cypher (its `Storage` has the capability `cypher`; see `pangloss_core.storage`) has a module `backend`
4
+ that gives the names of `Backend`. An add-on package (typology, calendar) uses them through `current()`:
5
+
6
+ ```python
7
+ from pangloss_core import backend
8
+
9
+ backend.current().database() # the database in use
10
+ ```
11
+
12
+ and annotates a transaction as `backend.Transaction`. (`pangloss-users` and `pangloss-review` use the backend's
13
+ `exposed_functions` instead, for what is theirs to do. This module is for the packages that write their own queries.)
14
+ See `implementation_docs/backend-neutral-addons.md`.
15
+ """
16
+
17
+ from collections.abc import Awaitable, Callable
18
+ from typing import Any, Protocol
19
+
20
+
21
+ class Transaction(Protocol):
22
+ """What a package may do with a transaction: run a query (`await tx.run(query, parameters, **named)`, giving a result
23
+ that is iterated with `async for` and has `single()` and `consume()`)"""
24
+
25
+ async def run(self, query: str, parameters: Any = None, **named: Any) -> Any: ...
26
+
27
+
28
+ class Backend(Protocol):
29
+ """The names that every backend's `backend` module gives"""
30
+
31
+ Database: Any
32
+ """The class"""
33
+
34
+ database: Callable[[], Any]
35
+ """`database()`: the database in use (a `Database`), which has `read_transaction` and `write_transaction` decorators"""
36
+
37
+ timeout_from_setting: Callable[..., Any]
38
+ """`@timeout_from_setting("SEARCH_TIMEOUT_SECONDS", 30)` under a transaction decorator: the time a read may take. A read
39
+ that takes longer raises `PanglossSearchTimeoutError`"""
40
+
41
+ unpublished_visible: Callable[[], bool]
42
+ """Whether the request in progress may see what is not published"""
43
+
44
+ ensure_lock: Callable[[str], Awaitable[None]]
45
+ """`await ensure_lock(key)` before the transaction that locks the key is opened: makes the lock's node"""
46
+
47
+ lock: Callable[[Any, str], Awaitable[None]]
48
+ """`await lock(tx, key)`: until the transaction ends, any other transaction that locks the same key waits for it (or runs
49
+ again), and then sees what it did. For a check that must not be raced"""
50
+
51
+ user_exists: Callable[[str], Awaitable[bool]]
52
+ """Whether there is a user of that name"""
53
+
54
+ fragments: Any
55
+ """Pieces of Cypher that know how models are stored (`pangloss_cypher.fragments`): `visible(node)`, the one rule of
56
+ what a reader sees (the query gives `$see_unpublished`), `not_deleted(node)`, `head_of(node, as_)`, and the checked
57
+ names `label(name)` and `field_edge(field)`. A query that reads model data uses them, not a copy of the rule"""
58
+
59
+ dialect: Any
60
+ """The backend's `Dialect` (`pangloss_cypher.dialect.Dialect`, the same object as `database().dialect` and as
61
+ `pangloss_cypher.transactions.dialect()` gives): the named points where the databases' Cypher differs, such as
62
+ `vector_search(index, k, vector, carry)`"""
63
+
64
+ install_query_module: Callable[..., Awaitable[bool]]
65
+ """Only where `Capabilities.query_modules` is true (Memgraph); a backend without it has no such name, so
66
+ `hasattr(backend, "install_query_module")` goes with the capability. `await install_query_module(name, source,
67
+ expects=(), library=False)` puts the Python text `source` into the database as the query module `name` (a name
68
+ without `.py`), if it is not there with that text already, and checks that it loaded: True if it was written"""
69
+
70
+
71
+ # The names of `Backend` that a backend gives only if it has a capability (`pangloss_core.storage.Capabilities`): the
72
+ # name is there exactly where the capability is true
73
+ ONLY_WITH_CAPABILITY = {"install_query_module": "query_modules"}
74
+
75
+
76
+ def current(storage: str | None = None) -> Backend:
77
+ """The backend of the project (its settings' `STORAGE`), or of the storage named (`pangloss_neo4j:storage`)"""
78
+ from pangloss_core.storage import load, storage_of
79
+
80
+ return (load(storage) if storage else storage_of()).cypher
@@ -0,0 +1,138 @@
1
+ """Logging for every Pangloss package.
2
+
3
+ All of Pangloss logs to loggers under `pangloss` (`pangloss.api.auth`, `pangloss.memgraph.queries`,
4
+ and so on), so that one area can be turned up or down alone (`logging.getLogger("pangloss.memgraph")`).
5
+ `configure_logging` (called when the app is made, and by the command line) puts one handler on
6
+ `pangloss`, from the settings `LOG_LEVEL` and `LOG_FORMAT` ("text", or "json": a line each).
7
+
8
+ What is logged follows these rules:
9
+
10
+ - Never a password, a token, an `Authorization` header, or the content of a document or entity: ids,
11
+ model names, counts and parameter names. A secret that gets into a message anyway is replaced by
12
+ `[redacted]` on the way out (`redact`), as a last defence.
13
+ - What comes from a client (a username) is logged with `%r`, so that it cannot make a line of its own.
14
+ - A failure is logged once, where it is dealt with.
15
+ - Each record has the `request_id` of the request it was made in (`request_id`), if there is one.
16
+ """
17
+
18
+ import contextvars
19
+ import datetime
20
+ import json
21
+ import logging
22
+ import re
23
+ import sys
24
+ from typing import Any, Literal
25
+
26
+ ROOT_LOGGER = "pangloss"
27
+ HANDLER_MARKER = "_pangloss_handler"
28
+
29
+ # The id of the request being dealt with, set by the API's middleware
30
+ request_id: contextvars.ContextVar[str | None] = contextvars.ContextVar(
31
+ "pangloss_request_id", default=None
32
+ )
33
+
34
+ REDACTED = "[redacted]"
35
+
36
+ # A secret that should never be in a log line: a JWT (the tokens of a session), a personal access
37
+ # token (`pgl_...`), the value of an Authorization header, a password given as `password=...`
38
+ SECRET_PATTERNS = [
39
+ re.compile(r"eyJ[\w-]{5,}\.[\w-]{5,}\.[\w-]*"),
40
+ re.compile(r"\bpgl_[\w-]{8,}"),
41
+ re.compile(r"(?i)\b(bearer|basic)\s+[\w.~+/=-]{8,}"),
42
+ re.compile(
43
+ r"(?i)\b(password|passwd|secret|token|authorization)(['\"]?\s*[:=]\s*['\"]?)[^\s,'\"}&]+"
44
+ ),
45
+ ]
46
+
47
+
48
+ def redact(text: str) -> str:
49
+ """`text` with anything that looks like a secret replaced"""
50
+ for pattern in SECRET_PATTERNS:
51
+ if pattern.groups == 1:
52
+ text = pattern.sub(lambda match: f"{match.group(1)} {REDACTED}", text)
53
+ elif pattern.groups == 2:
54
+ text = pattern.sub(
55
+ lambda match: f"{match.group(1)}{match.group(2)}{REDACTED}", text
56
+ )
57
+ else:
58
+ text = pattern.sub(REDACTED, text)
59
+ return text
60
+
61
+
62
+ class RequestIdFilter(logging.Filter):
63
+ """Gives each record the `request_id` of the request it was made in"""
64
+
65
+ def filter(self, record: logging.LogRecord) -> bool:
66
+ record.request_id = request_id.get()
67
+ return True
68
+
69
+
70
+ class TextFormatter(logging.Formatter):
71
+ """`2026-10-24 10:00:00 INFO pangloss.api.auth [3f2a...] message`, with secrets redacted"""
72
+
73
+ def __init__(self) -> None:
74
+ super().__init__(
75
+ "%(asctime)s %(levelname)s %(name)s%(request_tag)s %(message)s"
76
+ )
77
+
78
+ def format(self, record: logging.LogRecord) -> str:
79
+ rid = getattr(record, "request_id", None)
80
+ record.request_tag = f" [{rid}]" if rid else ""
81
+ return redact(super().format(record))
82
+
83
+
84
+ class JsonFormatter(logging.Formatter):
85
+ """One JSON object a line: `time`, `level`, `logger`, `message`, `request_id` (if any), and
86
+ `exception` (if any); with secrets redacted"""
87
+
88
+ def format(self, record: logging.LogRecord) -> str:
89
+ entry: dict[str, Any] = {
90
+ "time": datetime.datetime.fromtimestamp(
91
+ record.created, datetime.UTC
92
+ ).isoformat(timespec="milliseconds"),
93
+ "level": record.levelname,
94
+ "logger": record.name,
95
+ "message": redact(record.getMessage()),
96
+ }
97
+ if rid := getattr(record, "request_id", None):
98
+ entry["request_id"] = rid
99
+ if record.exc_info:
100
+ entry["exception"] = redact(self.formatException(record.exc_info))
101
+ # (redacted before `json.dumps`, which escapes the quotes the patterns look for)
102
+ return json.dumps(entry, default=str)
103
+
104
+
105
+ class StderrHandler(logging.StreamHandler):
106
+ """Writes to whatever `sys.stderr` is at the time (so a redirected one is followed, and a
107
+ closed one is not written to)"""
108
+
109
+ def __init__(self) -> None:
110
+ logging.Handler.__init__(self)
111
+
112
+ @property
113
+ def stream(self) -> Any: # ty: ignore[invalid-property-type-override]
114
+ return sys.stderr
115
+
116
+
117
+ def configure_logging(
118
+ level: str = "INFO", format: Literal["text", "json"] = "text", stream: Any = None
119
+ ) -> None:
120
+ """Put the handler on `pangloss` (once: calling it again changes the level, the format and
121
+ where it goes)"""
122
+ logger = logging.getLogger(ROOT_LOGGER)
123
+ for handler in list(logger.handlers):
124
+ if getattr(handler, HANDLER_MARKER, False):
125
+ logger.removeHandler(handler)
126
+
127
+ handler = logging.StreamHandler(stream) if stream else StderrHandler()
128
+ setattr(handler, HANDLER_MARKER, True)
129
+ handler.addFilter(RequestIdFilter())
130
+ handler.setFormatter(JsonFormatter() if format == "json" else TextFormatter())
131
+ logger.addHandler(handler)
132
+ logger.setLevel(level.upper())
133
+
134
+
135
+ def configure_from_settings(settings: Any) -> None:
136
+ configure_logging(
137
+ getattr(settings, "LOG_LEVEL", "INFO"), getattr(settings, "LOG_FORMAT", "text")
138
+ )
File without changes
@@ -0,0 +1,176 @@
1
+ import json
2
+ import re
3
+ import typing
4
+
5
+ from pydantic import AnyHttpUrl, field_validator, model_validator
6
+ from pydantic_settings import BaseSettings as PydanticBaseSettings
7
+ from pydantic_settings import NoDecode, SettingsConfigDict
8
+
9
+ # An origin is a scheme, host and (maybe) port, and no more
10
+ CORS_ORIGIN = re.compile(r"^https?://[^/\s?#]+$")
11
+
12
+
13
+ def normalise_cors_origins(value: typing.Any) -> list[str]:
14
+ """The origins that may use the API from a browser, from a list or a string of
15
+ them (comma separated, or a JSON list): as a browser sends them, without a
16
+ trailing `/`. `*` allows any."""
17
+ if isinstance(value, str):
18
+ value = value.strip()
19
+ value = json.loads(value) if value.startswith("[") else value.split(",")
20
+ if not isinstance(value, list | tuple | set):
21
+ raise ValueError(f"Not a list of origins: {value!r}")
22
+
23
+ origins = []
24
+ for item in value:
25
+ origin = str(item).strip().rstrip("/").lower()
26
+ if not origin:
27
+ continue
28
+ if origin != "*" and not CORS_ORIGIN.match(origin):
29
+ raise ValueError(
30
+ f"'{item}' is not an origin: it should be like 'https://example.com' "
31
+ "or 'http://localhost:5173' (no path), or '*'"
32
+ )
33
+ origins.append(origin)
34
+ return origins
35
+
36
+
37
+ class DatabaseSettings(PydanticBaseSettings):
38
+ pass
39
+
40
+
41
+ class ClientSettings(PydanticBaseSettings):
42
+ """What the models need of the settings: which apps declare them, and which storage
43
+ backend `save`, `get` and so on are bound to. A client of the API (the SDK) has no
44
+ more than this; the server's `BaseSettings` adds the rest.
45
+
46
+ Making settings makes them the project's (`SETTINGS`), once they are valid: `configure`
47
+ does the same for settings that were made before."""
48
+
49
+ INSTALLED_APPS: list[str]
50
+ # The storage backend, as `module:attribute`: "pangloss_memgraph:storage" (see `pangloss_core.storage`)
51
+ STORAGE: str | None = None
52
+ # (what came before `STORAGE`: the module path of the backend. Still read, with a warning)
53
+ DATABASE_MODULE: str | None = None
54
+ # The server's values of the settings that the models are made from (`model_settings`), for a client that has
55
+ # not got the server's settings: the SDK of a project fills it in
56
+ MODEL_SETTINGS: dict[str, typing.Any] = {}
57
+
58
+ model_config = SettingsConfigDict(case_sensitive=True, env_file=".env")
59
+
60
+ def __init__(self, *args, **kwargs):
61
+ super().__init__(*args, **kwargs)
62
+ configure(self)
63
+
64
+ @model_validator(mode="after")
65
+ def storage_is_named(self) -> typing.Self:
66
+ if not self.STORAGE and not self.DATABASE_MODULE:
67
+ raise ValueError(
68
+ "STORAGE is required: the storage backend, like 'pangloss_memgraph:storage'"
69
+ )
70
+ if not self.STORAGE and self.DATABASE_MODULE:
71
+ from pangloss_core.storage import warn_database_module
72
+
73
+ warn_database_module(self.DATABASE_MODULE)
74
+ return self
75
+
76
+
77
+ class BaseSettings[TDatabaseSettings: DatabaseSettings](ClientSettings):
78
+ PROJECT_NAME: str
79
+ # The origins (`http://localhost:5173`) of the frontends that may use the API
80
+ # from a browser. A comma-separated string is accepted too, as is `*` (see the API)
81
+ BACKEND_CORS_ORIGINS: typing.Annotated[list[typing.Any], NoDecode]
82
+ DATABASE: TDatabaseSettings
83
+
84
+ INTERFACE_LANGUAGES: list[str] = []
85
+ DEFAULT_INTERFACE_LANGUAGE: str = "en"
86
+
87
+ AUTHJWT_SECRET_KEY: str
88
+
89
+ # Authentication: how long tokens last, and how the session cookies are set
90
+ AUTH_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
91
+ AUTH_REFRESH_TOKEN_EXPIRE_DAYS: int = 14
92
+ AUTH_COOKIE_SAMESITE: typing.Literal["lax", "strict", "none"] = "lax"
93
+ AUTH_COOKIE_SECURE: bool = False
94
+
95
+ # After this many wrong passwords for a username within the window, it is refused
96
+ # (`429`) until they are out of it. 0 turns it off. Kept per server process
97
+ LOGIN_MAX_FAILURES: int = 10
98
+ LOGIN_FAILURE_WINDOW_SECONDS: int = 300
99
+
100
+ ENTITY_BASE_URL: AnyHttpUrl
101
+
102
+ # Logging (see `pangloss_core.logs`): what is logged under `pangloss`, and how: a line of
103
+ # text, or of JSON. Over `SLOW_QUERY_MS` a database transaction, and over `SLOW_REQUEST_MS` a
104
+ # request, is logged as a warning
105
+ LOG_LEVEL: typing.Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
106
+ LOG_FORMAT: typing.Literal["text", "json"] = "text"
107
+ SLOW_QUERY_MS: int = 500
108
+ SLOW_REQUEST_MS: int = 2000
109
+
110
+ # The most a structured search (`/api/search`) may take, in the database; one that takes longer is
111
+ # stopped and answered with a `504`, and is not tried again. 0 is no limit
112
+ SEARCH_TIMEOUT_SECONDS: float = 30
113
+
114
+ # The most hits the text index gives for each word of a search of a list (`?q=`, with or without `deep`):
115
+ # more than this are not looked at, and the page says `truncated`. (The index gives 1000 unless asked for more)
116
+ SEARCH_HIT_LIMIT: int = 100_000
117
+
118
+ # A merge of two entities (`Entity.merge`; implementation_docs/entity-identity.md) that would write more documents and entities than
119
+ # this is made only when asked for as a large one (by an admin), in batches; up to it, a merge is one transaction
120
+ MERGE_LIMIT: int = 1000
121
+ # How many seconds after a merge the references that writes under way left on the absorbed entity are looked for
122
+ # again (0: not again). None: what the database needs (Memgraph 0, Neo4j 5)
123
+ MERGE_SECOND_PASS_SECONDS: float | None = None
124
+ # Who may merge two entities, and undo a merge, without anyone else: "admin" (admins), "any" (every logged-in
125
+ # user) or "none" (nobody). Everyone else proposes it, and a second, different user carries it out
126
+ MERGE_DIRECTLY: typing.Literal["admin", "any", "none"] = "admin"
127
+
128
+ # What the server does at start-up if the project has migrations and the database is not
129
+ # what they say, or the models are not what they come to: "error" does not start, "warn"
130
+ # starts and says so, "off" does not look
131
+ MIGRATION_CHECK: typing.Literal["error", "warn", "off"] = "error"
132
+ # How often (seconds) a running server looks whether the database has been migrated under it, after
133
+ # which it answers 503 until it is restarted; 0: only before a write and after a failure
134
+ MIGRATION_WATCH_SECONDS: float = 10.0
135
+
136
+ @field_validator("BACKEND_CORS_ORIGINS", mode="before")
137
+ @classmethod
138
+ def assemble_cors_origins(cls, v: typing.Any) -> list[str]:
139
+ return normalise_cors_origins(v)
140
+
141
+
142
+ # (a client has only the `ClientSettings` part: the server code that uses the rest runs
143
+ # only where there is a `BaseSettings`)
144
+ SETTINGS: BaseSettings
145
+
146
+
147
+ def configure(settings: ClientSettings) -> None:
148
+ """Make these the project's settings"""
149
+ global SETTINGS
150
+ SETTINGS = typing.cast("BaseSettings", settings)
151
+
152
+
153
+ # The names of the settings that change what the models are, not only how a server runs (the languages that a type of
154
+ # `pangloss-typology` has a label in). A package that reads one while the models are made adds its name here and reads
155
+ # it with `model_setting`: the SDK of a project is built with their values, so that a client makes the server's models
156
+ model_settings: set[str] = set()
157
+
158
+
159
+ def model_setting(name: str, default: typing.Any = None) -> typing.Any:
160
+ """A setting that the models are made from: the project's, or on a client what its SDK says the server's is"""
161
+ settings = globals().get("SETTINGS")
162
+ if settings is None:
163
+ return default
164
+ if hasattr(settings, name):
165
+ return getattr(settings, name)
166
+ return settings.MODEL_SETTINGS.get(name, default)
167
+
168
+
169
+ def get_settings() -> BaseSettings:
170
+ """The project's settings: an error that says so if there are none yet"""
171
+ settings = globals().get("SETTINGS")
172
+ if settings is None:
173
+ raise RuntimeError(
174
+ "There are no settings yet: import the project's settings module (which makes them) first"
175
+ )
176
+ return settings
@@ -0,0 +1,204 @@
1
+ """The storage backend of a project: the object that the setting `STORAGE` names.
2
+
3
+ ```python
4
+ STORAGE = "pangloss_memgraph:storage"
5
+ ```
6
+
7
+ A backend package gives one `Storage`. It says what the backend can do (`capabilities`), and where its parts are:
8
+
9
+ - `operations`: the functions the models are bound to (`get`, `save`, `list`, ...; the module `exposed_functions`);
10
+ - `setup`: what the command line and the server need (`create_database`, `connect`, `disconnect`, `setup_database`);
11
+ - `migration_backend`: what the migrations need, if the backend has migrations;
12
+ - `cypher`: for an add-on that runs its own Cypher (typology, calendar), if the backend speaks Cypher (see
13
+ `pangloss_core.backend`).
14
+
15
+ The parts are imported when they are first asked for, so naming a backend imports nothing of it.
16
+
17
+ `DATABASE_MODULE`, the module path that came before `STORAGE`, is still read, with a warning: it is taken as a backend
18
+ whose parts are in that module (`storage_of` finds the backend's own `Storage` if it has one).
19
+ """
20
+
21
+ import dataclasses
22
+ import importlib
23
+ import warnings
24
+ from types import ModuleType
25
+ from typing import Any
26
+
27
+
28
+ @dataclasses.dataclass(frozen=True)
29
+ class Capabilities:
30
+ """What a backend can do, of what not every backend can"""
31
+
32
+ snapshots: bool = False
33
+ """`pangloss migrate --backup`, `pangloss backups` and `pangloss restore`"""
34
+
35
+ fast_bulk_load: bool = False
36
+ """A bulk load into an empty database in a mode of its own (`pangloss <backend> bulk-load`)"""
37
+
38
+ accent_folding: bool = False
39
+ """A search for `zurich` finds "Zürich\""""
40
+
41
+ deep_search: bool = False
42
+ """A list searched with `deep` finds what refers to what matches"""
43
+
44
+ cypher: bool = False
45
+ """An add-on that runs its own Cypher (typology, calendar) can be installed: `Storage.cypher` is there"""
46
+
47
+ vector_index: bool = False
48
+ """The database can make an index of vectors held in a property, and find the nodes nearest a vector by it"""
49
+
50
+ query_modules: bool = False
51
+ """Code can be installed in the database and called from Cypher (a procedure or function of a query module)"""
52
+
53
+
54
+ class PanglossStorageError(Exception):
55
+ """The backend named by the settings cannot be found, or cannot do what is asked of it"""
56
+
57
+
58
+ @dataclasses.dataclass(frozen=True)
59
+ class Storage:
60
+ """A storage backend: its name, what it can do, and the module that holds its parts"""
61
+
62
+ name: str
63
+ package: str
64
+ """The module whose submodules are the parts: `pangloss_memgraph.databases.memgraph`"""
65
+ capabilities: Capabilities = Capabilities()
66
+
67
+ def part(self, name: str) -> ModuleType:
68
+ return importlib.import_module(f"{self.package}.{name}")
69
+
70
+ @property
71
+ def operations(self) -> ModuleType:
72
+ """The functions the models are bound to (`exposed_functions`)"""
73
+ return self.part("exposed_functions")
74
+
75
+ @property
76
+ def setup(self) -> ModuleType:
77
+ return self.part("setup")
78
+
79
+ @property
80
+ def migration_backend(self) -> ModuleType | None:
81
+ """What the migrations need, or `None` if the backend has no migrations"""
82
+ try:
83
+ return self.part("migration_backend")
84
+ except ModuleNotFoundError as error:
85
+ if error.name == f"{self.package}.migration_backend":
86
+ return None
87
+ raise
88
+
89
+ @property
90
+ def cypher(self) -> Any:
91
+ """The backend's module for add-ons that run their own Cypher: a `pangloss_core.backend.Backend`"""
92
+ if not self.capabilities.cypher:
93
+ raise PanglossStorageError(
94
+ f"The storage backend {self.name!r} does not run Cypher, which this needs"
95
+ )
96
+ return self.part("backend")
97
+
98
+
99
+ def load(reference: str) -> Storage:
100
+ """The `Storage` named `module:attribute` (`pangloss_memgraph:storage`). The attribute may also be a class or a
101
+ function that makes one, called with nothing."""
102
+ module_name, _, attribute = reference.partition(":")
103
+ if not attribute:
104
+ raise PanglossStorageError(
105
+ f"STORAGE = {reference!r} should be 'module:attribute', like 'pangloss_memgraph:storage'"
106
+ )
107
+ try:
108
+ found = getattr(importlib.import_module(module_name), attribute)
109
+ except (ImportError, AttributeError) as error:
110
+ raise PanglossStorageError(
111
+ f"Cannot find the storage backend {reference!r}: {error}"
112
+ ) from error
113
+ if not isinstance(found, Storage) and callable(found):
114
+ found = found()
115
+ if not isinstance(found, Storage):
116
+ raise PanglossStorageError(
117
+ f"{reference!r} is not a storage backend (a `pangloss_core.storage.Storage`)"
118
+ )
119
+ return found
120
+
121
+
122
+ def from_module(database_module: str) -> Storage:
123
+ """The backend whose parts are in `database_module` (what `DATABASE_MODULE` named): the `storage` of its top-level
124
+ package if that is the one, or else one with no capabilities"""
125
+ try:
126
+ own = getattr(
127
+ importlib.import_module(database_module.partition(".")[0]), "storage", None
128
+ )
129
+ except ImportError:
130
+ own = None
131
+ if isinstance(own, Storage) and own.package == database_module:
132
+ return own
133
+ return Storage(name=database_module, package=database_module)
134
+
135
+
136
+ _loaded: dict[str, Storage] = {}
137
+
138
+
139
+ def storage_of(settings: Any = None) -> Storage:
140
+ """The backend of the settings (by default, those of the project: `pangloss_core.settings.SETTINGS`)"""
141
+ if settings is None:
142
+ from pangloss_core.settings import get_settings
143
+
144
+ settings = get_settings()
145
+ reference = getattr(settings, "STORAGE", None)
146
+ if reference:
147
+ if reference not in _loaded:
148
+ _loaded[reference] = load(reference)
149
+ return _loaded[reference]
150
+ database_module = getattr(settings, "DATABASE_MODULE", None)
151
+ if database_module:
152
+ key = f"DATABASE_MODULE={database_module}"
153
+ if key not in _loaded:
154
+ _loaded[key] = from_module(database_module)
155
+ return _loaded[key]
156
+ raise PanglossStorageError(
157
+ "The settings name no storage backend: give STORAGE, like 'pangloss_memgraph:storage'"
158
+ )
159
+
160
+
161
+ def check_requirements(settings: Any = None) -> None:
162
+ """Whether the backend can do what the installed apps need. An app says what in its package, by the names of the
163
+ `Capabilities` (`requires = {"cypher"}`); an app that says nothing needs nothing"""
164
+ if settings is None:
165
+ from pangloss_core.settings import get_settings
166
+
167
+ settings = get_settings()
168
+ storage = storage_of(settings)
169
+ names = {field.name for field in dataclasses.fields(Capabilities)}
170
+ problems = []
171
+ for app in getattr(settings, "INSTALLED_APPS", []):
172
+ try:
173
+ module = importlib.import_module(app)
174
+ except ModuleNotFoundError as error:
175
+ if error.name == app:
176
+ continue # (not this check's to report)
177
+ raise
178
+ required = set(getattr(module, "requires", ()))
179
+ unknown = sorted(required - names)
180
+ if unknown:
181
+ problems.append(
182
+ f"{app} requires {', '.join(unknown)}, which is not a capability of a storage backend "
183
+ f"(those are {', '.join(sorted(names))})"
184
+ )
185
+ missing = sorted(
186
+ name for name in required & names if not getattr(storage.capabilities, name)
187
+ )
188
+ if missing:
189
+ problems.append(
190
+ f"{app} needs a storage backend with {', '.join(missing)}, which {storage.name!r} does not have"
191
+ )
192
+ if problems:
193
+ raise PanglossStorageError(
194
+ "The storage backend cannot run the installed apps: " + "; ".join(problems)
195
+ )
196
+
197
+
198
+ def warn_database_module(database_module: str) -> None:
199
+ warnings.warn(
200
+ f"DATABASE_MODULE is replaced by STORAGE: instead of DATABASE_MODULE = {database_module!r}, give STORAGE "
201
+ "= '<package>:storage' (for Memgraph, 'pangloss_memgraph:storage'; for Neo4j, 'pangloss_neo4j:storage')",
202
+ DeprecationWarning,
203
+ stacklevel=4,
204
+ )