riffsdk 0.27.0__tar.gz → 0.28.0__tar.gz

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 (77) hide show
  1. {riffsdk-0.27.0 → riffsdk-0.28.0}/CHANGELOG.md +8 -0
  2. {riffsdk-0.27.0 → riffsdk-0.28.0}/PKG-INFO +37 -7
  3. {riffsdk-0.27.0 → riffsdk-0.28.0}/README.md +36 -6
  4. {riffsdk-0.27.0 → riffsdk-0.28.0}/pyproject.toml +1 -1
  5. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/_internal/transport.py +2 -2
  6. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/client.py +2 -2
  7. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/metrics/v0.py +96 -11
  8. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_imports.py +12 -2
  9. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_metrics_v0.py +159 -0
  10. {riffsdk-0.27.0 → riffsdk-0.28.0}/.github/workflows/ci.yml +0 -0
  11. {riffsdk-0.27.0 → riffsdk-0.28.0}/.github/workflows/pr-comment.yml +0 -0
  12. {riffsdk-0.27.0 → riffsdk-0.28.0}/.github/workflows/release.yml +0 -0
  13. {riffsdk-0.27.0 → riffsdk-0.28.0}/.gitignore +0 -0
  14. {riffsdk-0.27.0 → riffsdk-0.28.0}/.python-version +0 -0
  15. {riffsdk-0.27.0 → riffsdk-0.28.0}/AGENTS.md +0 -0
  16. {riffsdk-0.27.0 → riffsdk-0.28.0}/CLAUDE.md +0 -0
  17. {riffsdk-0.27.0 → riffsdk-0.28.0}/LICENCE +0 -0
  18. {riffsdk-0.27.0 → riffsdk-0.28.0}/LOCAL-TESTING.md +0 -0
  19. {riffsdk-0.27.0 → riffsdk-0.28.0}/USAGE_PROMPT.md +0 -0
  20. {riffsdk-0.27.0 → riffsdk-0.28.0}/examples/async_client.py +0 -0
  21. {riffsdk-0.27.0 → riffsdk-0.28.0}/examples/basic_crud.py +0 -0
  22. {riffsdk-0.27.0 → riffsdk-0.28.0}/examples/email_notice.py +0 -0
  23. {riffsdk-0.27.0 → riffsdk-0.28.0}/examples/file_upload_download.py +0 -0
  24. {riffsdk-0.27.0 → riffsdk-0.28.0}/examples/get_task.py +0 -0
  25. {riffsdk-0.27.0 → riffsdk-0.28.0}/examples/interpret_document.py +0 -0
  26. {riffsdk-0.27.0 → riffsdk-0.28.0}/examples/optimistic_concurrency.py +0 -0
  27. {riffsdk-0.27.0 → riffsdk-0.28.0}/examples/query_metrics.py +0 -0
  28. {riffsdk-0.27.0 → riffsdk-0.28.0}/mise.toml +0 -0
  29. {riffsdk-0.27.0 → riffsdk-0.28.0}/new-sdk-url-schema.md +0 -0
  30. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/__init__.py +0 -0
  31. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/__main__.py +0 -0
  32. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/_cli.py +0 -0
  33. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/_internal/__init__.py +0 -0
  34. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/_internal/auth.py +0 -0
  35. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/_internal/config.py +0 -0
  36. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/ai/__init__.py +0 -0
  37. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/ai/v0.py +0 -0
  38. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/context.py +0 -0
  39. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/email/__init__.py +0 -0
  40. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/email/v0.py +0 -0
  41. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/metrics/__init__.py +0 -0
  42. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/__init__.py +0 -0
  43. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/_async_client.py +0 -0
  44. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/_client.py +0 -0
  45. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/_common.py +0 -0
  46. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/_http.py +0 -0
  47. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/_mime.py +0 -0
  48. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/_models.py +0 -0
  49. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/_session.py +0 -0
  50. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/_streaming.py +0 -0
  51. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/_upload.py +0 -0
  52. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/exceptions.py +0 -0
  53. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/storage/py.typed +0 -0
  54. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/tasks/__init__.py +0 -0
  55. {riffsdk-0.27.0 → riffsdk-0.28.0}/src/riffsdk/tasks/v0.py +0 -0
  56. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/__init__.py +0 -0
  57. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/conftest.py +0 -0
  58. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_ai_v0.py +0 -0
  59. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_async_client.py +0 -0
  60. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_auth.py +0 -0
  61. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_cli.py +0 -0
  62. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_client.py +0 -0
  63. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_config.py +0 -0
  64. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_context.py +0 -0
  65. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_email_v0.py +0 -0
  66. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_exceptions.py +0 -0
  67. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_http.py +0 -0
  68. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_importance.py +0 -0
  69. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_integration.py +0 -0
  70. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_mime.py +0 -0
  71. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_models.py +0 -0
  72. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_session.py +0 -0
  73. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_single_put_upload.py +0 -0
  74. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_streaming.py +0 -0
  75. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_tasks_v0.py +0 -0
  76. {riffsdk-0.27.0 → riffsdk-0.28.0}/tests/test_upload.py +0 -0
  77. {riffsdk-0.27.0 → riffsdk-0.28.0}/uv.lock +0 -0
