tilo-sdk 0.5.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. tilo/__init__.py +67 -0
  2. tilo/_client.py +572 -0
  3. tilo/_errors.py +57 -0
  4. tilo/_native.pyi +82 -0
  5. tilo/_resource.py +462 -0
  6. tilo/_transport.py +317 -0
  7. tilo/_vault.py +257 -0
  8. tilo/py.typed +0 -0
  9. tilo/types/__init__.py +14 -0
  10. tilo/types/account.py +288 -0
  11. tilo/types/activity.py +98 -0
  12. tilo/types/api_tester.py +1015 -0
  13. tilo/types/api_v1.py +470 -0
  14. tilo/types/backups.py +721 -0
  15. tilo/types/board.py +224 -0
  16. tilo/types/browser.py +2304 -0
  17. tilo/types/calculator.py +259 -0
  18. tilo/types/calendar.py +1516 -0
  19. tilo/types/camera.py +1169 -0
  20. tilo/types/canvas.py +2645 -0
  21. tilo/types/chat.py +2008 -0
  22. tilo/types/chip_design.py +1512 -0
  23. tilo/types/clocks.py +462 -0
  24. tilo/types/code_editor.py +1699 -0
  25. tilo/types/console.py +307 -0
  26. tilo/types/contacts.py +751 -0
  27. tilo/types/containers.py +320 -0
  28. tilo/types/counter.py +135 -0
  29. tilo/types/db_client.py +1037 -0
  30. tilo/types/diffmerge.py +778 -0
  31. tilo/types/discord.py +799 -0
  32. tilo/types/discussion.py +273 -0
  33. tilo/types/disk_usage.py +380 -0
  34. tilo/types/disks.py +152 -0
  35. tilo/types/ebook.py +1124 -0
  36. tilo/types/feeds.py +796 -0
  37. tilo/types/file_explorer.py +1321 -0
  38. tilo/types/firewall.py +308 -0
  39. tilo/types/gallery.py +637 -0
  40. tilo/types/git_client.py +1237 -0
  41. tilo/types/hex_editor.py +1136 -0
  42. tilo/types/logs.py +267 -0
  43. tilo/types/mail.py +950 -0
  44. tilo/types/maps.py +1050 -0
  45. tilo/types/messages.py +1224 -0
  46. tilo/types/migrate.py +537 -0
  47. tilo/types/monitor.py +142 -0
  48. tilo/types/music.py +774 -0
  49. tilo/types/notes.py +689 -0
  50. tilo/types/onboarding.py +91 -0
  51. tilo/types/osk.py +502 -0
  52. tilo/types/passwords.py +674 -0
  53. tilo/types/pdf_viewer.py +1555 -0
  54. tilo/types/photos.py +1150 -0
  55. tilo/types/playback.py +657 -0
  56. tilo/types/poker.py +417 -0
  57. tilo/types/preview.py +1488 -0
  58. tilo/types/print_centre.py +714 -0
  59. tilo/types/publisher.py +291 -0
  60. tilo/types/remote.py +537 -0
  61. tilo/types/scratchpad.py +161 -0
  62. tilo/types/sections.py +2990 -0
  63. tilo/types/settings.py +299 -0
  64. tilo/types/sheets.py +1237 -0
  65. tilo/types/shell.py +1634 -0
  66. tilo/types/shortcuts.py +1463 -0
  67. tilo/types/slides.py +1109 -0
  68. tilo/types/snippets.py +356 -0
  69. tilo/types/speed_test.py +249 -0
  70. tilo/types/store.py +1326 -0
  71. tilo/types/tasks.py +1450 -0
  72. tilo/types/terminal.py +1545 -0
  73. tilo/types/today.py +108 -0
  74. tilo/types/totp.py +403 -0
  75. tilo/types/tube.py +1020 -0
  76. tilo/types/typst_editor.py +658 -0
  77. tilo/types/video.py +300 -0
  78. tilo/types/video_editor.py +2869 -0
  79. tilo/types/views.py +272 -0
  80. tilo/types/weather.py +583 -0
  81. tilo/types/windows.py +181 -0
  82. tilo/types/word_processor.py +813 -0
  83. tilo/types/workspace.py +1240 -0
  84. tilo_sdk-0.5.3.dist-info/METADATA +141 -0
  85. tilo_sdk-0.5.3.dist-info/RECORD +86 -0
  86. tilo_sdk-0.5.3.dist-info/WHEEL +4 -0
