plotroom 0.1.0__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.
- plotroom/__init__.py +0 -0
- plotroom/__main__.py +8 -0
- plotroom/_secret_file.py +8 -0
- plotroom/adapters/__init__.py +0 -0
- plotroom/adapters/claude_desktop.py +219 -0
- plotroom/adapters/embedding_http.py +175 -0
- plotroom/adapters/github/__init__.py +337 -0
- plotroom/adapters/github/app_credential.py +209 -0
- plotroom/adapters/github/ci.py +738 -0
- plotroom/adapters/github/commit_statuses.py +63 -0
- plotroom/adapters/github/deployments.py +213 -0
- plotroom/adapters/github/details.py +867 -0
- plotroom/adapters/github/issue_details.py +368 -0
- plotroom/adapters/github/junit.py +210 -0
- plotroom/adapters/github/junit_xml.py +162 -0
- plotroom/adapters/github/kodus_review.py +347 -0
- plotroom/adapters/github/pr_details.py +192 -0
- plotroom/adapters/github/pull_comparison.py +108 -0
- plotroom/adapters/github/read.py +530 -0
- plotroom/adapters/github/ticket_tree.py +336 -0
- plotroom/adapters/mcp/__init__.py +5 -0
- plotroom/adapters/mcp/proxy.py +722 -0
- plotroom/adapters/mcp/server.py +931 -0
- plotroom/adapters/openrouter.py +151 -0
- plotroom/adapters/store_sqlite/__init__.py +6 -0
- plotroom/adapters/store_sqlite/actions_sql.py +148 -0
- plotroom/adapters/store_sqlite/asks_sql.py +153 -0
- plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
- plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
- plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
- plotroom/adapters/store_sqlite/claims_sql.py +54 -0
- plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
- plotroom/adapters/store_sqlite/github_sql.py +331 -0
- plotroom/adapters/store_sqlite/goals_sql.py +57 -0
- plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
- plotroom/adapters/store_sqlite/items_sql.py +129 -0
- plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
- plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
- plotroom/adapters/store_sqlite/migrate.py +194 -0
- plotroom/adapters/store_sqlite/migrations/env.py +36 -0
- plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
- plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
- plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
- plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
- plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
- plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
- plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
- plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
- plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
- plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
- plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
- plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
- plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
- plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
- plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
- plotroom/adapters/store_sqlite/routes_sql.py +26 -0
- plotroom/adapters/store_sqlite/search_sql.py +116 -0
- plotroom/adapters/store_sqlite/store.py +623 -0
- plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
- plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
- plotroom/adapters/switchboard.py +152 -0
- plotroom/adapters/usage_fixture.py +11 -0
- plotroom/adapters/work_items_bmad.py +256 -0
- plotroom/adapters/work_items_github_issues.py +323 -0
- plotroom/app/__init__.py +0 -0
- plotroom/app/bridge.py +162 -0
- plotroom/app/clerk_import.py +349 -0
- plotroom/app/cli.py +290 -0
- plotroom/app/clock.py +12 -0
- plotroom/app/config.py +984 -0
- plotroom/app/daemon_start.py +453 -0
- plotroom/app/lock.py +77 -0
- plotroom/app/logging.py +93 -0
- plotroom/app/portfile.py +218 -0
- plotroom/app/runtime.py +518 -0
- plotroom/app/serve.py +671 -0
- plotroom/app/session_intake.py +51 -0
- plotroom/app/sqlite_floor.py +35 -0
- plotroom/app/tokens.py +265 -0
- plotroom/core/__init__.py +0 -0
- plotroom/core/actions.py +67 -0
- plotroom/core/ask_checks.py +124 -0
- plotroom/core/asks.py +123 -0
- plotroom/core/branch_updates.py +207 -0
- plotroom/core/bridge.py +112 -0
- plotroom/core/briefs.py +83 -0
- plotroom/core/budgets.py +182 -0
- plotroom/core/catalog.py +464 -0
- plotroom/core/checklists.py +151 -0
- plotroom/core/claims.py +296 -0
- plotroom/core/clerk_import.py +379 -0
- plotroom/core/commands.py +85 -0
- plotroom/core/deploy_window.py +21 -0
- plotroom/core/envelope.py +20 -0
- plotroom/core/events.py +227 -0
- plotroom/core/github.py +306 -0
- plotroom/core/github_projection.py +310 -0
- plotroom/core/goal_language.py +374 -0
- plotroom/core/goal_projection.py +146 -0
- plotroom/core/human_queue.py +119 -0
- plotroom/core/intake.py +106 -0
- plotroom/core/kodus_review.py +53 -0
- plotroom/core/lanes.py +281 -0
- plotroom/core/ledger.py +808 -0
- plotroom/core/merge_controller.py +344 -0
- plotroom/core/merge_flakes.py +422 -0
- plotroom/core/merge_gate.py +724 -0
- plotroom/core/merge_lane.py +70 -0
- plotroom/core/merge_overlap.py +76 -0
- plotroom/core/next_items.py +60 -0
- plotroom/core/operator_goals.py +103 -0
- plotroom/core/outbox.py +70 -0
- plotroom/core/pull_overlaps.py +152 -0
- plotroom/core/reports.py +62 -0
- plotroom/core/roles.py +100 -0
- plotroom/core/routing.py +55 -0
- plotroom/core/run_reports.py +53 -0
- plotroom/core/search.py +266 -0
- plotroom/core/search_sources.py +94 -0
- plotroom/core/snapshot.py +204 -0
- plotroom/core/trigger_actions.py +89 -0
- plotroom/core/triggers.py +550 -0
- plotroom/core/unit_of_work.py +541 -0
- plotroom/core/watchers.py +35 -0
- plotroom/core/work_items.py +23 -0
- plotroom/core/writer.py +164 -0
- plotroom/ports/__init__.py +6 -0
- plotroom/ports/clock.py +12 -0
- plotroom/ports/github_write.py +72 -0
- plotroom/ports/search.py +197 -0
- plotroom/ports/session_reader.py +23 -0
- plotroom/ports/store.py +323 -0
- plotroom/ports/usage_meter.py +35 -0
- plotroom/ports/work_items.py +22 -0
- plotroom/py.typed +0 -0
- plotroom-0.1.0.dist-info/METADATA +230 -0
- plotroom-0.1.0.dist-info/RECORD +150 -0
- plotroom-0.1.0.dist-info/WHEEL +4 -0
- plotroom-0.1.0.dist-info/entry_points.txt +2 -0
- plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"""Start ``plotroom serve`` on demand for ``plotroom connect --stdio`` (AD-3).
|
|
2
|
+
|
|
3
|
+
The daemon publishes its listeners in the data directory. Local readiness requires HTTP 401 on a
|
|
4
|
+
Unix connection to the verified lock owner. A second ``serve`` exits with the lock code, and the
|
|
5
|
+
client that started it waits for the lock's owner to answer.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import stat
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass, replace
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, cast
|
|
22
|
+
from urllib.parse import urlsplit
|
|
23
|
+
|
|
24
|
+
import httpx
|
|
25
|
+
|
|
26
|
+
from plotroom.adapters.mcp.proxy import LocalEndpoint, UpstreamStartError
|
|
27
|
+
from plotroom.app.cli import DEFAULT_START_TIMEOUT, EXIT_LOCKED
|
|
28
|
+
from plotroom.app.config import Config
|
|
29
|
+
from plotroom.app.lock import LOCK_FILE_NAME, DataDirLock, LockError
|
|
30
|
+
from plotroom.app.portfile import (
|
|
31
|
+
START_DIRECTORY_ENV,
|
|
32
|
+
DirectoryIdentity,
|
|
33
|
+
PublishedListener,
|
|
34
|
+
directory_identity,
|
|
35
|
+
directory_key,
|
|
36
|
+
published_socket,
|
|
37
|
+
read_listener,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
log = logging.getLogger("plotroom.daemon_start")
|
|
41
|
+
|
|
42
|
+
LOG_FILE_NAME = "plotroom-serve.log"
|
|
43
|
+
_POLL_SECONDS = 0.05
|
|
44
|
+
_PROBE_TIMEOUT = 2.0
|
|
45
|
+
_MAX_PID_RECORD_BYTES = 64
|
|
46
|
+
|
|
47
|
+
# What a daemon started for a client inherits: enough to run, nothing of the client's own
|
|
48
|
+
# environment (its tokens, its session variables). The PLOTROOM_* names are the config loader's
|
|
49
|
+
# closed override list, so the daemon resolves the same settings the proxy did.
|
|
50
|
+
_RUNTIME_KEYS = ("PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "LC_CTYPE", "TMPDIR", "TZ")
|
|
51
|
+
_CONFIG_KEYS = (
|
|
52
|
+
"PLOTROOM_CONFIG",
|
|
53
|
+
"PLOTROOM_DATA_DIR",
|
|
54
|
+
"PLOTROOM_HOST",
|
|
55
|
+
"PLOTROOM_PORT",
|
|
56
|
+
"PLOTROOM_ALLOWED_HOSTS",
|
|
57
|
+
"PLOTROOM_PROJECTS",
|
|
58
|
+
"PLOTROOM_LOG_MAX_BYTES",
|
|
59
|
+
"PLOTROOM_LOG_BACKUPS",
|
|
60
|
+
)
|
|
61
|
+
_PATH_KEYS = ("PLOTROOM_CONFIG", "PLOTROOM_DATA_DIR")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def daemon_env(env: Mapping[str, str]) -> dict[str, str]:
|
|
65
|
+
"""The environment a daemon started on demand runs with."""
|
|
66
|
+
clean = {key: env[key] for key in _RUNTIME_KEYS if key in env}
|
|
67
|
+
for key in _CONFIG_KEYS:
|
|
68
|
+
if key in env:
|
|
69
|
+
# relative paths mean the client's working directory, not the daemon's
|
|
70
|
+
clean[key] = (
|
|
71
|
+
str(Path(env[key]).expanduser().resolve()) if key in _PATH_KEYS else env[key]
|
|
72
|
+
)
|
|
73
|
+
return clean
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def serve_command(config_path: Path | None, log_path: Path | None = None) -> list[str]:
|
|
77
|
+
# -P: the daemon runs in the data directory, which must not shadow the installed package
|
|
78
|
+
command = [sys.executable, "-P", "-m", "plotroom", "serve"]
|
|
79
|
+
if log_path is not None:
|
|
80
|
+
# The daemon rotates its own log; it runs in the data directory, so the path is absolute.
|
|
81
|
+
command += ["--log-file", str(log_path.expanduser().resolve())]
|
|
82
|
+
if config_path is not None:
|
|
83
|
+
command += ["--config", str(config_path.expanduser().resolve())]
|
|
84
|
+
return command
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def start_daemon(
|
|
88
|
+
command: Sequence[str], env: Mapping[str, str], cwd: Path, log_path: Path
|
|
89
|
+
) -> subprocess.Popen[bytes]:
|
|
90
|
+
"""Run ``command`` detached from the client: its own session, no stdin, output to a file."""
|
|
91
|
+
cwd.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
with log_path.open("ab") as out:
|
|
93
|
+
return subprocess.Popen( # noqa: S603 - the command is this interpreter running plotroom
|
|
94
|
+
list(command),
|
|
95
|
+
stdin=subprocess.DEVNULL,
|
|
96
|
+
stdout=out,
|
|
97
|
+
stderr=subprocess.STDOUT,
|
|
98
|
+
env=dict(env),
|
|
99
|
+
cwd=cwd,
|
|
100
|
+
start_new_session=True,
|
|
101
|
+
close_fds=True,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
async def probe_status(endpoint: LocalEndpoint, *, within: float = _PROBE_TIMEOUT) -> int | None:
|
|
106
|
+
"""Read the bodyless readiness response from the verified peer."""
|
|
107
|
+
if within <= 0:
|
|
108
|
+
return None
|
|
109
|
+
try:
|
|
110
|
+
async with (
|
|
111
|
+
asyncio.timeout(min(within, _PROBE_TIMEOUT)),
|
|
112
|
+
endpoint.stream("HEAD") as response,
|
|
113
|
+
):
|
|
114
|
+
return response.status_code
|
|
115
|
+
except httpx.HTTPError, OSError, TimeoutError:
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _log_paths(log_path: Path, backups: int) -> list[Path]:
|
|
120
|
+
"""Return the retained files in age order, followed by the active log."""
|
|
121
|
+
numbered: list[tuple[int, Path]] = []
|
|
122
|
+
if backups:
|
|
123
|
+
prefix = log_path.name + "."
|
|
124
|
+
for path in log_path.parent.iterdir():
|
|
125
|
+
suffix = path.name.removeprefix(prefix)
|
|
126
|
+
if suffix != path.name and suffix.isascii() and suffix.isdecimal():
|
|
127
|
+
number = int(suffix)
|
|
128
|
+
if 1 <= number <= backups and suffix == str(number):
|
|
129
|
+
numbered.append((number, path))
|
|
130
|
+
return [path for _, path in sorted(numbered, reverse=True)] + [log_path]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _log_fingerprint(info: os.stat_result) -> tuple[int, int, int, int]:
|
|
134
|
+
# Renaming a backup does not change these fields; a reused inode alone is not a match.
|
|
135
|
+
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass(frozen=True)
|
|
139
|
+
class LogCheckpoint:
|
|
140
|
+
active: os.stat_result | None
|
|
141
|
+
archived: frozenset[tuple[int, int, int, int]]
|
|
142
|
+
backups: int
|
|
143
|
+
|
|
144
|
+
@classmethod
|
|
145
|
+
def capture(cls, log_path: Path, backups: int) -> LogCheckpoint:
|
|
146
|
+
archived: set[tuple[int, int, int, int]] = set()
|
|
147
|
+
try:
|
|
148
|
+
active = log_path.stat()
|
|
149
|
+
except FileNotFoundError:
|
|
150
|
+
active = None
|
|
151
|
+
try:
|
|
152
|
+
for path in _log_paths(log_path, backups)[:-1]:
|
|
153
|
+
try:
|
|
154
|
+
info = path.lstat()
|
|
155
|
+
except FileNotFoundError:
|
|
156
|
+
continue
|
|
157
|
+
if stat.S_ISREG(info.st_mode):
|
|
158
|
+
archived.add(_log_fingerprint(info))
|
|
159
|
+
except OSError:
|
|
160
|
+
# Incomplete backup metadata cannot establish which archives are old.
|
|
161
|
+
# Keep the active-file diagnostic and allow the daemon to start.
|
|
162
|
+
backups = 0
|
|
163
|
+
return cls(active, frozenset(archived), backups)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _startup_lines(log_path: Path, checkpoint: LogCheckpoint) -> Iterator[str]:
|
|
167
|
+
try:
|
|
168
|
+
paths = _log_paths(log_path, checkpoint.backups)
|
|
169
|
+
except OSError:
|
|
170
|
+
paths = [log_path]
|
|
171
|
+
for path in paths:
|
|
172
|
+
try:
|
|
173
|
+
flags = os.O_RDONLY | os.O_NONBLOCK
|
|
174
|
+
if path != log_path:
|
|
175
|
+
flags |= os.O_NOFOLLOW
|
|
176
|
+
fd = os.open(path, flags)
|
|
177
|
+
try:
|
|
178
|
+
info = os.fstat(fd)
|
|
179
|
+
if not stat.S_ISREG(info.st_mode) or _log_fingerprint(info) in checkpoint.archived:
|
|
180
|
+
continue
|
|
181
|
+
with os.fdopen(fd, "rb", closefd=False) as handle:
|
|
182
|
+
active = checkpoint.active
|
|
183
|
+
# The original active file may now be a backup. Skip its old prefix even
|
|
184
|
+
# there; a different active inode starts at byte zero regardless of its size.
|
|
185
|
+
if (
|
|
186
|
+
active is not None
|
|
187
|
+
and os.path.samestat(info, active)
|
|
188
|
+
and info.st_size >= active.st_size
|
|
189
|
+
):
|
|
190
|
+
handle.seek(active.st_size)
|
|
191
|
+
for line in handle:
|
|
192
|
+
yield line.decode("utf-8", errors="replace")
|
|
193
|
+
finally:
|
|
194
|
+
os.close(fd)
|
|
195
|
+
except OSError:
|
|
196
|
+
continue
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def logged_reason(log_path: Path, checkpoint: LogCheckpoint | None = None) -> str | None:
|
|
200
|
+
"""Return the last current error, or the last plain output line if no error was logged."""
|
|
201
|
+
reason: str | None = None
|
|
202
|
+
plain: str | None = None
|
|
203
|
+
try:
|
|
204
|
+
for line in _startup_lines(log_path, checkpoint or LogCheckpoint(None, frozenset(), 0)):
|
|
205
|
+
try:
|
|
206
|
+
entry: Any = json.loads(line)
|
|
207
|
+
except ValueError:
|
|
208
|
+
plain = line.strip() or plain
|
|
209
|
+
continue
|
|
210
|
+
if not isinstance(entry, dict):
|
|
211
|
+
continue
|
|
212
|
+
fields = cast("dict[str, Any]", entry)
|
|
213
|
+
if fields.get("level") in ("error", "critical"):
|
|
214
|
+
parts = [str(fields[key]) for key in ("msg", "reason") if fields.get(key)]
|
|
215
|
+
trace = str(fields.get("exc") or "").strip().splitlines()
|
|
216
|
+
if trace:
|
|
217
|
+
parts.append(trace[-1])
|
|
218
|
+
reason = ": ".join(parts) or reason
|
|
219
|
+
except OSError:
|
|
220
|
+
return None
|
|
221
|
+
found = reason or plain
|
|
222
|
+
return found[:400] if found else None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def lock_owner(data_dir: Path) -> int | None:
|
|
226
|
+
"""Read the recorded PID if it is live, even when the file is stale."""
|
|
227
|
+
try:
|
|
228
|
+
with open(
|
|
229
|
+
data_dir / LOCK_FILE_NAME,
|
|
230
|
+
"rb",
|
|
231
|
+
opener=lambda path, flags: os.open(path, flags | os.O_NONBLOCK),
|
|
232
|
+
) as handle:
|
|
233
|
+
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
|
|
234
|
+
return None
|
|
235
|
+
record = handle.read(_MAX_PID_RECORD_BYTES + 1)
|
|
236
|
+
if len(record) > _MAX_PID_RECORD_BYTES:
|
|
237
|
+
return None
|
|
238
|
+
pid = int(record.decode("utf-8"))
|
|
239
|
+
except OSError, ValueError:
|
|
240
|
+
return None
|
|
241
|
+
return pid if pid > 0 and _pid_alive(pid) else None
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def holds_lock(data_dir: Path) -> bool:
|
|
245
|
+
"""Whether a server owns ``data_dir`` right now."""
|
|
246
|
+
probe = DataDirLock(data_dir)
|
|
247
|
+
try:
|
|
248
|
+
probe.acquire()
|
|
249
|
+
except LockError:
|
|
250
|
+
return True
|
|
251
|
+
probe.release()
|
|
252
|
+
return False
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _lock_still_held_by(data_dir: Path, pid: int) -> bool:
|
|
256
|
+
"""Check the kernel lock and confirm the recorded PID after the check."""
|
|
257
|
+
return holds_lock(data_dir) and lock_owner(data_dir) == pid
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _pid_alive(pid: int) -> bool:
|
|
261
|
+
try:
|
|
262
|
+
os.kill(pid, 0)
|
|
263
|
+
except PermissionError: # the process exists but belongs to someone else
|
|
264
|
+
return True
|
|
265
|
+
except OSError, OverflowError:
|
|
266
|
+
return False
|
|
267
|
+
return True
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class DaemonLocation:
|
|
271
|
+
"""One canonical data directory shared by token selection, startup, and listener discovery."""
|
|
272
|
+
|
|
273
|
+
def __init__(self, config: Config) -> None:
|
|
274
|
+
self.config = config
|
|
275
|
+
self.identity = self._identify()
|
|
276
|
+
|
|
277
|
+
def _identify(self) -> DirectoryIdentity | None:
|
|
278
|
+
directory = self.config.data_dir
|
|
279
|
+
if directory.resolve() != directory:
|
|
280
|
+
raise UpstreamStartError("the canonical plotroom data directory changed")
|
|
281
|
+
try:
|
|
282
|
+
return directory_identity(directory)
|
|
283
|
+
except FileNotFoundError:
|
|
284
|
+
return None
|
|
285
|
+
|
|
286
|
+
def prepare(self) -> DirectoryIdentity:
|
|
287
|
+
current = self._identify()
|
|
288
|
+
if self.identity is None:
|
|
289
|
+
if current is None:
|
|
290
|
+
self.config.data_dir.mkdir(parents=True, exist_ok=True)
|
|
291
|
+
current = self._identify()
|
|
292
|
+
self.identity = current
|
|
293
|
+
if current is None or current != self.identity:
|
|
294
|
+
raise UpstreamStartError("the canonical plotroom data directory changed")
|
|
295
|
+
return current
|
|
296
|
+
|
|
297
|
+
def _publication(self) -> PublishedListener | None:
|
|
298
|
+
directory = self.config.data_dir
|
|
299
|
+
if self.identity is None or self._identify() != self.identity:
|
|
300
|
+
return None
|
|
301
|
+
published = read_listener(directory)
|
|
302
|
+
if published is None or self.config.port not in (0, published.port):
|
|
303
|
+
return None
|
|
304
|
+
# Both records may survive a crash. Confirm the recorded PID and the kernel lock, then
|
|
305
|
+
# make sure publication still comes from the directory selected by the proxy.
|
|
306
|
+
if lock_owner(directory) != published.pid or not _lock_still_held_by(
|
|
307
|
+
directory, published.pid
|
|
308
|
+
):
|
|
309
|
+
return None
|
|
310
|
+
return published if self._identify() == self.identity else None
|
|
311
|
+
|
|
312
|
+
def _current_endpoint(self) -> LocalEndpoint | None:
|
|
313
|
+
published = self._publication()
|
|
314
|
+
if published is None or published.host is None or self.identity is None:
|
|
315
|
+
return None
|
|
316
|
+
if published.local_unavailable:
|
|
317
|
+
raise UpstreamStartError("the running plotroom serve has no private local listener")
|
|
318
|
+
socket_path = (
|
|
319
|
+
published_socket(self.config.data_dir, self.identity, published.local_socket)
|
|
320
|
+
if published.local_socket is not None
|
|
321
|
+
else None
|
|
322
|
+
)
|
|
323
|
+
if socket_path is None:
|
|
324
|
+
return None
|
|
325
|
+
config = replace(self.config, port=published.port)
|
|
326
|
+
url = replace(config, host=published.host).url
|
|
327
|
+
alias = urlsplit(config.url).netloc.lower()
|
|
328
|
+
return LocalEndpoint(url, alias, str(socket_path), published.pid)
|
|
329
|
+
|
|
330
|
+
async def current_endpoint(self) -> LocalEndpoint | None:
|
|
331
|
+
return await asyncio.to_thread(self._current_endpoint)
|
|
332
|
+
|
|
333
|
+
async def requires_upgrade(self) -> bool:
|
|
334
|
+
published = await asyncio.to_thread(self._publication)
|
|
335
|
+
return published is not None and published.local_socket is None
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
async def _ready_endpoint(location: DaemonLocation, within: float) -> LocalEndpoint | None:
|
|
339
|
+
deadline = time.monotonic() + min(within, _PROBE_TIMEOUT)
|
|
340
|
+
endpoint = await location.current_endpoint()
|
|
341
|
+
if endpoint is None:
|
|
342
|
+
return None
|
|
343
|
+
alias, bound = endpoint.host, urlsplit(endpoint.url).netloc
|
|
344
|
+
for host in dict.fromkeys((alias, alias.rsplit(":", 1)[0], bound, bound.rsplit(":", 1)[0])):
|
|
345
|
+
candidate = replace(endpoint, host=host)
|
|
346
|
+
status = await probe_status(candidate, within=deadline - time.monotonic())
|
|
347
|
+
if status == 401:
|
|
348
|
+
return candidate if candidate == await location.current_endpoint() else None
|
|
349
|
+
if status != 421:
|
|
350
|
+
break
|
|
351
|
+
return None
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
async def require_daemon(location: DaemonLocation, *, within: float) -> LocalEndpoint:
|
|
355
|
+
"""Reach an already-running daemon without starting another process."""
|
|
356
|
+
deadline = time.monotonic() + within
|
|
357
|
+
endpoint = await _ready_endpoint(location, within)
|
|
358
|
+
if endpoint is None and (remaining := deadline - time.monotonic()) > 0:
|
|
359
|
+
endpoint = await _ready_endpoint(location, remaining)
|
|
360
|
+
if endpoint is None:
|
|
361
|
+
raise UpstreamStartError("no verified local daemon is running")
|
|
362
|
+
return endpoint
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
async def ensure_daemon(
|
|
366
|
+
location: DaemonLocation,
|
|
367
|
+
config_path: Path | None,
|
|
368
|
+
*,
|
|
369
|
+
env: Mapping[str, str],
|
|
370
|
+
wait: float = DEFAULT_START_TIMEOUT,
|
|
371
|
+
command: Sequence[str] | None = None,
|
|
372
|
+
) -> LocalEndpoint:
|
|
373
|
+
"""Find or start the daemon for the pinned data directory and verify its ready listener."""
|
|
374
|
+
identity = await asyncio.to_thread(location.prepare)
|
|
375
|
+
endpoint = await _ready_endpoint(location, _PROBE_TIMEOUT)
|
|
376
|
+
if endpoint is not None:
|
|
377
|
+
return endpoint
|
|
378
|
+
if await location.requires_upgrade():
|
|
379
|
+
raise UpstreamStartError(
|
|
380
|
+
"restart the running plotroom serve to enable verified local stdio"
|
|
381
|
+
)
|
|
382
|
+
config = location.config
|
|
383
|
+
log_path = config.data_dir / LOG_FILE_NAME
|
|
384
|
+
argv = list(command) if command is not None else serve_command(config_path, log_path)
|
|
385
|
+
# The child rereads the config from its own cwd. Pin the instance even if the file changes.
|
|
386
|
+
child_env = {
|
|
387
|
+
**daemon_env(env),
|
|
388
|
+
"PLOTROOM_DATA_DIR": str(config.data_dir),
|
|
389
|
+
START_DIRECTORY_ENV: directory_key(identity),
|
|
390
|
+
}
|
|
391
|
+
deadline = time.monotonic() + wait
|
|
392
|
+
reason: str | None = None
|
|
393
|
+
while True:
|
|
394
|
+
await asyncio.to_thread(location.prepare)
|
|
395
|
+
try:
|
|
396
|
+
checkpoint = await asyncio.to_thread(
|
|
397
|
+
LogCheckpoint.capture, log_path, config.log_backups
|
|
398
|
+
)
|
|
399
|
+
child = await asyncio.to_thread(
|
|
400
|
+
start_daemon, argv, child_env, config.data_dir, log_path
|
|
401
|
+
)
|
|
402
|
+
except OSError as exc:
|
|
403
|
+
raise UpstreamStartError(f"cannot start plotroom serve: {exc.strerror or exc}") from exc
|
|
404
|
+
log.info(
|
|
405
|
+
"started plotroom serve", extra={"pid": child.pid, "data_dir": str(config.data_dir)}
|
|
406
|
+
)
|
|
407
|
+
exited = False
|
|
408
|
+
# Wait on this child. When it loses the lock it waits for the winner to listen, and starts
|
|
409
|
+
# again only if that winner went away (a daemon still shutting down keeps the lock a while).
|
|
410
|
+
while (remaining := deadline - time.monotonic()) > 0:
|
|
411
|
+
endpoint = await _ready_endpoint(location, remaining)
|
|
412
|
+
if endpoint is not None:
|
|
413
|
+
return endpoint
|
|
414
|
+
code = child.poll()
|
|
415
|
+
if code is not None:
|
|
416
|
+
if not exited: # read the log once per child, off the event loop
|
|
417
|
+
exited = True
|
|
418
|
+
reason = await asyncio.to_thread(logged_reason, log_path, checkpoint)
|
|
419
|
+
if code != EXIT_LOCKED:
|
|
420
|
+
why = reason or f"exited with code {code}"
|
|
421
|
+
raise UpstreamStartError(f"plotroom serve could not start: {why}")
|
|
422
|
+
if not await asyncio.to_thread(holds_lock, config.data_dir):
|
|
423
|
+
break # the owner is gone: try again
|
|
424
|
+
await asyncio.sleep(_POLL_SECONDS)
|
|
425
|
+
else:
|
|
426
|
+
break
|
|
427
|
+
owner = await asyncio.to_thread(lock_owner, config.data_dir)
|
|
428
|
+
endpoint = await location.current_endpoint()
|
|
429
|
+
if await location.requires_upgrade():
|
|
430
|
+
raise UpstreamStartError(
|
|
431
|
+
"restart the running plotroom serve to enable verified local stdio"
|
|
432
|
+
)
|
|
433
|
+
url = endpoint.url if endpoint is not None else None
|
|
434
|
+
if (
|
|
435
|
+
owner is not None
|
|
436
|
+
and owner != child.pid
|
|
437
|
+
and await asyncio.to_thread(_lock_still_held_by, config.data_dir, owner)
|
|
438
|
+
):
|
|
439
|
+
if url is None:
|
|
440
|
+
answer = "it has published no address that answers"
|
|
441
|
+
elif config.port == 0:
|
|
442
|
+
answer = f"nothing answers at {url}, the address it published"
|
|
443
|
+
else:
|
|
444
|
+
answer = (
|
|
445
|
+
f"nothing answers at {url}; that server uses another address than this config's"
|
|
446
|
+
)
|
|
447
|
+
raise UpstreamStartError(
|
|
448
|
+
f"another plotroom serve owns {config.data_dir} (pid {owner}), and {answer}"
|
|
449
|
+
)
|
|
450
|
+
raise UpstreamStartError(
|
|
451
|
+
f"plotroom serve did not start listening{f' at {url}' if url else ''} within {wait:g}s"
|
|
452
|
+
+ (f" (earlier: {reason})" if reason else "")
|
|
453
|
+
)
|
plotroom/app/lock.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""The data-directory lock (AD-3): one ``plotroom serve`` per data directory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fcntl
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from types import TracebackType
|
|
9
|
+
from typing import IO
|
|
10
|
+
|
|
11
|
+
LOCK_FILE_NAME = "plotroom.lock"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class LockError(Exception):
|
|
15
|
+
"""Another process already owns the data directory."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DataDirLock:
|
|
19
|
+
"""An exclusive, non-blocking ``flock`` on a lock file inside the data directory.
|
|
20
|
+
|
|
21
|
+
The kernel drops the lock when the owning process exits, however it exits.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, data_dir: Path, *, directory_fd: int | None = None) -> None:
|
|
25
|
+
self._path = data_dir / LOCK_FILE_NAME
|
|
26
|
+
self._directory_fd = directory_fd
|
|
27
|
+
self._file: IO[str] | None = None
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def path(self) -> Path:
|
|
31
|
+
return self._path
|
|
32
|
+
|
|
33
|
+
def acquire(self) -> None:
|
|
34
|
+
if self._directory_fd is None:
|
|
35
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
handle = open( # noqa: SIM115 - release() closes the handle after dropping the lock.
|
|
37
|
+
self._path,
|
|
38
|
+
"a+",
|
|
39
|
+
encoding="utf-8",
|
|
40
|
+
opener=self._open_at if self._directory_fd is not None else None,
|
|
41
|
+
)
|
|
42
|
+
try:
|
|
43
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
44
|
+
except BlockingIOError:
|
|
45
|
+
handle.seek(0)
|
|
46
|
+
holder = handle.read().strip() or "unknown"
|
|
47
|
+
handle.close()
|
|
48
|
+
raise LockError(
|
|
49
|
+
f"another plotroom serve owns {self._path.parent} (pid {holder}); "
|
|
50
|
+
"stop it or use another data directory"
|
|
51
|
+
) from None
|
|
52
|
+
handle.seek(0)
|
|
53
|
+
handle.truncate()
|
|
54
|
+
handle.write(str(os.getpid()))
|
|
55
|
+
handle.flush()
|
|
56
|
+
self._file = handle
|
|
57
|
+
|
|
58
|
+
def _open_at(self, _path: str, flags: int) -> int:
|
|
59
|
+
return os.open(LOCK_FILE_NAME, flags | os.O_NOFOLLOW, dir_fd=self._directory_fd)
|
|
60
|
+
|
|
61
|
+
def release(self) -> None:
|
|
62
|
+
if self._file is not None:
|
|
63
|
+
fcntl.flock(self._file.fileno(), fcntl.LOCK_UN)
|
|
64
|
+
self._file.close()
|
|
65
|
+
self._file = None
|
|
66
|
+
|
|
67
|
+
def __enter__(self) -> DataDirLock:
|
|
68
|
+
self.acquire()
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
def __exit__(
|
|
72
|
+
self,
|
|
73
|
+
exc_type: type[BaseException] | None,
|
|
74
|
+
exc: BaseException | None,
|
|
75
|
+
tb: TracebackType | None,
|
|
76
|
+
) -> None:
|
|
77
|
+
self.release()
|
plotroom/app/logging.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Structured JSON logging. Event bodies and credentials never go through it (AD-12)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import logging.handlers
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, TextIO
|
|
14
|
+
|
|
15
|
+
from plotroom.app.config import DEFAULT_LOG_BACKUPS, DEFAULT_LOG_MAX_BYTES
|
|
16
|
+
|
|
17
|
+
# uvicorn adds a colored copy of its message as `color_message`; it is noise in JSON
|
|
18
|
+
_STANDARD = set(logging.LogRecord("", 0, "", 0, "", (), None).__dict__) | {
|
|
19
|
+
"message",
|
|
20
|
+
"asctime",
|
|
21
|
+
"color_message",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class JsonFormatter(logging.Formatter):
|
|
26
|
+
"""One JSON object per line: ``ts``, ``level``, ``logger``, ``msg`` and any ``extra`` fields."""
|
|
27
|
+
|
|
28
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
29
|
+
entry: dict[str, Any] = {
|
|
30
|
+
"ts": datetime.fromtimestamp(record.created, UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
|
|
31
|
+
"level": record.levelname.lower(),
|
|
32
|
+
"logger": record.name,
|
|
33
|
+
"msg": record.getMessage(),
|
|
34
|
+
}
|
|
35
|
+
for key, value in record.__dict__.items():
|
|
36
|
+
if key not in _STANDARD and not key.startswith("_"):
|
|
37
|
+
entry[key] = value
|
|
38
|
+
if record.exc_info:
|
|
39
|
+
entry["exc"] = self.formatException(record.exc_info)
|
|
40
|
+
return json.dumps(entry, default=str, separators=(",", ":"))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class BoundedFileHandler(logging.handlers.RotatingFileHandler):
|
|
44
|
+
"""A size-rotating log file that also stays bounded when no backups are kept.
|
|
45
|
+
|
|
46
|
+
The standard handler never rolls over with zero backups, so the file would grow without
|
|
47
|
+
limit; here the active file is emptied instead.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def doRollover(self) -> None:
|
|
51
|
+
if self.backupCount > 0:
|
|
52
|
+
super().doRollover()
|
|
53
|
+
return
|
|
54
|
+
if self.stream:
|
|
55
|
+
self.stream.close()
|
|
56
|
+
self.stream = None # pyright: ignore[reportAttributeAccessIssue]
|
|
57
|
+
with contextlib.suppress(FileNotFoundError):
|
|
58
|
+
os.remove(self.baseFilename)
|
|
59
|
+
if not self.delay:
|
|
60
|
+
self.stream = self._open()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def setup_logging(
|
|
64
|
+
stream: TextIO | None = None,
|
|
65
|
+
level: int = logging.INFO,
|
|
66
|
+
*,
|
|
67
|
+
file: Path | None = None,
|
|
68
|
+
max_bytes: int = DEFAULT_LOG_MAX_BYTES,
|
|
69
|
+
backups: int = DEFAULT_LOG_BACKUPS,
|
|
70
|
+
) -> None:
|
|
71
|
+
"""Route every logger as JSON lines to ``file`` if given, else to ``stream`` (stdout).
|
|
72
|
+
|
|
73
|
+
``file`` is rotated at ``max_bytes``, keeping ``backups`` old files (``.1`` is the newest); its
|
|
74
|
+
directory is created. Raises ``OSError`` when the file cannot be opened, leaving the loggers as
|
|
75
|
+
they were. The stdio proxy passes ``sys.stderr``: its stdout carries the protocol.
|
|
76
|
+
"""
|
|
77
|
+
handler: logging.Handler
|
|
78
|
+
if file is not None:
|
|
79
|
+
file.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
handler = BoundedFileHandler(
|
|
81
|
+
file, maxBytes=max_bytes, backupCount=backups, encoding="utf-8"
|
|
82
|
+
)
|
|
83
|
+
else:
|
|
84
|
+
handler = logging.StreamHandler(stream if stream is not None else sys.stdout)
|
|
85
|
+
handler.setFormatter(JsonFormatter())
|
|
86
|
+
root = logging.getLogger()
|
|
87
|
+
for existing in list(root.handlers):
|
|
88
|
+
root.removeHandler(existing)
|
|
89
|
+
root.addHandler(handler)
|
|
90
|
+
root.setLevel(level)
|
|
91
|
+
# httpx logs every request URL at INFO, query string and userinfo included
|
|
92
|
+
for noisy in ("httpx", "httpx2", "httpcore"):
|
|
93
|
+
logging.getLogger(noisy).setLevel(logging.WARNING)
|