@@ -2,6 +2,14 @@
2
2
 
3
3
  <!-- version list -->
4
4
 
5
+ ## v0.28.0 (2026-12-02)
6
+
7
+ ### Features
8
+
9
+ - **metrics**: Accept an optional project selector on query and get_schema
10
+ ([`53219e3`](https://github.com/databutton/riff-sdk-python/commit/53219e3d3eae11727913b7a0269f53455126e821))
11
+
12
+
5
13
  ## v0.27.0 (2026-12-01)
6
14
 
7
15
  ### Bug Fixes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: riffsdk
3
- Version: 0.27.0
3
+ Version: 0.28.0
4
4
  Summary: Python SDK for the Riff Storage API
5
5
  Project-URL: Homepage, https://riff.ai
6
6
  Author-email: Martin Sandve Alnæs <msa@databutton.io>
@@ -270,11 +270,41 @@ measures but not in `breakdown`; split by a task metadata key
270
270
  This is for what the orchestrator knows. ERP and other app data stay in the
271
271
  app, and raw rows (a list of tasks or tool calls) are not metrics.
272
272
 
273
- A project reads only its own metrics. The project, the account and the
273
+ By default a project reads only its own metrics. The account and the
274
274
  environment are decided by the credentials the request is made with: a
275
275
  deployed app sees its production data, the same app in the workspace sees the
276
- workspace's. Nothing in a query names them, and there is no way to reach
277
- another's.
276
+ workspace's. Nothing in a query names them.
277
+
278
+ ### Reading other projects (dashboards)
279
+
280
+ A *dashboard* project can read the metrics of other projects with the optional
281
+ `project=` argument on `query`, `query_async`, `get_schema` and
282
+ `get_schema_async`: one project id, or a list of up to ten.
283
+
284
+ ```python
285
+ result = metrics.query(
286
+ event="task_created",
287
+ last_days=30,
288
+ unit="week",
289
+ breakdown="project_id", # tell the projects apart
290
+ project=["proj-a", "proj-b"], # or project="proj-a"
291
+ )
292
+ schema = metrics.get_schema(project="proj-a") # sent as ?project=proj-a
293
+ ```
294
+
295
+ - Only dashboard projects may pass it. From any other kind of project it is
296
+ refused.
297
+ - Only projects of the caller's own account (or the caller itself) can be named.
298
+ - The environment is always the caller's: a workspace dashboard reads workspace
299
+ data and a deployed one production data. There is no `mode` to pass.
300
+ - A refusal (not a dashboard, another account, an unknown project, too many
301
+ targets) raises the usual `MetricsError` with a 4xx `status_code`; the
302
+ message does not say which rule applied.
303
+ - A list is sent as a list and a string as a string; `get_schema` sends a list
304
+ as repeated `?project=` parameters. More than ten ids, an empty list or an
305
+ empty id raises `ValueError` before anything is sent.
306
+ - Leaving `project` out gives exactly the behaviour above: the caller's own
307
+ metrics, and nothing extra on the wire.
278
308
 
279
309
  Import the version you are writing against, bound to a short name as above. A
280
310
  version does not change under you: when the API changes it appears as a new
@@ -285,14 +315,14 @@ or `riffsdk.metrics` loads no version.
285
315
 
286
316
  - `query(*, series=None, event=None, measure=None, filters=None, from_=None,
287
317
  to=None, last_days=None, unit=None, breakdown=None, formula=None, limit=None,
288
- client=None)` -- returns a `MetricsResult`. Either `event=` (with `measure=`,
318
+ project=None, client=None)` -- returns a `MetricsResult`. Either `event=` (with `measure=`,
289
319
  default `count()`, and `filters=`) for one series, or `series=[{"id", "event",
290
320
  "measure", "filters"?}, ...]`. Give the time as `from_` (and optionally `to`,
291
321
  exclusive) -- a `datetime` (naive ones are taken as UTC) or an ISO 8601
292
322
  string -- or as `last_days=N`. `limit` keeps the top N breakdown combinations.
293
323
  `query_async` is the async form.
294
- - `get_schema(*, client=None)` -- what can be queried. `get_schema_async` is the
295
- async form.
324
+ - `get_schema(*, project=None, client=None)` -- what can be queried.
325
+ `get_schema_async` is the async form.
296
326
  - `MetricsResult` is the answer as JSON plus the `version` of that shape. Read
297
327
  it by key (`result["meta"]`, `result.get("series")`, or `result.data`), so
298
328
  the server gaining a field needs no SDK release. `result.series` is the list
@@ -256,11 +256,41 @@ measures but not in `breakdown`; split by a task metadata key
256
256
  This is for what the orchestrator knows. ERP and other app data stay in the
257
257
  app, and raw rows (a list of tasks or tool calls) are not metrics.
258
258
 
259
- A project reads only its own metrics. The project, the account and the
259
+ By default a project reads only its own metrics. The account and the
260
260
  environment are decided by the credentials the request is made with: a
261
261
  deployed app sees its production data, the same app in the workspace sees the
262
- workspace's. Nothing in a query names them, and there is no way to reach
263
- another's.
262
+ workspace's. Nothing in a query names them.
263
+
264
+ ### Reading other projects (dashboards)
265
+
266
+ A *dashboard* project can read the metrics of other projects with the optional
267
+ `project=` argument on `query`, `query_async`, `get_schema` and
268
+ `get_schema_async`: one project id, or a list of up to ten.
269
+
270
+ ```python
271
+ result = metrics.query(
272
+ event="task_created",
273
+ last_days=30,
274
+ unit="week",
275
+ breakdown="project_id", # tell the projects apart
276
+ project=["proj-a", "proj-b"], # or project="proj-a"
277
+ )
278
+ schema = metrics.get_schema(project="proj-a") # sent as ?project=proj-a
279
+ ```
280
+
281
+ - Only dashboard projects may pass it. From any other kind of project it is
282
+ refused.
283
+ - Only projects of the caller's own account (or the caller itself) can be named.
284
+ - The environment is always the caller's: a workspace dashboard reads workspace
285
+ data and a deployed one production data. There is no `mode` to pass.
286
+ - A refusal (not a dashboard, another account, an unknown project, too many
287
+ targets) raises the usual `MetricsError` with a 4xx `status_code`; the
288
+ message does not say which rule applied.
289
+ - A list is sent as a list and a string as a string; `get_schema` sends a list
290
+ as repeated `?project=` parameters. More than ten ids, an empty list or an
291
+ empty id raises `ValueError` before anything is sent.
292
+ - Leaving `project` out gives exactly the behaviour above: the caller's own
293
+ metrics, and nothing extra on the wire.
264
294
 
265
295
  Import the version you are writing against, bound to a short name as above. A
266
296
  version does not change under you: when the API changes it appears as a new
@@ -271,14 +301,14 @@ or `riffsdk.metrics` loads no version.
271
301
 
272
302
  - `query(*, series=None, event=None, measure=None, filters=None, from_=None,
273
303
  to=None, last_days=None, unit=None, breakdown=None, formula=None, limit=None,
274
- client=None)` -- returns a `MetricsResult`. Either `event=` (with `measure=`,
304
+ project=None, client=None)` -- returns a `MetricsResult`. Either `event=` (with `measure=`,
275
305
  default `count()`, and `filters=`) for one series, or `series=[{"id", "event",
276
306
  "measure", "filters"?}, ...]`. Give the time as `from_` (and optionally `to`,
277
307
  exclusive) -- a `datetime` (naive ones are taken as UTC) or an ISO 8601
278
308
  string -- or as `last_days=N`. `limit` keeps the top N breakdown combinations.
279
309
  `query_async` is the async form.
280
- - `get_schema(*, client=None)` -- what can be queried. `get_schema_async` is the
281
- async form.
310
+ - `get_schema(*, project=None, client=None)` -- what can be queried.
311
+ `get_schema_async` is the async form.
282
312
  - `MetricsResult` is the answer as JSON plus the `version` of that shape. Read
283
313
  it by key (`result["meta"]`, `result.get("series")`, or `result.data`), so
284
314
  the server gaining a field needs no SDK release. `result.series` is the list
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "riffsdk"
7
- version = "0.27.0"
7
+ version = "0.28.0"
8
8
  description = "Python SDK for the Riff Storage API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -217,7 +217,7 @@ class Transport:
217
217
  *,
218
218
  json: Any = None,
219
219
  content: bytes | None = None,
220
- params: dict[str, str] | None = None,
220
+ params: dict[str, str | list[str]] | None = None,
221
221
  headers: dict[str, str] | None = None,
222
222
  context: dict[str, str] | None = None,
223
223
  timeout: float | None = None,
@@ -331,7 +331,7 @@ class AsyncTransport:
331
331
  *,
332
332
  json: Any = None,
333
333
  content: bytes | None = None,
334
- params: dict[str, str] | None = None,
334
+ params: dict[str, str | list[str]] | None = None,
335
335
  headers: dict[str, str] | None = None,
336
336
  context: dict[str, str] | None = None,
337
337
  timeout: float | None = None,
@@ -136,7 +136,7 @@ class RiffClient:
136
136
  path: str,
137
137
  *,
138
138
  json: Any = None,
139
- params: dict[str, str] | None = None,
139
+ params: dict[str, str | list[str]] | None = None,
140
140
  headers: dict[str, str] | None = None,
141
141
  timeout: float | None = None,
142
142
  max_retries: int | None = None,
@@ -206,7 +206,7 @@ class AsyncRiffClient:
206
206
  path: str,
207
207
  *,
208
208
  json: Any = None,
209
- params: dict[str, str] | None = None,
209
+ params: dict[str, str | list[str]] | None = None,
210
210
  headers: dict[str, str] | None = None,
211
211
  timeout: float | None = None,
212
212
  max_retries: int | None = None,
@@ -46,10 +46,22 @@ The answer arrives as JSON with a ``version`` alongside it. Read it by key
46
46
  (``result["meta"]``, ``result.series``) rather than expecting a fixed set, so
47
47
  that the server gaining a field does not need a new SDK release.
48
48
 
49
- A project reads only its own metrics. The project, the account and the
50
- environment (workspace or production) are decided by the credentials the
49
+ By default a project reads only its own metrics. The project, the account and
50
+ the environment (workspace or production) are decided by the credentials the
51
51
  request is made with, never by anything in the query, so this module has no way
52
- to name them.
52
+ to name an account or an environment.
53
+
54
+ A *dashboard* project may also read other projects' metrics by passing
55
+ ``project=`` (one project id, or a list of up to ten) to :func:`query` or
56
+ :func:`get_schema`::
57
+
58
+ metrics.query(event="task_created", last_days=7, project=["proj-a", "proj-b"])
59
+
60
+ The server only honours it for a dashboard project, only for projects of the
61
+ same account as the caller (or the caller itself), and always in the caller's
62
+ own environment (a workspace dashboard reads workspace data, a deployed one
63
+ production data). Anything else is refused, with the same error whichever the
64
+ reason, as a :class:`MetricsError`. Without ``project=`` nothing changes.
53
65
  """
54
66
 
55
67
  from __future__ import annotations
@@ -103,6 +115,7 @@ _DOMAIN = "metrics"
103
115
  _URL_VERSION = "v0"
104
116
  _MAX_SERIES = 4
105
117
  _MAX_BREAKDOWNS = 2
118
+ _MAX_PROJECTS = 10
106
119
  _SINGLE_SERIES_ID = "a"
107
120
 
108
121
 
@@ -248,6 +261,33 @@ def where(prop: str, op: str, value: Any = _UNSET) -> dict[str, Any]:
248
261
  # -- building the request ----------------------------------------------------
249
262
 
250
263
 
264
+ def _project_selector(project: str | list[str] | None) -> str | list[str] | None:
265
+ """The ``project`` selector as it goes on the wire, or ``ValueError``.
266
+
267
+ A string stays a string and a list stays a list, so what the caller passed
268
+ is what the server sees. Whether the caller may read those projects is the
269
+ server's to decide.
270
+ """
271
+ if project is None:
272
+ return None
273
+ if isinstance(project, str):
274
+ if not project.strip():
275
+ raise ValueError("project must not be empty")
276
+ return project
277
+ if isinstance(project, (list, tuple)):
278
+ targets = list(project)
279
+ if not targets:
280
+ raise ValueError("project must not be an empty list")
281
+ if len(targets) > _MAX_PROJECTS:
282
+ raise ValueError(
283
+ f"at most {_MAX_PROJECTS} projects per query, got {len(targets)}"
284
+ )
285
+ if not all(isinstance(p, str) and p.strip() for p in targets):
286
+ raise ValueError("project entries must be non-empty project ids")
287
+ return targets
288
+ raise ValueError("project must be a project id or a list of project ids")
289
+
290
+
251
291
  def _iso_utc(name: str, value: datetime | date | str) -> str:
252
292
  """A time as an ISO 8601 string in UTC.
253
293
 
@@ -319,13 +359,15 @@ def _query_body(
319
359
  breakdown: str | list[str] | None,
320
360
  formula: str | None,
321
361
  limit: int | None,
362
+ project: str | list[str] | None = None,
322
363
  ) -> dict[str, Any]:
323
364
  """The JSON body of a query, or ``ValueError`` for one that cannot be valid.
324
365
 
325
366
  Only what is cheap to know is checked here: the shape, and the counts the
326
367
  server caps. Which events, properties, operators and units exist is the
327
368
  server's to say, so a catalogue that grows needs no new SDK release.
328
- Nothing here can name a project, an account or an environment.
369
+ Nothing here can name an account or an environment, and ``project`` is
370
+ left out of the body unless it was given.
329
371
  """
330
372
  body: dict[str, Any] = {
331
373
  "series": _series_list(series, event, measure, filters),
@@ -368,6 +410,9 @@ def _query_body(
368
410
  if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
369
411
  raise ValueError("limit must be a positive whole number")
370
412
  body["limit"] = limit
413
+ selector = _project_selector(project)
414
+ if selector is not None:
415
+ body["project"] = selector
371
416
  return body
372
417
 
373
418
 
@@ -478,6 +523,7 @@ def query(
478
523
  breakdown: str | list[str] | None = None,
479
524
  formula: str | None = None,
480
525
  limit: int | None = None,
526
+ project: str | list[str] | None = None,
481
527
  client: RiffClient | None = None,
482
528
  ) -> MetricsResult:
483
529
  """Run a metrics query and return its :class:`MetricsResult`.
@@ -501,8 +547,16 @@ def query(
501
547
  ``limit`` keeps the top N breakdown combinations (the server's default is
502
548
  20).
503
549
 
550
+ ``project`` reads another project's metrics instead of the caller's own: a
551
+ project id, or a list of up to ten (use ``breakdown="project_id"`` to tell
552
+ them apart). Only a dashboard project may pass it, only for projects of its
553
+ own account, and always in the caller's own environment; the server refuses
554
+ anything else with a :class:`MetricsError` (a 4xx that does not say which
555
+ rule applied). Leave it out for the caller's own metrics.
556
+
504
557
  Raises ``ValueError`` for a query that cannot be valid (no series or more
505
- than four, more than two breakdowns, ``last_days`` together with ``from_``).
558
+ than four, more than two breakdowns, ``last_days`` together with ``from_``,
559
+ an empty or more than ten ``project`` ids).
506
560
  Raises :class:`MetricsError` if the server rejected the query (``status_code``
507
561
  400 with its reason, or 422 if it is too expensive to run) or did not
508
562
  answer, including on a persistent 429/5xx after retrying (two attempts for a
@@ -524,6 +578,7 @@ def query(
524
578
  breakdown=breakdown,
525
579
  formula=formula,
526
580
  limit=limit,
581
+ project=project,
527
582
  )
528
583
  client = client or RiffClient.default()
529
584
  try:
@@ -546,6 +601,7 @@ async def query_async(
546
601
  breakdown: str | list[str] | None = None,
547
602
  formula: str | None = None,
548
603
  limit: int | None = None,
604
+ project: str | list[str] | None = None,
549
605
  client: AsyncRiffClient | None = None,
550
606
  ) -> MetricsResult:
551
607
  """Async form of :func:`query`."""
@@ -561,6 +617,7 @@ async def query_async(
561
617
  breakdown=breakdown,
562
618
  formula=formula,
563
619
  limit=limit,
620
+ project=project,
564
621
  )
565
622
  client = client or AsyncRiffClient.default()
566
623
  try:
@@ -570,27 +627,55 @@ async def query_async(
570
627
  return _to_result(resp)
571
628
 
572
629
 
573
- def get_schema(*, client: RiffClient | None = None) -> MetricsResult:
630
+ def _schema_params(
631
+ project: str | list[str] | None,
632
+ ) -> dict[str, str | list[str]] | None:
633
+ """The query string of a schema lookup: ``?project=a&project=b``.
634
+
635
+ A list goes as a repeated parameter. ``None`` sends no query string at all.
636
+ """
637
+ selector = _project_selector(project)
638
+ if selector is None:
639
+ return None
640
+ return {"project": selector}
641
+
642
+
643
+ def get_schema(
644
+ *, project: str | list[str] | None = None, client: RiffClient | None = None
645
+ ) -> MetricsResult:
574
646
  """What can be queried: events, their properties and types, the measures,
575
647
  filter operators and units (one list each, shared by all events), the
576
648
  limits, and this project's task metadata keys in the caller's environment.
577
649
 
578
- Call it before writing a query instead of guessing names. Raises
579
- :class:`MetricsError` if the lookup failed.
650
+ ``project`` asks about another project instead (a project id, or a list of
651
+ up to ten, sent as repeated ``?project=`` parameters), under the same rules
652
+ as :func:`query`: dashboard callers only, same account, caller's own
653
+ environment. Call it before writing a query instead of guessing names.
654
+ Raises :class:`MetricsError` if the lookup failed, including a refused
655
+ ``project``, and ``ValueError`` for an empty or more than ten ``project``
656
+ ids.
580
657
  """
658
+ params = _schema_params(project)
581
659
  client = client or RiffClient.default()
582
660
  try:
583
- resp = client.request("GET", _SCHEMA_PATH, timeout=_DEFAULT_TIMEOUT)
661
+ resp = client.request(
662
+ "GET", _SCHEMA_PATH, params=params, timeout=_DEFAULT_TIMEOUT
663
+ )
584
664
  except RetryableTransportError as e:
585
665
  raise MetricsError(str(e), status_code=e.status_code) from e
586
666
  return _to_result(resp)
587
667
 
588
668
 
589
- async def get_schema_async(*, client: AsyncRiffClient | None = None) -> MetricsResult:
669
+ async def get_schema_async(
670
+ *, project: str | list[str] | None = None, client: AsyncRiffClient | None = None
671
+ ) -> MetricsResult:
590
672
  """Async form of :func:`get_schema`."""
673
+ params = _schema_params(project)
591
674
  client = client or AsyncRiffClient.default()
592
675
  try:
593
- resp = await client.request("GET", _SCHEMA_PATH, timeout=_DEFAULT_TIMEOUT)
676
+ resp = await client.request(
677
+ "GET", _SCHEMA_PATH, params=params, timeout=_DEFAULT_TIMEOUT
678
+ )
594
679
  except RetryableTransportError as e:
595
680
  raise MetricsError(str(e), status_code=e.status_code) from e
596
681
  return _to_result(resp)
@@ -62,14 +62,24 @@ def test_the_documented_metrics_import_binds_the_version_to_a_short_name():
62
62
 
63
63
 
64
64
  def test_metrics_has_no_tenancy_concept():
65
- """Project, account and environment come from the credentials, not the call."""
65
+ """Account and environment come from the credentials, not the call.
66
+
67
+ ``project`` is allowed: it only selects other projects of the caller's own
68
+ account, which the server checks, and never widens to another account or mode.
69
+ """
66
70
  import inspect
67
71
 
68
72
  import riffsdk.metrics.v0 as metrics
69
73
 
70
- for fn in (metrics.query, metrics.query_async):
74
+ for fn in (
75
+ metrics.query,
76
+ metrics.query_async,
77
+ metrics.get_schema,
78
+ metrics.get_schema_async,
79
+ ):
71
80
  params = set(inspect.signature(fn).parameters)
72
81
  assert not params & {"project_id", "account_id", "mode", "scope"}
82
+ assert "project" in params
73
83
 
74
84
 
75
85
  def test_import_email_version():
@@ -626,6 +626,165 @@ class TestSchema:
626
626
  assert excinfo.value.status_code == 400
627
627
 
628
628
 
629
+ class TestProjectSelector:
630
+ """A dashboard may name other projects of its account; the default is untouched."""
631
+
632
+ def test_default_body_and_query_are_unchanged(self):
633
+ request, body = _sent()
634
+
635
+ assert "project" not in body
636
+ assert set(body) == {"series", "time"}
637
+ assert request.url.query == b""
638
+
639
+ def test_a_string_stays_a_string(self):
640
+ _, body = _sent(project="proj-2")
641
+
642
+ assert body["project"] == "proj-2"
643
+
644
+ def test_a_list_stays_a_list(self):
645
+ _, body = _sent(project=["proj-2", "proj-3"])
646
+
647
+ assert body["project"] == ["proj-2", "proj-3"]
648
+
649
+ def test_a_single_item_list_stays_a_list(self):
650
+ _, body = _sent(project=["proj-2"])
651
+
652
+ assert body["project"] == ["proj-2"]
653
+
654
+ def test_a_tuple_is_sent_as_a_list(self):
655
+ _, body = _sent(project=("proj-2", "proj-3"))
656
+
657
+ assert body["project"] == ["proj-2", "proj-3"]
658
+
659
+ def test_other_body_fields_are_unaffected(self):
660
+ _, with_project = _sent(project="proj-2", unit="week", limit=5)
661
+ _, without = _sent(unit="week", limit=5)
662
+
663
+ assert {k: v for k, v in with_project.items() if k != "project"}.keys() == (
664
+ without.keys()
665
+ )
666
+
667
+ def test_ten_projects_are_allowed(self):
668
+ ids = [f"proj-{i}" for i in range(10)]
669
+ _, body = _sent(project=ids)
670
+
671
+ assert body["project"] == ids
672
+
673
+ def test_eleven_projects_are_refused_before_sending(self):
674
+ calls: list[httpx.Request] = []
675
+
676
+ def handler(request: httpx.Request) -> httpx.Response:
677
+ calls.append(request)
678
+ return httpx.Response(200, json=_query_body())
679
+
680
+ with pytest.raises(ValueError, match="at most 10 projects"):
681
+ _call(handler, project=[f"proj-{i}" for i in range(11)])
682
+ assert calls == []
683
+
684
+ @pytest.mark.parametrize(
685
+ "bad", ["", " ", [], [""], ["proj-1", " "], [None], ["proj-1", 3], 7, {"a": 1}]
686
+ )
687
+ def test_invalid_selectors_are_refused_before_sending(self, bad):
688
+ calls: list[httpx.Request] = []
689
+
690
+ def handler(request: httpx.Request) -> httpx.Response:
691
+ calls.append(request)
692
+ return httpx.Response(200, json=_query_body())
693
+
694
+ with pytest.raises(ValueError, match="project"):
695
+ _call(handler, project=bad)
696
+ assert calls == []
697
+
698
+ def test_a_denial_raises_the_existing_error(self):
699
+ with pytest.raises(MetricsError) as excinfo:
700
+ _call(
701
+ lambda req: httpx.Response(403, json={"version": 1, "error": "denied"}),
702
+ project="proj-2",
703
+ )
704
+
705
+ assert excinfo.value.status_code == 403
706
+
707
+ def test_schema_default_has_no_query_string(self):
708
+ seen: list[httpx.Request] = []
709
+
710
+ def handler(request: httpx.Request) -> httpx.Response:
711
+ seen.append(request)
712
+ return httpx.Response(200, json={"version": 1})
713
+
714
+ with patch.dict(os.environ, ENV, clear=True), _mock_transport(handler):
715
+ get_schema(client=RiffClient(auth=_FakeAuth()))
716
+
717
+ assert seen[0].url.query == b""
718
+
719
+ def test_schema_sends_a_string_as_one_param(self):
720
+ seen: list[httpx.Request] = []
721
+
722
+ def handler(request: httpx.Request) -> httpx.Response:
723
+ seen.append(request)
724
+ return httpx.Response(200, json={"version": 1})
725
+
726
+ with patch.dict(os.environ, ENV, clear=True), _mock_transport(handler):
727
+ get_schema(project="proj-2", client=RiffClient(auth=_FakeAuth()))
728
+
729
+ assert seen[0].method == "GET"
730
+ assert seen[0].url.path == "/_projects/proj-1/sdk/v0/metrics/schema"
731
+ assert seen[0].url.params.get_list("project") == ["proj-2"]
732
+
733
+ def test_schema_repeats_the_param_for_a_list(self):
734
+ seen: list[httpx.Request] = []
735
+
736
+ def handler(request: httpx.Request) -> httpx.Response:
737
+ seen.append(request)
738
+ return httpx.Response(200, json={"version": 1})
739
+
740
+ with patch.dict(os.environ, ENV, clear=True), _mock_transport(handler):
741
+ get_schema(
742
+ project=["proj-2", "proj-3"], client=RiffClient(auth=_FakeAuth())
743
+ )
744
+
745
+ assert seen[0].url.query == b"project=proj-2&project=proj-3"
746
+
747
+ def test_schema_validates_the_selector(self):
748
+ with pytest.raises(ValueError, match="at most 10 projects"):
749
+ get_schema(project=[f"p{i}" for i in range(11)])
750
+ with pytest.raises(ValueError, match="empty"):
751
+ get_schema(project=[])
752
+
753
+ @pytest.mark.asyncio
754
+ async def test_query_async_sends_the_selector(self):
755
+ seen: list[httpx.Request] = []
756
+
757
+ def handler(request: httpx.Request) -> httpx.Response:
758
+ seen.append(request)
759
+ return httpx.Response(200, json=_query_body())
760
+
761
+ with patch.dict(os.environ, ENV, clear=True), _mock_transport(handler):
762
+ await query_async(
763
+ event="x",
764
+ from_=FROM,
765
+ project=["proj-2", "proj-3"],
766
+ client=AsyncRiffClient(auth=_FakeAuth()),
767
+ )
768
+
769
+ assert json.loads(seen[0].content)["project"] == ["proj-2", "proj-3"]
770
+
771
+ @pytest.mark.asyncio
772
+ async def test_schema_async_sends_the_selector(self):
773
+ seen: list[httpx.Request] = []
774
+
775
+ def handler(request: httpx.Request) -> httpx.Response:
776
+ seen.append(request)
777
+ return httpx.Response(200, json={"version": 1})
778
+
779
+ with patch.dict(os.environ, ENV, clear=True), _mock_transport(handler):
780
+ await get_schema_async(
781
+ project=["proj-2", "proj-3"],
782
+ client=AsyncRiffClient(auth=_FakeAuth()),
783
+ )
784
+
785
+ assert seen[0].url.params.get_list("project") == ["proj-2", "proj-3"]
786
+
787
+
629
788
  class TestSandbox:
630
789
  """Inside a sandbox the request goes over the egress socket."""
631
790
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes