strata-python 0.2.0__py3-none-any.whl → 0.2.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.
- strata_python/__init__.py +2 -1
- strata_python/cli.py +99 -20
- strata_python/clients/__init__.py +2 -0
- strata_python/clients/models.py +780 -0
- strata_python/db/__init__.py +116 -0
- strata_python/db/__main__.py +5 -0
- strata_python/db/_alembic/env.py +24 -0
- strata_python/db/_alembic/script.py.mako +28 -0
- strata_python/db/cli.py +199 -0
- strata_python/db/config.py +85 -0
- strata_python/db/engine.py +53 -0
- strata_python/db/guard.py +159 -0
- strata_python/db/migrations.py +243 -0
- strata_python/db/models.py +62 -0
- strata_python/db/project.py +98 -0
- strata_python/db/pytest_plugin.py +205 -0
- strata_python/db/scratch.py +143 -0
- strata_python/db/settings.py +63 -0
- strata_python/db/testing.py +43 -0
- strata_python/db/testserver.py +205 -0
- strata_python/oslib.py +44 -5
- strata_python/pages/__init__.py +21 -0
- strata_python/pages/model.py +241 -0
- strata_python/pages/render.py +273 -0
- strata_python/public_check.py +54 -8
- strata_python/pytest_plugin.py +70 -1
- strata_python/settings.py +243 -42
- strata_python/testing.py +257 -0
- strata_python/web.py +15 -6
- strata_python-0.2.2.dist-info/METADATA +334 -0
- strata_python-0.2.2.dist-info/RECORD +38 -0
- {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/entry_points.txt +2 -0
- strata_python-0.2.0.dist-info/METADATA +0 -82
- strata_python-0.2.0.dist-info/RECORD +0 -16
- {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/WHEEL +0 -0
- {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Throwaway databases for tests and autogenerate.
|
|
2
|
+
|
|
3
|
+
Postgres: created and dropped through an admin connection on a throwaway server, never the real one.
|
|
4
|
+
`STRATA_DB_TEST_ADMIN_URL` names it (in CI a service container); unset, a private server is started for the process
|
|
5
|
+
(strata_python.db.testserver). A server that holds the shared database (`STRATA_DB_DATABASE`) is refused: that is
|
|
6
|
+
the real one.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import sqlite3
|
|
13
|
+
import tempfile
|
|
14
|
+
import uuid
|
|
15
|
+
from collections.abc import Generator
|
|
16
|
+
from contextlib import contextmanager
|
|
17
|
+
|
|
18
|
+
from sqlalchemy import create_engine, text
|
|
19
|
+
from sqlalchemy.engine import Engine
|
|
20
|
+
|
|
21
|
+
from .config import normalise_url, shared_database
|
|
22
|
+
from .guard import TEST_ADMIN_URL, THROWAWAY_PREFIX, is_throwaway, testing
|
|
23
|
+
|
|
24
|
+
ADMIN_URL = "STRATA_DB_ADMIN_URL"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class RealServerRefused(RuntimeError):
|
|
28
|
+
"""The test admin URL points at the real server (it holds the shared database)."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
_checked: set[str] = set()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def admin_url() -> str:
|
|
35
|
+
"""Admin URL of the throwaway server for test and scratch databases (starts the private one if needed)."""
|
|
36
|
+
from . import testserver
|
|
37
|
+
|
|
38
|
+
url = normalise_url(os.environ.get(TEST_ADMIN_URL) or testserver.url())
|
|
39
|
+
if url not in _checked:
|
|
40
|
+
refuse_real_server(url)
|
|
41
|
+
_checked.add(url)
|
|
42
|
+
return url
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def refuse_real_server(url: str) -> None:
|
|
46
|
+
"""RealServerRefused when the server behind `url` holds the shared database."""
|
|
47
|
+
database = shared_database()
|
|
48
|
+
if not database: # nothing named, so nothing to recognise; the guard still keeps tests on throwaway names
|
|
49
|
+
return
|
|
50
|
+
eng = create_engine(url, pool_size=1)
|
|
51
|
+
try:
|
|
52
|
+
with eng.connect() as c:
|
|
53
|
+
real = c.execute(text("SELECT 1 FROM pg_database WHERE datname = :d"), {"d": database}).scalar()
|
|
54
|
+
finally:
|
|
55
|
+
eng.dispose()
|
|
56
|
+
if real:
|
|
57
|
+
raise RealServerRefused(
|
|
58
|
+
f"{TEST_ADMIN_URL} points at a server that holds the shared database {database!r}: test and scratch "
|
|
59
|
+
"databases never go on the real server. Unset it (a private throwaway server is started) or point it at "
|
|
60
|
+
"a throwaway one."
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def live_admin_url() -> str:
|
|
65
|
+
"""Admin URL for `strata-db new-app` on the real server: `STRATA_DB_ADMIN_URL`, else you over the local socket.
|
|
66
|
+
Under tests it is the throwaway server instead."""
|
|
67
|
+
if testing():
|
|
68
|
+
return admin_url()
|
|
69
|
+
return normalise_url(os.environ.get(ADMIN_URL, "postgresql+psycopg:///postgres"))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _admin() -> Engine:
|
|
73
|
+
return create_engine(admin_url(), isolation_level="AUTOCOMMIT", pool_size=1)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def pg_available() -> bool:
|
|
77
|
+
"""A throwaway Postgres can be had: `STRATA_DB_TEST_ADMIN_URL` reachable, or server binaries for a private one."""
|
|
78
|
+
from . import testserver
|
|
79
|
+
|
|
80
|
+
if not os.environ.get(TEST_ADMIN_URL) and not testserver.available():
|
|
81
|
+
return False
|
|
82
|
+
try:
|
|
83
|
+
eng = create_engine(admin_url(), pool_size=1)
|
|
84
|
+
with eng.connect() as c:
|
|
85
|
+
c.execute(text("SELECT 1"))
|
|
86
|
+
eng.dispose()
|
|
87
|
+
except RealServerRefused:
|
|
88
|
+
raise
|
|
89
|
+
except Exception: # unreachable for any reason: the caller falls back to SQLite and says so
|
|
90
|
+
return False
|
|
91
|
+
return True
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def pg_url(dbname: str) -> str:
|
|
95
|
+
u = create_engine(admin_url()).url.set(database=dbname)
|
|
96
|
+
return u.render_as_string(hide_password=False)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def create_pg(name: str, template: str | None = None) -> str:
|
|
100
|
+
eng = _admin()
|
|
101
|
+
with eng.connect() as c:
|
|
102
|
+
q = c.dialect.identifier_preparer.quote_identifier
|
|
103
|
+
c.execute(text(f"CREATE DATABASE {q(name)}" + (f" TEMPLATE {q(template)}" if template else "")))
|
|
104
|
+
eng.dispose()
|
|
105
|
+
return pg_url(name)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def drop_pg(name: str) -> None:
|
|
109
|
+
if not is_throwaway(name):
|
|
110
|
+
raise ValueError(f"drop_pg only drops throwaway databases ({THROWAWAY_PREFIX}*), not {name!r}")
|
|
111
|
+
eng = _admin()
|
|
112
|
+
with eng.connect() as c:
|
|
113
|
+
c.execute(text(f"DROP DATABASE IF EXISTS {c.dialect.identifier_preparer.quote_identifier(name)} WITH (FORCE)"))
|
|
114
|
+
eng.dispose()
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def unique(kind: str) -> str:
|
|
118
|
+
"""A throwaway database name: `strata_db_<kind>_<pid>_<random>`."""
|
|
119
|
+
return f"{THROWAWAY_PREFIX}{kind}_{os.getpid()}_{uuid.uuid4().hex[:8]}"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@contextmanager
|
|
123
|
+
def scratch_database(postgres: bool, kind: str = "scratch") -> Generator[str]:
|
|
124
|
+
"""URL of an empty database that is gone afterwards: a temp SQLite file, or a new Postgres database."""
|
|
125
|
+
if postgres:
|
|
126
|
+
name = unique(kind)
|
|
127
|
+
url = create_pg(name)
|
|
128
|
+
try:
|
|
129
|
+
yield url
|
|
130
|
+
finally:
|
|
131
|
+
drop_pg(name)
|
|
132
|
+
else:
|
|
133
|
+
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as d: # Windows: a file still open at exit
|
|
134
|
+
yield "sqlite:///" + os.path.join(d, "scratch.db")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def sqlite_copy_to_memory(path: str) -> sqlite3.Connection:
|
|
138
|
+
"""An in-memory SQLite connection holding a copy of the file (fast per-test clone of a migrated template)."""
|
|
139
|
+
src = sqlite3.connect(path)
|
|
140
|
+
mem = sqlite3.connect(":memory:", check_same_thread=False)
|
|
141
|
+
src.backup(mem)
|
|
142
|
+
src.close()
|
|
143
|
+
return mem
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""An app's settings kept in its database: the `SettingsStore` for `strata_python.settings.Settings.bind`.
|
|
2
|
+
|
|
3
|
+
# models.py: the table is part of the app's models, so its migrations create it
|
|
4
|
+
from strata_python.db.settings import settings_table
|
|
5
|
+
SETTINGS_TABLE = settings_table(Base.metadata)
|
|
6
|
+
|
|
7
|
+
# at service start, after the migrations
|
|
8
|
+
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # copies ~/.<app>/settings.json in once
|
|
9
|
+
|
|
10
|
+
One row per key, the value as JSON text (a string or a list of strings), so the table has the same shape on SQLite and
|
|
11
|
+
Postgres and in every app. Each update is one transaction with an upsert per key, so concurrent saves of different keys
|
|
12
|
+
never lose one (strata-models' service and its CLI write at the same time).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
from collections.abc import Mapping
|
|
19
|
+
|
|
20
|
+
from sqlalchemy import Column, MetaData, String, Table, Text, delete, select
|
|
21
|
+
from sqlalchemy.dialects import postgresql, sqlite
|
|
22
|
+
from sqlalchemy.engine import Engine
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def settings_table(metadata: MetaData, name: str = "settings") -> Table:
|
|
26
|
+
"""The settings table in the app's MetaData (its naming convention names the primary key)."""
|
|
27
|
+
return Table(
|
|
28
|
+
name,
|
|
29
|
+
metadata,
|
|
30
|
+
Column("key", String(200), primary_key=True),
|
|
31
|
+
Column("value", Text, nullable=False), # JSON
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TableStore:
|
|
36
|
+
"""Settings in a `settings_table` (see the module docstring)."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, engine: Engine, table: Table) -> None:
|
|
39
|
+
self.engine = engine
|
|
40
|
+
self.table = table
|
|
41
|
+
|
|
42
|
+
def load(self) -> dict[str, object]:
|
|
43
|
+
with self.engine.connect() as c:
|
|
44
|
+
rows = c.execute(select(self.table.c.key, self.table.c.value)).all()
|
|
45
|
+
out: dict[str, object] = {}
|
|
46
|
+
for key, value in rows:
|
|
47
|
+
try:
|
|
48
|
+
out[str(key)] = json.loads(value)
|
|
49
|
+
except ValueError:
|
|
50
|
+
continue # a row edited by hand into something that is not JSON reads as missing, like a broken file
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
def update(self, changes: Mapping[str, object]) -> dict[str, object]:
|
|
54
|
+
t = self.table
|
|
55
|
+
insert = postgresql.insert if self.engine.dialect.name == "postgresql" else sqlite.insert
|
|
56
|
+
with self.engine.begin() as c:
|
|
57
|
+
for k, v in changes.items():
|
|
58
|
+
if v is None:
|
|
59
|
+
c.execute(delete(t).where(t.c.key == k))
|
|
60
|
+
else:
|
|
61
|
+
stmt = insert(t).values(key=k, value=json.dumps(v))
|
|
62
|
+
c.execute(stmt.on_conflict_do_update(index_elements=[t.c.key], set_={"value": stmt.excluded.value}))
|
|
63
|
+
return self.load()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Standard database tests every app runs, so no app writes (or forgets) its own. Import them into one test module:
|
|
2
|
+
|
|
3
|
+
# tests/unit/test_database.py
|
|
4
|
+
from strata_python.db.testing import test_migrations, test_schema_matches_models # noqa: F401
|
|
5
|
+
|
|
6
|
+
pytest collects imported test functions like local ones. They use the plugin's fixtures, so they run on SQLite by
|
|
7
|
+
default and on a throwaway Postgres with `pytest --pg` (always Postgres for engine = "postgres" apps), and never on
|
|
8
|
+
the app's real database.
|
|
9
|
+
|
|
10
|
+
test_schema_matches_models the migrated test database matches the models (a model changed without a revision)
|
|
11
|
+
test_migrations on a new, empty scratch database: one head and one base, upgrade to head matches the
|
|
12
|
+
models, downgrade to base leaves nothing, and each revision goes up, down one step and
|
|
13
|
+
up again (what `strata-db check` does, as part of the app's own test run)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from sqlalchemy import create_engine
|
|
19
|
+
from sqlalchemy.engine import Engine
|
|
20
|
+
|
|
21
|
+
from .engine import connect
|
|
22
|
+
from .migrations import check_migrations, drift
|
|
23
|
+
from .project import Project
|
|
24
|
+
from .scratch import scratch_database
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def scratch_engine(url: str) -> Engine:
|
|
28
|
+
"""An engine on a scratch database's URL: SQLite with the server-like pragmas, Postgres as it is."""
|
|
29
|
+
return connect(url) if url.startswith("sqlite") else create_engine(url)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_schema_matches_models(db_engine: Engine, db_project: Project) -> None:
|
|
33
|
+
assert drift(db_engine, db_project.metadata) == [] # noqa: S101 (a test, collected in the app's run)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_migrations(db_backend: str, db_project: Project) -> None:
|
|
37
|
+
with scratch_database(db_backend == "postgres") as url:
|
|
38
|
+
eng = scratch_engine(url)
|
|
39
|
+
try:
|
|
40
|
+
problems = check_migrations(eng, db_project.migrations_dir, db_project.metadata)
|
|
41
|
+
finally:
|
|
42
|
+
eng.dispose()
|
|
43
|
+
assert problems == [] # noqa: S101
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""A private, throwaway PostgreSQL server for tests and scratch databases, so they never touch the real one.
|
|
2
|
+
|
|
3
|
+
When `STRATA_DB_TEST_ADMIN_URL` is not set, the first test or scratch database a process needs starts its own
|
|
4
|
+
cluster: `initdb` into a new temp directory, `postgres` listening only on a Unix socket in that directory (no TCP;
|
|
5
|
+
on Windows, loopback on a free port), fsync off. It costs about a second, once per process. It is stopped and deleted
|
|
6
|
+
when the process exits; a small watchdog process does the same if the process is killed instead (SIGKILL, a crashed
|
|
7
|
+
test run), and the next start removes anything a watchdog could not.
|
|
8
|
+
|
|
9
|
+
The server binaries (initdb, pg_ctl, postgres) come from PATH, `PGBIN`, `pg_config --bindir`, or the usual install
|
|
10
|
+
folders (/usr/lib/postgresql/*/bin, C:\\Program Files\\PostgreSQL\\*\\bin). Extensions installed system-wide
|
|
11
|
+
(pgvector) work as usual, and you are its superuser.
|
|
12
|
+
|
|
13
|
+
The URL is exported as `STRATA_DB_TEST_ADMIN_URL`, so subprocesses (strata-db, app scripts under test) reuse it.
|
|
14
|
+
CI may set `STRATA_DB_TEST_ADMIN_URL` to a service container instead, and nothing is started.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import atexit
|
|
20
|
+
import getpass
|
|
21
|
+
import glob
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
import shutil
|
|
25
|
+
import socket
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
import tempfile
|
|
29
|
+
import uuid
|
|
30
|
+
from urllib.parse import quote
|
|
31
|
+
|
|
32
|
+
from strata_python.oslib import WIN, pid_alive
|
|
33
|
+
|
|
34
|
+
from .guard import TEST_ADMIN_URL
|
|
35
|
+
|
|
36
|
+
PREFIX = "strata-db-pg-"
|
|
37
|
+
_url: str | None = None
|
|
38
|
+
|
|
39
|
+
# Runs in its own process, so it outlives a killed test run: wait for the owner to go, then stop and delete.
|
|
40
|
+
WATCHDOG = """
|
|
41
|
+
import os, shutil, subprocess, sys, time
|
|
42
|
+
from strata_python.oslib import pid_alive
|
|
43
|
+
owner, pg_ctl, d = int(sys.argv[1]), sys.argv[2], sys.argv[3]
|
|
44
|
+
while pid_alive(owner):
|
|
45
|
+
time.sleep(2)
|
|
46
|
+
subprocess.run([pg_ctl, "-D", d + "/data", "-m", "immediate", "stop"], capture_output=True, cwd=os.path.dirname(pg_ctl))
|
|
47
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _version(path: str) -> int:
|
|
52
|
+
m = re.search(r"[\\/](\d+)[\\/]bin", path)
|
|
53
|
+
return int(m.group(1)) if m else 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _has_initdb(d: str) -> bool:
|
|
57
|
+
return shutil.which("initdb", path=d) is not None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _bindir() -> str | None:
|
|
61
|
+
initdb = shutil.which("initdb")
|
|
62
|
+
if initdb and shutil.which("pg_ctl"):
|
|
63
|
+
return os.path.dirname(initdb)
|
|
64
|
+
if (d := os.environ.get("PGBIN")) and _has_initdb(d): # set on GitHub's Windows runners
|
|
65
|
+
return d
|
|
66
|
+
if pg_config := shutil.which("pg_config"):
|
|
67
|
+
try:
|
|
68
|
+
d = subprocess.run( # noqa: S603 (pg_config found on PATH, fixed argument)
|
|
69
|
+
[pg_config, "--bindir"], capture_output=True, text=True, check=True
|
|
70
|
+
).stdout.strip()
|
|
71
|
+
if _has_initdb(d):
|
|
72
|
+
return d
|
|
73
|
+
except (OSError, subprocess.CalledProcessError):
|
|
74
|
+
pass
|
|
75
|
+
patterns = ["C:/Program Files/PostgreSQL/*/bin"] if WIN else ["/usr/lib/postgresql/*/bin"]
|
|
76
|
+
found = sorted((d for p in patterns for d in glob.glob(p) if _has_initdb(d)), key=_version)
|
|
77
|
+
return found[-1] if found else None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def available() -> bool:
|
|
81
|
+
return _bindir() is not None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _tmp_root() -> str:
|
|
85
|
+
# A Unix socket path must fit in ~107 bytes: a long TMPDIR falls back to /tmp.
|
|
86
|
+
t = tempfile.gettempdir()
|
|
87
|
+
return t if WIN or len(t) < 60 else "/tmp" # noqa: S108 (a private 0700 mkdtemp below it, not a fixed file)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _tool(bindir: str, name: str) -> str:
|
|
91
|
+
return shutil.which(name, path=bindir) or os.path.join(bindir, name)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _stop(d: str, bindir: str | None) -> None:
|
|
95
|
+
data = os.path.join(d, "data")
|
|
96
|
+
if bindir and os.path.exists(os.path.join(data, "postmaster.pid")):
|
|
97
|
+
subprocess.run( # noqa: S603 (the server's own pg_ctl on its own data dir)
|
|
98
|
+
[_tool(bindir, "pg_ctl"), "-D", data, "-m", "immediate", "-w", "stop"], capture_output=True, cwd=bindir
|
|
99
|
+
)
|
|
100
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def reap(bindir: str | None = None, root: str | None = None) -> None:
|
|
104
|
+
"""Stop and delete private servers whose owning process has gone (left by a killed run), in `root` (default: the
|
|
105
|
+
folder servers are started in)."""
|
|
106
|
+
bindir = bindir or _bindir()
|
|
107
|
+
for d in glob.glob(os.path.join(root or _tmp_root(), PREFIX + "*")):
|
|
108
|
+
try:
|
|
109
|
+
with open(os.path.join(d, "owner"), encoding="utf-8") as f:
|
|
110
|
+
owner = int(f.read().strip())
|
|
111
|
+
except (OSError, ValueError):
|
|
112
|
+
continue
|
|
113
|
+
if not pid_alive(owner):
|
|
114
|
+
_stop(d, bindir)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _free_port() -> int:
|
|
118
|
+
with socket.socket() as s:
|
|
119
|
+
s.bind(("127.0.0.1", 0))
|
|
120
|
+
return int(s.getsockname()[1])
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _initdb(bindir: str, data: str, user: str) -> subprocess.CompletedProcess[str]:
|
|
124
|
+
cmd = [_tool(bindir, "initdb"), "-D", data, "-A", "trust", "-U", user, "--no-sync", "-E", "UTF8"]
|
|
125
|
+
# Same collation as a current server (builtin C.UTF-8, PostgreSQL 17+); an older initdb falls back to its default.
|
|
126
|
+
r = subprocess.run( # noqa: S603
|
|
127
|
+
[*cmd, "--locale-provider=builtin", "--builtin-locale=C.UTF-8"], capture_output=True, text=True, cwd=bindir
|
|
128
|
+
)
|
|
129
|
+
if r.returncode:
|
|
130
|
+
shutil.rmtree(data, ignore_errors=True)
|
|
131
|
+
r = subprocess.run(cmd, capture_output=True, text=True, cwd=bindir) # noqa: S603
|
|
132
|
+
return r
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _watch(owner: int, bindir: str, d: str) -> None:
|
|
136
|
+
# DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: the watchdog must not die with the test run's console
|
|
137
|
+
flags = 0x00000008 | 0x00000200 if WIN else 0
|
|
138
|
+
subprocess.Popen( # noqa: S603 (this interpreter, a fixed script)
|
|
139
|
+
[sys.executable, "-c", WATCHDOG, str(owner), _tool(bindir, "pg_ctl"), d],
|
|
140
|
+
stdin=subprocess.DEVNULL,
|
|
141
|
+
stdout=subprocess.DEVNULL,
|
|
142
|
+
stderr=subprocess.DEVNULL,
|
|
143
|
+
start_new_session=not WIN,
|
|
144
|
+
creationflags=flags,
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def url() -> str:
|
|
149
|
+
"""Admin URL of this process's private server, starting it on first use."""
|
|
150
|
+
global _url
|
|
151
|
+
if _url:
|
|
152
|
+
return _url
|
|
153
|
+
bindir = _bindir()
|
|
154
|
+
if not bindir:
|
|
155
|
+
raise RuntimeError(
|
|
156
|
+
"no PostgreSQL server binaries (initdb, pg_ctl) found for a private test server: install the PostgreSQL "
|
|
157
|
+
f"server package, or set {TEST_ADMIN_URL} to a throwaway server"
|
|
158
|
+
)
|
|
159
|
+
reap(bindir)
|
|
160
|
+
if WIN:
|
|
161
|
+
# initdb and pg_ctl run as administrator drop to a restricted token, which cannot open a folder made with
|
|
162
|
+
# mkdtemp (0o700 becomes an owner-only ACL from Python 3.13): make it with the default ACL instead.
|
|
163
|
+
d = os.path.join(_tmp_root(), PREFIX + uuid.uuid4().hex[:8])
|
|
164
|
+
os.mkdir(d)
|
|
165
|
+
else:
|
|
166
|
+
d = tempfile.mkdtemp(prefix=PREFIX, dir=_tmp_root())
|
|
167
|
+
with open(os.path.join(d, "owner"), "w", encoding="utf-8") as f:
|
|
168
|
+
f.write(str(os.getpid()))
|
|
169
|
+
data, user = os.path.join(d, "data"), getpass.getuser()
|
|
170
|
+
r = _initdb(bindir, data, user)
|
|
171
|
+
if r.returncode:
|
|
172
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
173
|
+
raise RuntimeError(f"initdb failed for the private test server:\n{r.stderr}")
|
|
174
|
+
if WIN: # no Unix sockets for libpq here: loopback only, on a port nobody else has
|
|
175
|
+
port = _free_port()
|
|
176
|
+
# In the config file, not -o: pg_ctl's command line on Windows keeps the quotes of '' as the folder's name.
|
|
177
|
+
with open(os.path.join(data, "postgresql.auto.conf"), "a", encoding="utf-8") as conf:
|
|
178
|
+
conf.write("unix_socket_directories = ''\n")
|
|
179
|
+
listen = f"-c listen_addresses=127.0.0.1 -p {port}"
|
|
180
|
+
where = f"127.0.0.1:{port}/postgres"
|
|
181
|
+
else:
|
|
182
|
+
listen = f"-k {d} -c listen_addresses=''"
|
|
183
|
+
where = f"localhost/postgres?host={quote(d, safe='')}" # also parses as a WHATWG URL
|
|
184
|
+
opts = f"{listen} -c fsync=off -c synchronous_commit=off -c full_page_writes=off -c max_connections=200"
|
|
185
|
+
log, out = os.path.join(d, "log"), os.path.join(d, "pg_ctl.out")
|
|
186
|
+
# pg_ctl's output goes to a file, not a pipe: on Windows the server it starts inherits the pipe, so reading it
|
|
187
|
+
# to the end would wait for the server to exit.
|
|
188
|
+
with open(out, "w", encoding="utf-8") as sink:
|
|
189
|
+
r = subprocess.run( # noqa: S603 (the server's own pg_ctl)
|
|
190
|
+
[_tool(bindir, "pg_ctl"), "-D", data, "-l", log, "-o", opts, "-w", "start"],
|
|
191
|
+
stdin=subprocess.DEVNULL,
|
|
192
|
+
stdout=sink,
|
|
193
|
+
stderr=subprocess.STDOUT,
|
|
194
|
+
cwd=bindir,
|
|
195
|
+
)
|
|
196
|
+
if r.returncode:
|
|
197
|
+
said = "".join(open(f, encoding="utf-8", errors="replace").read() for f in (out, log) if os.path.exists(f)) # noqa: SIM115
|
|
198
|
+
_stop(d, bindir)
|
|
199
|
+
raise RuntimeError(f"could not start the private test server:\n{said}")
|
|
200
|
+
owner = os.getpid()
|
|
201
|
+
_watch(owner, bindir, d)
|
|
202
|
+
atexit.register(lambda: os.getpid() == owner and _stop(d, bindir)) # not in forked children
|
|
203
|
+
_url = f"postgresql+psycopg://{quote(user)}@{where}"
|
|
204
|
+
os.environ[TEST_ADMIN_URL] = _url
|
|
205
|
+
return _url
|
strata_python/oslib.py
CHANGED
|
@@ -93,18 +93,57 @@ def kill_tree(pid: int | str, sig: int = 15) -> None:
|
|
|
93
93
|
os.kill(int(pid), sig)
|
|
94
94
|
|
|
95
95
|
|
|
96
|
-
|
|
97
|
-
|
|
96
|
+
# ioprio_set's syscall number per Linux architecture (Python has no wrapper). Elsewhere `ionice` does the same.
|
|
97
|
+
_IOPRIO_SET = {"x86_64": 251, "aarch64": 30, "riscv64": 30, "i686": 289, "i386": 289, "armv7l": 314, "ppc64le": 273}
|
|
98
|
+
_IOPRIO_IDLE = 3 << 13 # IOPRIO_CLASS_IDLE in the top bits of the priority value; idle has no level
|
|
99
|
+
MAC = sys.platform == "darwin"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def lower_priority(nice: int = 19, io: bool = False) -> None:
|
|
103
|
+
"""Run this process at lower CPU priority (nice value on POSIX, below-normal/idle class on Windows). Children
|
|
104
|
+
inherit it. Best effort: a refusal is skipped.
|
|
105
|
+
|
|
106
|
+
`io=True` also lowers its disk priority, for batch jobs that read many large files (hashing an archive, exiftool
|
|
107
|
+
over a folder) and should not slow interactive use of the same disk: the idle I/O class on Linux (children
|
|
108
|
+
inherit it), background mode on Windows (CPU and I/O; this process only, Windows does not pass it on), I/O
|
|
109
|
+
throttling on macOS (this process)."""
|
|
98
110
|
if WIN:
|
|
99
111
|
import ctypes
|
|
100
112
|
|
|
101
113
|
with contextlib.suppress(Exception):
|
|
102
|
-
ctypes.windll.kernel32
|
|
103
|
-
|
|
104
|
-
|
|
114
|
+
k32 = ctypes.windll.kernel32
|
|
115
|
+
k32.SetPriorityClass(k32.GetCurrentProcess(), 0x40 if nice >= 15 else 0x4000) # IDLE / BELOW_NORMAL
|
|
116
|
+
if io:
|
|
117
|
+
k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00100000) # PROCESS_MODE_BACKGROUND_BEGIN
|
|
105
118
|
return
|
|
106
119
|
with contextlib.suppress(OSError, AttributeError):
|
|
107
120
|
os.nice(nice)
|
|
121
|
+
if io:
|
|
122
|
+
_lower_io_priority()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _lower_io_priority(pid: int = 0) -> None:
|
|
126
|
+
"""Idle I/O for `pid` (0: this process). Other pids are for the tests, which must not lower their own."""
|
|
127
|
+
import ctypes
|
|
128
|
+
import ctypes.util
|
|
129
|
+
import platform
|
|
130
|
+
import shutil
|
|
131
|
+
|
|
132
|
+
if MAC: # pragma: no cover - the Linux leg runs the tests that count; macOS is best effort
|
|
133
|
+
with contextlib.suppress(Exception):
|
|
134
|
+
libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)
|
|
135
|
+
libc.setiopolicy_np(0, 0, 3) # IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE
|
|
136
|
+
return
|
|
137
|
+
number = _IOPRIO_SET.get(platform.machine()) if sys.platform.startswith("linux") else None
|
|
138
|
+
if number is not None:
|
|
139
|
+
with contextlib.suppress(Exception):
|
|
140
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
141
|
+
if libc.syscall(number, 1, pid, _IOPRIO_IDLE) == 0: # IOPRIO_WHO_PROCESS
|
|
142
|
+
return
|
|
143
|
+
ionice = shutil.which("ionice")
|
|
144
|
+
if ionice: # another architecture or a refused syscall: util-linux's ionice does the same for our pid
|
|
145
|
+
with contextlib.suppress(OSError):
|
|
146
|
+
subprocess.run([ionice, "-c3", "-p", str(pid or os.getpid())], capture_output=True, check=False) # noqa: S603 (ionice from PATH, our pid)
|
|
108
147
|
|
|
109
148
|
|
|
110
149
|
def venv_python(venv: str) -> str:
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Scanned pages rebuilt as PDFs: the page description (`model`, plain data) and its renderer (`render`, the `[pdf]`
|
|
2
|
+
extra: ReportLab to write, pdfium to read back). See `model` for the shape and `render` for what is drawn how.
|
|
3
|
+
|
|
4
|
+
from strata_python.pages import Block, Figure, Line, Page, Span
|
|
5
|
+
from strata_python.pages.render import rasterise, read_text, render"""
|
|
6
|
+
|
|
7
|
+
from strata_python.pages.model import (
|
|
8
|
+
ALIGNS,
|
|
9
|
+
FIGURE_KINDS,
|
|
10
|
+
ROLES,
|
|
11
|
+
STYLES,
|
|
12
|
+
Block,
|
|
13
|
+
Box,
|
|
14
|
+
Figure,
|
|
15
|
+
Line,
|
|
16
|
+
Page,
|
|
17
|
+
PageError,
|
|
18
|
+
Span,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = ["ALIGNS", "FIGURE_KINDS", "ROLES", "STYLES", "Block", "Box", "Figure", "Line", "Page", "PageError", "Span"]
|