tilo/__init__.py ADDED
@@ -0,0 +1,67 @@
1
+ """Drive Tilo workspaces from Python.
2
+
3
+ ```python
4
+ from tilo import Tilo, run
5
+
6
+ async with Tilo() as tilo: # this computer's daemon
7
+ workspace = tilo.workspace() # the workspace it serves
8
+ page = await workspace.resource("notes/Todo").load()
9
+ page.title = "Done" # a field edit
10
+ await page.flush()
11
+ await run(workspace, {"path": "notes", "action": "new-note"}, {"title": "Next"})
12
+ ```
13
+
14
+ `Tilo` and `Workspace` are the API's operations, written from its description by `tilo sdk
15
+ gen`: `workspace.list_resources`, `workspace.run_action`, `workspace.events`,
16
+ `workspace.put_content`, … Each goes through this computer's daemon (the `tilo._native`
17
+ extension), which answers `/v1` as whoever connected, or by URL with a key
18
+ (`Tilo(key=...)`).
19
+ """
20
+
21
+ # The SDK's version, which its transports name themselves with: set before they are imported.
22
+ __version__ = "0.1.0"
23
+
24
+ from ._errors import Refused
25
+ from ._resource import Entry, FieldMap, Resource, exported, made, resource_proxy, rows
26
+ from ._client import InvocationGroup, Tilo, Workspace, run
27
+ from ._transport import (
28
+ CallAsk,
29
+ CallFrame,
30
+ Daemon,
31
+ DaemonConnection,
32
+ DEFAULT_URL,
33
+ NATIVE_MODULE,
34
+ Send,
35
+ VERSION,
36
+ )
37
+ from ._vault import CallLane, Vault
38
+
39
+ # The same client, under the name its async interface was first written with.
40
+ AsyncTilo = Tilo
41
+
42
+ __all__ = [
43
+ "AsyncTilo",
44
+ "CallAsk",
45
+ "CallFrame",
46
+ "CallLane",
47
+ "Daemon",
48
+ "DaemonConnection",
49
+ "DEFAULT_URL",
50
+ "Entry",
51
+ "exported",
52
+ "FieldMap",
53
+ "InvocationGroup",
54
+ "made",
55
+ "NATIVE_MODULE",
56
+ "Refused",
57
+ "Resource",
58
+ "resource_proxy",
59
+ "rows",
60
+ "run",
61
+ "Send",
62
+ "Tilo",
63
+ "Vault",
64
+ "VERSION",
65
+ "Workspace",
66
+ "__version__",
67
+ ]
tilo/_client.py ADDED
@@ -0,0 +1,572 @@
1
+ """The client: Tilo's API, `/v1`, as the generated operations describe it, carried by this
2
+ computer's daemon or by a key.
3
+
4
+ What is written here is how a request goes out and comes back, what names an invocation group,
5
+ and the two things an operation alone does not do: following an action to its end, and putting
6
+ a file up in pieces.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import contextvars
13
+ import json
14
+ import re
15
+ import uuid
16
+ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
17
+ from typing import Any
18
+ from urllib.parse import quote, urlencode
19
+
20
+ import blake3
21
+
22
+ from ._errors import Refused, refusal_of
23
+ from ._resource import Resource, resource_proxy
24
+ from ._transport import (
25
+ Daemon,
26
+ DaemonConnection,
27
+ KeySend,
28
+ Reply,
29
+ Send,
30
+ url_from,
31
+ key_from,
32
+ )
33
+ from .types.api_v1 import AccountOperations, ActionAnswer, Operation, OPERATIONS, WorkspaceOperations
34
+ from ._vault import CallLane, Vault
35
+
36
+ #: How long a request keeps asking again while the API is briefly unavailable, in seconds.
37
+ RETRY_DEADLINE = 60.0
38
+ #: The most one request of an upload carries; a larger file goes up in pieces.
39
+ PIECE = 16 * 1024 * 1024
40
+ _UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I)
41
+
42
+ _current_group: contextvars.ContextVar[InvocationGroup | None] = contextvars.ContextVar(
43
+ "tilo_invocation_group", default=None
44
+ )
45
+
46
+
47
+ def current_group() -> InvocationGroup | None:
48
+ """The invocation group the current call is made in, when one is open."""
49
+ return _current_group.get()
50
+
51
+
52
+ class InvocationGroup:
53
+ """An invocation group: every request made inside `ws.invocation(title)` names it in
54
+ `Tilo-Invocation` and `Tilo-Invocation-Title`, so the apps record one undo step and History
55
+ shows the title.
56
+
57
+ `links` are the records its calls changed, each once; `link` is the one when they changed
58
+ one.
59
+ """
60
+
61
+ def __init__(self, workspace: Workspace, title: str, id: str) -> None:
62
+ self.workspace = workspace
63
+ """The workspace its calls are in."""
64
+ self.title = title
65
+ """What History calls it."""
66
+ self.id = id
67
+ """What every request of the group names it by."""
68
+ self.invocations: list[str] = []
69
+ """The invocations its calls answered, in order."""
70
+ self.links: list[str] = []
71
+ """The links to the records its calls changed, each once."""
72
+
73
+ @property
74
+ def link(self) -> str | None:
75
+ """The link to the one record its calls changed, or `None`."""
76
+ return self.links[0] if len(self.links) == 1 else None
77
+
78
+ async def undo(self) -> ActionAnswer:
79
+ """Take back what its calls changed, in every record."""
80
+ if not self.invocations:
81
+ raise Refused(
82
+ {"code": "not_found", "message": "the invocation group made no call to take back"}
83
+ )
84
+ return await self.workspace.undo_invocation(invocation=self.invocations[-1])
85
+
86
+ def note(self, answer: Any) -> None:
87
+ """What one of its calls answered."""
88
+ said = answer if isinstance(answer, Mapping) else {}
89
+ invocation = said.get("invocation")
90
+ if isinstance(invocation, str) and invocation not in self.invocations:
91
+ self.invocations.append(invocation)
92
+ for link in [said.get("link"), *(said.get("links") or [])]:
93
+ if isinstance(link, str) and link and link not in self.links:
94
+ self.links.append(link)
95
+
96
+
97
+ class _InvocationOpening:
98
+ """`ws.invocation(title)`: `async with` groups every call inside into one undo step."""
99
+
100
+ def __init__(self, workspace: Workspace, title: str) -> None:
101
+ self.workspace = workspace
102
+ self.title = title
103
+ self.group: InvocationGroup | None = None
104
+ self._token: contextvars.Token[InvocationGroup | None] | None = None
105
+
106
+ async def __aenter__(self) -> InvocationGroup:
107
+ slug = re.sub(r"[^a-z0-9]+", "-", self.title.lower()).strip("-")[:40]
108
+ self.group = InvocationGroup(
109
+ self.workspace,
110
+ self.title,
111
+ f"sdk:{slug or 'invocation'}:{uuid.uuid4().hex[:8]}",
112
+ )
113
+ self._token = _current_group.set(self.group)
114
+ return self.group
115
+
116
+ async def __aexit__(self, *_: Any) -> None:
117
+ if self._token is not None:
118
+ _current_group.reset(self._token)
119
+ self._token = None
120
+
121
+
122
+ def _address(path: str, params: Mapping[str, Any], query: Sequence[str]) -> str:
123
+ """`path` with `params` in its braces, each segment percent-encoded, and its query."""
124
+
125
+ def fill(match: re.Match[str]) -> str:
126
+ name = match.group(1)
127
+ value = params.get(name)
128
+ if value is None:
129
+ raise TypeError(f"{path} names {{{name}}}, and the call gave none")
130
+ return "/".join(quote(part, safe="") for part in str(value).split("/"))
131
+
132
+ path = re.sub(r"\{(\w+)\}", fill, path)
133
+ said = urlencode([(name, params[name]) for name in query if params.get(name) is not None])
134
+ return path if said == "" else f"{path}?{said}"
135
+
136
+
137
+ async def _all(reply: Reply) -> bytes:
138
+ """Every piece of `reply`'s body."""
139
+ pieces: list[bytes] = []
140
+ while True:
141
+ piece = await reply.next()
142
+ if piece is None:
143
+ return b"".join(pieces)
144
+ pieces.append(piece)
145
+
146
+
147
+ async def _answer_of(reply: Reply, operation: Operation) -> Any:
148
+ """What a successful answer carries, as `operation` answers it."""
149
+ if operation.answer == "bytes":
150
+ return await _all(reply)
151
+ text = (await _all(reply)).decode("utf-8", "replace")
152
+ return json.loads(text) if text.strip() else {}
153
+
154
+
155
+ def _retry_after_ms(reply: Reply) -> int:
156
+ for name, value in reply.headers:
157
+ if name.lower() == "retry-after":
158
+ try:
159
+ return int(float(value) * 1000)
160
+ except ValueError:
161
+ return 0
162
+ return 0
163
+
164
+
165
+ async def _refusal_of_reply(reply: Reply) -> tuple[Refused, int]:
166
+ """The refusal an answer that is not a success is: its body's, else its status."""
167
+ text = (await _all(reply)).decode("utf-8", "replace")
168
+ try:
169
+ body = json.loads(text)
170
+ except ValueError:
171
+ body = None
172
+ if isinstance(body, Mapping) and body.get("error") is not None:
173
+ return refusal_of(body, reply.status), _retry_after_ms(reply)
174
+ return (
175
+ Refused(
176
+ {
177
+ "code": "unavailable" if reply.status == 503 else "failed",
178
+ "message": f"the API answered {reply.status}: {text[:200]}",
179
+ },
180
+ reply.status,
181
+ ),
182
+ _retry_after_ms(reply),
183
+ )
184
+
185
+
186
+ def _event_of(frame: str, workspace: str) -> dict[str, Any] | None:
187
+ """One server-sent event's frame; `None` for a comment that keeps the stream alive."""
188
+ id = ""
189
+ type = "message"
190
+ data: list[str] = []
191
+ for line in re.split(r"\r?\n", frame):
192
+ if line == "" or line.startswith(":"):
193
+ continue
194
+ at = line.find(":")
195
+ field = line if at < 0 else line[:at]
196
+ value = "" if at < 0 else line[at + 1 :].removeprefix(" ")
197
+ if field == "id":
198
+ id = value
199
+ elif field == "event":
200
+ type = value
201
+ elif field == "data":
202
+ data.append(value)
203
+ if not data:
204
+ return None
205
+ parsed = json.loads("\n".join(data))
206
+ if type == "error":
207
+ raise refusal_of(parsed)
208
+ return {"id": id, "type": type, "workspace": workspace, "data": parsed}
209
+
210
+
211
+ def stream_of(
212
+ open_reply: Callable[[], Awaitable[tuple[Reply, str]]],
213
+ ) -> AsyncIterator[dict[str, Any]]:
214
+ """The server-sent events of a request `open_reply` makes, each the event's `id`, `type`,
215
+ `workspace` and `data`. An `error` event raises its refusal. Ending the iterator closes the
216
+ stream at once, even while it waits on a quiet one."""
217
+
218
+ async def events() -> AsyncIterator[dict[str, Any]]:
219
+ reply: Reply | None = None
220
+ buffer = b""
221
+ try:
222
+ reply, workspace = await open_reply()
223
+ while True:
224
+ piece = await reply.next()
225
+ if piece is None:
226
+ return
227
+ buffer += piece
228
+ while b"\n\n" in buffer:
229
+ frame, buffer = buffer.split(b"\n\n", 1)
230
+ event = _event_of(frame.decode("utf-8", "replace"), workspace)
231
+ if event is not None:
232
+ yield event
233
+ finally:
234
+ close = getattr(reply, "aclose", None) if reply is not None else None
235
+ if close is not None:
236
+ await close()
237
+
238
+ return events()
239
+
240
+
241
+ class Tilo(AccountOperations):
242
+ """The account, and where every request goes.
243
+
244
+ `Tilo()` reaches this computer's daemon through the `tilo._native` extension, which answers
245
+ `/v1` in process as whoever connected; `Tilo(key=...)` reaches `/v1` by URL. Its methods are
246
+ the API's account operations; `workspace(...)` names one workspace.
247
+ """
248
+
249
+ def __init__(
250
+ self,
251
+ key: str | None = None,
252
+ url: str | None = None,
253
+ *,
254
+ socket: str | None = None,
255
+ workspace: str | None = None,
256
+ daemon: DaemonConnection | None = None,
257
+ http: Any = None,
258
+ send: Send | None = None,
259
+ retry_deadline: float = RETRY_DEADLINE,
260
+ ) -> None:
261
+ """Where the requests go.
262
+
263
+ `daemon` is a connection of your own; `send` makes requests itself. Else a key (`key`, or
264
+ `TILO_API_KEY`) reaches the API server at `url` (`TILO_API_URL`, `https://api.tilo.sh`)
265
+ over HTTPS. Else the client reaches this computer's daemon through the `tilo._native`
266
+ extension, connecting as whoever runs this program: `socket` names the daemon's endpoint
267
+ when it is not the one this computer's login keeps, and `workspace` the one workspace the
268
+ connection acts in when the launcher said nothing.
269
+
270
+ `retry_deadline` is how long, in seconds, a request keeps asking again while the API is
271
+ briefly unavailable (60 by default; 0 raises its refusal at once).
272
+ """
273
+ self.retry_deadline = retry_deadline
274
+ named = key_from(key)
275
+ if daemon is not None:
276
+
277
+ async def opened() -> DaemonConnection:
278
+ return daemon
279
+
280
+ self.daemon: Daemon | None = Daemon(opened)
281
+ elif named is None:
282
+ self.daemon = Daemon.native(socket, workspace)
283
+ else:
284
+ self.daemon = None
285
+ self._keysend: KeySend | None = None
286
+ if send is not None:
287
+ self._send_request = send
288
+ elif self.daemon is not None:
289
+ self._send_request = self.daemon.send
290
+ else:
291
+ self._keysend = KeySend(url_from(url), named or "", http)
292
+ self._send_request = self._keysend
293
+
294
+ def workspace(self, ref: str | None = None) -> Workspace:
295
+ """One workspace, by its id or its name; with none, the one the daemon's connection
296
+ acts in."""
297
+ return Workspace(self, ref)
298
+
299
+ async def aclose(self) -> None:
300
+ """End the requests of a key's client still open."""
301
+ if self._keysend is not None:
302
+ await self._keysend.aclose()
303
+
304
+ async def __aenter__(self) -> Tilo:
305
+ return self
306
+
307
+ async def __aexit__(self, *_: Any) -> None:
308
+ await self.aclose()
309
+
310
+ async def _send(
311
+ self,
312
+ operation: Operation,
313
+ params: Mapping[str, Any],
314
+ body: Any,
315
+ headers: Mapping[str, str],
316
+ ) -> Any:
317
+ return await _answer_of(await self._request(operation, params, body, headers), operation)
318
+
319
+ def _stream(
320
+ self,
321
+ operation: Operation,
322
+ params: Mapping[str, Any],
323
+ body: Any,
324
+ headers: Mapping[str, str],
325
+ ) -> AsyncIterator[dict[str, Any]]:
326
+ async def open_reply() -> tuple[Reply, str]:
327
+ return await self._request(operation, params, body, headers), ""
328
+
329
+ return stream_of(open_reply)
330
+
331
+ async def _request(
332
+ self,
333
+ operation: Operation,
334
+ params: Mapping[str, Any],
335
+ body: Any,
336
+ headers: Mapping[str, str],
337
+ ) -> Reply:
338
+ """One request for `operation`: its answer, or the refusal it raises.
339
+
340
+ A request names the invocation group it is made in, and a mutating one an
341
+ `Idempotency-Key`, so asking again while the API is briefly unavailable runs it once.
342
+ """
343
+ sent: dict[str, str] = {
344
+ "accept": {"json": "application/json", "events": "text/event-stream", "bytes": "*/*"}[
345
+ operation.answer
346
+ ]
347
+ }
348
+ group = current_group()
349
+ if group is not None:
350
+ sent["tilo-invocation"] = group.id
351
+ sent["tilo-invocation-title"] = group.title
352
+ if operation.mutating:
353
+ sent["idempotency-key"] = str(uuid.uuid4())
354
+ content: bytes | None = None
355
+ if operation.body == "json":
356
+ content = json.dumps(body if body is not None else {}).encode()
357
+ sent["content-type"] = "application/json"
358
+ elif operation.body == "bytes":
359
+ content = bytes(body)
360
+ sent["content-type"] = "application/octet-stream"
361
+ for name, value in headers.items():
362
+ sent[name.lower()] = value
363
+ target = _address(operation.path, params, operation.query)
364
+ deadline = asyncio.get_running_loop().time() + self.retry_deadline
365
+ attempt = 0
366
+ while True:
367
+ reply = await self._send_request(operation.method, target, list(sent.items()), content)
368
+ if 200 <= reply.status < 300:
369
+ return reply
370
+ refusal, asked = await _refusal_of_reply(reply)
371
+ wait = max(
372
+ asked,
373
+ refusal.retry_after_ms or 0,
374
+ min(50 * 2**attempt, 2_000),
375
+ )
376
+ if (
377
+ reply.status != 503
378
+ or asyncio.get_running_loop().time() + wait / 1000 > deadline
379
+ ):
380
+ raise refusal
381
+ await asyncio.sleep(wait / 1000)
382
+ attempt += 1
383
+
384
+
385
+ class Workspace(WorkspaceOperations):
386
+ """One workspace, named by its id or its name; named by neither, the one the daemon's
387
+ connection acts in.
388
+
389
+ Its methods are the API's workspace operations, each naming this workspace.
390
+ """
391
+
392
+ def __init__(self, client: Tilo, ref: str | None = None) -> None:
393
+ self.client = client
394
+ """The client its requests go through."""
395
+ self.ref = ref
396
+ """What it was named by: an id, a name, or `None` for the daemon's own."""
397
+ self.vault = Vault(self)
398
+ """The person's vault, as this workspace's calls reach it."""
399
+ self.call_lane = CallLane(self)
400
+ """The call lane of an app's own connection."""
401
+ self._id: str | None = None
402
+ self._resolving: asyncio.Task[str] | None = None
403
+
404
+ async def id(self) -> str:
405
+ """Its id: the one it was named by, the daemon's own, or the one the account lists by
406
+ its name."""
407
+ if self._id is not None:
408
+ return self._id
409
+ if self._resolving is None:
410
+ self._resolving = asyncio.ensure_future(self._resolve())
411
+ try:
412
+ self._id = await self._resolving
413
+ except BaseException:
414
+ self._resolving = None
415
+ raise
416
+ return self._id
417
+
418
+ async def _resolve(self) -> str:
419
+ if self.ref is not None and _UUID.match(self.ref):
420
+ return self.ref
421
+ served = None
422
+ if self.client.daemon is not None:
423
+ served = (await self.client.daemon.opened()).workspace
424
+ if self.ref is None or self.ref == served:
425
+ if served is None:
426
+ raise Refused(
427
+ {"code": "invalid_request", "message": "name a workspace: a key's client serves none"}
428
+ )
429
+ return served
430
+ listed = await run(self.client, {"path": "account/workspaces", "action": "list"})
431
+ named = (listed.get("result") or {}).get("workspaces") if isinstance(listed, Mapping) else None
432
+ found = next(
433
+ (workspace for workspace in named or [] if isinstance(workspace, Mapping) and workspace.get("name") == self.ref),
434
+ None,
435
+ )
436
+ if not isinstance(found, Mapping) or not isinstance(found.get("id"), str):
437
+ raise Refused(
438
+ {
439
+ "code": "not_found",
440
+ "message": f"no workspace {self.ref}",
441
+ "next_steps": ["account/workspaces#list names them"],
442
+ }
443
+ )
444
+ return str(found["id"])
445
+
446
+ async def _send(
447
+ self,
448
+ operation: Operation,
449
+ params: Mapping[str, Any],
450
+ body: Any,
451
+ headers: Mapping[str, str],
452
+ ) -> Any:
453
+ reply = await self.client._request(
454
+ operation, {**params, "workspace": await self.id()}, body, headers
455
+ )
456
+ answer = await _answer_of(reply, operation)
457
+ group = current_group()
458
+ if group is not None and group.workspace is self:
459
+ group.note(answer)
460
+ return answer
461
+
462
+ def _stream(
463
+ self,
464
+ operation: Operation,
465
+ params: Mapping[str, Any],
466
+ body: Any,
467
+ headers: Mapping[str, str],
468
+ ) -> AsyncIterator[dict[str, Any]]:
469
+ async def open_reply() -> tuple[Reply, str]:
470
+ workspace = await self.id()
471
+ reply = await self.client._request(
472
+ operation, {**params, "workspace": workspace}, body, headers
473
+ )
474
+ return reply, workspace
475
+
476
+ return stream_of(open_reply)
477
+
478
+ def resource(self, path: str, surface: Any = None) -> ResourceType:
479
+ """A resource as a typed object: its fields, its actions and its edits. `surface` is the
480
+ app's version generated types were made from, which every call through it names."""
481
+ return resource_proxy(self, path, surface)
482
+
483
+ def invocation(self, title: str) -> _InvocationOpening:
484
+ """`async with ws.invocation(title)`: every call inside names it, so the apps record one
485
+ undo step and History shows `title`."""
486
+ return _InvocationOpening(self, title)
487
+
488
+ async def upload(self, data: Any) -> str:
489
+ """Put a file's bytes into the workspace: the `tilo.content:` reference an action takes
490
+ it by.
491
+
492
+ The bytes are addressed by their BLAKE3 hash, so a file goes up once whatever it is
493
+ called; one larger than a request carries goes up in pieces, each continuing where the
494
+ put stands.
495
+ """
496
+ content = _bytes_of(data)
497
+ hash = blake3.blake3(content).hexdigest()
498
+ offset = 0
499
+ while True:
500
+ end = min(offset + PIECE, len(content))
501
+ range = (
502
+ {}
503
+ if offset == 0 and end == len(content)
504
+ else {"content-range": f"bytes {offset}-{end - 1}/{len(content)}"}
505
+ )
506
+ put = await self.put_content(hash, content[offset:end], headers=range)
507
+ reference = put.get("content") if isinstance(put, Mapping) else None
508
+ if isinstance(reference, str) and reference:
509
+ return reference
510
+ stands = put.get("offset") if isinstance(put, Mapping) else None
511
+ if not isinstance(stands, int) or stands <= offset:
512
+ raise Refused(
513
+ {
514
+ "code": "upload_failed",
515
+ "message": f"the put stands at {stands} after a piece from {offset}",
516
+ }
517
+ )
518
+ offset = stands
519
+
520
+ async def download(self, reference: str) -> bytes:
521
+ """The bytes a `tilo.content:` reference names."""
522
+ return await self.get_content(reference.removeprefix("tilo.content:"))
523
+
524
+
525
+ def _bytes_of(data: Any) -> bytes:
526
+ """A file's bytes: the bytes themselves, a file object, or a path."""
527
+ if isinstance(data, bytes):
528
+ return data
529
+ if isinstance(data, (bytearray, memoryview)):
530
+ return bytes(data)
531
+ if hasattr(data, "read"):
532
+ return data.read()
533
+ with open(data, "rb") as file:
534
+ return file.read()
535
+
536
+
537
+ async def run(
538
+ where: Tilo | Workspace,
539
+ params: Mapping[str, str],
540
+ args: Mapping[str, Any] | None = None,
541
+ headers: Mapping[str, str] | None = None,
542
+ ) -> ActionAnswer:
543
+ """Run `action` on the resource `path` until it is no longer pending: its answer, `result`
544
+ what the action produced. A refusal raises.
545
+
546
+ In a workspace a pending action is followed by its invocation; the account's is asked again
547
+ with the same `Idempotency-Key`, which asks about the same invocation.
548
+ """
549
+ arguments = dict(args or {})
550
+ if isinstance(where, Workspace):
551
+ answer = await where.run_action(
552
+ params["path"], params["action"], arguments, headers=dict(headers or {})
553
+ )
554
+ while (
555
+ isinstance(answer, Mapping)
556
+ and answer.get("status") == "pending"
557
+ and isinstance(answer.get("invocation"), str)
558
+ ):
559
+ answer = await where.get_invocation(answer["invocation"], wait="60")
560
+ return answer
561
+ again: dict[str, str] = {
562
+ "prefer": "wait=60",
563
+ "idempotency-key": str(uuid.uuid4()),
564
+ }
565
+ for name, value in (headers or {}).items():
566
+ again[name.lower()] = value
567
+ while True:
568
+ answer = await where.run_account_action(
569
+ params["path"], params["action"], arguments, headers=again
570
+ )
571
+ if not isinstance(answer, Mapping) or answer.get("status") != "pending":
572
+ return answer
tilo/_errors.py ADDED
@@ -0,0 +1,57 @@
1
+ """A refusal: what the API, the daemon or the vault answered instead of doing what was asked."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+
9
+ class Refused(Exception):
10
+ """The call was refused, in the API's one refusal shape.
11
+
12
+ `error` is the whole body the API answered (`code`, `message`, `next_steps`,
13
+ `retry_after_ms` and the refused action's row where there are any), and
14
+ `status` the HTTP status it came with, 0 for a refusal of the daemon's own
15
+ connection. `code` is stable and typed, what a program branches on
16
+ (`not_permitted`, `key_revoked`, `surface_changed`, …); `message` is for
17
+ people.
18
+ """
19
+
20
+ def __init__(self, error: Mapping[str, Any] | None = None, status: int = 0) -> None:
21
+ body = dict(error or {})
22
+ self.error = body
23
+ self.status = status
24
+ super().__init__(str(body.get("message") or body.get("code") or "the call was refused"))
25
+
26
+ @property
27
+ def code(self) -> str:
28
+ """What a program branches on: `not_found`, `not_permitted`, `key_revoked`, …"""
29
+ return str(self.error.get("code") or "failed")
30
+
31
+ @property
32
+ def message(self) -> str:
33
+ """The API's words for people."""
34
+ return str(self.error.get("message") or "")
35
+
36
+ @property
37
+ def next_steps(self) -> list[str]:
38
+ """The calls that would work instead, each a sentence."""
39
+ return [str(step) for step in self.error.get("next_steps") or []]
40
+
41
+ @property
42
+ def retry_after_ms(self) -> int | None:
43
+ """How long the refusal asks to wait before the same call works."""
44
+ asked = self.error.get("retry_after_ms")
45
+ return asked if isinstance(asked, int) and asked >= 0 else None
46
+
47
+ def __str__(self) -> str:
48
+ text = f"{self.code}: {self.message}" if self.message else self.code
49
+ if self.next_steps:
50
+ text = text + "\n" + "\n".join(self.next_steps)
51
+ return text
52
+
53
+
54
+ def refusal_of(body: Any, status: int = 0) -> Refused:
55
+ """The refusal `body` (`{error: {...}}`) is."""
56
+ error = body.get("error") if isinstance(body, Mapping) else None
57
+ return Refused(error if isinstance(error, Mapping) else {}, status)