github-statistics 0.1.0__tar.gz → 0.2.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 (88) hide show
  1. {github_statistics-0.1.0 → github_statistics-0.2.0}/PKG-INFO +69 -2
  2. {github_statistics-0.1.0 → github_statistics-0.2.0}/README.md +68 -1
  3. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/_version.py +2 -2
  4. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/app.py +48 -0
  5. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/collect.py +85 -13
  6. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/options.py +7 -0
  7. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/run.py +17 -3
  8. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/client/budget.py +68 -15
  9. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/run.py +54 -28
  10. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/steps.py +105 -4
  11. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/config/loader.py +2 -0
  12. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/config/models.py +3 -0
  13. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/config/schema.py +1 -0
  14. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/render/bars3d.py +78 -180
  15. github_statistics-0.2.0/src/github_statistics/render/furniture.py +145 -0
  16. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/render/layout.py +8 -5
  17. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/render/model.py +1 -1
  18. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/series/daily.py +10 -3
  19. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/series/leaderboard.py +3 -2
  20. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/series/repositories.py +4 -5
  21. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/store/aggregates.py +36 -31
  22. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/store/models.py +4 -2
  23. {github_statistics-0.1.0 → github_statistics-0.2.0}/.gitignore +0 -0
  24. {github_statistics-0.1.0 → github_statistics-0.2.0}/LICENSE +0 -0
  25. {github_statistics-0.1.0 → github_statistics-0.2.0}/LICENSES/Apache-2.0.txt +0 -0
  26. {github_statistics-0.1.0 → github_statistics-0.2.0}/pyproject.toml +0 -0
  27. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/__init__.py +0 -0
  28. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/__main__.py +0 -0
  29. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/__init__.py +0 -0
  30. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/cache.py +0 -0
  31. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/common.py +0 -0
  32. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/config.py +0 -0
  33. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/doctor.py +0 -0
  34. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/export.py +0 -0
  35. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/render.py +0 -0
  36. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/scope.py +0 -0
  37. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/cli/site.py +0 -0
  38. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/client/__init__.py +0 -0
  39. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/client/accounting.py +0 -0
  40. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/client/cooldown.py +0 -0
  41. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/client/errors.py +0 -0
  42. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/client/graphql.py +0 -0
  43. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/client/paging.py +0 -0
  44. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/client/policy.py +0 -0
  45. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/client/transport.py +0 -0
  46. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/__init__.py +0 -0
  47. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/common.py +0 -0
  48. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/enrich_items.py +0 -0
  49. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/items.py +0 -0
  50. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/jobs.py +0 -0
  51. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/listed.py +0 -0
  52. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/members.py +0 -0
  53. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/reader.py +0 -0
  54. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/runs.py +0 -0
  55. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/slices.py +0 -0
  56. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/collect/sweep.py +0 -0
  57. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/config/__init__.py +0 -0
  58. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/export/__init__.py +0 -0
  59. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/export/csv.py +0 -0
  60. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/export/documents.py +0 -0
  61. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/export/json.py +0 -0
  62. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/py.typed +0 -0
  63. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/render/__init__.py +0 -0
  64. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/render/charts.py +0 -0
  65. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/render/demo.py +0 -0
  66. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/render/images.py +0 -0
  67. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/render/palette.py +0 -0
  68. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/scope/__init__.py +0 -0
  69. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/scope/apply.py +0 -0
  70. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/scope/resolver.py +0 -0
  71. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/series/__init__.py +0 -0
  72. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/series/actors.py +0 -0
  73. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/series/coverage.py +0 -0
  74. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/site/__init__.py +0 -0
  75. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/site/assets/site.css +0 -0
  76. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/site/build.py +0 -0
  77. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/site/templates/base.html.j2 +0 -0
  78. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/site/templates/index.html.j2 +0 -0
  79. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/site/templates/macros.html.j2 +0 -0
  80. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/site/templates/site.js.j2 +0 -0
  81. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/site/templates/target.html.j2 +0 -0
  82. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/store/__init__.py +0 -0
  83. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/store/activity.py +0 -0
  84. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/store/base.py +0 -0
  85. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/store/codec.py +0 -0
  86. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/store/paths.py +0 -0
  87. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/store/schema.py +0 -0
  88. {github_statistics-0.1.0 → github_statistics-0.2.0}/src/github_statistics/store/sqlite.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: github-statistics
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Daily, visual activity statistics for GitHub organisations and repositories
5
5
  Project-URL: Homepage, https://github.com/lfreleng-actions/github-statistics-action
