github-statistics 0.1.0__py3-none-any.whl → 0.2.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.
@@ -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
@@ -3,17 +3,27 @@
3
3
  """One target's budgeted, self-healing sync (design §6.5).
4
4
 
5
5
  `collect` runs the collectors in a fixed order, sharing the
6
- transport's one budget: scope, public members, the incremental reads,
7
- enrichment, backfill, then the re-run sweep. The incremental reads and
8
- enrichment always come before backfill, so yesterday is complete while
9
- history still fills in. Each step's listing sync ends before the next
10
- step starts, so enrichment never runs alongside a listing (design §6.3).
6
+ transport's one budget: scope, public members, every repository's
7
+ item listing, the recent runs, enrichment, the runs backfill, job
8
+ counts of what that backfill stored, then the re-run sweep. Items come
9
+ first because their listing costs a small fraction of a cold runs
10
+ read, and the recent runs and the first enrichment always come before
11
+ the runs backfill, so yesterday is complete while history still
12
+ fills in. Each step's listing sync ends before the next step starts,
13
+ so enrichment never runs alongside a listing (design §6.3).
11
14
  """
12
15
 
13
16
  from __future__ import annotations
14
17
 
15
18
  import dataclasses
16
- from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping
19
+ from collections.abc import (
20
+ Awaitable,
21
+ Callable,
22
+ Coroutine,
23
+ Iterable,
24
+ Mapping,
25
+ Sequence,
26
+ )
17
27
  from dataclasses import dataclass, field
18
28
  from datetime import UTC, date, datetime, timedelta
19
29
  from typing import Any
@@ -149,7 +159,7 @@ class _Plan:
149
159
 
150
160
 
151
161
  async def _sync(steps: Steps, transport: Transport, store: Store, plan: _Plan) -> None:
152
- """Steps 3 to 6 of `collect` over ``plan``'s repositories."""
162
+ """Steps 3 to 7 of `collect` over ``plan``'s repositories."""
153
163
  window, now = {"window_start": plan.window_start}, plan.now
154
164
 
155
165
  def fresh(key: str) -> bool:
@@ -188,6 +198,8 @@ async def _sync(steps: Steps, transport: Transport, store: Store, plan: _Plan) -
188
198
 
189
199
  if plan.items and later:
190
200
  await items(INCREMENTAL, later)
201
+ if plan.items and first:
202
+ await items(BACKFILL, first)
191
203
  if plan.runs:
192
204
  finished = await each(
193
205
  steps, INCREMENTAL, (guarded(sync, sync.recent) for sync in syncs)
@@ -195,58 +207,71 @@ async def _sync(steps: Steps, transport: Transport, store: Store, plan: _Plan) -
195
207
  steps.phases(INCREMENTAL, syncs, finished)
196
208
  current = [s for s, done in zip(syncs, finished, strict=True) if done]
197
209
 
198
- await _enrich(steps, transport, store, plan)
210
+ await _enrich(
211
+ steps,
212
+ transport,
213
+ store,
214
+ plan.keys if plan.jobs else [],
215
+ items=plan.keys if plan.items else [],
216
+ )
199
217
 
200
- if plan.items and first:
201
- await items(BACKFILL, first)
218
+ stored: list[str] = []
202
219
  if current:
220
+ before = {sync.key: sync.result().runs for sync in current}
203
221
  backfilled = await each(
204
222
  steps, BACKFILL, (guarded(sync, sync.backfill) for sync in current)
205
223
  )
206
224
  steps.phases(BACKFILL, current, backfilled)
225
+ stored = [s.key for s in current if s.result().runs > before[s.key]]
207
226
  for sync in syncs:
208
227
  result = sync.result()
209
228
  steps.runs(sync.key, result.unreadable, result.stalled)
210
229
 
230
+ await _enrich(steps, transport, store, stored if plan.jobs else [])
231
+
211
232
  if current:
212
233
  await _sweep(steps, transport, store, [sync.key for sync in current], now)
213
234
 
214
235
 
215
236
  async def _enrich(
216
- steps: Steps, transport: Transport, store: Store, plan: _Plan
237
+ steps: Steps,
238
+ transport: Transport,
239
+ store: Store,
240
+ runs: list[str],
241
+ items: Sequence[str] = (),
217
242
  ) -> None:
218
- """Step 4: enrich items, then count jobs; report the repositories they failed.
243
+ """Steps 4 and 6: enrich the items of ``items``, then count the jobs of ``runs``.
219
244
 
220
- An id that failed alone, unlike one the budget left, makes the
221
- repository holding it unreadable.
245
+ Step 6 passes no ``items``: every item listing ends before step 4.
246
+ Either list may be empty, and skips its half. Reports the
247
+ repositories they failed: an id that failed alone, unlike one the
248
+ budget left, makes the repository holding it unreadable.
222
249
  """
223
- if plan.items:
224
- enriched = await steps.run(
225
- ENRICHMENT, enrich_items(transport, store, plan.keys)
226
- )
250
+ if items:
251
+ enriched = await steps.run(ENRICHMENT, enrich_items(transport, store, items))
227
252
  if enriched is not None and enriched.failed:
228
253
  ids = set(enriched.failed)
229
254
  steps.failed(
230
255
  "item enrichment",
231
256
  (
232
257
  item.repo
233
- for key in plan.keys
258
+ for key in items
234
259
  for item in store.items_needing_enrichment(key, PER_REPOSITORY)
235
260
  if item.node_id in ids
236
261
  ),
237
262
  )
238
- if plan.jobs:
239
- counted = await steps.run(ENRICHMENT, enrich_jobs(transport, store, plan.keys))
263
+ if runs:
264
+ counted = await steps.run(ENRICHMENT, enrich_jobs(transport, store, runs))
240
265
  if counted is not None and counted.failed:
241
266
  ids = set(counted.failed)
242
- runs = store.runs_needing_jobs(ALL_RUNS)
243
- steps.failed("job counts", (r.repo for r in runs if r.node_id in ids))
267
+ needing = store.runs_needing_jobs(ALL_RUNS)
268
+ steps.failed("job counts", (r.repo for r in needing if r.node_id in ids))
244
269
 
245
270
 
246
271
  async def _sweep(
247
272
  steps: Steps, transport: Transport, store: Store, keys: list[str], now: datetime
248
273
  ) -> None:
249
- """Step 6: the re-run sweep of ``keys``, where due."""
274
+ """Step 7: the re-run sweep of ``keys``, where due."""
250
275
  sweeps = await each(
251
276
  steps,
252
277
  SWEEP,
@@ -281,10 +306,11 @@ async def collect(
281
306
  The window is ``config.window.days`` days ending on ``until``,
282
307
  by default the day before ``now``, in UTC; ``now`` stays the time
283
308
  of the reads. Steps: resolve the scope and apply it to the store;
284
- read public members; the incremental reads of items, from
285
- repositories with a watermark, then of runs; enrich items, then
286
- count jobs; backfill, first item syncs then runs; the re-run sweep,
287
- where due. A disabled metric's collectors do not run. An empty scope
309
+ read public members; list the items of every repository, from its
310
+ watermark or, with none yet, as its first sync; read the recent
311
+ runs; enrich items, then count jobs; backfill runs; count the jobs
312
+ of the runs the backfill stored, whatever REST budget it left; the
313
+ re-run sweep, where due. A disabled metric's collectors do not run. An empty scope
288
314
  makes no call after its resolution, and a scope the budget stops
289
315
  applies nothing. A repository whose read outlasts its retries is
290
316
  unreadable, and the outage ends its step; the repositories that