strata-python 0.2.1__py3-none-any.whl → 0.2.3__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.
@@ -0,0 +1,149 @@
1
+ """The data shapes the strata apps share across their HTTP APIs, written once as pydantic models.
2
+
3
+ Every app's server returned these as plain dicts and every web app retyped them by hand (`web/src/api.ts`), with the
4
+ field names drifting (a job's `state` or `status`, progress text as `current`, `text` or `stage`). Declared as a route's
5
+ `response_model`, a shape is checked on the way out and lands in `/api/openapi.json`, so a web app's TypeScript can be
6
+ generated from it instead of copied.
7
+
8
+ Health GET /api/health: ok, version, commit, plus the app's own fields (web.base_app)
9
+ SystemInfo GET /api/system: version, commit, Python, platform, folders with their disks, services it calls (web.add_system)
10
+ ErrorBody every error response: detail, and a payload when the error carries one (web.add_error_handlers)
11
+ Task a job or task row: id, kind, state, times, error, result, progress (tasks.Queue answers these)
12
+ Progress how far a task has got: done of total, a line of text, the stage (tasks.ProgressReporter writes these)
13
+ Page[T] one page of a list: items, the cursor for the next page (None at the end), the total when it is known
14
+ FileRef a file by content and place: sha256, size, mtime, root, rel (the path under that root)
15
+ Judgment one pairwise choice by a person or a model: a, b, the winner (a, b or tie), who, when, undone when
16
+
17
+ Times are timezone-aware datetimes, sent as ISO 8601 with their offset: the apps had both ISO text and float epochs,
18
+ and only one of those reads correctly in a browser. Use `utc(epoch)` to turn a stored float into one."""
19
+
20
+ from __future__ import annotations
21
+
22
+ import datetime
23
+ from typing import Any, Generic, Literal, TypeVar
24
+
25
+ from pydantic import BaseModel, ConfigDict, Field
26
+
27
+
28
+ def utc(epoch: float | None) -> datetime.datetime | None:
29
+ """A float epoch (`time.time()`) as an aware UTC datetime; None stays None."""
30
+ return None if epoch is None else datetime.datetime.fromtimestamp(epoch, datetime.UTC)
31
+
32
+
33
+ class Health(BaseModel):
34
+ """What `GET /api/health` answers. Extra fields are the app's own (strata-models adds `gpu`)."""
35
+
36
+ model_config = ConfigDict(extra="allow")
37
+ ok: bool
38
+ version: str
39
+ commit: str | None = None # the source commit the server runs, so a probe can tell a stale deploy
40
+
41
+
42
+ class Folder(BaseModel):
43
+ """A folder the app uses, and the disk it is on (None when the folder does not exist yet)."""
44
+
45
+ name: str
46
+ path: str
47
+ exists: bool
48
+ free_bytes: int | None = None
49
+ total_bytes: int | None = None
50
+
51
+
52
+ class ServiceStatus(BaseModel):
53
+ """Another strata service this app calls, as its health endpoint answered just now."""
54
+
55
+ name: str
56
+ url: str
57
+ ok: bool
58
+ version: str | None = None
59
+ detail: str | None = None # why it is not ok: not reachable, or what it answered
60
+
61
+
62
+ class SystemInfo(BaseModel):
63
+ """What `GET /api/system` answers: what is running, where its data is, and whether its services answer."""
64
+
65
+ model_config = ConfigDict(extra="allow")
66
+ version: str
67
+ commit: str | None = None
68
+ python: str
69
+ platform: str
70
+ started_at: datetime.datetime
71
+ folders: list[Folder] = Field(default_factory=lambda: [])
72
+ services: list[ServiceStatus] = Field(default_factory=lambda: [])
73
+
74
+
75
+ class ErrorBody(BaseModel):
76
+ """The body of every error the app answers. `detail` is what FastAPI already uses, so clients that read it keep
77
+ working; `payload` carries what the error wants the client to have (the job row of a refused job)."""
78
+
79
+ detail: str
80
+ payload: Any = None
81
+
82
+
83
+ TaskState = Literal["queued", "running", "done", "failed", "cancelled"]
84
+ FINISHED: frozenset[str] = frozenset({"done", "failed", "cancelled"})
85
+
86
+
87
+ class Progress(BaseModel):
88
+ """How far a task has got. `total` None means not known yet; `text` is the line a person reads ("Page 3 of 40")."""
89
+
90
+ done: float = 0
91
+ total: float | None = None
92
+ text: str = ""
93
+ stage: str | None = None
94
+ at: datetime.datetime | None = None
95
+
96
+ @property
97
+ def fraction(self) -> float | None:
98
+ return None if not self.total else min(max(self.done / self.total, 0.0), 1.0)
99
+
100
+
101
+ class Task(BaseModel):
102
+ """A job or task row as an API answers it."""
103
+
104
+ id: int | str
105
+ kind: str
106
+ state: TaskState
107
+ created_at: datetime.datetime
108
+ started_at: datetime.datetime | None = None
109
+ finished_at: datetime.datetime | None = None
110
+ error: str | None = None
111
+ result: Any = None
112
+ progress: Progress | None = None
113
+ attempts: int = 0
114
+ domain: str | None = None # what the task is about in the app's terms (a book id, a folder)
115
+
116
+
117
+ T = TypeVar("T")
118
+
119
+
120
+ class Page(BaseModel, Generic[T]): # Generic, not `Page[T]`: Python 3.11 is supported
121
+ """One page of a list. `next` is an opaque cursor (pass it back as `after`), None on the last page; a cursor, not an
122
+ offset, so rows added while a person pages through do not repeat or vanish."""
123
+
124
+ items: list[T]
125
+ next: str | None = None
126
+ total: int | None = None
127
+
128
+
129
+ class FileRef(BaseModel):
130
+ """A file by content and place. `sha256` is lower-case hex (the apps had hex and raw bytes); `rel` is the path under
131
+ `root` with `/` separators, so the same file found from two machines or two apps joins on (sha256) or (root, rel)."""
132
+
133
+ sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
134
+ size: int = Field(ge=0)
135
+ mtime: float
136
+ root: str
137
+ rel: str
138
+
139
+
140
+ class Judgment(BaseModel):
141
+ """One pairwise choice: `a` and `b` are the two things compared, `winner` names a side (or a tie), `rater` who chose
142
+ (a person's name in the app, or a model's). Undoing keeps the row and sets `undone_at`, so a ranking can be rebuilt."""
143
+
144
+ a: str
145
+ b: str
146
+ winner: Literal["a", "b", "tie"]
147
+ rater: str
148
+ at: datetime.datetime
149
+ undone_at: datetime.datetime | None = None
@@ -2,10 +2,13 @@
2
2
  SQLAlchemy models, Alembic migrations generated from them, the `strata-db` command and pytest fixtures. Install the
