perception-sdk 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.
@@ -0,0 +1,816 @@
1
+ """`Client`: what a tenant does with one of its API keys."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ import mimetypes
8
+ import os
9
+ import re
10
+ from collections.abc import Callable
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ import httpx
16
+
17
+ from ._http import HTTP, seg
18
+ from .errors import ConfigurationError, UploadError
19
+ from .models import ApiKey, IssuedApiKey, KeyList, Source, WhoAmI
20
+
21
+ if TYPE_CHECKING: # typing.Self is 3.11+; the import is never made at runtime
22
+ from typing_extensions import Self
23
+
24
+
25
+ # 5 MiB: the smallest part S3 accepts for any part but the last.
26
+ PART_SIZE = 5 * 1024 * 1024
27
+ # S3 numbers parts 1..10000, so a file bigger than 10000 parts gets bigger parts.
28
+ MAX_PARTS = 10_000
29
+ # Part URLs are asked for a few at a time, just before they are used, so none expires waiting.
30
+ URL_BATCH = 16
31
+
32
+ ProgressCallback = Callable[[int, int], None]
33
+
34
+
35
+ def _setting(value: str | None, env: str, what: str) -> str:
36
+ value = value or os.environ.get(env)
37
+ if not value:
38
+ raise ConfigurationError(f"no {what}: pass it to the client or set {env}")
39
+ return value
40
+
41
+
42
+ def _when(value: datetime | str | None) -> str | None:
43
+ if isinstance(value, datetime):
44
+ return value.isoformat()
45
+ return value
46
+
47
+
48
+ def _body(**fields: Any) -> dict[str, Any]:
49
+ """A request body with the fields the caller left out omitted, so the API's defaults apply."""
50
+ return {k: v for k, v in fields.items() if v is not None}
51
+
52
+
53
+ class Client:
54
+ """A client for one tenant, authenticated with one of its API keys.
55
+
56
+ `base_url` and `api_key` fall back to the ``PERCEPTION_API_URL`` and ``PERCEPTION_API_KEY``
57
+ environment variables. `transport` carries the requests to the API and `blob_transport` the
58
+ upload parts sent to the blob store's pre-signed URLs; both default to httpx's own. Use it as a
59
+ context manager, or call `close()`, to release its connections."""
60
+
61
+ def __init__(
62
+ self,
63
+ base_url: str | None = None,
64
+ api_key: str | None = None,
65
+ *,
66
+ timeout: float = 30.0,
67
+ transport: httpx.BaseTransport | None = None,
68
+ blob_transport: httpx.BaseTransport | None = None,
69
+ ) -> None:
70
+ url = _setting(base_url, "PERCEPTION_API_URL", "API URL")
71
+ key = _setting(api_key, "PERCEPTION_API_KEY", "API key")
72
+ self.timeout = timeout
73
+ self._http = HTTP(
74
+ url, key, timeout=timeout, transport=transport, blob_transport=blob_transport
75
+ )
76
+ self.keys = Keys(self._http)
77
+ self.sources = Sources(self._http)
78
+ self.sessions = Sessions(self._http)
79
+ self.live_streams = LiveStreams(self._http)
80
+ self.outputs = Outputs(self._http)
81
+ self.projects = Projects(self._http)
82
+ self.threads = Threads(self._http)
83
+ self.workflows = Workflows(self._http)
84
+ self.jobs = Jobs(self._http)
85
+ self.connectors = Connectors(self._http)
86
+
87
+ @property
88
+ def base_url(self) -> str:
89
+ return self._http.base_url
90
+
91
+ def __repr__(self) -> str:
92
+ return f"Client(base_url={self.base_url!r})"
93
+
94
+ def __enter__(self) -> Self:
95
+ return self
96
+
97
+ def __exit__(self, *exc: object) -> None:
98
+ self.close()
99
+
100
+ def close(self) -> None:
101
+ self._http.close()
102
+
103
+ def whoami(self) -> WhoAmI:
104
+ """The tenant and key this client authenticates as."""
105
+ return WhoAmI.from_dict(self._http.get("/whoami"))
106
+
107
+ def catalogue(self) -> dict[str, Any]:
108
+ """Every pipeline node in order, with its defaults, its editable prompts and the models it
109
+ may use on this server: what a workflow version's `config` is written against."""
110
+ return self._http.get("/pipeline/catalogue")
111
+
112
+ def query(self, subject_id: str, body: dict[str, Any]) -> dict[str, Any]:
113
+ """Ask a question about a subject. `body` is the API's query request, passed as is."""
114
+ return self._http.post(f"/subjects/{seg(subject_id)}/query", body)
115
+
116
+ def perceive_sync(
117
+ self,
118
+ subject_id: str,
119
+ stream_id: str,
120
+ source_id: str,
121
+ *,
122
+ deadline_s: int | None = None,
123
+ window_us: int | None = None,
124
+ overlap_us: int | None = None,
125
+ ) -> dict[str, Any]:
126
+ """Perceive a short, already uploaded source within this request. The API answers 200
127
+ when it finished and 206 with ``"incomplete": true`` when the deadline came first; both
128
+ come back as the dict. The request waits up to the deadline (the API's default is 120 s)
129
+ plus a margin, whatever the client's own timeout."""
130
+ wait = max(self.timeout, (deadline_s or 120) + 30)
131
+ body = _body(
132
+ stream_id=stream_id,
133
+ source_id=source_id,
134
+ deadline_s=deadline_s,
135
+ window_us=window_us,
136
+ overlap_us=overlap_us,
137
+ )
138
+ return self._http.post(f"/subjects/{seg(subject_id)}/perceive:sync", body, timeout=wait)
139
+
140
+
141
+ class Keys:
142
+ """The caller's own tenant's API keys."""
143
+
144
+ def __init__(self, http: HTTP) -> None:
145
+ self._http = http
146
+
147
+ def list(self) -> KeyList:
148
+ """The tenant's keys, newest first, revoked and expired ones included. At most 200 come
149
+ back; `.truncated` says whether there are more."""
150
+ return KeyList.from_dict(self._http.get("/api-keys"))
151
+
152
+ def create(self, name: str, expires_at: datetime | str | None = None) -> IssuedApiKey:
153
+ """Issue a key named `name` (1 to 200 characters). `expires_at` must be in the future and
154
+ carry a time zone; without it the key never expires. Its secret, `.api_key`, is returned
155
+ this once and never again."""
156
+ body = _body(name=name, expires_at=_when(expires_at))
157
+ return IssuedApiKey.from_dict(self._http.post("/api-keys", body))
158
+
159
+ def revoke(self, key_id: str) -> ApiKey:
160
+ """Revoke a key; it stays in the list with its `revoked_at`. Revoking the key this client
161
+ authenticates with is refused (`ConflictError`): revoke it with another key."""
162
+ return ApiKey.from_dict(self._http.post(f"/api-keys/{seg(key_id)}:revoke"))
163
+
164
+ def delete(self, key_id: str) -> None:
165
+ """`DELETE /api-keys/{key_id}`: the same as `revoke`, answering nothing. The key's record
166
+ stays, so the list can say when it stopped working."""
167
+ self._http.delete(f"/api-keys/{seg(key_id)}")
168
+
169
+ def rotate(self, key_id: str, expires_at: datetime | str | None = None) -> IssuedApiKey:
170
+ """Revoke a key and issue its replacement, under the same name, in one step. The key this
171
+ client authenticates with may be rotated; after that this client's key no longer works
172
+ and the answer's `.api_key` is the one to use. Without `expires_at` the new key never
173
+ expires, even if the old key had an expiry."""
174
+ body = _body(expires_at=_when(expires_at))
175
+ return IssuedApiKey.from_dict(
176
+ self._http.post(f"/api-keys/{seg(key_id)}:rotate", body or None)
177
+ )
178
+
179
+
180
+ class Sources:
181
+ """Media: register it, upload it, start processing it."""
182
+
183
+ def __init__(self, http: HTTP) -> None:
184
+ self._http = http
185
+
186
+ def _path(self, subject_id: str, stream_id: str, source_id: str) -> str:
187
+ return f"/subjects/{seg(subject_id)}/streams/{seg(stream_id)}/sources/{seg(source_id)}"
188
+
189
+ def register(
190
+ self,
191
+ subject_id: str,
192
+ stream_id: str,
193
+ client_ref: str,
194
+ media_type: str,
195
+ content_type: str,
196
+ *,
197
+ session_id: str | None = None,
198
+ roster_override: list[dict[str, Any]] | None = None,
199
+ stream_offset_us: int = 0,
200
+ ) -> Source:
201
+ """Register a source. Registration is idempotent on (stream_id, client_ref): the same
202
+ pair returns the source already registered, uploaded or not."""
203
+ body = _body(
204
+ stream_id=stream_id,
205
+ client_ref=client_ref,
206
+ media_type=media_type,
207
+ content_type=content_type,
208
+ session_id=session_id,
209
+ roster_override=roster_override,
210
+ stream_offset_us=stream_offset_us,
211
+ )
212
+ return Source.from_dict(self._http.post(f"/subjects/{seg(subject_id)}/sources", body))
213
+
214
+ def get(self, subject_id: str, stream_id: str, source_id: str) -> Source:
215
+ return Source.from_dict(self._http.get(self._path(subject_id, stream_id, source_id)))
216
+
217
+ def upload_parts(
218
+ self, subject_id: str, stream_id: str, source_id: str, part_numbers: list[int]
219
+ ) -> dict[str, Any]:
220
+ """Pre-signed PUT URLs for these part numbers: ``{"parts": [{part_number, url}]}``."""
221
+ path = self._path(subject_id, stream_id, source_id) + "/upload-parts"
222
+ return self._http.post(path, {"part_numbers": part_numbers})
223
+
224
+ def complete(
225
+ self, subject_id: str, stream_id: str, source_id: str, parts: list[dict[str, Any]]
226
+ ) -> Source:
227
+ """Finish an upload from its parts' ``{"part_number", "etag"}``, sent in part order."""
228
+ path = self._path(subject_id, stream_id, source_id) + "/complete"
229
+ ordered = sorted(parts, key=lambda p: p["part_number"])
230
+ return Source.from_dict(self._http.post(path, {"parts": ordered}))
231
+
232
+ def process(
233
+ self,
234
+ subject_id: str,
235
+ stream_id: str,
236
+ source_id: str,
237
+ *,
238
+ window_us: int | None = None,
239
+ overlap_us: int | None = None,
240
+ workflow: dict[str, Any] | None = None,
241
+ ) -> dict[str, Any]:
242
+ """Start processing an uploaded source. Answers with the workflow that runs it.
243
+ `workflow` names a workflow version, ``{"tenant_id", "workflow_id", "version"}``, to run it
244
+ under; without it the engine's defaults apply."""
245
+ path = self._path(subject_id, stream_id, source_id) + "/process"
246
+ body = _body(window_us=window_us, overlap_us=overlap_us, workflow=workflow)
247
+ return self._http.post(path, body or None)
248
+
249
+ def upload(
250
+ self,
251
+ subject_id: str,
252
+ path: str | os.PathLike[str],
253
+ *,
254
+ stream_id: str | None = None,
255
+ client_ref: str | None = None,
256
+ media_type: str | None = None,
257
+ content_type: str | None = None,
258
+ session_id: str | None = None,
259
+ roster_override: list[dict[str, Any]] | None = None,
260
+ stream_offset_us: int = 0,
261
+ part_size: int = PART_SIZE,
262
+ on_progress: ProgressCallback | None = None,
263
+ ) -> Source:
264
+ """Upload a file as a source: register it, PUT its parts straight to the blob store, and
265
+ complete it. The file is read one part at a time, never whole.
266
+
267
+ `content_type` is guessed from the file name and `media_type` from that (video, audio,
268
+ image, document or text); pass them when the guess is wrong or impossible. `client_ref`
269
+ defaults to the file name, and `stream_id` to the file's stem plus a digest of its
270
+ content, which costs one extra read of the file. Because registration is idempotent,
271
+ uploading the same file again returns the source already there.
272
+
273
+ A part that fails in a way that can pass is retried three times (after 0.5, 1 and 2 s)
274
+ before `UploadError` is raised. `on_progress(sent_bytes, total_bytes)` is called after each
275
+ part. Processing is not started: call `process()` for that."""
276
+ file = Path(path)
277
+ total = file.stat().st_size
278
+ if total == 0:
279
+ raise ValueError(f"{file} is empty")
280
+ if part_size < PART_SIZE:
281
+ raise ValueError(f"part_size must be at least {PART_SIZE} bytes (S3's minimum)")
282
+ content_type = content_type or mimetypes.guess_type(file.name)[0]
283
+ if content_type is None:
284
+ raise ValueError(f"cannot tell the content type of {file.name}: pass content_type")
285
+ media_type = media_type or _media_type_of(content_type)
286
+ if media_type is None:
287
+ raise ValueError(f"cannot tell the media type of {content_type}: pass media_type")
288
+ if stream_id is None:
289
+ stream_id = _stream_id(file)
290
+ source = self.register(
291
+ subject_id,
292
+ stream_id,
293
+ client_ref or _client_ref(file.name),
294
+ media_type,
295
+ content_type,
296
+ session_id=session_id,
297
+ roster_override=roster_override,
298
+ stream_offset_us=stream_offset_us,
299
+ )
300
+ if source.size_bytes is not None: # uploaded before
301
+ if on_progress is not None:
302
+ on_progress(total, total)
303
+ return source
304
+
305
+ part_size = max(part_size, math.ceil(total / MAX_PARTS))
306
+ count = math.ceil(total / part_size)
307
+ parts: list[dict[str, Any]] = []
308
+ sent = 0
309
+ with file.open("rb") as f:
310
+ for first in range(1, count + 1, URL_BATCH):
311
+ numbers = list(range(first, min(first + URL_BATCH, count + 1)))
312
+ answer = self.upload_parts(subject_id, stream_id, source.source_id, numbers)
313
+ urls = _urls_for(numbers, answer)
314
+ for number in numbers:
315
+ f.seek((number - 1) * part_size)
316
+ chunk = f.read(part_size)
317
+ etag = self._http.put_part(urls[number], chunk, number)
318
+ parts.append({"part_number": number, "etag": etag})
319
+ sent += len(chunk)
320
+ if on_progress is not None:
321
+ on_progress(sent, total)
322
+ return self.complete(subject_id, stream_id, source.source_id, parts)
323
+
324
+
325
+ def _urls_for(numbers: list[int], answer: Any) -> dict[int, str]:
326
+ """Each requested part's URL. An answer that is not ``{"parts": [{part_number, url}, ...]}``,
327
+ or names any other set of parts (short, extra, repeated or renumbered), is refused before a
328
+ byte is sent, so `complete` only ever gets exactly the parts that were asked for."""
329
+ parts = answer.get("parts") if isinstance(answer, dict) else None
330
+ if not isinstance(parts, list) or not all(
331
+ isinstance(p, dict)
332
+ and isinstance(p.get("part_number"), int)
333
+ and isinstance(p.get("url"), str)
334
+ for p in parts
335
+ ):
336
+ raise UploadError(
337
+ 0,
338
+ "malformed_answer",
339
+ "the API's answer for upload URLs was not a list of part numbers and URLs",
340
+ )
341
+ answered = sorted(p["part_number"] for p in parts)
342
+ if answered != numbers:
343
+ raise UploadError(
344
+ 0,
345
+ "part_mismatch",
346
+ f"asked for URLs for parts {numbers[0]}-{numbers[-1]}; the API answered for {answered}",
347
+ )
348
+ return {p["part_number"]: p["url"] for p in parts}
349
+
350
+
351
+ _UNSAFE_REF = re.compile(r"[^A-Za-z0-9_.:-]+")
352
+ _UNSAFE_ID = re.compile(r"[^A-Za-z0-9_-]+")
353
+
354
+
355
+ def _client_ref(name: str) -> str:
356
+ """The file name, made into a `client_ref` the API accepts (``[A-Za-z0-9_.:-]{1,256}``)."""
357
+ return _UNSAFE_REF.sub("-", name).strip("-")[:256] or "upload"
358
+
359
+
360
+ def _stream_id(file: Path) -> str:
361
+ """``<stem>-<12 hex of sha256>``, within the API's ``[A-Za-z0-9_-]{1,128}``. The same file
362
+ always lands on the same stream, so a repeated upload finds the source it made before; two
363
+ different files never share one."""
364
+ digest = hashlib.sha256()
365
+ with file.open("rb") as f:
366
+ for block in iter(lambda: f.read(1024 * 1024), b""):
367
+ digest.update(block)
368
+ stem = _UNSAFE_ID.sub("-", file.stem).strip("-")[:100] or "upload"
369
+ return f"{stem}-{digest.hexdigest()[:12]}"
370
+
371
+
372
+ def _media_type_of(content_type: str) -> str | None:
373
+ kind = content_type.lower()
374
+ for major in ("video", "audio", "image"):
375
+ if kind.startswith(major + "/"):
376
+ return major
377
+ if kind == "application/pdf" or "wordprocessingml" in kind:
378
+ return "document"
379
+ if kind.startswith("text/") or kind == "application/json":
380
+ return "text"
381
+ return None
382
+
383
+
384
+ class Sessions:
385
+ """Sessions: a span of time several streams were recorded in, with who was there."""
386
+
387
+ def __init__(self, http: HTTP) -> None:
388
+ self._http = http
389
+
390
+ def _path(self, subject_id: str, session_id: str) -> str:
391
+ return f"/subjects/{seg(subject_id)}/sessions/{seg(session_id)}"
392
+
393
+ def create(
394
+ self,
395
+ subject_id: str,
396
+ client_ref: str,
397
+ *,
398
+ gap_timeout_s: int | None = None,
399
+ attributes: dict[str, Any] | None = None,
400
+ streams: list[dict[str, Any]] | None = None,
401
+ roster: list[dict[str, Any]] | None = None,
402
+ ) -> dict[str, Any]:
403
+ """Open a session. Idempotent on `client_ref`: the same one returns the same session."""
404
+ body = _body(
405
+ client_ref=client_ref,
406
+ gap_timeout_s=gap_timeout_s,
407
+ attributes=attributes,
408
+ streams=streams,
409
+ roster=roster,
410
+ )
411
+ return self._http.post(f"/subjects/{seg(subject_id)}/sessions", body)
412
+
413
+ def get(self, subject_id: str, session_id: str) -> dict[str, Any]:
414
+ return self._http.get(self._path(subject_id, session_id))
415
+
416
+ def add_stream(
417
+ self,
418
+ subject_id: str,
419
+ session_id: str,
420
+ stream_id: str,
421
+ *,
422
+ device_id: str | None = None,
423
+ declared_offset_us: int | None = None,
424
+ clock_rate_ppm: int | None = None,
425
+ ) -> dict[str, Any]:
426
+ body = _body(
427
+ stream_id=stream_id,
428
+ device_id=device_id,
429
+ declared_offset_us=declared_offset_us,
430
+ clock_rate_ppm=clock_rate_ppm,
431
+ )
432
+ return self._http.post(self._path(subject_id, session_id) + "/streams", body)
433
+
434
+ def update_roster(
435
+ self, subject_id: str, session_id: str, entries: list[dict[str, Any]]
436
+ ) -> dict[str, Any]:
437
+ """Add or update roster entries; answers ``{"roster_entry_ids": [...]}``."""
438
+ return self._http.post(self._path(subject_id, session_id) + "/roster", {"entries": entries})
439
+
440
+ def close(self, subject_id: str, session_id: str) -> dict[str, Any]:
441
+ return self._http.post(self._path(subject_id, session_id) + ":close")
442
+
443
+
444
+ class LiveStreams:
445
+ """Live streams put on the media gateway."""
446
+
447
+ def __init__(self, http: HTTP) -> None:
448
+ self._http = http
449
+
450
+ def _path(self, subject_id: str, stream_id: str) -> str:
451
+ return f"/subjects/{seg(subject_id)}/live-streams/{seg(stream_id)}"
452
+
453
+ def open(
454
+ self,
455
+ subject_id: str,
456
+ stream_id: str,
457
+ mediamtx_path: str,
458
+ *,
459
+ media_type: str | None = None,
460
+ content_type: str | None = None,
461
+ session_id: str | None = None,
462
+ rotate_token: bool | None = None,
463
+ ) -> dict[str, Any]:
464
+ """Open a live stream. The answer's ``ingest_token`` is returned this once."""
465
+ body = _body(
466
+ stream_id=stream_id,
467
+ mediamtx_path=mediamtx_path,
468
+ media_type=media_type,
469
+ content_type=content_type,
470
+ session_id=session_id,
471
+ rotate_token=rotate_token,
472
+ )
473
+ return self._http.post(f"/subjects/{seg(subject_id)}/live-streams", body)
474
+
475
+ def get(self, subject_id: str, stream_id: str) -> dict[str, Any]:
476
+ return self._http.get(self._path(subject_id, stream_id))
477
+
478
+ def segments(
479
+ self, subject_id: str, stream_id: str, since_us: int | None = None
480
+ ) -> dict[str, Any]:
481
+ """The stream's segments in media order, and the gaps between them."""
482
+ return self._http.get(
483
+ self._path(subject_id, stream_id) + "/segments", params={"since_us": since_us}
484
+ )
485
+
486
+ def close(self, subject_id: str, stream_id: str) -> dict[str, Any]:
487
+ return self._http.post(self._path(subject_id, stream_id) + ":close")
488
+
489
+
490
+ class Outputs:
491
+ """What the engine produced for a subject, read in order."""
492
+
493
+ def __init__(self, http: HTTP) -> None:
494
+ self._http = http
495
+
496
+ def list(
497
+ self,
498
+ subject_id: str,
499
+ *,
500
+ after_sequence: int | None = None,
501
+ limit: int | None = None,
502
+ stream: str | None = None,
503
+ ) -> dict[str, Any]:
504
+ """``{"outputs": [...], "next_after_sequence": n}``; pass that back to read on."""
505
+ params = {"after_sequence": after_sequence, "limit": limit, "stream": stream}
506
+ return self._http.get(f"/subjects/{seg(subject_id)}/outputs", params=params)
507
+
508
+ def get(self, subject_id: str, output_id: str) -> dict[str, Any]:
509
+ """One output record, with a pre-signed ``url`` for its payload."""
510
+ return self._http.get(f"/subjects/{seg(subject_id)}/outputs/{seg(output_id)}")
511
+
512
+
513
+ # --- the console: projects, threads, workflows, jobs and connectors -----------------------------
514
+ # Each method is one route of the console API and returns its JSON answer as a dict. A list route
515
+ # answers with the list under its name and, where the API caps it, `truncated`.
516
+
517
+ _UNSET: Any = object()
518
+
519
+
520
+ def _project(project_id: str) -> str:
521
+ return f"/projects/{seg(project_id)}"
522
+
523
+
524
+ def _version_ref(workflow_id: str | None, version: int | None) -> dict[str, Any] | None:
525
+ if workflow_id is None and version is None:
526
+ return None
527
+ if workflow_id is None or version is None:
528
+ raise ValueError("name both workflow_id and version, or neither")
529
+ return {"workflow_id": workflow_id, "version": version}
530
+
531
+
532
+ class Projects:
533
+ """Projects: each holds threads, workflows, jobs and connectors."""
534
+
535
+ def __init__(self, http: HTTP) -> None:
536
+ self._http = http
537
+
538
+ def create(self, name: str) -> dict[str, Any]:
539
+ """A project, made with a workflow named "Default" at version 1."""
540
+ return self._http.post("/projects", {"name": name})
541
+
542
+ def list(self) -> dict[str, Any]:
543
+ """``{"projects": [...], "truncated": bool}``."""
544
+ return self._http.get("/projects")
545
+
546
+ def get(self, project_id: str) -> dict[str, Any]:
547
+ return self._http.get(_project(project_id))
548
+
549
+ def update(
550
+ self, project_id: str, *, name: str | None = None, destination: Any = _UNSET
551
+ ) -> dict[str, Any]:
552
+ """Rename the project, and choose where finished jobs go besides the download:
553
+ ``{"kind": "connector", "connector_id": ...}``, or None for the download only. Leave
554
+ `destination` out to keep the one it has."""
555
+ body = _body(name=name)
556
+ if destination is not _UNSET:
557
+ body["destination"] = destination
558
+ return self._http.patch(_project(project_id), body)
559
+
560
+
561
+ class Threads:
562
+ """Threads: a project's memory of one subject. A thread's `subject_id` is where its files are
563
+ uploaded (`client.sources.upload(thread["subject_id"], ...)`)."""
564
+
565
+ def __init__(self, http: HTTP) -> None:
566
+ self._http = http
567
+
568
+ def _path(self, project_id: str, thread_id: str) -> str:
569
+ return f"{_project(project_id)}/threads/{seg(thread_id)}"
570
+
571
+ def create(
572
+ self,
573
+ project_id: str,
574
+ name: str,
575
+ *,
576
+ workflow_id: str | None = None,
577
+ version: int | None = None,
578
+ ) -> dict[str, Any]:
579
+ """A thread and its subject. A workflow version, when named, seeds its assembly and People
580
+ settings."""
581
+ body = _body(name=name, workflow=_version_ref(workflow_id, version))
582
+ return self._http.post(f"{_project(project_id)}/threads", body)
583
+
584
+ def list(self, project_id: str) -> dict[str, Any]:
585
+ """``{"threads": [...], "truncated": bool}``."""
586
+ return self._http.get(f"{_project(project_id)}/threads")
587
+
588
+ def get(self, project_id: str, thread_id: str) -> dict[str, Any]:
589
+ return self._http.get(self._path(project_id, thread_id))
590
+
591
+ def rename(self, project_id: str, thread_id: str, name: str) -> dict[str, Any]:
592
+ return self._http.patch(self._path(project_id, thread_id), {"name": name})
593
+
594
+ def delete(self, project_id: str, thread_id: str) -> None:
595
+ """Remove a thread no job has read into (`ConflictError` otherwise)."""
596
+ self._http.delete(self._path(project_id, thread_id))
597
+
598
+ def reassemble(
599
+ self, project_id: str, thread_id: str, workflow_id: str, version: int
600
+ ) -> dict[str, Any]:
601
+ """Rebuild the thread under a workflow version's assembly and People settings."""
602
+ body = {"workflow_id": workflow_id, "version": version}
603
+ return self._http.post(self._path(project_id, thread_id) + ":reassemble", body)
604
+
605
+ def cancel_rebuild(self, project_id: str, thread_id: str) -> dict[str, Any]:
606
+ return self._http.post(self._path(project_id, thread_id) + ":cancel-rebuild")
607
+
608
+ def take_file(
609
+ self, project_id: str, thread_id: str, *, connector_id: str, key: str
610
+ ) -> dict[str, Any]:
611
+ """Copy one file from a source connector (S3 or a link) into the thread's subject;
612
+ answers ``{"source_id", "name"}`` once it is stored."""
613
+ body = {"connector_id": connector_id, "key": key}
614
+ return self._http.post(self._path(project_id, thread_id) + "/sources", body)
615
+
616
+
617
+ def _run_body(
618
+ source_ids: list[str], thread_id: str | None, request_id: str | None
619
+ ) -> dict[str, Any]:
620
+ return _body(source_ids=list(source_ids), thread_id=thread_id, request_id=request_id)
621
+
622
+
623
+ class Workflows:
624
+ """Workflows and their numbered versions. A version is never changed once saved."""
625
+
626
+ def __init__(self, http: HTTP) -> None:
627
+ self._http = http
628
+
629
+ def _path(self, project_id: str, workflow_id: str) -> str:
630
+ return f"{_project(project_id)}/workflows/{seg(workflow_id)}"
631
+
632
+ def create(self, project_id: str, name: str) -> dict[str, Any]:
633
+ """A workflow at version 1, running the engine's defaults."""
634
+ return self._http.post(f"{_project(project_id)}/workflows", {"name": name})
635
+
636
+ def list(self, project_id: str) -> dict[str, Any]:
637
+ """``{"workflows": [...], "truncated": bool}``."""
638
+ return self._http.get(f"{_project(project_id)}/workflows")
639
+
640
+ def get(self, project_id: str, workflow_id: str) -> dict[str, Any]:
641
+ return self._http.get(self._path(project_id, workflow_id))
642
+
643
+ def rename(self, project_id: str, workflow_id: str, name: str) -> dict[str, Any]:
644
+ return self._http.patch(self._path(project_id, workflow_id), {"name": name})
645
+
646
+ def save_version(
647
+ self,
648
+ project_id: str,
649
+ workflow_id: str,
650
+ config: dict[str, Any],
651
+ *,
652
+ note: str | None = None,
653
+ ) -> dict[str, Any]:
654
+ """Save the next version with this configuration (see `client.catalogue()`)."""
655
+ body = _body(config=config, note=note)
656
+ return self._http.post(self._path(project_id, workflow_id) + "/versions", body)
657
+
658
+ def list_versions(self, project_id: str, workflow_id: str) -> dict[str, Any]:
659
+ """``{"versions": [...], "truncated": bool}``, newest first."""
660
+ return self._http.get(self._path(project_id, workflow_id) + "/versions")
661
+
662
+ def get_version(self, project_id: str, workflow_id: str, version: int) -> dict[str, Any]:
663
+ return self._http.get(f"{self._path(project_id, workflow_id)}/versions/{seg(version)}")
664
+
665
+ def restore_version(self, project_id: str, workflow_id: str, version: int) -> dict[str, Any]:
666
+ """Save a new version with `version`'s configuration."""
667
+ path = f"{self._path(project_id, workflow_id)}/versions/{seg(version)}:restore"
668
+ return self._http.post(path)
669
+
670
+ def run(
671
+ self,
672
+ project_id: str,
673
+ workflow_id: str,
674
+ source_ids: list[str],
675
+ *,
676
+ thread_id: str | None = None,
677
+ version: int | None = None,
678
+ request_id: str | None = None,
679
+ ) -> dict[str, Any]:
680
+ """Start a job on this workflow, at `version` or else its latest. The sources must already
681
+ be uploaded into the thread's subject. A `request_id` (a UUID) makes sending the same
682
+ request again return the same job."""
683
+ body = _run_body(source_ids, thread_id, request_id)
684
+ body.update(_body(version=version))
685
+ return self._http.post(self._path(project_id, workflow_id) + ":run", body)
686
+
687
+
688
+ class Jobs:
689
+ """Jobs: a workflow version run over a thread's files."""
690
+
691
+ def __init__(self, http: HTTP) -> None:
692
+ self._http = http
693
+
694
+ def _path(self, project_id: str, job_id: str) -> str:
695
+ return f"{_project(project_id)}/jobs/{seg(job_id)}"
696
+
697
+ def create(
698
+ self,
699
+ project_id: str,
700
+ workflow_id: str,
701
+ version: int,
702
+ source_ids: list[str],
703
+ *,
704
+ thread_id: str | None = None,
705
+ request_id: str | None = None,
706
+ ) -> dict[str, Any]:
707
+ """Start a job pinned to a workflow version over files already uploaded into the thread's
708
+ subject. A `request_id` (a UUID) makes sending the same request again return the same
709
+ job."""
710
+ body = {"workflow_id": workflow_id, "version": version}
711
+ body.update(_run_body(source_ids, thread_id, request_id))
712
+ return self._http.post(f"{_project(project_id)}/jobs", body)
713
+
714
+ def list(
715
+ self,
716
+ project_id: str,
717
+ *,
718
+ thread: str | None = None,
719
+ after: str | None = None,
720
+ limit: int | None = None,
721
+ ) -> dict[str, Any]:
722
+ """``{"jobs": [...], "next_after": job_id | None}``, newest first; pass `next_after` back
723
+ as `after` for the next page."""
724
+ params = {"thread": thread, "after": after, "limit": limit}
725
+ return self._http.get(f"{_project(project_id)}/jobs", params=params)
726
+
727
+ def get(self, project_id: str, job_id: str) -> dict[str, Any]:
728
+ return self._http.get(self._path(project_id, job_id))
729
+
730
+ def status(self, project_id: str, job_id: str) -> dict[str, Any]:
731
+ """The job's state and, step by step, how far it has got, what it cost and any problem."""
732
+ return self._http.get(self._path(project_id, job_id) + "/status")
733
+
734
+ def retry_failure(self, project_id: str, job_id: str, dead_letter_id: str) -> dict[str, Any]:
735
+ """Send one failed part of the job, as its status names it, back to be tried again."""
736
+ path = f"{self._path(project_id, job_id)}/failures/{seg(dead_letter_id)}:retry"
737
+ return self._http.post(path)
738
+
739
+ def output(self, project_id: str, job_id: str) -> dict[str, Any]:
740
+ """A summary of the job's results and their first elements. `NotFoundError` until the
741
+ results are written."""
742
+ return self._http.get(self._path(project_id, job_id) + "/output")
743
+
744
+ def download_url(self, project_id: str, job_id: str) -> str:
745
+ """A short-lived link to the job's whole results file (`.json.gz`)."""
746
+ return self._http.location(self._path(project_id, job_id) + "/output:download")
747
+
748
+
749
+ class Connectors:
750
+ """A project's sources (S3, a link, live) and destinations (S3, a webhook, Postgres).
751
+
752
+ Secrets are sent once and never answered back; a webhook's signing secret is answered the
753
+ once it is made."""
754
+
755
+ def __init__(self, http: HTTP) -> None:
756
+ self._http = http
757
+
758
+ def _path(self, project_id: str, connector_id: str) -> str:
759
+ return f"{_project(project_id)}/connectors/{seg(connector_id)}"
760
+
761
+ def list(self, project_id: str) -> dict[str, Any]:
762
+ """``{"connectors": [...]}``, oldest first."""
763
+ return self._http.get(f"{_project(project_id)}/connectors")
764
+
765
+ def create(
766
+ self,
767
+ project_id: str,
768
+ name: str,
769
+ *,
770
+ role: str,
771
+ kind: str,
772
+ config: dict[str, str] | None = None,
773
+ secrets: dict[str, str] | None = None,
774
+ ) -> dict[str, Any]:
775
+ """`role` is ``"source"`` or ``"destination"``; `kind` is one the role allows."""
776
+ body = _body(name=name, role=role, kind=kind, config=config, secrets=secrets)
777
+ return self._http.post(f"{_project(project_id)}/connectors", body)
778
+
779
+ def get(self, project_id: str, connector_id: str) -> dict[str, Any]:
780
+ return self._http.get(self._path(project_id, connector_id))
781
+
782
+ def update(
783
+ self,
784
+ project_id: str,
785
+ connector_id: str,
786
+ *,
787
+ name: str | None = None,
788
+ config: dict[str, str] | None = None,
789
+ secrets: dict[str, str] | None = None,
790
+ new_signing_secret: bool | None = None,
791
+ ) -> dict[str, Any]:
792
+ """Change what is named and keep the rest."""
793
+ body = _body(
794
+ name=name, config=config, secrets=secrets, new_signing_secret=new_signing_secret
795
+ )
796
+ return self._http.patch(self._path(project_id, connector_id), body)
797
+
798
+ def delete(self, project_id: str, connector_id: str) -> None:
799
+ self._http.delete(self._path(project_id, connector_id))
800
+
801
+ def check(self, project_id: str, connector_id: str) -> dict[str, Any]:
802
+ """Try the saved settings: ``{"ok": bool, "message": str}``."""
803
+ return self._http.post(self._path(project_id, connector_id) + ":check")
804
+
805
+ def objects(
806
+ self,
807
+ project_id: str,
808
+ connector_id: str,
809
+ *,
810
+ prefix: str | None = None,
811
+ cursor: str | None = None,
812
+ limit: int | None = None,
813
+ ) -> dict[str, Any]:
814
+ """One page of an S3 source's files: ``{"objects", "truncated", "next_cursor"}``."""
815
+ params = {"prefix": prefix, "cursor": cursor, "limit": limit}
816
+ return self._http.get(self._path(project_id, connector_id) + "/objects", params=params)