sysprims 0.4.0__cp310-abi3-win_amd64.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.
- sysprims/__init__.py +1017 -0
- sysprims/__init__.pyi +181 -0
- sysprims/_sysprims.pyd +0 -0
- sysprims/py.typed +0 -0
- sysprims-0.4.0.dist-info/METADATA +41 -0
- sysprims-0.4.0.dist-info/RECORD +10 -0
- sysprims-0.4.0.dist-info/WHEEL +4 -0
- sysprims-0.4.0.dist-info/licenses/LICENSE-APACHE +190 -0
- sysprims-0.4.0.dist-info/licenses/LICENSE-MIT +21 -0
- sysprims-0.4.0.dist-info/licenses/NOTICE +23 -0
sysprims/__init__.py
ADDED
|
@@ -0,0 +1,1017 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Cross-platform process inspection, signal dispatch, containment, timeout, and RFC 5545 recurrence primitives."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Mapping, Sequence
|
|
7
|
+
from enum import IntEnum
|
|
8
|
+
import json
|
|
9
|
+
from typing import Any, Final, Union
|
|
10
|
+
import weakref
|
|
11
|
+
|
|
12
|
+
from . import _sysprims as _native
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ContainedProcess",
|
|
16
|
+
"RECURRENCE_CONTRACT",
|
|
17
|
+
"RECURRENCE_CORPUS_DIGEST",
|
|
18
|
+
"RECURRENCE_REFUSAL_REASONS",
|
|
19
|
+
"RecurrenceQueryError",
|
|
20
|
+
"RecurrenceRefusal",
|
|
21
|
+
"RecurrenceRule",
|
|
22
|
+
"SIGHUP",
|
|
23
|
+
"SIGINT",
|
|
24
|
+
"SIGKILL",
|
|
25
|
+
"SIGTERM",
|
|
26
|
+
"SIGUSR1",
|
|
27
|
+
"SIGUSR2",
|
|
28
|
+
"SysprimsError",
|
|
29
|
+
"SysprimsErrorCode",
|
|
30
|
+
"abi_version",
|
|
31
|
+
"ancestors",
|
|
32
|
+
"descendants",
|
|
33
|
+
"force_kill",
|
|
34
|
+
"force_kill_many",
|
|
35
|
+
"guard_step",
|
|
36
|
+
"kill_descendants",
|
|
37
|
+
"kill_many",
|
|
38
|
+
"list_fds",
|
|
39
|
+
"listening_ports",
|
|
40
|
+
"platform",
|
|
41
|
+
"proc_get",
|
|
42
|
+
"process_list",
|
|
43
|
+
"run_nohup",
|
|
44
|
+
"run_setsid",
|
|
45
|
+
"run_with_timeout",
|
|
46
|
+
"self_getpgid",
|
|
47
|
+
"self_getsid",
|
|
48
|
+
"signal_send",
|
|
49
|
+
"signal_send_group",
|
|
50
|
+
"spawn_contained",
|
|
51
|
+
"spawn_in_group",
|
|
52
|
+
"terminate",
|
|
53
|
+
"terminate_many",
|
|
54
|
+
"terminate_tree",
|
|
55
|
+
"tzdb_version",
|
|
56
|
+
"wait_pid",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
__version__: Final[str] = _native.VERSION
|
|
60
|
+
|
|
61
|
+
RECURRENCE_CONTRACT: Final[str] = _native.RECURRENCE_CONTRACT
|
|
62
|
+
RECURRENCE_CORPUS_DIGEST: Final[str] = _native.RECURRENCE_CORPUS_DIGEST
|
|
63
|
+
RECURRENCE_REFUSAL_REASONS: Final[tuple[str, ...]] = (
|
|
64
|
+
"invalid_rule",
|
|
65
|
+
"invalid_text",
|
|
66
|
+
"unsupported_part",
|
|
67
|
+
"invalid_tzid",
|
|
68
|
+
"invalid_date",
|
|
69
|
+
"dtstart_not_synchronized",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
SIGHUP: Final[int] = _native.SIGHUP
|
|
73
|
+
SIGINT: Final[int] = _native.SIGINT
|
|
74
|
+
SIGKILL: Final[int] = _native.SIGKILL
|
|
75
|
+
SIGTERM: Final[int] = _native.SIGTERM
|
|
76
|
+
SIGUSR1: Final[int] = _native.SIGUSR1
|
|
77
|
+
SIGUSR2: Final[int] = _native.SIGUSR2
|
|
78
|
+
|
|
79
|
+
_U32_MAX: Final[int] = 0xFFFF_FFFF
|
|
80
|
+
_MAX_SAFE_PID: Final[int] = 0x7FFF_FFFF
|
|
81
|
+
_MAX_DURATION_MS: Final[int] = 86_400_000
|
|
82
|
+
|
|
83
|
+
_BATCH_KILL_SCHEMA_ID: Final[str] = (
|
|
84
|
+
"https://schemas.3leaps.dev/sysprims/signal/v1.0.0/batch-kill-result.schema.json"
|
|
85
|
+
)
|
|
86
|
+
_RUN_SETSID_SCHEMA_ID: Final[str] = (
|
|
87
|
+
"https://schemas.3leaps.dev/sysprims/session/v1.0.0/run-setsid-config.schema.json"
|
|
88
|
+
)
|
|
89
|
+
_RUN_NOHUP_SCHEMA_ID: Final[str] = (
|
|
90
|
+
"https://schemas.3leaps.dev/sysprims/session/v1.0.0/run-nohup-config.schema.json"
|
|
91
|
+
)
|
|
92
|
+
_SPAWN_IN_GROUP_SCHEMA_ID: Final[str] = (
|
|
93
|
+
"https://schemas.3leaps.dev/sysprims/process/v1.0.0/spawn-in-group-config.schema.json"
|
|
94
|
+
)
|
|
95
|
+
_TERMINATE_TREE_SCHEMA_ID: Final[str] = (
|
|
96
|
+
"https://schemas.3leaps.dev/sysprims/process/v1.0.0/terminate-tree-config.schema.json"
|
|
97
|
+
)
|
|
98
|
+
_CONTAINMENT_SPAWN_SCHEMA_ID: Final[str] = (
|
|
99
|
+
"https://schemas.3leaps.dev/sysprims/timeout/v1.0.0/containment-spawn-config.schema.json"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
BytesInput = Union[bytes, bytearray, memoryview, str]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class SysprimsErrorCode(IntEnum):
|
|
106
|
+
"""Error codes shared across sysprims language bindings."""
|
|
107
|
+
|
|
108
|
+
OK = 0
|
|
109
|
+
INVALID_ARGUMENT = 1
|
|
110
|
+
SPAWN_FAILED = 2
|
|
111
|
+
TIMEOUT = 3
|
|
112
|
+
PERMISSION_DENIED = 4
|
|
113
|
+
NOT_FOUND = 5
|
|
114
|
+
NOT_SUPPORTED = 6
|
|
115
|
+
GROUP_CREATION_FAILED = 7
|
|
116
|
+
SYSTEM = 8
|
|
117
|
+
INTERNAL = 99
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class SysprimsError(RuntimeError):
|
|
121
|
+
"""Structured error raised by sysprims process, signal, session, and timeout APIs."""
|
|
122
|
+
|
|
123
|
+
def __init__(self, code: SysprimsErrorCode | int, message: str) -> None:
|
|
124
|
+
try:
|
|
125
|
+
resolved = SysprimsErrorCode(int(code))
|
|
126
|
+
except ValueError:
|
|
127
|
+
resolved = SysprimsErrorCode.INTERNAL
|
|
128
|
+
super().__init__(f"[{resolved.name}] {message}")
|
|
129
|
+
self.code: SysprimsErrorCode = resolved
|
|
130
|
+
self.message: str = message
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class RecurrenceRefusal(ValueError):
|
|
134
|
+
"""Refusal raised when an RFC 5545 recurrence rule or JSON document is invalid."""
|
|
135
|
+
|
|
136
|
+
def __init__(self, reason: str, detail: str) -> None:
|
|
137
|
+
super().__init__(f"{reason}: {detail}")
|
|
138
|
+
self.reason: str = reason
|
|
139
|
+
self.detail: str = detail
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class RecurrenceQueryError(RuntimeError):
|
|
143
|
+
"""Error raised when a recurrence expansion query fails (`reversed_range` or `search_limit_exceeded`)."""
|
|
144
|
+
|
|
145
|
+
def __init__(self, kind: str, message: str) -> None:
|
|
146
|
+
super().__init__(message)
|
|
147
|
+
self.kind: str = kind
|
|
148
|
+
self.message: str = message
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _require_int(value: Any, name: str) -> int:
|
|
152
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
153
|
+
raise SysprimsError(
|
|
154
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
155
|
+
f"{name} must be an int, not {type(value).__name__}",
|
|
156
|
+
)
|
|
157
|
+
return value
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _require_pid(value: Any, name: str = "pid") -> int:
|
|
161
|
+
iv = _require_int(value, name)
|
|
162
|
+
if iv < 1 or iv > _MAX_SAFE_PID:
|
|
163
|
+
raise SysprimsError(
|
|
164
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
165
|
+
f"{name} must be between 1 and {_MAX_SAFE_PID}",
|
|
166
|
+
)
|
|
167
|
+
return iv
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _require_bool(value: Any, name: str) -> bool:
|
|
171
|
+
if not isinstance(value, bool):
|
|
172
|
+
raise SysprimsError(
|
|
173
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
174
|
+
f"{name} must be a bool, not {type(value).__name__}",
|
|
175
|
+
)
|
|
176
|
+
return value
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _require_argv(argv: Sequence[str]) -> list[str]:
|
|
180
|
+
if isinstance(argv, (str, bytes, bytearray)) or not isinstance(argv, Sequence):
|
|
181
|
+
raise SysprimsError(
|
|
182
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
183
|
+
"argv must be a non-empty sequence of strings",
|
|
184
|
+
)
|
|
185
|
+
items = list(argv)
|
|
186
|
+
if not items:
|
|
187
|
+
raise SysprimsError(
|
|
188
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "argv must not be empty"
|
|
189
|
+
)
|
|
190
|
+
for idx, entry in enumerate(items):
|
|
191
|
+
if not isinstance(entry, str) or not entry:
|
|
192
|
+
raise SysprimsError(
|
|
193
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
194
|
+
f"argv[{idx}] must be a non-empty string",
|
|
195
|
+
)
|
|
196
|
+
return items
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _require_env(env: Mapping[str, str] | None) -> dict[str, str] | None:
|
|
200
|
+
if env is None:
|
|
201
|
+
return None
|
|
202
|
+
if not isinstance(env, Mapping):
|
|
203
|
+
raise SysprimsError(
|
|
204
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
205
|
+
"env must be a mapping of string keys to string values",
|
|
206
|
+
)
|
|
207
|
+
out: dict[str, str] = {}
|
|
208
|
+
for k, v in env.items():
|
|
209
|
+
if not isinstance(k, str) or not isinstance(v, str):
|
|
210
|
+
raise SysprimsError(
|
|
211
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
212
|
+
"env keys and values must be strings",
|
|
213
|
+
)
|
|
214
|
+
out[k] = v
|
|
215
|
+
return out
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _bytes_input(data: BytesInput, label: str = "input") -> bytes:
|
|
219
|
+
if isinstance(data, str):
|
|
220
|
+
return data.encode("utf-8")
|
|
221
|
+
try:
|
|
222
|
+
view = memoryview(data)
|
|
223
|
+
except TypeError:
|
|
224
|
+
raise TypeError(
|
|
225
|
+
f"{label} must be bytes-like or str, not {type(data).__name__}"
|
|
226
|
+
) from None
|
|
227
|
+
with view:
|
|
228
|
+
return view.tobytes()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _serialize_json_mapping(mapping: Mapping[str, Any] | None, label: str) -> str:
|
|
232
|
+
if mapping is None:
|
|
233
|
+
return ""
|
|
234
|
+
if not isinstance(mapping, Mapping):
|
|
235
|
+
raise SysprimsError(
|
|
236
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
237
|
+
f"{label} must be a mapping",
|
|
238
|
+
)
|
|
239
|
+
if not mapping:
|
|
240
|
+
return ""
|
|
241
|
+
try:
|
|
242
|
+
return json.dumps(dict(mapping), allow_nan=False)
|
|
243
|
+
except (TypeError, ValueError) as exc:
|
|
244
|
+
raise SysprimsError(
|
|
245
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
246
|
+
f"invalid {label}: {exc}",
|
|
247
|
+
) from None
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _process_options_json(include_env: bool, include_threads: bool) -> str:
|
|
251
|
+
_require_bool(include_env, "include_env")
|
|
252
|
+
_require_bool(include_threads, "include_threads")
|
|
253
|
+
if not include_env and not include_threads:
|
|
254
|
+
return ""
|
|
255
|
+
wire: dict[str, bool] = {}
|
|
256
|
+
if include_env:
|
|
257
|
+
wire["include_env"] = True
|
|
258
|
+
if include_threads:
|
|
259
|
+
wire["include_threads"] = True
|
|
260
|
+
return json.dumps(wire)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _call_json(fn: Any, *args: Any) -> dict[str, Any]:
|
|
264
|
+
try:
|
|
265
|
+
payload = fn(*args)
|
|
266
|
+
except _native.RawSysprimsError as exc:
|
|
267
|
+
raise SysprimsError(*exc.args) from None
|
|
268
|
+
result: dict[str, Any] = json.loads(payload)
|
|
269
|
+
return result
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _call_void(fn: Any, *args: Any) -> None:
|
|
273
|
+
try:
|
|
274
|
+
fn(*args)
|
|
275
|
+
except _native.RawSysprimsError as exc:
|
|
276
|
+
raise SysprimsError(*exc.args) from None
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _call_u32(fn: Any, *args: Any) -> int:
|
|
280
|
+
try:
|
|
281
|
+
value: int = fn(*args)
|
|
282
|
+
return value
|
|
283
|
+
except _native.RawSysprimsError as exc:
|
|
284
|
+
raise SysprimsError(*exc.args) from None
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def abi_version() -> int:
|
|
288
|
+
"""Return the sysprims native ABI version."""
|
|
289
|
+
return int(_native.abi_version())
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def platform() -> str:
|
|
293
|
+
"""Return the canonical sysprims platform identifier (`linux`, `macos`, `windows`)."""
|
|
294
|
+
return str(_native.platform())
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
# =============================================================================
|
|
298
|
+
# Process Inspection & Guard
|
|
299
|
+
# =============================================================================
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def proc_get(
|
|
303
|
+
pid: int,
|
|
304
|
+
*,
|
|
305
|
+
include_env: bool = False,
|
|
306
|
+
include_threads: bool = False,
|
|
307
|
+
) -> dict[str, Any]:
|
|
308
|
+
"""Inspect a single process by PID."""
|
|
309
|
+
checked_pid = _require_pid(pid, "pid")
|
|
310
|
+
opts_json = _process_options_json(include_env, include_threads)
|
|
311
|
+
return _call_json(_native.proc_get, checked_pid, opts_json)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def process_list(
|
|
315
|
+
filter: Mapping[str, Any] | None = None,
|
|
316
|
+
*,
|
|
317
|
+
include_env: bool = False,
|
|
318
|
+
include_threads: bool = False,
|
|
319
|
+
) -> dict[str, Any]:
|
|
320
|
+
"""Return a filtered snapshot of running processes."""
|
|
321
|
+
filter_json = _serialize_json_mapping(filter, "filter")
|
|
322
|
+
opts_json = _process_options_json(include_env, include_threads)
|
|
323
|
+
return _call_json(_native.proc_list, filter_json, opts_json)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def listening_ports(filter: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
327
|
+
"""Return listening TCP/UDP socket port bindings."""
|
|
328
|
+
filter_json = _serialize_json_mapping(filter, "filter")
|
|
329
|
+
return _call_json(_native.proc_listening_ports, filter_json)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def list_fds(pid: int, filter: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
333
|
+
"""Return open file descriptors for `pid` (Unix/macOS/Linux where supported)."""
|
|
334
|
+
checked_pid = _require_pid(pid, "pid")
|
|
335
|
+
filter_json = _serialize_json_mapping(filter, "filter")
|
|
336
|
+
return _call_json(_native.proc_list_fds, checked_pid, filter_json)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def wait_pid(pid: int, timeout_ms: int) -> dict[str, Any]:
|
|
340
|
+
"""Wait up to `timeout_ms` milliseconds for `pid` to exit."""
|
|
341
|
+
checked_pid = _require_pid(pid, "pid")
|
|
342
|
+
checked_timeout = _require_int(timeout_ms, "timeout_ms")
|
|
343
|
+
if checked_timeout < 0 or checked_timeout > _U32_MAX:
|
|
344
|
+
raise SysprimsError(
|
|
345
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
346
|
+
f"timeout_ms must be between 0 and {_U32_MAX}",
|
|
347
|
+
)
|
|
348
|
+
return _call_json(_native.proc_wait_pid, checked_pid, checked_timeout)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _descendants_config_json(
|
|
352
|
+
filter: Mapping[str, Any] | None,
|
|
353
|
+
cpu_mode: str | None,
|
|
354
|
+
sample_duration_ms: int | None,
|
|
355
|
+
cascade: bool = False,
|
|
356
|
+
) -> str:
|
|
357
|
+
wire: dict[str, Any] = {}
|
|
358
|
+
if filter is not None:
|
|
359
|
+
if not isinstance(filter, Mapping):
|
|
360
|
+
raise SysprimsError(
|
|
361
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "filter must be a mapping"
|
|
362
|
+
)
|
|
363
|
+
wire.update(filter)
|
|
364
|
+
if cpu_mode is not None:
|
|
365
|
+
if cpu_mode not in ("lifetime", "monitor"):
|
|
366
|
+
raise SysprimsError(
|
|
367
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
368
|
+
f"invalid cpu_mode: {cpu_mode!r}",
|
|
369
|
+
)
|
|
370
|
+
wire["cpu_mode"] = cpu_mode
|
|
371
|
+
if sample_duration_ms is not None:
|
|
372
|
+
dur = _require_int(sample_duration_ms, "sample_duration_ms")
|
|
373
|
+
if dur < 0 or dur > _MAX_DURATION_MS:
|
|
374
|
+
raise SysprimsError(
|
|
375
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
376
|
+
f"sample_duration_ms must be between 0 and {_MAX_DURATION_MS}",
|
|
377
|
+
)
|
|
378
|
+
wire["sample_duration_ms"] = dur
|
|
379
|
+
_require_bool(cascade, "cascade")
|
|
380
|
+
if cascade:
|
|
381
|
+
wire["cascade"] = True
|
|
382
|
+
return json.dumps(wire, allow_nan=False) if wire else ""
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def descendants(
|
|
386
|
+
root_pid: int,
|
|
387
|
+
*,
|
|
388
|
+
max_levels: int | None = None,
|
|
389
|
+
filter: Mapping[str, Any] | None = None,
|
|
390
|
+
cpu_mode: str | None = None,
|
|
391
|
+
sample_duration_ms: int | None = None,
|
|
392
|
+
include_env: bool = False,
|
|
393
|
+
include_threads: bool = False,
|
|
394
|
+
) -> dict[str, Any]:
|
|
395
|
+
"""Traverse descendant processes below `root_pid`."""
|
|
396
|
+
checked_root = _require_pid(root_pid, "root_pid")
|
|
397
|
+
levels = _U32_MAX if max_levels is None else _require_int(max_levels, "max_levels")
|
|
398
|
+
if levels < 0 or levels > _U32_MAX:
|
|
399
|
+
raise SysprimsError(
|
|
400
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
401
|
+
f"max_levels must be between 0 and {_U32_MAX}",
|
|
402
|
+
)
|
|
403
|
+
cfg_json = _descendants_config_json(filter, cpu_mode, sample_duration_ms, False)
|
|
404
|
+
opts_json = _process_options_json(include_env, include_threads)
|
|
405
|
+
return _call_json(
|
|
406
|
+
_native.proc_descendants, checked_root, levels, cfg_json, opts_json
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def kill_descendants(
|
|
411
|
+
root_pid: int,
|
|
412
|
+
*,
|
|
413
|
+
signal: int = SIGTERM,
|
|
414
|
+
max_levels: int | None = None,
|
|
415
|
+
filter: Mapping[str, Any] | None = None,
|
|
416
|
+
cpu_mode: str | None = None,
|
|
417
|
+
sample_duration_ms: int | None = None,
|
|
418
|
+
cascade: bool = False,
|
|
419
|
+
) -> dict[str, Any]:
|
|
420
|
+
"""Send `signal` to matched descendants of `root_pid` (excluding self, parent, and PID 1)."""
|
|
421
|
+
checked_root = _require_pid(root_pid, "root_pid")
|
|
422
|
+
checked_sig = _require_int(signal, "signal")
|
|
423
|
+
levels = _U32_MAX if max_levels is None else _require_int(max_levels, "max_levels")
|
|
424
|
+
if levels < 0 or levels > _U32_MAX:
|
|
425
|
+
raise SysprimsError(
|
|
426
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
427
|
+
f"max_levels must be between 0 and {_U32_MAX}",
|
|
428
|
+
)
|
|
429
|
+
cfg_json = _descendants_config_json(filter, cpu_mode, sample_duration_ms, cascade)
|
|
430
|
+
return _call_json(
|
|
431
|
+
_native.proc_kill_descendants, checked_root, levels, checked_sig, cfg_json
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def guard_step(config: Mapping[str, Any]) -> dict[str, Any]:
|
|
436
|
+
"""Run one single-shot descendant guard evaluation/remediation step."""
|
|
437
|
+
if not isinstance(config, Mapping) or not config:
|
|
438
|
+
raise SysprimsError(
|
|
439
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
440
|
+
"guard config must be a non-empty mapping",
|
|
441
|
+
)
|
|
442
|
+
cfg_json = _serialize_json_mapping(config, "guard config")
|
|
443
|
+
return _call_json(_native.proc_guard_step, cfg_json)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def ancestors(
|
|
447
|
+
pid: int,
|
|
448
|
+
*,
|
|
449
|
+
max_depth: int = 64,
|
|
450
|
+
include_env: bool = False,
|
|
451
|
+
include_threads: bool = False,
|
|
452
|
+
) -> dict[str, Any]:
|
|
453
|
+
"""Walk the parent chain starting at `pid` up to `max_depth` ancestors."""
|
|
454
|
+
checked_pid = _require_pid(pid, "pid")
|
|
455
|
+
depth = _require_int(max_depth, "max_depth")
|
|
456
|
+
if depth < 0 or depth > _U32_MAX:
|
|
457
|
+
raise SysprimsError(
|
|
458
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
459
|
+
f"max_depth must be between 0 and {_U32_MAX}",
|
|
460
|
+
)
|
|
461
|
+
opts_json = _process_options_json(include_env, include_threads)
|
|
462
|
+
return _call_json(_native.proc_ancestors, checked_pid, depth, opts_json)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
# =============================================================================
|
|
466
|
+
# Self Introspection & Signals
|
|
467
|
+
# =============================================================================
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def self_getpgid() -> int:
|
|
471
|
+
"""Return the calling process's process group ID (Unix only)."""
|
|
472
|
+
return _call_u32(_native.self_getpgid)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def self_getsid() -> int:
|
|
476
|
+
"""Return the calling process's session ID (Unix only)."""
|
|
477
|
+
return _call_u32(_native.self_getsid)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def signal_send(pid: int, signal: int) -> None:
|
|
481
|
+
"""Send `signal` to `pid`."""
|
|
482
|
+
checked_pid = _require_pid(pid, "pid")
|
|
483
|
+
checked_sig = _require_int(signal, "signal")
|
|
484
|
+
_call_void(_native.signal_send, checked_pid, checked_sig)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def signal_send_group(pgid: int, signal: int) -> None:
|
|
488
|
+
"""Send `signal` to process group `pgid` (Unix only)."""
|
|
489
|
+
checked_pgid = _require_pid(pgid, "pgid")
|
|
490
|
+
checked_sig = _require_int(signal, "signal")
|
|
491
|
+
_call_void(_native.signal_send_group, checked_pgid, checked_sig)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def terminate(pid: int) -> None:
|
|
495
|
+
"""Terminate `pid` gracefully (`SIGTERM` on Unix, `TerminateProcess` on Windows)."""
|
|
496
|
+
checked_pid = _require_pid(pid, "pid")
|
|
497
|
+
_call_void(_native.terminate, checked_pid)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def force_kill(pid: int) -> None:
|
|
501
|
+
"""Forcefully kill `pid` (`SIGKILL` on Unix, `TerminateProcess` on Windows)."""
|
|
502
|
+
checked_pid = _require_pid(pid, "pid")
|
|
503
|
+
_call_void(_native.force_kill, checked_pid)
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _validate_pid_list(pids: Sequence[int]) -> list[int]:
|
|
507
|
+
if isinstance(pids, (str, bytes, bytearray)) or not isinstance(pids, Sequence):
|
|
508
|
+
raise SysprimsError(
|
|
509
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
510
|
+
"pids must be a non-empty sequence of PIDs",
|
|
511
|
+
)
|
|
512
|
+
items = [_require_pid(p, f"pids[{idx}]") for idx, p in enumerate(pids)]
|
|
513
|
+
if not items:
|
|
514
|
+
raise SysprimsError(
|
|
515
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "pids must not be empty"
|
|
516
|
+
)
|
|
517
|
+
return items
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def kill_many(pids: Sequence[int], signal: int) -> dict[str, Any]:
|
|
521
|
+
"""Send `signal` to multiple PIDs, collecting per-PID successes and failures."""
|
|
522
|
+
checked_pids = _validate_pid_list(pids)
|
|
523
|
+
checked_sig = _require_int(signal, "signal")
|
|
524
|
+
return _call_json(_native.signal_kill_many, checked_pids, checked_sig)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def terminate_many(pids: Sequence[int]) -> dict[str, Any]:
|
|
528
|
+
"""Terminate multiple PIDs gracefully across Unix and Windows."""
|
|
529
|
+
checked_pids = _validate_pid_list(pids)
|
|
530
|
+
succeeded: list[int] = []
|
|
531
|
+
failed: list[dict[str, Any]] = []
|
|
532
|
+
for pid in checked_pids:
|
|
533
|
+
try:
|
|
534
|
+
terminate(pid)
|
|
535
|
+
succeeded.append(pid)
|
|
536
|
+
except SysprimsError as exc:
|
|
537
|
+
failed.append({"pid": pid, "error": exc.message})
|
|
538
|
+
return {
|
|
539
|
+
"schema_id": _BATCH_KILL_SCHEMA_ID,
|
|
540
|
+
"succeeded": succeeded,
|
|
541
|
+
"failed": failed,
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def force_kill_many(pids: Sequence[int]) -> dict[str, Any]:
|
|
546
|
+
"""Forcefully kill multiple PIDs across Unix and Windows."""
|
|
547
|
+
checked_pids = _validate_pid_list(pids)
|
|
548
|
+
succeeded: list[int] = []
|
|
549
|
+
failed: list[dict[str, Any]] = []
|
|
550
|
+
for pid in checked_pids:
|
|
551
|
+
try:
|
|
552
|
+
force_kill(pid)
|
|
553
|
+
succeeded.append(pid)
|
|
554
|
+
except SysprimsError as exc:
|
|
555
|
+
failed.append({"pid": pid, "error": exc.message})
|
|
556
|
+
return {
|
|
557
|
+
"schema_id": _BATCH_KILL_SCHEMA_ID,
|
|
558
|
+
"succeeded": succeeded,
|
|
559
|
+
"failed": failed,
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
# =============================================================================
|
|
564
|
+
# Terminate Tree & Timeout Execution
|
|
565
|
+
# =============================================================================
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def terminate_tree(pid: int, config: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
569
|
+
"""Terminate a process with escalation (`signal` -> wait -> `kill_signal`)."""
|
|
570
|
+
checked_pid = _require_pid(pid, "pid")
|
|
571
|
+
if config is None:
|
|
572
|
+
return _call_json(_native.terminate_tree, checked_pid, "")
|
|
573
|
+
if not isinstance(config, Mapping):
|
|
574
|
+
raise SysprimsError(
|
|
575
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "config must be a mapping"
|
|
576
|
+
)
|
|
577
|
+
wire = {
|
|
578
|
+
"schema_id": config.get("schema_id", _TERMINATE_TREE_SCHEMA_ID),
|
|
579
|
+
**dict(config),
|
|
580
|
+
}
|
|
581
|
+
return _call_json(
|
|
582
|
+
_native.terminate_tree, checked_pid, _serialize_json_mapping(wire, "config")
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def run_with_timeout(
|
|
587
|
+
command: str,
|
|
588
|
+
args: Sequence[str] = (),
|
|
589
|
+
*,
|
|
590
|
+
timeout_ms: int,
|
|
591
|
+
kill_after_ms: int | None = None,
|
|
592
|
+
signal: int | None = None,
|
|
593
|
+
grouping: str = "group_by_default",
|
|
594
|
+
preserve_status: bool = False,
|
|
595
|
+
) -> dict[str, Any]:
|
|
596
|
+
"""Execute `command` with `args` under `timeout_ms`, escalating if needed."""
|
|
597
|
+
if not isinstance(command, str) or not command:
|
|
598
|
+
raise SysprimsError(
|
|
599
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "command must be a non-empty string"
|
|
600
|
+
)
|
|
601
|
+
if isinstance(args, (str, bytes, bytearray)) or not isinstance(args, Sequence):
|
|
602
|
+
raise SysprimsError(
|
|
603
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "args must be a sequence of strings"
|
|
604
|
+
)
|
|
605
|
+
arg_list: list[str] = []
|
|
606
|
+
for idx, item in enumerate(args):
|
|
607
|
+
if not isinstance(item, str):
|
|
608
|
+
raise SysprimsError(
|
|
609
|
+
SysprimsErrorCode.INVALID_ARGUMENT, f"args[{idx}] must be a string"
|
|
610
|
+
)
|
|
611
|
+
arg_list.append(item)
|
|
612
|
+
checked_timeout = _require_int(timeout_ms, "timeout_ms")
|
|
613
|
+
if checked_timeout < 0 or checked_timeout > _MAX_DURATION_MS:
|
|
614
|
+
raise SysprimsError(
|
|
615
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
616
|
+
f"timeout_ms must be between 0 and {_MAX_DURATION_MS}",
|
|
617
|
+
)
|
|
618
|
+
if grouping not in ("group_by_default", "foreground"):
|
|
619
|
+
raise SysprimsError(
|
|
620
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
621
|
+
f"grouping must be 'group_by_default' or 'foreground', got {grouping!r}",
|
|
622
|
+
)
|
|
623
|
+
_require_bool(preserve_status, "preserve_status")
|
|
624
|
+
wire: dict[str, Any] = {
|
|
625
|
+
"command": command,
|
|
626
|
+
"args": arg_list,
|
|
627
|
+
"timeout_ms": checked_timeout,
|
|
628
|
+
"grouping": grouping,
|
|
629
|
+
"preserve_status": preserve_status,
|
|
630
|
+
}
|
|
631
|
+
if kill_after_ms is not None:
|
|
632
|
+
ka = _require_int(kill_after_ms, "kill_after_ms")
|
|
633
|
+
if ka < 0 or ka > _MAX_DURATION_MS:
|
|
634
|
+
raise SysprimsError(
|
|
635
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
636
|
+
f"kill_after_ms must be between 0 and {_MAX_DURATION_MS}",
|
|
637
|
+
)
|
|
638
|
+
wire["kill_after_ms"] = ka
|
|
639
|
+
if signal is not None:
|
|
640
|
+
wire["signal"] = _require_int(signal, "signal")
|
|
641
|
+
return _call_json(_native.run_with_timeout, json.dumps(wire, allow_nan=False))
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
# =============================================================================
|
|
645
|
+
# Session Spawn, Group Spawn & Containment
|
|
646
|
+
# =============================================================================
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def run_setsid(
|
|
650
|
+
argv: Sequence[str],
|
|
651
|
+
*,
|
|
652
|
+
cwd: str | None = None,
|
|
653
|
+
env: Mapping[str, str] | None = None,
|
|
654
|
+
wait: bool = False,
|
|
655
|
+
) -> dict[str, Any]:
|
|
656
|
+
"""Spawn `argv` in a detached session (`setsid` on Unix, detached console/group on Windows)."""
|
|
657
|
+
checked_argv = _require_argv(argv)
|
|
658
|
+
checked_env = _require_env(env)
|
|
659
|
+
_require_bool(wait, "wait")
|
|
660
|
+
if cwd is not None and (not isinstance(cwd, str) or not cwd):
|
|
661
|
+
raise SysprimsError(
|
|
662
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "cwd must be a non-empty string"
|
|
663
|
+
)
|
|
664
|
+
wire: dict[str, Any] = {
|
|
665
|
+
"schema_id": _RUN_SETSID_SCHEMA_ID,
|
|
666
|
+
"argv": checked_argv,
|
|
667
|
+
"wait": wait,
|
|
668
|
+
}
|
|
669
|
+
if cwd is not None:
|
|
670
|
+
wire["cwd"] = cwd
|
|
671
|
+
if checked_env is not None:
|
|
672
|
+
wire["env"] = checked_env
|
|
673
|
+
return _call_json(_native.run_setsid, json.dumps(wire, allow_nan=False))
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def run_nohup(
|
|
677
|
+
argv: Sequence[str],
|
|
678
|
+
*,
|
|
679
|
+
cwd: str | None = None,
|
|
680
|
+
env: Mapping[str, str] | None = None,
|
|
681
|
+
wait: bool = False,
|
|
682
|
+
output_file: str | None = None,
|
|
683
|
+
) -> dict[str, Any]:
|
|
684
|
+
"""Spawn `argv` with `SIGHUP` ignored in the inherited session (Unix only)."""
|
|
685
|
+
checked_argv = _require_argv(argv)
|
|
686
|
+
checked_env = _require_env(env)
|
|
687
|
+
_require_bool(wait, "wait")
|
|
688
|
+
if cwd is not None and (not isinstance(cwd, str) or not cwd):
|
|
689
|
+
raise SysprimsError(
|
|
690
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "cwd must be a non-empty string"
|
|
691
|
+
)
|
|
692
|
+
if output_file is not None and (
|
|
693
|
+
not isinstance(output_file, str) or not output_file
|
|
694
|
+
):
|
|
695
|
+
raise SysprimsError(
|
|
696
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
697
|
+
"output_file must be a non-empty string",
|
|
698
|
+
)
|
|
699
|
+
wire: dict[str, Any] = {
|
|
700
|
+
"schema_id": _RUN_NOHUP_SCHEMA_ID,
|
|
701
|
+
"argv": checked_argv,
|
|
702
|
+
"wait": wait,
|
|
703
|
+
}
|
|
704
|
+
if cwd is not None:
|
|
705
|
+
wire["cwd"] = cwd
|
|
706
|
+
if checked_env is not None:
|
|
707
|
+
wire["env"] = checked_env
|
|
708
|
+
if output_file is not None:
|
|
709
|
+
wire["output_file"] = output_file
|
|
710
|
+
return _call_json(_native.run_nohup, json.dumps(wire, allow_nan=False))
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def spawn_in_group(
|
|
714
|
+
argv: Sequence[str],
|
|
715
|
+
*,
|
|
716
|
+
cwd: str | None = None,
|
|
717
|
+
env: Mapping[str, str] | None = None,
|
|
718
|
+
) -> dict[str, Any]:
|
|
719
|
+
"""Spawn `argv` in a new process group or Windows Job Object."""
|
|
720
|
+
checked_argv = _require_argv(argv)
|
|
721
|
+
checked_env = _require_env(env)
|
|
722
|
+
if cwd is not None and (not isinstance(cwd, str) or not cwd):
|
|
723
|
+
raise SysprimsError(
|
|
724
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "cwd must be a non-empty string"
|
|
725
|
+
)
|
|
726
|
+
wire: dict[str, Any] = {
|
|
727
|
+
"schema_id": _SPAWN_IN_GROUP_SCHEMA_ID,
|
|
728
|
+
"argv": checked_argv,
|
|
729
|
+
}
|
|
730
|
+
if cwd is not None:
|
|
731
|
+
wire["cwd"] = cwd
|
|
732
|
+
if checked_env is not None:
|
|
733
|
+
wire["env"] = checked_env
|
|
734
|
+
return _call_json(_native.spawn_in_group, json.dumps(wire, allow_nan=False))
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def _close_token_quietly(token: int) -> None:
|
|
738
|
+
try:
|
|
739
|
+
_native.containment_close(token)
|
|
740
|
+
except Exception:
|
|
741
|
+
pass
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
class ContainedProcess:
|
|
745
|
+
"""Opaque handle to a native-owned contained process (`spawn_contained`).
|
|
746
|
+
|
|
747
|
+
Supports `with spawn_contained(...) as proc:` context management; exiting the
|
|
748
|
+
`with` block closes the handle (terminating and reaping the contained group
|
|
749
|
+
or Job Object if still active).
|
|
750
|
+
"""
|
|
751
|
+
|
|
752
|
+
__slots__ = ("_finalizer", "_token", "__weakref__")
|
|
753
|
+
|
|
754
|
+
def __init__(self, _token: int, *, _internal: bool = False) -> None:
|
|
755
|
+
if not _internal:
|
|
756
|
+
raise TypeError("ContainedProcess must be created via spawn_contained()")
|
|
757
|
+
self._token: int | None = _token
|
|
758
|
+
self._finalizer = weakref.finalize(self, _close_token_quietly, _token)
|
|
759
|
+
|
|
760
|
+
def _require_token(self) -> int:
|
|
761
|
+
if self._token is None:
|
|
762
|
+
raise SysprimsError(
|
|
763
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
764
|
+
"containment handle is stale or closed",
|
|
765
|
+
)
|
|
766
|
+
return self._token
|
|
767
|
+
|
|
768
|
+
@property
|
|
769
|
+
def closed(self) -> bool:
|
|
770
|
+
"""Whether `close()` has completed on this handle."""
|
|
771
|
+
return self._token is None
|
|
772
|
+
|
|
773
|
+
def identity(self) -> dict[str, Any]:
|
|
774
|
+
"""Return the active or inert containment snapshot without polling child exit."""
|
|
775
|
+
return _call_json(_native.containment_identity, self._require_token())
|
|
776
|
+
|
|
777
|
+
def poll(self) -> dict[str, Any]:
|
|
778
|
+
"""Poll the contained leader process without blocking."""
|
|
779
|
+
return _call_json(_native.containment_poll, self._require_token())
|
|
780
|
+
|
|
781
|
+
def wait(self, timeout_ms: int | None = None) -> dict[str, Any]:
|
|
782
|
+
"""Wait for the contained leader process to finish (`None` waits without timeout)."""
|
|
783
|
+
token = self._require_token()
|
|
784
|
+
if timeout_ms is None:
|
|
785
|
+
return _call_json(_native.containment_wait, token, None)
|
|
786
|
+
checked = _require_int(timeout_ms, "timeout_ms")
|
|
787
|
+
if checked < 0 or checked > _MAX_DURATION_MS:
|
|
788
|
+
raise SysprimsError(
|
|
789
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
790
|
+
f"timeout_ms must be between 0 and {_MAX_DURATION_MS}",
|
|
791
|
+
)
|
|
792
|
+
return _call_json(_native.containment_wait, token, checked)
|
|
793
|
+
|
|
794
|
+
def terminate(self) -> dict[str, Any]:
|
|
795
|
+
"""Terminate the contained group or Job Object with configured escalation."""
|
|
796
|
+
return _call_json(_native.containment_terminate, self._require_token())
|
|
797
|
+
|
|
798
|
+
def close(self) -> None:
|
|
799
|
+
"""Release the native containment slot (idempotent; terminates if still running)."""
|
|
800
|
+
token = self._token
|
|
801
|
+
if token is None:
|
|
802
|
+
return
|
|
803
|
+
_call_void(_native.containment_close, token)
|
|
804
|
+
self._token = None
|
|
805
|
+
self._finalizer.detach()
|
|
806
|
+
|
|
807
|
+
def __enter__(self) -> ContainedProcess:
|
|
808
|
+
self._require_token()
|
|
809
|
+
return self
|
|
810
|
+
|
|
811
|
+
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
812
|
+
self.close()
|
|
813
|
+
|
|
814
|
+
def __repr__(self) -> str:
|
|
815
|
+
state = "closed" if self._token is None else "open"
|
|
816
|
+
return f"<ContainedProcess {state}>"
|
|
817
|
+
|
|
818
|
+
def __copy__(self) -> ContainedProcess:
|
|
819
|
+
raise TypeError("ContainedProcess cannot be copied")
|
|
820
|
+
|
|
821
|
+
def __deepcopy__(self, memo: Any) -> ContainedProcess:
|
|
822
|
+
raise TypeError("ContainedProcess cannot be deep-copied")
|
|
823
|
+
|
|
824
|
+
def __reduce__(self) -> Any:
|
|
825
|
+
raise TypeError("ContainedProcess cannot be pickled")
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def spawn_contained(
|
|
829
|
+
argv: Sequence[str],
|
|
830
|
+
*,
|
|
831
|
+
cwd: str | None = None,
|
|
832
|
+
env: Mapping[str, str] | None = None,
|
|
833
|
+
execution_timeout_ms: int | None = None,
|
|
834
|
+
grace_timeout_ms: int | None = None,
|
|
835
|
+
kill_timeout_ms: int | None = None,
|
|
836
|
+
signal: int | None = None,
|
|
837
|
+
kill_signal: int | None = None,
|
|
838
|
+
) -> ContainedProcess:
|
|
839
|
+
"""Spawn `argv` inside an owned containment boundary and return a `ContainedProcess`."""
|
|
840
|
+
checked_argv = _require_argv(argv)
|
|
841
|
+
checked_env = _require_env(env)
|
|
842
|
+
if cwd is not None and (not isinstance(cwd, str) or not cwd):
|
|
843
|
+
raise SysprimsError(
|
|
844
|
+
SysprimsErrorCode.INVALID_ARGUMENT, "cwd must be a non-empty string"
|
|
845
|
+
)
|
|
846
|
+
wire: dict[str, Any] = {
|
|
847
|
+
"schema_id": _CONTAINMENT_SPAWN_SCHEMA_ID,
|
|
848
|
+
"argv": checked_argv,
|
|
849
|
+
}
|
|
850
|
+
if cwd is not None:
|
|
851
|
+
wire["cwd"] = cwd
|
|
852
|
+
if checked_env is not None:
|
|
853
|
+
wire["env"] = checked_env
|
|
854
|
+
if execution_timeout_ms is not None:
|
|
855
|
+
et = _require_int(execution_timeout_ms, "execution_timeout_ms")
|
|
856
|
+
if et < 1 or et > _MAX_DURATION_MS:
|
|
857
|
+
raise SysprimsError(
|
|
858
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
859
|
+
f"execution_timeout_ms must be between 1 and {_MAX_DURATION_MS}",
|
|
860
|
+
)
|
|
861
|
+
wire["execution_timeout_ms"] = et
|
|
862
|
+
if grace_timeout_ms is not None:
|
|
863
|
+
gt = _require_int(grace_timeout_ms, "grace_timeout_ms")
|
|
864
|
+
if gt < 0 or gt > _MAX_DURATION_MS:
|
|
865
|
+
raise SysprimsError(
|
|
866
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
867
|
+
f"grace_timeout_ms must be between 0 and {_MAX_DURATION_MS}",
|
|
868
|
+
)
|
|
869
|
+
wire["grace_timeout_ms"] = gt
|
|
870
|
+
if kill_timeout_ms is not None:
|
|
871
|
+
kt = _require_int(kill_timeout_ms, "kill_timeout_ms")
|
|
872
|
+
if kt < 0 or kt > _MAX_DURATION_MS:
|
|
873
|
+
raise SysprimsError(
|
|
874
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
875
|
+
f"kill_timeout_ms must be between 0 and {_MAX_DURATION_MS}",
|
|
876
|
+
)
|
|
877
|
+
wire["kill_timeout_ms"] = kt
|
|
878
|
+
if signal is not None:
|
|
879
|
+
sig = _require_int(signal, "signal")
|
|
880
|
+
if sig == 0:
|
|
881
|
+
raise SysprimsError(
|
|
882
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
883
|
+
"signal 0 is not a valid termination policy",
|
|
884
|
+
)
|
|
885
|
+
wire["signal"] = sig
|
|
886
|
+
if kill_signal is not None:
|
|
887
|
+
ksig = _require_int(kill_signal, "kill_signal")
|
|
888
|
+
if ksig == 0:
|
|
889
|
+
raise SysprimsError(
|
|
890
|
+
SysprimsErrorCode.INVALID_ARGUMENT,
|
|
891
|
+
"kill_signal 0 is not a valid termination policy",
|
|
892
|
+
)
|
|
893
|
+
wire["kill_signal"] = ksig
|
|
894
|
+
try:
|
|
895
|
+
token: int = _native.containment_spawn(json.dumps(wire, allow_nan=False))
|
|
896
|
+
except _native.RawSysprimsError as exc:
|
|
897
|
+
raise SysprimsError(*exc.args) from None
|
|
898
|
+
return ContainedProcess(token, _internal=True)
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
# =============================================================================
|
|
902
|
+
# RFC 5545 Recurrence (`contract: recurrence/v0`)
|
|
903
|
+
# =============================================================================
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
class RecurrenceRule:
|
|
907
|
+
"""Validated, normalized RFC 5545 recurrence rule (`contract: recurrence/v0`)."""
|
|
908
|
+
|
|
909
|
+
__slots__ = ("_raw",)
|
|
910
|
+
|
|
911
|
+
def __init__(self, _raw: Any, *, _internal: bool = False) -> None:
|
|
912
|
+
if not _internal:
|
|
913
|
+
raise TypeError(
|
|
914
|
+
"RecurrenceRule must be constructed via from_json(), from_document_json(), or from_text()"
|
|
915
|
+
)
|
|
916
|
+
self._raw = _raw
|
|
917
|
+
|
|
918
|
+
@classmethod
|
|
919
|
+
def from_json(cls, data: BytesInput) -> RecurrenceRule:
|
|
920
|
+
"""Decode and validate a rule from a JSON rule object (`bytes` or `str`)."""
|
|
921
|
+
raw_bytes = _bytes_input(data, "data")
|
|
922
|
+
try:
|
|
923
|
+
return cls(_native.RawRecurrenceRule.from_json(raw_bytes), _internal=True)
|
|
924
|
+
except _native.RawRecurrenceRefusal as exc:
|
|
925
|
+
raise RecurrenceRefusal(*exc.args) from None
|
|
926
|
+
|
|
927
|
+
@classmethod
|
|
928
|
+
def from_document_json(cls, data: BytesInput) -> RecurrenceRule:
|
|
929
|
+
"""Decode and validate a rule from a capability-enveloped JSON document."""
|
|
930
|
+
raw_bytes = _bytes_input(data, "data")
|
|
931
|
+
try:
|
|
932
|
+
return cls(
|
|
933
|
+
_native.RawRecurrenceRule.from_document_json(raw_bytes), _internal=True
|
|
934
|
+
)
|
|
935
|
+
except _native.RawRecurrenceRefusal as exc:
|
|
936
|
+
raise RecurrenceRefusal(*exc.args) from None
|
|
937
|
+
|
|
938
|
+
@classmethod
|
|
939
|
+
def from_text(cls, lines: Sequence[str]) -> RecurrenceRule:
|
|
940
|
+
"""Decode and validate a rule from RFC 5545 content lines."""
|
|
941
|
+
if isinstance(lines, (str, bytes, bytearray)) or not isinstance(
|
|
942
|
+
lines, Sequence
|
|
943
|
+
):
|
|
944
|
+
raise TypeError(
|
|
945
|
+
"lines must be a sequence of strings, not a single str/bytes"
|
|
946
|
+
)
|
|
947
|
+
line_list = list(lines)
|
|
948
|
+
for idx, line in enumerate(line_list):
|
|
949
|
+
if not isinstance(line, str):
|
|
950
|
+
raise TypeError(
|
|
951
|
+
f"lines[{idx}] must be a str, not {type(line).__name__}"
|
|
952
|
+
)
|
|
953
|
+
try:
|
|
954
|
+
return cls(_native.RawRecurrenceRule.from_text(line_list), _internal=True)
|
|
955
|
+
except _native.RawRecurrenceRefusal as exc:
|
|
956
|
+
raise RecurrenceRefusal(*exc.args) from None
|
|
957
|
+
|
|
958
|
+
@property
|
|
959
|
+
def dtstart(self) -> str:
|
|
960
|
+
"""Local civil start timestamp (`YYYY-MM-DDTHH:MM:SS`)."""
|
|
961
|
+
return str(self._raw.dtstart())
|
|
962
|
+
|
|
963
|
+
@property
|
|
964
|
+
def tzid(self) -> str:
|
|
965
|
+
"""IANA time-zone identifier from the compiled tzdb bundle."""
|
|
966
|
+
return str(self._raw.tzid())
|
|
967
|
+
|
|
968
|
+
@property
|
|
969
|
+
def freq(self) -> str:
|
|
970
|
+
"""Normalized frequency (`MINUTELY`, `HOURLY`, `DAILY`, `WEEKLY`, `MONTHLY`, `YEARLY`)."""
|
|
971
|
+
return str(self._raw.freq())
|
|
972
|
+
|
|
973
|
+
def to_canonical_json(self) -> bytes:
|
|
974
|
+
"""Return RFC 8785 (JCS) canonical UTF-8 bytes of the normalized rule."""
|
|
975
|
+
out: bytes = self._raw.to_canonical_json()
|
|
976
|
+
return out
|
|
977
|
+
|
|
978
|
+
def digest(self) -> str:
|
|
979
|
+
"""Return `sha256:<hex>` of `to_canonical_json()`."""
|
|
980
|
+
return str(self._raw.digest())
|
|
981
|
+
|
|
982
|
+
def to_text(self) -> list[str]:
|
|
983
|
+
"""Return canonical RFC 5545 content lines."""
|
|
984
|
+
return list(self._raw.to_text())
|
|
985
|
+
|
|
986
|
+
def expand(self, from_utc: str, to_utc: str, limit: int) -> list[str]:
|
|
987
|
+
"""Expand occurrences in the half-open UTC range `[from_utc, to_utc)` up to `limit`."""
|
|
988
|
+
if isinstance(limit, bool) or not isinstance(limit, int):
|
|
989
|
+
raise TypeError(f"limit must be an int, not {type(limit).__name__}")
|
|
990
|
+
try:
|
|
991
|
+
return list(self._raw.expand(from_utc, to_utc, limit))
|
|
992
|
+
except _native.RawRecurrenceQueryError as exc:
|
|
993
|
+
raise RecurrenceQueryError(*exc.args) from None
|
|
994
|
+
|
|
995
|
+
def next_after(self, after_utc: str) -> str | None:
|
|
996
|
+
"""Return the earliest occurrence strictly after `after_utc`, or `None` if exhausted."""
|
|
997
|
+
try:
|
|
998
|
+
res: str | None = self._raw.next_after(after_utc)
|
|
999
|
+
return res
|
|
1000
|
+
except _native.RawRecurrenceQueryError as exc:
|
|
1001
|
+
raise RecurrenceQueryError(*exc.args) from None
|
|
1002
|
+
|
|
1003
|
+
def __eq__(self, other: object) -> bool:
|
|
1004
|
+
if not isinstance(other, RecurrenceRule):
|
|
1005
|
+
return NotImplemented
|
|
1006
|
+
return self.to_canonical_json() == other.to_canonical_json()
|
|
1007
|
+
|
|
1008
|
+
def __hash__(self) -> int:
|
|
1009
|
+
return hash(self.to_canonical_json())
|
|
1010
|
+
|
|
1011
|
+
def __repr__(self) -> str:
|
|
1012
|
+
return f"RecurrenceRule(dtstart={self.dtstart!r}, tzid={self.tzid!r}, freq={self.freq!r})"
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
def tzdb_version() -> str:
|
|
1016
|
+
"""Return the IANA tzdb version compiled into `sysprims-recurrence`."""
|
|
1017
|
+
return str(_native.tzdb_version())
|