3
3
  extra: `strata-python[db]`.
4
4
 
5
- from strata_python.db import connect, make_base, session
6
- from sqlalchemy.orm import Mapped, mapped_column
5
+ from sqlalchemy import MetaData
6
+ from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column
7
+ from strata_python.db import NAMING_CONVENTION, connect, session
8
+
9
+ class Base(MappedAsDataclass, DeclarativeBase): # the app's own base: written out, so ty and pyright accept it
10
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
7
11
 
8
- Base = make_base()
9
12
  class Note(Base): # a typed record; Alembic generates the table from it
10
13
  __tablename__ = "notes"
11
14
  id: Mapped[int] = mapped_column(primary_key=True, init=False)
@@ -1,7 +1,11 @@
1
1
  """Declarative bases for apps' models.
2
2
 
3
- from strata_python.db import make_base
4
- Base = make_base() # one per app, in its models module
3
+ from sqlalchemy import MetaData
4
+ from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column
5
+ from strata_python.db import NAMING_CONVENTION
6
+
7
+ class Base(MappedAsDataclass, DeclarativeBase): # one per app, in its models module
8
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
5
9
 
6
10
  class Note(Base):
7
11
  __tablename__ = "notes"
@@ -13,6 +17,12 @@ convention gives every index and constraint a stable name, which Alembic needs t
13
17
  especially on SQLite (batch mode recreates tables and must name what it recreates). It must stay exactly as it is:
14
18
  the apps' existing revisions and databases carry these names, and a change would make every one of them drift.
15
19
  `Base` is a ready-made shared one for scripts that only ever load one app's models.
20
+
21
+ An app writes its base class out, as above, rather than `Base = make_base()` (issue #20): ty cannot take a value of
22
+ type `type[...]` as a base class, since it cannot know that value's MRO, and the gate fails on its warning. pyright
23
+ accepts either. A class statement cannot be shared from here instead: SQLAlchemy makes only a *direct* subclass of
24
+ DeclarativeBase a base with its own registry and MetaData, so a subclass of a base defined here would put every app's
25
+ tables in one MetaData. `make_base()` stays for code that needs a fresh base at run time (tests, scripts).
16
26
  """