6
6
  Project-URL: Repository, https://github.com/lfreleng-actions/github-statistics-action
@@ -63,7 +63,11 @@ action wraps it for use in workflows.
63
63
 
64
64
  ## 🗒️ Published reports
65
65
 
66
- The link to the published site will appear here once the site goes live.
66
+ <https://lfreleng-actions.github.io/github-statistics-action/>
67
+
68
+ The [daily workflow](.github/workflows/statistics.yaml) rebuilds the
69
+ site at 05:00 UTC; see [Secrets and variables](#secrets-and-variables)
70
+ for its settings.
67
71
 
68
72
  ## Usage
69
73
 
@@ -120,6 +124,7 @@ commas, spaces or newlines between items.
120
124
  | `output_dir` | Site root (default `site`) |
121
125
  | `cache_dir` | Store root (default `~/.cache/github-statistics`) |
122
126
  | `budget` | REST requests this run may spend |
127
+ | `max_minutes` | Minutes collection may take (default: no limit); the stages after it still run |
123
128
  | `refresh` | `true` to ignore watermarks and re-read the window (`run`) |
124
129
  | `strict` | `true` to exit 2 when a repository was unreadable (`run`) |
125
130
  | `org_bots` | The organisation's own bots; replaces the configured list |
@@ -271,6 +276,53 @@ inputs that become them; `targets[].identities` for that target;
271
276
  top-level `identities`; the built-in defaults, which are empty lists
272
277
  and `member_orgs` equal to the target owner.
273
278
 
279
+ ## Secrets and variables
280
+
281
+ `.github/workflows/statistics.yaml` collects, renders and deploys the
282
+ published site every day, and on `workflow_dispatch` with optional
283
+ `repositories`, `refresh` and `use_local_source` inputs. It reads
284
+ these from the `production` environment, the repository or the
285
+ organisation, and the nearest one of a name wins:
286
+
287
+ <!-- markdownlint-disable MD013 -->
288
+
289
+ | Name | Kind | Purpose |
290
+ | --------------------------- | ------------------ | ------------------------------------------------------------------------------- |
291
+ | `LF_RELENG_BOT_CLIENT_ID` | Variable | Client ID of the organisation App that mints the read token |
292
+ | `LF_RELENG_BOT_PRIVATE_KEY` | Secret | Private key of that App |
293
+ | `GHS_CONFIG` | Secret or variable | Configuration JSON, raw or base64; the secret wins when both exist |
294
+ | `GHS_STORE_KEY` | Secret | Passphrase that encrypts the store in the cache and the artifact |
295
+ | `GHS_ORG_BOTS` | Variable | Feeds the `org_bots` input |
296
+ | `GHS_EXTERNAL_BOTS` | Variable | Feeds the `external_bots` input |
297
+ | `GHS_MEMBERS` | Variable | Feeds the `members` input |
298
+ | `GHS_MEMBER_ORGS` | Variable | Feeds the `member_orgs` input |
299
+ | `GHS_IGNORE_LOGINS` | Variable | Feeds the `ignore_logins` input |
300
+ | `SLACK_BOT_TOKEN` | Secret | Bot token that posts the failure notice |
301
+ | `SLACK_CHANNEL_ID` | Variable | Channel for the failure notice |
302
+
303
+ <!-- markdownlint-enable MD013 -->
304
+
305
+ Every one is optional except the App pair, which the workflow needs
306
+ whenever the scope holds a repository. The action passes its token to
307
+ the tool as `GITHUB_TOKEN`, so a `GHS_CONFIG` must leave each target's
308
+ `token_env` at its default. The workflow sets the store root itself:
309
+ a `cache.directory` in `GHS_CONFIG` has no effect there. Without
310
+ `GHS_STORE_KEY` the workflow neither restores nor saves the store and
311
+ says so in a notice; each run then backfills from empty. Without both
312
+ Slack settings the workflow sends no failure notice and warns instead.
313
+
314
+ The App token names the public repositories the scope resolves to,
315
+ with read access alone and no organisation permission, so it cannot
316
+ read a private repository. An App token names at most 500
317
+ repositories: an organisation with more fails the run, and needs a
318
+ fine-grained personal access token limited to public repositories
319
+ instead. The workflow restores the store from the Actions cache, or
320
+ on a miss from the newest `github-statistics-store` artifact uploaded
321
+ by its own scheduled or dispatched runs on the default branch.
322
+
323
+ Before the first run, set the repository's Pages source to GitHub
324
+ Actions.
325
+
274
326
  ## Running locally
275
327
 
276
328
  [uv](https://docs.astral.sh/uv/) runs a published release without
@@ -285,6 +337,21 @@ uvx github-statistics scope --org lfreleng-actions --format csv
285
337
 
286
338
  Open `site/index.html` in a browser to view the result.
287
339
 
340
+ `--max-minutes N` stops collection `N` minutes after the command
341
+ starts, as a spent budget does: the run exits 0 and still renders,
342
+ exports and builds the site, and the next run resumes. It overrides
343
+ `budget.minutes`, which sets no time limit by default.
344
+
345
+ ### Logging
346
+
347
+ Every command logs its progress to stderr at `INFO`: each `collect`
348
+ step as it starts and ends, with the REST requests and GraphQL points
349
+ spent and left, and a line per repository per step with what it read
350
+ and stored. Timestamps are in UTC. Set `--log-level` (`debug`, `info`,
351
+ `warning` or `error`) before the command, or `GHS_LOG_LEVEL`; the
352
+ option wins. Log lines never carry a token. The summary tables stay on
353
+ stdout.
354
+
288
355
  ## Development
289
356
 
290
357
  The project uses [uv](https://docs.astral.sh/uv/) and needs Python
@@ -19,7 +19,11 @@ action wraps it for use in workflows.
19
19
 
20
20
  ## 🗒️ Published reports
21
21
 
22
- The link to the published site will appear here once the site goes live.
22
+ <https://lfreleng-actions.github.io/github-statistics-action/>
23
+
24
+ The [daily workflow](.github/workflows/statistics.yaml) rebuilds the
25
+ site at 05:00 UTC; see [Secrets and variables](#secrets-and-variables)
26
+ for its settings.
23
27
 
24
28
  ## Usage
25
29
 
@@ -76,6 +80,7 @@ commas, spaces or newlines between items.
76
80
  | `output_dir` | Site root (default `site`) |
77
81
  | `cache_dir` | Store root (default `~/.cache/github-statistics`) |
78
82
  | `budget` | REST requests this run may spend |
83
+ | `max_minutes` | Minutes collection may take (default: no limit); the stages after it still run |
79
84
  | `refresh` | `true` to ignore watermarks and re-read the window (`run`) |
80
85
  | `strict` | `true` to exit 2 when a repository was unreadable (`run`) |
81
86
  | `org_bots` | The organisation's own bots; replaces the configured list |
@@ -227,6 +232,53 @@ inputs that become them; `targets[].identities` for that target;
227
232
  top-level `identities`; the built-in defaults, which are empty lists
228
233
  and `member_orgs` equal to the target owner.
229
234
 
235
+ ## Secrets and variables
236
+
237
+ `.github/workflows/statistics.yaml` collects, renders and deploys the
238
+ published site every day, and on `workflow_dispatch` with optional
239
+ `repositories`, `refresh` and `use_local_source` inputs. It reads
240
+ these from the `production` environment, the repository or the
241
+ organisation, and the nearest one of a name wins:
242
+
243
+ <!-- markdownlint-disable MD013 -->
244
+
245
+ | Name | Kind | Purpose |
246
+ | --------------------------- | ------------------ | ------------------------------------------------------------------------------- |
247
+ | `LF_RELENG_BOT_CLIENT_ID` | Variable | Client ID of the organisation App that mints the read token |
248
+ | `LF_RELENG_BOT_PRIVATE_KEY` | Secret | Private key of that App |
249
+ | `GHS_CONFIG` | Secret or variable | Configuration JSON, raw or base64; the secret wins when both exist |
250
+ | `GHS_STORE_KEY` | Secret | Passphrase that encrypts the store in the cache and the artifact |
251
+ | `GHS_ORG_BOTS` | Variable | Feeds the `org_bots` input |
252
+ | `GHS_EXTERNAL_BOTS` | Variable | Feeds the `external_bots` input |
253
+ | `GHS_MEMBERS` | Variable | Feeds the `members` input |
254
+ | `GHS_MEMBER_ORGS` | Variable | Feeds the `member_orgs` input |
255
+ | `GHS_IGNORE_LOGINS` | Variable | Feeds the `ignore_logins` input |
256
+ | `SLACK_BOT_TOKEN` | Secret | Bot token that posts the failure notice |
257
+ | `SLACK_CHANNEL_ID` | Variable | Channel for the failure notice |
258
+
259
+ <!-- markdownlint-enable MD013 -->
260
+
261
+ Every one is optional except the App pair, which the workflow needs
262
+ whenever the scope holds a repository. The action passes its token to
263
+ the tool as `GITHUB_TOKEN`, so a `GHS_CONFIG` must leave each target's
264
+ `token_env` at its default. The workflow sets the store root itself:
265
+ a `cache.directory` in `GHS_CONFIG` has no effect there. Without
266
+ `GHS_STORE_KEY` the workflow neither restores nor saves the store and
267
+ says so in a notice; each run then backfills from empty. Without both
268
+ Slack settings the workflow sends no failure notice and warns instead.
269
+
270
+ The App token names the public repositories the scope resolves to,
271
+ with read access alone and no organisation permission, so it cannot
272
+ read a private repository. An App token names at most 500
273
+ repositories: an organisation with more fails the run, and needs a
274
+ fine-grained personal access token limited to public repositories
275
+ instead. The workflow restores the store from the Actions cache, or
276
+ on a miss from the newest `github-statistics-store` artifact uploaded
277
+ by its own scheduled or dispatched runs on the default branch.
278
+
279
+ Before the first run, set the repository's Pages source to GitHub
280
+ Actions.
281
+
230
282
  ## Running locally
231
283
 
232
284
  [uv](https://docs.astral.sh/uv/) runs a published release without
@@ -241,6 +293,21 @@ uvx github-statistics scope --org lfreleng-actions --format csv
241
293
 
242
294
  Open `site/index.html` in a browser to view the result.
243
295
 
296
+ `--max-minutes N` stops collection `N` minutes after the command
297
+ starts, as a spent budget does: the run exits 0 and still renders,
298
+ exports and builds the site, and the next run resumes. It overrides
299
+ `budget.minutes`, which sets no time limit by default.
300
+
301
+ ### Logging
302
+
303
+ Every command logs its progress to stderr at `INFO`: each `collect`
304
+ step as it starts and ends, with the REST requests and GraphQL points
305
+ spent and left, and a line per repository per step with what it read
306
+ and stored. Timestamps are in UTC. Set `--log-level` (`debug`, `info`,
307
+ `warning` or `error`) before the command, or `GHS_LOG_LEVEL`; the
308
+ option wins. Log lines never carry a token. The summary tables stay on
309
+ stdout.
310
+
244
311
  ## Development
245
312
 
246
313
  The project uses [uv](https://docs.astral.sh/uv/) and needs Python
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.1.0'
22
- __version_tuple__ = version_tuple = (0, 1, 0)
21
+ __version__ = version = '0.2.0'
22
+ __version_tuple__ = version_tuple = (0, 2, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -4,8 +4,11 @@
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
+ import logging
8
+ import sys
7
9
  import time
8
10
  from datetime import UTC, date, datetime, timedelta
11
+ from enum import StrEnum
9
12
  from pathlib import Path
10
13
 
11
14
  import typer
@@ -25,6 +28,10 @@ from .site import site
25
28
  DERIVATIVE_WIDTH = 1920
26
29
  DEMO_MIN_DAYS = 7
27
30
  DEMO_MAX_DAYS = 730
31
+ LOG_FORMAT = "%(asctime)s %(levelname)s %(message)s"
32
+ LOG_HANDLER = "github-statistics"
33
+ # httpx logs every request URL at INFO; these speak only at DEBUG.
34
+ QUIET_LOGGERS = ("httpx", "httpcore", "matplotlib")
28
35
 
29
36
  app = typer.Typer(
30
37
  name="github-statistics",
@@ -49,6 +56,39 @@ def _version_callback(value: bool) -> None:
49
56
  raise typer.Exit()
50
57
 
51
58
 
59
+ class LogLevel(StrEnum):
60
+ """The levels ``--log-level`` accepts."""
61
+
62
+ DEBUG = "debug"
63
+ INFO = "info"
64
+ WARNING = "warning"
65
+ ERROR = "error"
66
+
67
+
68
+ def configure_logging(level: LogLevel) -> None:
69
+ """Log to stderr at ``level``, with UTC timestamps.
70
+
71
+ A handler is added only when the root logger has none. Third-party
72
+ loggers stay at WARNING unless ``level`` is DEBUG; the handler takes
73
+ ``level`` too, since their records skip the root logger's own level.
74
+ """
75
+ numeric = logging.getLevelName(level.value.upper())
76
+ handler = logging.StreamHandler(sys.stderr)
77
+ handler.set_name(LOG_HANDLER)
78
+ formatter = logging.Formatter(LOG_FORMAT)
79
+ formatter.converter = time.gmtime
80
+ handler.setFormatter(formatter)
81
+ logging.basicConfig(level=numeric, handlers=[handler])
82
+ root = logging.getLogger()
83
+ root.setLevel(numeric)
84
+ for installed in root.handlers:
85
+ if installed.get_name() == LOG_HANDLER:
86
+ installed.setLevel(numeric)
87
+ quiet = logging.DEBUG if level is LogLevel.DEBUG else logging.WARNING
88
+ for name in QUIET_LOGGERS:
89
+ logging.getLogger(name).setLevel(quiet)
90
+
91
+
52
92
  @app.callback()
53
93
  def main(
54
94
  version: bool = typer.Option(
@@ -59,8 +99,16 @@ def main(
59
99
  callback=_version_callback,
60
100
  is_eager=True,
61
101
  ),
102
+ log_level: LogLevel = typer.Option(
103
+ LogLevel.INFO,
104
+ "--log-level",
105
+ envvar="GHS_LOG_LEVEL",
106
+ case_sensitive=False,
107
+ help="Level of the progress log written to stderr.",
108
+ ),
62
109
  ) -> None:
63
110
  """Daily, visual activity statistics for GitHub organisations and repositories."""
111
+ configure_logging(log_level)
64
112
 
65
113
 
66
114
  def _yesterday() -> date:
@@ -4,18 +4,22 @@
4
4
 
5
5
  Each target syncs into its own store under its own budget, and the
6
6
  command prints a short table of what each did. A spent budget exits 0:
7
- a cold start takes several runs. ``--strict`` exits 2 once every target
8
- is done if any repository was unreadable; a rejected token exits 3 at
9
- once, naming the variable that holds it, never its value.
7
+ a cold start takes several runs. So does a run that reaches its time
8
+ limit, ``--max-minutes`` from the command's start, which the budget
9
+ treats as spent. ``--strict`` exits 2 once every target is done if any
10
+ repository was unreadable; a rejected token exits 3 at once, naming the
11
+ variable that holds it, never its value.
10
12
  """
11
13
 
12
14
  from __future__ import annotations
13
15
 
14
16
  import asyncio
15
17
  import contextlib
16
- from collections.abc import Sequence
18
+ import dataclasses
19
+ from collections.abc import Awaitable, Callable, Sequence
17
20
  from datetime import UTC, date, datetime
18
21
  from pathlib import Path
22
+ from time import monotonic
19
23
 
20
24
  import httpx
21
25
  import typer
@@ -44,10 +48,34 @@ from .options import SharedOptions, shared_options
44
48
 
45
49
  STRICT_EXIT = 2
46
50
  AUTH_EXIT = 3
51
+ TIME_LIMIT = "time limit reached"
47
52
 
48
53
  _Table = tuple[str, list[str], list[list[str]]]
49
54
 
50
55
 
56
+ def _backoff_within(
57
+ budget: Budget,
58
+ *,
59
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
60
+ ) -> Callable[[float], Awaitable[None]]:
61
+ """A transport's backoff ``sleep`` that ends at ``budget``'s deadline.
62
+
63
+ No retry starts at or past the deadline, not even one of the
64
+ uncharged ``GET /rate_limit`` seed, which the budget never refuses:
65
+ a backoff that would end later waits until the deadline, so a
66
+ rate-limit pause still holds until then, and raises
67
+ ``BudgetExhaustedError``, as does one that wakes with time up.
68
+ """
69
+
70
+ async def backoff(delay: float) -> None:
71
+ left = delay if budget.deadline is None else budget.deadline - budget.clock()
72
+ await sleep(max(min(delay, left), 0))
73
+ if left < delay or budget.timed_out:
74
+ raise BudgetExhaustedError("time limit reached; not retrying")
75
+
76
+ return backoff
77
+
78
+
51
79
  async def _collect_target(
52
80
  resolution: Resolution,
53
81
  target: Target,
@@ -55,26 +83,41 @@ async def _collect_target(
55
83
  now: datetime,
56
84
  until: date | None,
57
85
  refresh: bool,
86
+ deadline: float | None,
58
87
  ) -> CollectResult:
59
88
  """Collect ``target`` with its own transport, budget and store.
60
89
 
61
90
  ``until`` ends the window, by default the day before ``now``.
91
+ ``deadline``, a `monotonic` time, ends the reads like a spent
92
+ budget. The step it stopped is marked `TIME_LIMIT`; when a count
93
+ stopped an earlier step first, that step is named and the time
94
+ limit noted as reached later.
62
95
  """
63
96
  config = resolution.config
64
97
  limits = config.budget
65
98
  budget = Budget(
66
- rest=limits.rest, graphql_points=limits.graphql_points, reserve=limits.reserve
99
+ rest=limits.rest,
100
+ graphql_points=limits.graphql_points,
101
+ reserve=limits.reserve,
102
+ deadline=deadline,
103
+ clock=monotonic,
67
104
  )
68
105
  directory = config.cache.directory
69
106
  cache = Path(directory) if directory else default_cache_dir()
70
- async with Transport(resolve_token(target), budget=budget) as transport:
107
+ async with Transport(
108
+ resolve_token(target), budget=budget, sleep=_backoff_within(budget)
109
+ ) as transport:
71
110
  # A rate limit outlasting the retries has stopped the transport:
72
111
  # collect then sends nothing and reports its scope step spent.
73
- with contextlib.suppress(BudgetExhaustedError):
74
- await transport.seed_budget()
112
+ # Past the deadline, as an earlier target may leave it, the seed
113
+ # is skipped too, and collect only reports what is stored; one
114
+ # whose retries reach the deadline stops the same way.
115
+ if not budget.timed_out:
116
+ with contextlib.suppress(BudgetExhaustedError):
117
+ await transport.seed_budget()
75
118
  host = httpx.URL(transport.api_url).host
76
119
  with Store(store_path(cache, host, target.owner)) as store:
77
- return await collect(
120
+ result = await collect(
78
121
  config,
79
122
  target,
80
123
  now=now,
@@ -84,6 +127,20 @@ async def _collect_target(
84
127
  refresh=refresh,
85
128
  until=until,
86
129
  )
130
+ if result.exhausted and budget.timed_out:
131
+ # The step named is the first one stopped: the time limit's own,
132
+ # unless a count stopped the run before the deadline did.
133
+ if budget.stopped_by_count:
134
+ exhausted = f"{result.exhausted}; {TIME_LIMIT} later"
135
+ else:
136
+ exhausted = f"{result.exhausted} ({TIME_LIMIT})"
137
+ result = dataclasses.replace(result, exhausted=exhausted)
138
+ return result
139
+
140
+
141
+ def collection_deadline(minutes: int | None) -> float | None:
142
+ """The `monotonic` time ``minutes`` from now; ``None`` for no limit."""
143
+ return None if minutes is None else monotonic() + minutes * 60
87
144
 
88
145
 
89
146
  def _tables(results: Sequence[CollectResult]) -> list[_Table]:
@@ -151,15 +208,24 @@ def collect_target(
151
208
  now: datetime,
152
209
  until: date | None,
153
210
  refresh: bool,
211
+ deadline: float | None = None,
154
212
  ) -> CollectResult:
155
213
  """Collect ``target``; a rejected token or a failed read raises the exit to raise.
156
214
 
157
- A rejected token exits `AUTH_EXIT`, naming the variable that holds
158
- it, never its value; any other client failure exits 1.
215
+ ``deadline``, from `collection_deadline`, bounds the reads. A
216
+ rejected token exits `AUTH_EXIT`, naming the variable that holds it,
217
+ never its value; any other client failure exits 1.
159
218
  """
160
219
  try:
161
220
  return asyncio.run(
162
- _collect_target(resolution, target, now=now, until=until, refresh=refresh)
221
+ _collect_target(
222
+ resolution,
223
+ target,
224
+ now=now,
225
+ until=until,
226
+ refresh=refresh,
227
+ deadline=deadline,
228
+ )
163
229
  )
164
230
  except AuthError:
165
231
  raise fail(
@@ -206,10 +272,16 @@ def collect_command(
206
272
  resolution = options.resolve()
207
273
  except ConfigError as exc:
208
274
  raise fail(str(exc)) from None
275
+ deadline = collection_deadline(resolution.config.budget.minutes)
209
276
  now = datetime.now(UTC)
210
277
  results = [
211
278
  collect_target(
212
- resolution, target, now=now, until=options.until, refresh=refresh
279
+ resolution,
280
+ target,
281
+ now=now,
282
+ until=options.until,
283
+ refresh=refresh,
284
+ deadline=deadline,
213
285
  )
214
286
  for target in resolution.config.targets
215
287
  ]
@@ -76,6 +76,7 @@ def _build(**values: Any) -> SharedOptions:
76
76
  output_dir=values["output_dir"] or None,
77
77
  cache_dir=values["cache_dir"] or None,
78
78
  budget=values["budget"],
79
+ max_minutes=values["max_minutes"],
79
80
  token_env=values["token_env"] or None,
80
81
  identities=Identities(
81
82
  org_bots=_identity(values["org_bots"]),
@@ -131,6 +132,12 @@ def _parameters() -> list[inspect.Parameter]:
131
132
  _option("output_dir", text, "DIR", "Site root."),
132
133
  _option("cache_dir", text, "DIR", "Store root."),
133
134
  _option("budget", number, "N", "REST requests this run may spend."),
135
+ _option(
136
+ "max_minutes",
137
+ number,
138
+ "N",
139
+ "Minutes collection may take (default: no limit).",
140
+ ),
134
141
  _option("token_env", text, "NAME", "Environment variable holding the token."),
135
142
  _option(
136
143
  "org_bots", lists, "LOGINS", f"The organisation's bots; {_IDENTITY_HELP}."
@@ -6,7 +6,9 @@ For each target in turn ``run`` clears the target's ``img/`` and
6
6
  ``data/`` directories, then collects, renders, exports and reads what
7
7
  the target's pages show; the pages and the landing page are written
8
8
  once, after every target. A spent budget is not a failure: rendering
9
- and the site go on, and the charts show the gaps. A rejected token or
9
+ and the site go on, and the charts show the gaps. Neither is the time
10
+ limit, which bounds collection alone: it counts from the command's
11
+ start, and the stages that need no network always run. A rejected token or
10
12
  an invalid configuration stops the run before anything is rendered.
11
13
  Exit codes are those of ``collect``: 1 for an invalid configuration or
12
14
  a failed stage, 2 with ``--strict`` once the site is written if a
@@ -26,7 +28,13 @@ import typer
26
28
  from github_statistics.config import ConfigError, Resolution, Target, default_cache_dir
27
29
  from github_statistics.store import path_component, store_path
28
30
 
29
- from .collect import STRICT_EXIT, collect_outputs, collect_target, report
31
+ from .collect import (
32
+ STRICT_EXIT,
33
+ collect_outputs,
34
+ collect_target,
35
+ collection_deadline,
36
+ report,
37
+ )
30
38
  from .common import (
31
39
  API_HOST,
32
40
  ReadOnlyStore,
@@ -98,6 +106,7 @@ def run(
98
106
  except ConfigError as exc:
99
107
  raise fail(str(exc)) from None
100
108
  config = resolution.config
109
+ deadline = collection_deadline(config.budget.minutes)
101
110
  now = datetime.now(UTC)
102
111
  until = options.until or now.date() - timedelta(days=1)
103
112
  output_dir = Path(config.output.directory)
@@ -108,7 +117,12 @@ def run(
108
117
  clear_target_output(output_dir, target.owner)
109
118
  results.append(
110
119
  collect_target(
111
- resolution, target, now=now, until=options.until, refresh=refresh
120
+ resolution,
121
+ target,
122
+ now=now,
123
+ until=options.until,
124
+ refresh=refresh,
125
+ deadline=deadline,
112
126
  )
113
127
  )
114
128
  _echo(render_targets(resolution, [target], until=until, now=now))
@@ -6,12 +6,16 @@ The budget is a courtesy limit, not exact accounting: GitHub enforces
6
6
  the real rate limit, and the transport backs off on it. The budget lets
7
7
  a run stop cleanly and leave headroom for other consumers. Nothing here
8
8
  raises; the transport raises ``BudgetExhaustedError`` when a reservation
9
- is refused, and a collector that meets it stops cleanly.
9
+ is refused, and a collector that meets it stops cleanly. An optional
10
+ deadline ends the run the same way: once it passes, the budget reports
11
+ itself spent.
10
12
  """
11
13
 
12
14
  from __future__ import annotations
13
15
 
14
- from dataclasses import dataclass
16
+ import time
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass, field
15
19
 
16
20
  DEFAULT_REST = 3000
17
21
  DEFAULT_GRAPHQL_POINTS = 1500
@@ -40,8 +44,20 @@ class Budget:
40
44
  ``rest`` bounds the run. Exactness beyond that is a non-goal.
41
45
 
42
46
  A GraphQL rate limit stops the GraphQL budget for the rest of the
43
- run: ``graphql_stopped`` is never cleared, so a query that settles
44
- afterwards cannot reopen it.
47
+ run: ``graphql_rate_limited`` is never cleared, so a query that
48
+ settles afterwards cannot reopen it.
49
+
50
+ ``deadline``, a time on ``clock`` (``time.monotonic`` unless a test
51
+ injects another), bounds how long the run may take: from it on,
52
+ every reservation is refused as if both counts were spent, and
53
+ ``timed_out`` tells the two apart. Requests already in flight finish;
54
+ ``graphql_stopped`` then keeps a query that holds its points but has
55
+ not been sent, or would retry, from sending. ``stopped_by_count``
56
+ records that a count or a GraphQL rate limit stopped the run before
57
+ the deadline did, so a report can tell which stopped it first. Only
58
+ a stop counts: a refused reservation, a count found spent where a
59
+ caller stops on it, or a rate limit; points a queued query holds
60
+ and then gives back do not.
45
61
  """
46
62
 
47
63
  rest: int = DEFAULT_REST
@@ -51,7 +67,12 @@ class Budget:
51
67
  graphql_spent: int = 0
52
68
  remaining: int | None = None
53
69
  reset: int | None = None
54
- graphql_stopped: bool = False
70
+ graphql_rate_limited: bool = False
71
+ deadline: float | None = None
72
+ clock: Callable[[], float] = field(
73
+ default=time.monotonic, repr=False, compare=False
74
+ )
75
+ stopped_by_count: bool = field(default=False, init=False)
55
76
 
56
77
  def observe(self, remaining: int, reset: int | None = None) -> None:
57
78
  """Take the core ``remaining`` count of the window ending ``reset``.
@@ -82,7 +103,10 @@ class Budget:
82
103
  def try_spend_graphql(self, estimate: int) -> bool:
83
104
  """Take ``estimate`` GraphQL points before a query; false when not left."""
84
105
  estimate = max(estimate, 0)
85
- if self.graphql_exhausted or self.graphql_left < estimate:
106
+ if self.graphql_exhausted:
107
+ return False
108
+ if self.graphql_left < estimate:
109
+ self.stopped_by_count = True
86
110
  return False
87
111
  self.graphql_spent += estimate
88
112
  return True
@@ -96,20 +120,40 @@ class Budget:
96
120
 
97
121
  def exhaust_graphql(self) -> None:
98
122
  """Stop GraphQL for the run, after GitHub rate-limited a query."""
99
- self.graphql_stopped = True
123
+ if not self.timed_out:
124
+ self.stopped_by_count = True
125
+ self.graphql_rate_limited = True
126
+
127
+ @property
128
+ def graphql_stopped(self) -> bool:
129
+ """True once GraphQL is done for the run: rate limited or timed out."""
130
+ return self.graphql_rate_limited or self.timed_out
131
+
132
+ @property
133
+ def timed_out(self) -> bool:
134
+ """True once the deadline, if any, has passed."""
135
+ return self.deadline is not None and self.clock() >= self.deadline
100
136
 
101
137
  @property
102
138
  def rest_left(self) -> int:
103
- """REST requests left: the allowance, less the reserve once observed."""
139
+ """REST requests left: the allowance, less the reserve once observed.
140
+
141
+ Zero once the deadline has passed. Before it, finding none left
142
+ sets ``stopped_by_count``: every caller stops on that.
143
+ """
144
+ if self.timed_out:
145
+ return 0
104
146
  left = max(self.rest - self.rest_spent, 0)
105
- if self.remaining is None:
106
- return left
107
- reserve = DEFAULT_RESERVE if self.reserve is None else self.reserve
108
- return min(left, max(0, self.remaining - reserve))
147
+ if self.remaining is not None:
148
+ reserve = DEFAULT_RESERVE if self.reserve is None else self.reserve
149
+ left = min(left, max(0, self.remaining - reserve))
150
+ if left == 0:
151
+ self.stopped_by_count = True
152
+ return left
109
153
 
110
154
  @property
111
155
  def graphql_left(self) -> int:
112
- """GraphQL points left to spend; none once GraphQL is stopped."""
156
+ """GraphQL points left to spend; none once stopped or timed out."""
113
157
  if self.graphql_stopped:
114
158
  return 0
115
159
  return max(self.graphql_points - self.graphql_spent, 0)
@@ -121,5 +165,14 @@ class Budget:
121
165
 
122
166
  @property
123
167
  def graphql_exhausted(self) -> bool:
124
- """True once no GraphQL point is left."""
125
- return self.graphql_left == 0
168
+ """True once no GraphQL point is left.
169
+
170
+ Before the deadline, a true answer sets ``stopped_by_count``: a
171
+ caller stops on it. ``graphql_left`` alone, read to size a batch,
172
+ does not.
173
+ """
174
+ if self.graphql_left > 0:
175
+ return False
176
+ if not self.timed_out:
177
+ self.stopped_by_count = True
178
+ return True