resource-engine 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.
Files changed (128) hide show
  1. resource_engine/__init__.py +96 -0
  2. resource_engine/application/__init__.py +1 -0
  3. resource_engine/application/actions.py +48 -0
  4. resource_engine/application/context.py +111 -0
  5. resource_engine/application/events.py +54 -0
  6. resource_engine/application/hooks.py +272 -0
  7. resource_engine/application/idempotency.py +277 -0
  8. resource_engine/application/manager.py +1987 -0
  9. resource_engine/application/query.py +47 -0
  10. resource_engine/application/registry.py +137 -0
  11. resource_engine/application/relations.py +470 -0
  12. resource_engine/application/resource.py +984 -0
  13. resource_engine/application/searching.py +162 -0
  14. resource_engine/application/settings.py +169 -0
  15. resource_engine/application/slots.py +67 -0
  16. resource_engine/application/state_machines.py +177 -0
  17. resource_engine/application/timers.py +347 -0
  18. resource_engine/application/transaction.py +100 -0
  19. resource_engine/application/views.py +239 -0
  20. resource_engine/audit/__init__.py +40 -0
  21. resource_engine/audit/export.py +280 -0
  22. resource_engine/audit/history.py +165 -0
  23. resource_engine/audit/janitor.py +257 -0
  24. resource_engine/audit/model.py +98 -0
  25. resource_engine/audit/recorder.py +145 -0
  26. resource_engine/audit/resource.py +68 -0
  27. resource_engine/audit/seal.py +327 -0
  28. resource_engine/audit/sink.py +69 -0
  29. resource_engine/authz/__init__.py +72 -0
  30. resource_engine/authz/apikeys.py +300 -0
  31. resource_engine/authz/base.py +143 -0
  32. resource_engine/authz/catalog.py +291 -0
  33. resource_engine/authz/conditions.py +416 -0
  34. resource_engine/authz/config.py +77 -0
  35. resource_engine/authz/evaluator.py +382 -0
  36. resource_engine/authz/external.py +249 -0
  37. resource_engine/authz/fields.py +44 -0
  38. resource_engine/authz/model.py +145 -0
  39. resource_engine/authz/resources.py +289 -0
  40. resource_engine/authz/roles.py +101 -0
  41. resource_engine/cache.py +144 -0
  42. resource_engine/calls.py +100 -0
  43. resource_engine/capabilities.py +145 -0
  44. resource_engine/composite.py +295 -0
  45. resource_engine/documents/__init__.py +69 -0
  46. resource_engine/documents/content.py +57 -0
  47. resource_engine/documents/events.py +49 -0
  48. resource_engine/documents/janitor.py +93 -0
  49. resource_engine/documents/machine.py +38 -0
  50. resource_engine/documents/manager.py +704 -0
  51. resource_engine/documents/model.py +91 -0
  52. resource_engine/documents/pipeline.py +98 -0
  53. resource_engine/documents/processors.py +320 -0
  54. resource_engine/documents/resource.py +39 -0
  55. resource_engine/domain/__init__.py +10 -0
  56. resource_engine/domain/events.py +50 -0
  57. resource_engine/domain/exceptions.py +23 -0
  58. resource_engine/email.py +417 -0
  59. resource_engine/errors.py +562 -0
  60. resource_engine/explorer.py +133 -0
  61. resource_engine/exports.py +687 -0
  62. resource_engine/generation.py +233 -0
  63. resource_engine/i18n.py +251 -0
  64. resource_engine/identity.py +46 -0
  65. resource_engine/integration.py +80 -0
  66. resource_engine/jobs.py +390 -0
  67. resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
  68. resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
  69. resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
  70. resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
  71. resource_engine/logs.py +201 -0
  72. resource_engine/messaging/__init__.py +73 -0
  73. resource_engine/messaging/asyncapi.py +529 -0
  74. resource_engine/messaging/cloudevents.py +98 -0
  75. resource_engine/messaging/consumer.py +165 -0
  76. resource_engine/messaging/delivery.py +115 -0
  77. resource_engine/messaging/envelope.py +193 -0
  78. resource_engine/messaging/hub.py +148 -0
  79. resource_engine/messaging/inbound.py +76 -0
  80. resource_engine/messaging/inspection.py +113 -0
  81. resource_engine/messaging/janitor.py +136 -0
  82. resource_engine/messaging/live.py +179 -0
  83. resource_engine/messaging/processing.py +357 -0
  84. resource_engine/messaging/publishing.py +318 -0
  85. resource_engine/messaging/relay.py +84 -0
  86. resource_engine/messaging/worker.py +166 -0
  87. resource_engine/nosql.py +394 -0
  88. resource_engine/ports/__init__.py +13 -0
  89. resource_engine/ports/activity.py +171 -0
  90. resource_engine/ports/audit.py +42 -0
  91. resource_engine/ports/authz.py +132 -0
  92. resource_engine/ports/cache.py +41 -0
  93. resource_engine/ports/email.py +118 -0
  94. resource_engine/ports/event_publisher.py +34 -0
  95. resource_engine/ports/idempotency.py +69 -0
  96. resource_engine/ports/identity.py +112 -0
  97. resource_engine/ports/locks.py +28 -0
  98. resource_engine/ports/messaging.py +197 -0
  99. resource_engine/ports/observability.py +60 -0
  100. resource_engine/ports/ratelimit.py +59 -0
  101. resource_engine/ports/repository.py +56 -0
  102. resource_engine/ports/storage.py +93 -0
  103. resource_engine/ports/templates.py +54 -0
  104. resource_engine/ports/tracing.py +61 -0
  105. resource_engine/ports/unit_of_work.py +46 -0
  106. resource_engine/processes.py +408 -0
  107. resource_engine/py.typed +0 -0
  108. resource_engine/querying.py +319 -0
  109. resource_engine/ratelimit.py +217 -0
  110. resource_engine/reporting.py +230 -0
  111. resource_engine/schema_examples.py +51 -0
  112. resource_engine/templates.py +143 -0
  113. resource_engine/tenancy.py +68 -0
  114. resource_engine/testing/__init__.py +34 -0
  115. resource_engine/testing/activity.py +123 -0
  116. resource_engine/testing/contracts.py +1416 -0
  117. resource_engine/testing/email.py +36 -0
  118. resource_engine/testing/engine.py +40 -0
  119. resource_engine/testing/memory.py +603 -0
  120. resource_engine/testing/storage.py +110 -0
  121. resource_engine/testing/tracing.py +100 -0
  122. resource_engine/tracing.py +156 -0
  123. resource_engine/translatable.py +80 -0
  124. resource_engine/versions.py +189 -0
  125. resource_engine-0.1.0.dist-info/METADATA +36 -0
  126. resource_engine-0.1.0.dist-info/RECORD +128 -0
  127. resource_engine-0.1.0.dist-info/WHEEL +4 -0
  128. resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,687 @@