17
27
 
18
28
  from __future__ import annotations
@@ -39,7 +49,9 @@ if TYPE_CHECKING:
39
49
 
40
50
 
41
51
  def make_base() -> type[DataclassBase]:
42
- """A new declarative base with its own MetaData (so two apps' models never mix in one process)."""
52
+ """A new declarative base with its own MetaData (so two apps' models never mix in one process), for code that needs
53
+ one at run time. An app's models module writes its class out instead (see the module docstring): ty cannot
54
+ subclass the result."""
43
55
 
44
56
  class AppBase(MappedAsDataclass, DeclarativeBase):
45
57
  metadata = MetaData(naming_convention=NAMING_CONVENTION)
@@ -26,6 +26,20 @@ if TYPE_CHECKING:
26
26
  TABLE = "strata-db"
27
27
 
28
28
 
29
+ def find_table(start: str | os.PathLike[str] | None = None) -> tuple[Path, dict[str, Any]] | None:
30
+ """The nearest pyproject.toml with [tool.strata-db], from start (default: cwd) upwards: its folder and the table.
31
+ Standard library only, so the pytest plugin can ask without loading SQLAlchemy."""
32
+ p = Path(start or os.getcwd()).resolve()
33
+ for d in [p, *p.parents] if p.is_dir() else [p.parent, *p.parent.parents]:
34
+ f = d / "pyproject.toml"
35
+ if not f.is_file():
36
+ continue
37
+ cfg = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {})).get(TABLE)
38
+ if cfg:
39
+ return d, cast("dict[str, Any]", cfg)
40
+ return None
41
+
42
+
29
43
  @dataclass
30
44
  class Project:
31
45
  root: Path
@@ -41,22 +55,21 @@ class Project:
41
55
  @classmethod
42
56
  def load(cls, start: str | os.PathLike[str] | None = None) -> Project:
43
57
  """Find the nearest pyproject.toml with [tool.strata-db], from start (default: cwd) upwards."""
44
- p = Path(start or os.getcwd()).resolve()
45
- for d in [p, *p.parents] if p.is_dir() else [p.parent, *p.parent.parents]:
46
- f = d / "pyproject.toml"
47
- if not f.is_file():
48
- continue
49
- cfg = cast("dict[str, Any]", tomllib.loads(f.read_text(encoding="utf-8")).get("tool", {})).get(TABLE)
50
- if cfg:
51
- return cls(
52
- root=d,
53
- app=cfg["app"],
54
- models=cfg["models"],
55
- migrations_dir=(d / cfg.get("migrations", "migrations")).resolve(),
56
- engine=cfg.get("engine", "portable"),
57
- schema=cfg.get("schema", cfg["app"]),
58
- )
59
- raise FileNotFoundError(f"no pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)")
58
+ found = find_table(start)
59
+ if found is None:
60
+ p = Path(start or os.getcwd()).resolve()
61
+ raise FileNotFoundError(
62
+ f"no pyproject.toml with [tool.{TABLE}] in {p} or above (strata-db init writes one)"
63
+ )
64
+ d, cfg = found
65
+ return cls(
66
+ root=d,
67
+ app=cfg["app"],
68
+ models=cfg["models"],
69
+ migrations_dir=(d / cfg.get("migrations", "migrations")).resolve(),
70
+ engine=cfg.get("engine", "portable"),
71
+ schema=cfg.get("schema", cfg["app"]),
72
+ )
60
73
 
61
74
  @property
62
75
  def metadata(self) -> MetaData:
@@ -11,26 +11,34 @@ unless the db extra is installed: nothing here imports SQLAlchemy until a fixtur
11
11
 
12
12
  Default backend: SQLite. The migrations run ONCE per session into a template; each test gets a copy (in memory for
13
13
  db_engine, a file for db_url), so a test costs a copy, not a migration.