1
+ """Table export: a resource's list as CSV or XLSX, with the caller's filters,
2
+ sorting, permissions, hidden fields and tenant, exactly as the API lists it.
3
+
4
+ ```python
5
+ from resource_engine.exports import export_table
6
+
7
+ content, media_type, filename = await export_table(
8
+ manager, "invoices", ListQuery(filters={"status": "approved"}), format="xlsx", actor=user
9
+ )
10
+ ```
11
+
12
+ Rows are read page by page through ``manager.list`` as the caller, so a user
13
+ exports what they could list and nothing else: rows outside their row filter
14
+ or tenant aren't there, and hidden fields are empty. ``max_rows`` (10 000 by
15
+ default) caps an export; above it, narrow the filters. Over HTTP:
16
+ ``GET /<resource>/export?format=csv|xlsx`` with the list's filters
17
+ (``mount_resources``). XLSX needs ``resource-engine[xlsx]`` (openpyxl).
18
+
19
+ **Large exports** run in the background (``ExportJobs``, available as
20
+ ``manager.exports`` when a blob store is configured): the request checks the
21
+ permission and the query and returns at once; a worker job writes the file to
22
+ the blob store, where the requester downloads it until it expires:
23
+
24
+ ```python
25
+ job = await manager.exports.request("invoices", query, format="xlsx", actor=user)
26
+ runner.add("exports", manager.exports, every=5, single=True) # the worker
27
+ job = await manager.exports.get(job.id, actor=user) # pending, running, done, failed
28
+ meta, stream = await manager.exports.open(job.id, actor=user)
29
+ ```
30
+
31
+ Over HTTP: ``POST /<resource>/exports`` (202), ``GET /exports/{id}`` and
32
+ ``GET /exports/{id}/content``. See docs/exports.md.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import csv
38
+ import dataclasses
39
+ import enum
40
+ import io
41
+ import json
42
+ import logging
43
+ import re
44
+ import secrets
45
+ import tempfile
46
+ from collections.abc import AsyncIterator, Callable, Mapping, Sequence
47
+ from dataclasses import dataclass, field
48
+ from datetime import UTC, date, datetime, timedelta
49
+ from decimal import Decimal
50
+ from typing import Any, Literal
51
+
52
+ from pydantic import BaseModel
53
+
54
+ from resource_engine.application.query import ListQuery
55
+ from resource_engine.errors import (
56
+ BlobNotFound,
57
+ ConfigurationError,
58
+ DocumentNotAvailable,
59
+ EntityNotFound,
60
+ InvalidQuery,
61
+ ResourceEngineError,
62
+ )
63
+ from resource_engine.ports.identity import Principal
64
+ from resource_engine.ports.storage import BlobStore, PresignedRequest, SupportsPresignedUrls
65
+
66
+ log = logging.getLogger("resource_engine.exports")
67
+
68
+ type ExportFormat = Literal["csv", "xlsx"]
69
+
70
+ MEDIA_TYPES = {
71
+ "csv": "text/csv; charset=utf-8",
72
+ "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
73
+ }
74
+
75
+
76
+ def columns_of(manager: Any, resource: str) -> list[str]:
77
+ """The export's columns: the read schema's fields, in order."""
78
+ definition = manager.registry.get(resource)
79
+ read = definition.schemas.get("read")
80
+ return list(read.model_fields) if read is not None else []
81
+
82
+
83
+ async def iter_rows(
84
+ manager: Any,
85
+ resource: str,
86
+ query: ListQuery | None = None,
87
+ *,
88
+ actor: Any = None,
89
+ tenant: str | None = None,
90
+ page_size: int = 500,
91
+ max_rows: int = 10_000,
92
+ ) -> AsyncIterator[dict[str, Any]]:
93
+ """The caller's rows as dicts (hidden fields left out), page by page."""
94
+ from resource_engine.authz.fields import hidden_fields
95
+
96
+ query = query or ListQuery()
97
+ page_size = min(page_size, manager.registry.get(resource).max_page_size)
98
+ offset, sent = 0, 0
99
+ while True:
100
+ page_query = ListQuery(
101
+ offset=offset,
102
+ limit=page_size,
103
+ order_by=list(query.order_by),
104
+ filters=dict(query.filters),
105
+ search=query.search,
106
+ )
107
+ page = await manager.list(resource, page_query, actor=actor, tenant=tenant)
108
+ if offset == 0 and page.total > max_rows:
109
+ raise InvalidQuery(
110
+ f"{page.total} {resource} match; an export is limited to {max_rows} rows",
111
+ details={"total": page.total, "max_rows": max_rows},
112
+ hint="Narrow the filters, or export in parts.",
113
+ )
114
+ for item in page.items:
115
+ if isinstance(item, BaseModel):
116
+ yield item.model_dump(exclude=set(hidden_fields(item)))
117
+ else:
118
+ yield dict(vars(item))
119
+ sent += 1
120
+ offset += page_size
121
+ if len(page.items) < page_size or sent >= page.total:
122
+ return
123
+
124
+
125
+ def _cell(value: Any, *, native: bool) -> Any:
126
+ """A value for a cell: numbers and dates stay native in XLSX; lists and
127
+ objects become JSON; ``None`` is empty."""
128
+ if value is None:
129
+ return "" if not native else None
130
+ if isinstance(value, enum.Enum):
131
+ value = value.value
132
+ if isinstance(value, bool):
133
+ return value if native else ("true" if value else "false")
134
+ if isinstance(value, int | float | Decimal):
135
+ return value if native else str(value)
136
+ if isinstance(value, datetime):
137
+ if native: # Excel has no time zones: UTC, without the offset
138
+ return value.astimezone(UTC).replace(tzinfo=None) if value.tzinfo else value
139
+ return value.isoformat()
140
+ if isinstance(value, date):
141
+ return value if native else value.isoformat()
142
+ if isinstance(value, str):
143
+ return value
144
+ if isinstance(value, BaseModel):
145
+ value = value.model_dump(mode="json")
146
+ return json.dumps(value, default=str, ensure_ascii=False)
147
+
148
+
149
+ async def stream_csv(
150
+ rows: AsyncIterator[dict[str, Any]],
151
+ columns: Sequence[str],
152
+ *,
153
+ delimiter: str = ",",
154
+ excel: bool = True,
155
+ batch: int = 500,
156
+ ) -> AsyncIterator[bytes]:
157
+ """CSV with a header row, as UTF-8 chunks of ``batch`` rows. ``excel`` adds
158
+ a byte order mark so Excel opens accented text correctly."""
159
+ out = io.StringIO()
160
+ writer = csv.writer(out, delimiter=delimiter, lineterminator="\r\n")
161
+ if excel:
162
+ out.write("\ufeff")
163
+ writer.writerow(columns)
164
+ count = 0
165
+ async for row in rows:
166
+ writer.writerow([_cell(row.get(c), native=False) for c in columns])
167
+ count += 1
168
+ if count % batch == 0:
169
+ yield out.getvalue().encode("utf-8")
170
+ out.seek(0)
171
+ out.truncate()
172
+ if out.tell():
173
+ yield out.getvalue().encode("utf-8")
174
+
175
+
176
+ async def write_csv(
177
+ rows: AsyncIterator[dict[str, Any]],
178
+ columns: Sequence[str],
179
+ *,
180
+ delimiter: str = ",",
181
+ excel: bool = True,
182
+ ) -> bytes:
183
+ """CSV with a header row (see ``stream_csv``), in memory."""
184
+ parts = [part async for part in stream_csv(rows, columns, delimiter=delimiter, excel=excel)]
185
+ return b"".join(parts)
186
+
187
+
188
+ async def _workbook(rows: AsyncIterator[dict[str, Any]], columns: Sequence[str], sheet: str) -> Any:
189
+ try:
190
+ from openpyxl import Workbook
191
+ from openpyxl.cell import WriteOnlyCell
192
+ from openpyxl.styles import Font
193
+ except ImportError: # pragma: no cover - depends on the extra
194
+ raise InvalidQuery(
195
+ "XLSX export needs openpyxl",
196
+ hint="Install resource-engine[xlsx], or export as CSV.",
197
+ ) from None
198
+ book = Workbook(write_only=True)
199
+ page = book.create_sheet(sheet[:31] or "export")
200
+ page.freeze_panes = "A2"
201
+ bold = Font(bold=True)
202
+ header = []
203
+ for name in columns:
204
+ cell = WriteOnlyCell(page, value=name)
205
+ cell.font = bold
206
+ header.append(cell)
207
+ page.append(header)
208
+ async for row in rows:
209
+ page.append([_cell(row.get(c), native=True) for c in columns])
210
+ return book
211
+
212
+
213
+ async def write_xlsx(
214
+ rows: AsyncIterator[dict[str, Any]], columns: Sequence[str], *, sheet: str = "export"
215
+ ) -> bytes:
216
+ """An XLSX workbook (one sheet, header row frozen), written in openpyxl's
217
+ streaming mode."""
218
+ book = await _workbook(rows, columns, sheet)
219
+ out = io.BytesIO()
220
+ book.save(out)
221
+ return out.getvalue()
222
+
223
+
224
+ async def stream_xlsx(
225
+ rows: AsyncIterator[dict[str, Any]],
226
+ columns: Sequence[str],
227
+ *,
228
+ sheet: str = "export",
229
+ chunk: int = 256 * 1024,
230
+ ) -> AsyncIterator[bytes]:
231
+ """An XLSX workbook saved to a temporary file (spilled to disk past 8 MB)
232
+ and streamed from it, for exports too large to hold in memory."""
233
+ book = await _workbook(rows, columns, sheet)
234
+ with tempfile.SpooledTemporaryFile(max_size=8 * 1024 * 1024) as tmp:
235
+ book.save(tmp) # same thread: openpyxl's write-only sheets can't move between threads
236
+ tmp.seek(0)
237
+ while part := tmp.read(chunk):
238
+ yield part
239
+
240
+
241
+ async def export_table(
242
+ manager: Any,
243
+ resource: str,
244
+ query: ListQuery | None = None,
245
+ *,
246
+ format: ExportFormat = "csv",
247
+ actor: Any = None,
248
+ tenant: str | None = None,
249
+ max_rows: int = 10_000,
250
+ columns: Sequence[str] | None = None,
251
+ ) -> tuple[bytes, str, str]:
252
+ """``(content, media type, file name)`` of a resource's list."""
253
+ if format not in MEDIA_TYPES:
254
+ raise InvalidQuery(f"Unknown export format {format!r}; use csv or xlsx")
255
+ names = list(columns or columns_of(manager, resource))
256
+ rows = iter_rows(manager, resource, query, actor=actor, tenant=tenant, max_rows=max_rows)
257
+ content = (
258
+ await write_xlsx(rows, names, sheet=resource)
259
+ if format == "xlsx"
260
+ else await write_csv(rows, names)
261
+ )
262
+ stamp = datetime.now(UTC).strftime("%Y%m%d-%H%M")
263
+ return content, MEDIA_TYPES[format], f"{resource}-{stamp}.{format}"
264
+
265
+
266
+ # --------------------------------------------------------- background exports
267
+
268
+ type ExportStatus = Literal["pending", "running", "done", "failed"]
269
+
270
+ _JOB_ID = re.compile(r"^[0-9a-f]{32}$")
271
+
272
+
273
+ def dump_actor(actor: Any) -> Any:
274
+ """The requester, as JSON, for the worker to export as them: ``None``,
275
+ a string or a ``Principal`` (roles, tenant and claims as they were when
276
+ the export was requested). Other actor types need ``ExportJobs(dump_actor=,
277
+ load_actor=)``."""
278
+ from resource_engine.authz.base import SystemPrincipal
279
+
280
+ if actor is None or isinstance(actor, str):
281
+ return actor
282
+ if isinstance(actor, SystemPrincipal):
283
+ return {"system": actor.subject}
284
+ if isinstance(actor, Principal):
285
+ data = dataclasses.asdict(actor)
286
+ for name in ("roles", "groups", "scopes"):
287
+ data[name] = sorted(data[name])
288
+ data["claims"] = json.loads(json.dumps(data["claims"], default=str))
289
+ return {"principal": data}
290
+ raise ConfigurationError(
291
+ f"Background exports can't store a {type(actor).__name__} actor",
292
+ hint="Pass ExportJobs(dump_actor=..., load_actor=...) for this actor type.",
293
+ doc="docs/exports.md#background-exports",
294
+ )
295
+
296
+
297
+ def load_actor(data: Any) -> Any:
298
+ """The actor stored with an export job, back as the principal it was."""
299
+ if isinstance(data, Mapping) and "system" in data:
300
+ from resource_engine.authz.base import system_principal
301
+
302
+ return system_principal(str(data["system"]))
303
+ if isinstance(data, Mapping) and "principal" in data:
304
+ values = dict(data["principal"])
305
+ for name in ("roles", "groups", "scopes"):
306
+ values[name] = frozenset(values.get(name) or ())
307
+ return Principal(**values)
308
+ return data
309
+
310
+
311
+ def _actor_label(actor: Any) -> str | None:
312
+ from resource_engine.audit.recorder import actor_id
313
+
314
+ if actor is None or isinstance(actor, str):
315
+ return actor
316
+ return actor_id(actor) or str(actor)
317
+
318
+
319
+ def _now() -> datetime:
320
+ return datetime.now(UTC)
321
+
322
+
323
+ def _time(value: str | None) -> datetime | None:
324
+ return datetime.fromisoformat(value) if value else None
325
+
326
+
327
+ @dataclass
328
+ class ExportJob:
329
+ """A background export and where it is.
330
+
331
+ Attributes:
332
+ status: ``pending`` (waiting for the worker), ``running``, ``done``
333
+ (the file can be downloaded until ``expires_at``) or ``failed``
334
+ (``error`` says why).
335
+ rows: How many rows matched when the export was requested.
336
+ requested_by: The requester; only they can see and download it.
337
+ """
338
+
339
+ id: str
340
+ resource: str
341
+ format: ExportFormat
342
+ filters: dict[str, Any] = field(default_factory=dict)
343
+ order_by: list[str] = field(default_factory=list)
344
+ search: str | None = None
345
+ tenant: str | None = None
346
+ requested_by: str | None = None
347
+ actor: Any = None
348
+ status: ExportStatus = "pending"
349
+ rows: int | None = None
350
+ created_at: datetime = field(default_factory=_now)
351
+ started_at: datetime | None = None
352
+ finished_at: datetime | None = None
353
+ expires_at: datetime | None = None
354
+ attempts: int = 0
355
+ filename: str | None = None
356
+ size: int | None = None
357
+ error: dict[str, Any] | None = None
358
+
359
+ def to_dict(self) -> dict[str, Any]:
360
+ """Everything but the stored actor: what the API shows."""
361
+ data = {
362
+ "id": self.id,
363
+ "resource": self.resource,
364
+ "format": self.format,
365
+ "status": self.status,
366
+ "rows": self.rows,
367
+ "filename": self.filename,
368
+ "size": self.size,
369
+ "created_at": self.created_at.isoformat(),
370
+ "started_at": self.started_at.isoformat() if self.started_at else None,
371
+ "finished_at": self.finished_at.isoformat() if self.finished_at else None,
372
+ "expires_at": self.expires_at.isoformat() if self.expires_at else None,
373
+ "error": self.error,
374
+ }
375
+ return data
376
+
377
+ def _manifest(self) -> bytes:
378
+ data = self.to_dict()
379
+ data.update(
380
+ filters=self.filters,
381
+ order_by=self.order_by,
382
+ search=self.search,
383
+ tenant=self.tenant,
384
+ requested_by=self.requested_by,
385
+ actor=self.actor,
386
+ attempts=self.attempts,
387
+ )
388
+ return json.dumps(data, default=str, ensure_ascii=False).encode("utf-8")
389
+
390
+ @classmethod
391
+ def _load(cls, raw: bytes) -> ExportJob:
392
+ data = json.loads(raw)
393
+ return cls(
394
+ id=data["id"],
395
+ resource=data["resource"],
396
+ format=data["format"],
397
+ filters=data.get("filters") or {},
398
+ order_by=list(data.get("order_by") or ()),
399
+ search=data.get("search"),
400
+ tenant=data.get("tenant"),
401
+ requested_by=data.get("requested_by"),
402
+ actor=data.get("actor"),
403
+ status=data["status"],
404
+ rows=data.get("rows"),
405
+ created_at=_time(data["created_at"]) or _now(),
406
+ started_at=_time(data.get("started_at")),
407
+ finished_at=_time(data.get("finished_at")),
408
+ expires_at=_time(data.get("expires_at")),
409
+ attempts=int(data.get("attempts") or 0),
410
+ filename=data.get("filename"),
411
+ size=data.get("size"),
412
+ error=data.get("error"),
413
+ )
414
+
415
+
416
+ class ExportJobs:
417
+ """Exports too large to answer in one request, written by a worker job.
418
+
419
+ Each export is two objects in the blob store: ``<prefix><id>.json`` (the
420
+ job: query, status, the requester) and ``<prefix><id>.<format>`` (the
421
+ file). Nothing else is needed: no table, no broker.
422
+
423
+ Args:
424
+ manager: The ``ResourceManager`` the rows are read through.
425
+ store: Where jobs and files go (the documents' blob store by default).
426
+ prefix: Key prefix of the jobs and files.
427
+ max_rows: The most rows one background export may have.
428
+ retention: How long a finished export (and its file) is kept.
429
+ stale_after: A ``running`` job not finished after this long (its
430
+ worker died) runs again, up to ``max_attempts`` times.
431
+ dump_actor / load_actor: How the requester is stored for the worker.
432
+ path: URL segment of the HTTP routes (``/exports/{id}``).
433
+
434
+ Run it as a job: ``runner.add("exports", manager.exports, every=5,
435
+ single=True)``. Rows are read as the requester, with the roles they had
436
+ when they asked: someone who loses access after asking still gets the
437
+ file, within ``retention``.
438
+ """
439
+
440
+ def __init__(
441
+ self,
442
+ manager: Any,
443
+ store: BlobStore,
444
+ *,
445
+ prefix: str = "exports/",
446
+ max_rows: int = 1_000_000,
447
+ retention: timedelta = timedelta(days=1),
448
+ stale_after: timedelta = timedelta(minutes=30),
449
+ max_attempts: int = 3,
450
+ download_ttl: timedelta = timedelta(minutes=15),
451
+ dump_actor: Callable[[Any], Any] = dump_actor,
452
+ load_actor: Callable[[Any], Any] = load_actor,
453
+ path: str = "exports",
454
+ ) -> None:
455
+ self.manager = manager
456
+ self.store = store
457
+ self.prefix = prefix
458
+ self.max_rows = max_rows
459
+ self.retention = retention
460
+ self.stale_after = stale_after
461
+ self.max_attempts = max_attempts
462
+ self.download_ttl = download_ttl
463
+ self.dump_actor = dump_actor
464
+ self.load_actor = load_actor
465
+ self.path = path.strip("/")
466
+
467
+ # ------------------------------------------------------------- storage
468
+
469
+ def _job_key(self, job_id: str) -> str:
470
+ return f"{self.prefix}{job_id}.json"
471
+
472
+ def _file_key(self, job: ExportJob) -> str:
473
+ return f"{self.prefix}{job.id}.{job.format}"
474
+
475
+ async def _save(self, job: ExportJob) -> None:
476
+ await self.store.put(
477
+ self._job_key(job.id), job._manifest(), content_type="application/json"
478
+ )
479
+
480
+ async def _load(self, job_id: str) -> ExportJob | None:
481
+ if not _JOB_ID.match(job_id):
482
+ return None
483
+ try:
484
+ raw = b"".join([part async for part in self.store.open(self._job_key(job_id))])
485
+ except BlobNotFound:
486
+ return None
487
+ return ExportJob._load(raw)
488
+
489
+ # ------------------------------------------------------------ requests
490
+
491
+ async def request(
492
+ self,
493
+ resource: str,
494
+ query: ListQuery | None = None,
495
+ *,
496
+ format: ExportFormat = "csv",
497
+ actor: Any = None,
498
+ tenant: str | None = None,
499
+ ) -> ExportJob:
500
+ """Check that ``actor`` may list ``resource`` with ``query`` and queue
501
+ the export. Raises what the list would (permission, invalid query)
502
+ and ``InvalidQuery`` past ``max_rows``."""
503
+ if format not in MEDIA_TYPES:
504
+ raise InvalidQuery(f"Unknown export format {format!r}; use csv or xlsx")
505
+ query = query or ListQuery()
506
+ probe = ListQuery(
507
+ offset=0,
508
+ limit=1,
509
+ order_by=list(query.order_by),
510
+ filters=dict(query.filters),
511
+ search=query.search,
512
+ )
513
+ page = await self.manager.list(resource, probe, actor=actor, tenant=tenant)
514
+ if page.total > self.max_rows:
515
+ raise InvalidQuery(
516
+ f"{page.total} {resource} match; an export is limited to {self.max_rows} rows",
517
+ details={"total": page.total, "max_rows": self.max_rows},
518
+ hint="Narrow the filters, or export in parts.",
519
+ )
520
+ job = ExportJob(
521
+ id=secrets.token_hex(16),
522
+ resource=resource,
523
+ format=format,
524
+ filters=json.loads(json.dumps(dict(query.filters), default=str)),
525
+ order_by=list(query.order_by),
526
+ search=query.search,
527
+ tenant=tenant,
528
+ requested_by=_actor_label(actor),
529
+ actor=self.dump_actor(actor),
530
+ rows=page.total,
531
+ )
532
+ await self._save(job)
533
+ log.info(
534
+ "export requested",
535
+ extra={"export_id": job.id, "resource": resource, "rows": page.total},
536
+ )
537
+ return job
538
+
539
+ async def get(self, job_id: str, *, actor: Any = None) -> ExportJob:
540
+ """The export ``job_id`` of ``actor`` (``EntityNotFound`` for anyone else)."""
541
+ job = await self._load(job_id)
542
+ if job is None or job.requested_by != _actor_label(actor):
543
+ raise EntityNotFound(f"Export {job_id!r} does not exist")
544
+ return job
545
+
546
+ async def _ready(self, job_id: str, actor: Any) -> ExportJob:
547
+ job = await self.get(job_id, actor=actor)
548
+ if job.status != "done":
549
+ raise DocumentNotAvailable(
550
+ f"Export {job_id!r} is {job.status}",
551
+ hint="Wait until its status is done.",
552
+ details={"status": job.status, "error": job.error},
553
+ )
554
+ return job
555
+
556
+ async def open(
557
+ self, job_id: str, *, actor: Any = None
558
+ ) -> tuple[ExportJob, AsyncIterator[bytes]]:
559
+ """The finished export and a stream of its file."""
560
+ job = await self._ready(job_id, actor)
561
+ return job, self.store.open(self._file_key(job))
562
+
563
+ async def download_url(self, job_id: str, *, actor: Any = None) -> PresignedRequest:
564
+ """A presigned URL that downloads the finished export of ``actor``."""
565
+ if not isinstance(self.store, SupportsPresignedUrls):
566
+ raise ConfigurationError(f"{type(self.store).__name__} cannot presign downloads")
567
+ job = await self._ready(job_id, actor)
568
+ return await self.store.presign_get(
569
+ self._file_key(job), expires=self.download_ttl, download_name=job.filename
570
+ )
571
+
572
+ # -------------------------------------------------------------- worker
573
+
574
+ async def __call__(self) -> int:
575
+ """Run once (as a job); returns how many exports were produced."""
576
+ return await self.run_once()
577
+
578
+ async def jobs(self) -> list[ExportJob]:
579
+ """Every stored export, oldest first."""
580
+ found = []
581
+ async for info in self.store.list(self.prefix):
582
+ name = info.key[len(self.prefix) :]
583
+ if name.endswith(".json") and _JOB_ID.match(name.removesuffix(".json")):
584
+ job = await self._load(name.removesuffix(".json"))
585
+ if job is not None:
586
+ found.append(job)
587
+ found.sort(key=lambda j: j.created_at)
588
+ return found
589
+
590
+ async def run_once(self, *, limit: int = 5) -> int:
591
+ """Write up to ``limit`` waiting exports and delete expired ones.
592
+ Returns how many exports were written."""
593
+ now = _now()
594
+ written = 0
595
+ for job in await self.jobs():
596
+ if job.expires_at is not None and job.expires_at <= now:
597
+ await self.store.delete([self._file_key(job), self._job_key(job.id)])
598
+ continue
599
+ if job.status == "pending" and job.created_at + self.retention <= now:
600
+ job.status, job.finished_at, job.expires_at = "failed", now, now + self.retention
601
+ job.error = {"code": "RE-E000", "message": "No worker ran the export in time"}
602
+ await self._save(job)
603
+ continue
604
+ stale = (
605
+ job.status == "running"
606
+ and job.started_at is not None
607
+ and job.started_at + self.stale_after <= now
608
+ )
609
+ if written < limit and (job.status == "pending" or stale):
610
+ await self.run(job)
611
+ written += 1
612
+ return written
613
+
614
+ async def run(self, job: ExportJob) -> ExportJob:
615
+ """Write one export's file, as its requester."""
616
+ from resource_engine.reporting import report_error
617
+
618
+ job.attempts += 1
619
+ if job.attempts > self.max_attempts:
620
+ return await self._fail(job, {"code": "RE-E000", "message": "The export kept failing"})
621
+ job.status, job.started_at = "running", _now()
622
+ await self._save(job)
623
+ actor = self.load_actor(job.actor)
624
+ query = ListQuery(order_by=list(job.order_by), filters=dict(job.filters), search=job.search)
625
+ names = columns_of(self.manager, job.resource)
626
+ rows = iter_rows(
627
+ self.manager,
628
+ job.resource,
629
+ query,
630
+ actor=actor,
631
+ tenant=job.tenant,
632
+ max_rows=self.max_rows,
633
+ )
634
+ content = (
635
+ stream_xlsx(rows, names, sheet=job.resource)
636
+ if job.format == "xlsx"
637
+ else stream_csv(rows, names)
638
+ )
639
+ try:
640
+ info = await self.store.put(
641
+ self._file_key(job), content, content_type=MEDIA_TYPES[job.format].split(";")[0]
642
+ )
643
+ except ResourceEngineError as exc:
644
+ await _close(content)
645
+ return await self._fail(job, {"code": exc.code, "message": exc.message})
646
+ except Exception as exc:
647
+ await _close(content)
648
+ await report_error(exc, where="exports.run", actor=actor, export_id=job.id)
649
+ return await self._fail(job, {"code": "RE-E000", "message": "Internal error"})
650
+ stamp = job.created_at.strftime("%Y%m%d-%H%M")
651
+ job.status, job.finished_at, job.size = "done", _now(), info.size
652
+ job.filename = f"{job.resource}-{stamp}.{job.format}"
653
+ job.expires_at = job.finished_at + self.retention
654
+ job.error = None
655
+ await self._save(job)
656
+ log.info("export written", extra={"export_id": job.id, "bytes": info.size})
657
+ return job
658
+
659
+ async def _fail(self, job: ExportJob, error: dict[str, Any]) -> ExportJob:
660
+ job.status, job.finished_at, job.error = "failed", _now(), error
661
+ job.expires_at = job.finished_at + self.retention
662
+ await self._save(job)
663
+ log.warning("export failed", extra={"export_id": job.id, "code": error.get("code")})
664
+ return job
665
+
666
+
667
+ __all__ = [
668
+ "MEDIA_TYPES",
669
+ "ExportJob",
670
+ "ExportJobs",
671
+ "columns_of",
672
+ "dump_actor",
673
+ "export_table",
674
+ "iter_rows",
675
+ "load_actor",
676
+ "stream_csv",
677
+ "stream_xlsx",
678
+ "write_csv",
679
+ "write_xlsx",
680
+ ]
681
+
682
+
683
+ async def _close(stream: Any) -> None:
684
+ """Close an async generator that stopped half-way (other iterators have nothing to close)."""
685
+ aclose = getattr(stream, "aclose", None)
686
+ if aclose is not None:
687
+ await aclose()