14
- `pytest --pg` (or STRATA_DB_TEST=postgres, or engine = "postgres" in the project) uses a real Postgres instead:
14
+ `pytest --pg` (also `--strata-pg`; or STRATA_DB_TEST=postgres, or engine = "postgres" in the project) uses a real Postgres instead:
15
15
  a template database is migrated once and each test gets `CREATE DATABASE ... TEMPLATE` (a file copy on the server,
16
16
  milliseconds), dropped afterwards. That server is a throwaway one, never the real server: STRATA_DB_TEST_ADMIN_URL
17
17
  if set (CI), otherwise a private server started for the run (strata_python.db.testserver).
18
18
 
19
- With the extra installed, loading this plugin switches on the test guard (strata_python.db.guard) before conftest.py
20
- or any app module is imported: for the whole run, every Postgres connection in the process (connect(),
19
+ When is it on? Only for an app that uses strata_python.db: SQLAlchemy and Alembic are installed (the db extra) AND
20
+ the project says so, by a [tool.strata-db] table in its pyproject.toml (found from pytest's rootdir upwards) or by
21
+ `strata_db = true` in its pytest ini options (`strata_db = false` turns it off whatever else is there). Having
22
+ SQLAlchemy and Alembic installed by some other package is not enough (issue #19): such an app, or one still on the old
23
+ database package, must be able to run pytest with this plugin registered and inert.
24
+
25
+ When it is on, the plugin switches on the test guard (strata_python.db.guard) in pytest_load_initial_conftests, before
26
+ conftest.py or any app module is imported (or, when it is loaded from a conftest.py itself, as in this repo's own
27
+ tests, in pytest_configure, before any test runs): for the whole run, every Postgres connection in the process (connect(),
21
28
  create_engine(), psycopg.connect()) and in its subprocesses (STRATA_DB_TESTING=1) is refused unless it is a
22
29
  throwaway strata_db_* database. A test that would reach the shared database fails with LiveDatabaseRefused instead.
23
30
  """
24
31
 
25
32
  from __future__ import annotations
26
33
 
34
+ import contextlib
27
35
  import os
28
36
  import shutil
29
37
  import tempfile
30
38
  from collections.abc import Iterator
31
39
  from importlib.util import find_spec
32
40
  from pathlib import Path
33
- from typing import TYPE_CHECKING
41
+ from typing import TYPE_CHECKING, cast
34
42
 
35
43
  import pytest
36
44
 
@@ -44,25 +52,71 @@ if TYPE_CHECKING:
44
52
 
45
53
  TEST_BACKEND = "STRATA_DB_TEST"
46
54
  INSTALLED = find_spec("sqlalchemy") is not None and find_spec("alembic") is not None
47
-
48
- if INSTALLED:
49
- guard.enter_test_mode() # at import: before conftest.py and the app's modules are loaded
55
+ INI = "strata_db"
56
+ PG_DEST = "strata_db_pg"
57
+ PG_HELP = "run strata_python.db fixtures on a throwaway PostgreSQL"
58
+ _ACTIVE = pytest.StashKey[bool]() # per Config, not a module global: pytester runs nested sessions in one process
50
59
 
51
60
 
52
61
  def pytest_addoption(parser: pytest.Parser) -> None:
53
- parser.addoption("--pg", action="store_true", help="run strata_python.db fixtures on a throwaway PostgreSQL")
62
+ # Only names of our own here: another plugin (the old database package) may also add --pg, and two addoption
63
+ # calls for one name raise. --pg itself is added once we know the plugin is on (_activate).
64
+ parser.addoption("--strata-pg", action="store_true", dest=PG_DEST, help=PG_HELP)
65
+ parser.addini(INI, type="bool", default=None, help="turn the strata_python.db fixtures and test guard on or off")
66
+
67
+
68
+ def active(config: pytest.Config) -> bool:
69
+ """Whether this run uses strata_python.db (see the module docstring)."""
70
+ if not INSTALLED:
71
+ return False
72
+ wanted = cast("bool | None", config.getini(INI))
73
+ if wanted is not None:
74
+ return bool(wanted)
75
+ from .project import find_table
76
+
77
+ return find_table(config.rootpath) is not None
78
+
79
+
80
+ def _activate(config: pytest.Config, parser: pytest.Parser | None) -> None:
81
+ if _ACTIVE in config.stash:
82
+ return
83
+ config.stash[_ACTIVE] = on = active(config)
84
+ if not on:
85
+ return
86
+ guard.enter_test_mode()
87
+ if parser is not None: # still before the full command line is parsed, so --pg given there is recognised
88
+ # ValueError: another plugin (the old database package) has --pg; it means the same, and db_backend reads it
89
+ with contextlib.suppress(ValueError):
90
+ parser.addoption("--pg", action="store_true", dest=PG_DEST, help=PG_HELP)
91
+
92
+
93
+ @pytest.hookimpl(tryfirst=True)
94
+ def pytest_load_initial_conftests(early_config: pytest.Config, parser: pytest.Parser) -> None:
95
+ _activate(early_config, parser) # entry point or -p: before conftest.py and the app's modules are imported
96
+
97
+
98
+ def pytest_configure(config: pytest.Config) -> None:
99
+ _activate(config, None) # loaded from a conftest.py (pytest_plugins): the hook above has already run
54
100
 
55
101
 
56
102
  @pytest.fixture(scope="session")
57
103
  def db_project(request: pytest.FixtureRequest) -> Project:
58
104
  from .project import Project
59
105
 
106
+ if not request.config.stash.get(_ACTIVE, False):
107
+ pytest.fail(
108
+ "the strata_python.db fixtures are off: they need the db extra (strata-python[db]) and a [tool.strata-db]"
109
+ f" table in pyproject.toml, or {INI} = true in the pytest ini options",
110
+ pytrace=False,
111
+ )
60
112
  return Project.load(request.config.rootpath)
61
113
 
62
114
 
63
115
  @pytest.fixture(scope="session")
64
116
  def db_backend(request: pytest.FixtureRequest, db_project: Project) -> str:
65
- pg = request.config.getoption("--pg") or os.environ.get(TEST_BACKEND) == "postgres" or db_project.postgres_only
117
+ cfg = request.config
118
+ pg = cfg.getoption(PG_DEST) or cfg.getoption("--pg", default=False) # ours, or another plugin's --pg
119
+ pg = pg or os.environ.get(TEST_BACKEND) == "postgres" or db_project.postgres_only
66
120
  return "postgres" if pg else "sqlite"
67
121
 
68
122
 
@@ -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()
strata_python/oslib.py CHANGED
@@ -9,9 +9,10 @@ import contextlib
9
9
  import os
10
10
  import subprocess
11
11
  import sys
12
+ import threading
12
13
  import time
13
- from collections.abc import Generator
14
- from typing import IO, Any, cast
14
+ from collections.abc import Generator, Mapping
15
+ from typing import IO, Any, Literal, cast, overload
15
16
 
16
17
  WIN = sys.platform == "win32"
17
18
 
@@ -93,18 +94,57 @@ def kill_tree(pid: int | str, sig: int = 15) -> None:
93
94
  os.kill(int(pid), sig)
94
95
 
95
96
 
96
- def lower_priority(nice: int = 19) -> None:
97
- """Run this process at lower CPU priority (nice value on POSIX, below-normal/idle class on Windows). Children inherit it."""
97
+ # ioprio_set's syscall number per Linux architecture (Python has no wrapper). Elsewhere `ionice` does the same.
98
+ _IOPRIO_SET = {"x86_64": 251, "aarch64": 30, "riscv64": 30, "i686": 289, "i386": 289, "armv7l": 314, "ppc64le": 273}
99
+ _IOPRIO_IDLE = 3 << 13 # IOPRIO_CLASS_IDLE in the top bits of the priority value; idle has no level
100
+ MAC = sys.platform == "darwin"
101
+
102
+
103
+ def lower_priority(nice: int = 19, io: bool = False) -> None:
104
+ """Run this process at lower CPU priority (nice value on POSIX, below-normal/idle class on Windows). Children
105
+ inherit it. Best effort: a refusal is skipped.
106
+
107
+ `io=True` also lowers its disk priority, for batch jobs that read many large files (hashing an archive, exiftool
108
+ over a folder) and should not slow interactive use of the same disk: the idle I/O class on Linux (children
109
+ inherit it), background mode on Windows (CPU and I/O; this process only, Windows does not pass it on), I/O
110
+ throttling on macOS (this process)."""
98
111
  if WIN:
99
112
  import ctypes
100
113
 
101
114
  with contextlib.suppress(Exception):
102
- ctypes.windll.kernel32.SetPriorityClass(
103
- ctypes.windll.kernel32.GetCurrentProcess(), 0x40 if nice >= 15 else 0x4000
104
- ) # IDLE / BELOW_NORMAL
115
+ k32 = ctypes.windll.kernel32
116
+ k32.SetPriorityClass(k32.GetCurrentProcess(), 0x40 if nice >= 15 else 0x4000) # IDLE / BELOW_NORMAL
117
+ if io:
118
+ k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00100000) # PROCESS_MODE_BACKGROUND_BEGIN
105
119
  return
106
120
  with contextlib.suppress(OSError, AttributeError):
107
121
  os.nice(nice)
122
+ if io:
123
+ _lower_io_priority()
124
+
125
+
126
+ def _lower_io_priority(pid: int = 0) -> None:
127
+ """Idle I/O for `pid` (0: this process). Other pids are for the tests, which must not lower their own."""
128
+ import ctypes
129
+ import ctypes.util
130
+ import platform
131
+ import shutil
132
+
133
+ if MAC: # pragma: no cover - the Linux leg runs the tests that count; macOS is best effort
134
+ with contextlib.suppress(Exception):
135
+ libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)
136
+ libc.setiopolicy_np(0, 0, 3) # IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE
137
+ return
138
+ number = _IOPRIO_SET.get(platform.machine()) if sys.platform.startswith("linux") else None
139
+ if number is not None:
140
+ with contextlib.suppress(Exception):
141
+ libc = ctypes.CDLL(None, use_errno=True)
142
+ if libc.syscall(number, 1, pid, _IOPRIO_IDLE) == 0: # IOPRIO_WHO_PROCESS
143
+ return
144
+ ionice = shutil.which("ionice")
145
+ if ionice: # another architecture or a refused syscall: util-linux's ionice does the same for our pid
146
+ with contextlib.suppress(OSError):
147
+ subprocess.run([ionice, "-c3", "-p", str(pid or os.getpid())], capture_output=True, check=False) # noqa: S603 (ionice from PATH, our pid)
108
148
 
109
149
 
110
150
  def venv_python(venv: str) -> str:
@@ -115,3 +155,131 @@ def venv_python(venv: str) -> str:
115
155
  def cli_command(module: str) -> list[str]:
116
156
  """Command prefix that runs `module` (`python -m <module>`) with the interpreter running this process: works on POSIX and Windows, with or without a venv, and does not touch the environment."""
117
157
  return [sys.executable, "-m", module]
158
+
159
+
160
+ def detached_kwargs() -> dict[str, Any]:
161
+ """`subprocess.Popen` keyword arguments that start a process outside this one's session (POSIX) or console and
162
+ process group (Windows), so it keeps running when the server that started it restarts, and a Ctrl+C or a stopped
163
+ service unit aimed at the server does not reach it. `kill_tree` still stops it and its children."""
164
+ if WIN:
165
+ return {"creationflags": 0x00000200 | 0x00000008} # CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
166
+ return {"start_new_session": True}
167
+
168
+
169
+ def load_average() -> tuple[float, float, float] | None:
170
+ """The 1, 5 and 15 minute load averages, or None where the OS has none (Windows)."""
171
+ try:
172
+ return os.getloadavg()
173
+ except (AttributeError, OSError):
174
+ return None
175
+
176
+
177
+ # --- supervised children: listory's per-job process groups -----------------------------------------------------------
178
+
179
+ SUPERVISED_ENV = "STRATA_SUPERVISED"
180
+
181
+
182
+ @overload
183
+ def start_supervised(
184
+ cmd: list[str], *, env: Mapping[str, str] | None = None, cwd: str | None = None, text: Literal[False] = False
185
+ ) -> subprocess.Popen[bytes]: ...
186
+ @overload
187
+ def start_supervised(
188
+ cmd: list[str], *, env: Mapping[str, str] | None = None, cwd: str | None = None, text: Literal[True]
189
+ ) -> subprocess.Popen[str]: ...
190
+ def start_supervised(
191
+ cmd: list[str], *, env: Mapping[str, str] | None = None, cwd: str | None = None, text: bool = False
192
+ ) -> subprocess.Popen[Any]:
193
+ """Start `cmd` in its own process group, with a lifeline on its stdin, so that `kill_group` stops it and every
194
+ tool it started, and so that it stops itself when this process dies, however it dies (`watch_supervisor`, called
195
+ in the child, sees the pipe close). `text=True` also pipes its stdout, as text, for a child that answers on it
196
+ (`tasks.child`); otherwise its output goes where this process's goes."""
197
+ return subprocess.Popen( # noqa: S603 - the app's own command
198
+ cmd,
199
+ stdin=subprocess.PIPE,
200
+ stdout=subprocess.PIPE if text else None,
201
+ text=text,
202
+ encoding="utf8" if text else None,
203
+ env={**(env or os.environ), SUPERVISED_ENV: "1"},
204
+ cwd=cwd,
205
+ start_new_session=not WIN,
206
+ creationflags=0x00000200 if WIN else 0, # CREATE_NEW_PROCESS_GROUP
207
+ )
208
+
209
+
210
+ def stdout_to_stderr() -> int:
211
+ """Point this process's stdout at its stderr, for it and every process it starts, and return a new fd on the old
212
+ stdout (for a child that answers its parent there). On Windows the Win32 standard handle is moved too: moving
213
+ fd 1 alone leaves the handle a started tool inherits on the old pipe."""
214
+ sys.stdout.flush()
215
+ saved = os.dup(1)
216
+ os.dup2(2, 1)
217
+ if WIN:
218
+ import ctypes
219
+ import msvcrt
220
+
221
+ ctypes.windll.kernel32.SetStdHandle(-11, msvcrt.get_osfhandle(2)) # STD_OUTPUT_HANDLE
222
+ return saved
223
+
224
+
225
+ def stdin_from_devnull() -> int:
226
+ """Give this process (and every process it starts) an empty stdin, and return a new fd on the old one, for a
227
+ child that reads its parent's commands there. On Windows this is what keeps a tool from hanging: a thread blocked
228
+ reading a synchronous pipe holds that pipe, and a tool that inherits it as stdin blocks starting up."""
229
+ saved = os.dup(0)
230
+ null = os.open(os.devnull, os.O_RDONLY)
231
+ os.dup2(null, 0)
232
+ os.close(null)
233
+ if WIN:
234
+ import ctypes
235
+ import msvcrt
236
+
237
+ ctypes.windll.kernel32.SetStdHandle(-10, msvcrt.get_osfhandle(0)) # STD_INPUT_HANDLE
238
+ sys.stdin = open(0, closefd=False) # noqa: SIM115 - fd 0 for the life of the process
239
+ return saved
240
+
241
+
242
+ def watch_supervisor() -> bool:
243
+ """In a child that `start_supervised` started: end this process group when the parent's end of the lifeline
244
+ closes (the parent exited, crashed or was killed), so no tool is left running for a server that is gone. True
245
+ when it is watching; False when this process was not started that way."""
246
+ if os.environ.pop(SUPERVISED_ENV, None) != "1": # popped: this process's own children are not supervised by it
247
+ return False
248
+
249
+ def watch() -> None:
250
+ try:
251
+ while os.read(0, 1): # the parent never writes: this returns b"" (EOF) when its end closes
252
+ pass
253
+ finally:
254
+ terminate_own_group()
255
+
256
+ threading.Thread(target=watch, name="strata-supervisor-watch", daemon=True).start()
257
+ return True
258
+
259
+
260
+ def terminate_own_group() -> None:
261
+ """Kill this process and everything in its group (or, on Windows, its process tree), at once."""
262
+ if WIN:
263
+ kill_tree(os.getpid())
264
+ elif os.getpgrp() == os.getpid(): # only a group this process leads, never the server's own session
265
+ import signal
266
+
267
+ with contextlib.suppress(OSError):
268
+ os.killpg(os.getpid(), signal.SIGKILL)
269
+ os._exit(1)
270
+
271
+
272
+ def kill_group(proc: subprocess.Popen[Any], timeout: float = 5.0) -> None:
273
+ """Stop a `start_supervised` child and every process in its group now, and reap it."""
274
+ if WIN:
275
+ kill_tree(proc.pid)
276
+ else:
277
+ import signal
278
+
279
+ with contextlib.suppress(OSError):
280
+ os.killpg(proc.pid, signal.SIGKILL)
281
+ with contextlib.suppress(subprocess.TimeoutExpired):
282
+ proc.wait(timeout)
283
+ if proc.stdin is not None:
284
+ with contextlib.suppress(OSError):
285
+ proc.stdin.close()