@vibelord/lanes 1.7.3 → 1.7.5

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 (57) hide show
  1. package/README.md +9 -0
  2. package/package.json +1 -1
  3. package/payload/lanes/VERSION +1 -1
  4. package/payload/lanes/bin/lanes +128 -24
  5. package/payload/lanes/bin/lanes-site-serve +15 -0
  6. package/payload/lanes/bin-rs/BINARIES.json +5 -0
  7. package/payload/lanes/container/lane-mcp +108 -5
  8. package/payload/lanes/container/lane_core.py +116 -0
  9. package/payload/lanes/container/throttle-pulse +159 -14
  10. package/payload/lanes/docs/ARCHITECTURE.md +132 -13
  11. package/payload/lanes/docs/DESIGN.md +10 -8
  12. package/payload/lanes/docs/INSTALL.md +1 -1
  13. package/payload/lanes/docs/RUNBOOK.md +436 -8
  14. package/payload/lanes/docs/USERGUIDE.md +82 -9
  15. package/payload/lanes/install/host-install.sh +35 -4
  16. package/payload/lanes/libexec/adopt.py +364 -0
  17. package/payload/lanes/libexec/attach.py +35 -5
  18. package/payload/lanes/libexec/cutover.py +656 -0
  19. package/payload/lanes/libexec/docsd.py +12 -8
  20. package/payload/lanes/libexec/doctor_lanes2.py +284 -0
  21. package/payload/lanes/libexec/economy_poll.py +87 -2
  22. package/payload/lanes/libexec/gc_unregistered.py +407 -0
  23. package/payload/lanes/libexec/lanes_lib.py +474 -2
  24. package/payload/lanes/libexec/native.sh +38 -0
  25. package/payload/lanes/libexec/native_bin.py +670 -0
  26. package/payload/lanes/libexec/session_actions.py +85 -7
  27. package/payload/lanes/libexec/shadow.py +1311 -0
  28. package/payload/lanes/libexec/sidebar.py +252 -30
  29. package/payload/lanes/libexec/sidebar_status.py +373 -25
  30. package/payload/lanes/libexec/statusd.py +67 -3
  31. package/payload/lanes/libexec/tokens.py +99 -131
  32. package/payload/lanes/libexec/tokens.sh +1 -1
  33. package/payload/lanes/libexec/update.py +78 -8
  34. package/payload/lanes/libexec/users.py +282 -0
  35. package/payload/lanes/site/README.md +9 -0
  36. package/payload/lanes/site/conformance.py +280 -0
  37. package/payload/lanes/site/protocol.py +368 -0
  38. package/payload/lanes/site/server.py +314 -0
  39. package/payload/lanes/systemd/lanes-gc.service +1 -1
  40. package/payload/lanes/systemd/lanes-gc.timer +14 -3
  41. package/payload/lanes/tokens/README.md +156 -0
  42. package/payload/lanes/tokens/generate.py +930 -0
  43. package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
  44. package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
  45. package/payload/lanes/tokens/tokens.v1.json +763 -0
  46. package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
  47. package/payload/lanes/web/Caddyfile +11 -0
  48. package/payload/lanes/web/README.md +253 -4
  49. package/payload/lanes/web/directory.css +95 -0
  50. package/payload/lanes/web/directory.js +951 -0
  51. package/payload/lanes/web/generated/README.md +107 -0
  52. package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
  53. package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
  54. package/payload/lanes/web/inbox.js +1140 -0
  55. package/payload/lanes/web/mobile.js +35 -45
  56. package/payload/lanes/web/tokens.css +137 -0
  57. package/payload/manifest.json +7 -4
@@ -1352,9 +1352,19 @@ class Handler(BaseHTTPRequestHandler):
1352
1352
  D.audit('upload', login, None, None, None, None, 'busy')
1353
1353
  raise _Reply(503, 'busy', (('Retry-After', str(BUSY_RETRY)),))
1354
1354
  try:
1355
- return self._upload_in_slot(login)
1355
+ status, receipts, error = self._upload_in_slot(login)
1356
1356
  finally:
1357
1357
  service.give_upload_slot(login)
1358
+ # Processing has ended and its body buffer is gone. Release custody
1359
+ # before the client can read a complete response and start its next
1360
+ # upload; response delivery cannot keep a completed upload busy.
1361
+ headers = (('Retry-After', str(BUSY_RETRY)),) if status == 503 else ()
1362
+ if wants_html(self.headers):
1363
+ return self._page(status, receipts_page(receipts, error), headers)
1364
+ payload = {'receipts': receipts}
1365
+ if error:
1366
+ payload['error'] = error
1367
+ return self._json(status, payload, headers)
1358
1368
 
1359
1369
  def _upload_in_slot(self, login):
1360
1370
  boundary = form_boundary(self.headers.get('Content-Type'))
@@ -1405,13 +1415,7 @@ class Handler(BaseHTTPRequestHandler):
1405
1415
  finally:
1406
1416
  os.close(uploads)
1407
1417
  status, error = failure if failure else (200, None)
1408
- headers = (('Retry-After', str(BUSY_RETRY)),) if status == 503 else ()
1409
- if wants_html(self.headers):
1410
- return self._page(status, receipts_page(receipts, error), headers)
1411
- payload = {'receipts': receipts}
1412
- if error:
1413
- payload['error'] = error
1414
- return self._json(status, payload, headers)
1418
+ return status, receipts, error
1415
1419
 
1416
1420
 
1417
1421
  class Server(ThreadingHTTPServer):
@@ -0,0 +1,284 @@
1
+ #!/usr/bin/env python3
2
+ """`lanes doctor`'s Lanes 2.0 runtime signals (lanes2 Round 2 R2-DOCTOR; RT 16.3, TI 11; BEY-6988). Python 3 stdlib.
3
+
4
+ A Lanes 2.0 host keeps one bounded metrics registry (crates/lanes-runtime/src/signals) and exports it as the snapshot
5
+ `$LANES_STATE/signals/lanes2.json` (`lanes2.signals.snapshot/2`, the manifest docs/contracts/lanes2/manifests/
6
+ signals.json revision 2; DM-LANES2-RT16-SIGNALS). The snapshot is self-describing: every signal carries its doctor
7
+ phrase, unit, kind, delay origin, state (ok, warn, alert or unavailable with a reason) and per label its value, its
8
+ increase in the window (a counter) or its rise (a high-water mark), its state and reason, and the threshold the host
9
+ resolved from its resource manifest (lane G2), benchmark.json (RT 14.1, 15.3) or the subsystem's own reported cap.
10
+ This module only renders it, so the same text comes out wherever it runs (an installed tree has no docs/). A Throttle
11
+ monitor tab on the same host may read the same file; none does yet.
12
+
13
+ `doctor_lines(state)` -> [(mark, text)] in `lanes doctor`'s protocol (`✓`/`✗` are checks, `⚠` a warning, `` an
14
+ information line):
15
+
16
+ - no snapshot file: nothing (no Lanes 2.0 host exports one before integration gate I1);
17
+ - a snapshot that cannot be read, is not one, lacks a field the renderer prints, or exceeds MAX_BYTES: one ✗ line and
18
+ nothing else (never an exception: `lanes doctor` goes on to its later checks);
19
+ - otherwise a header (the host instance, lanes-runtime version, source revision, installed version, profile and
20
+ manifest revisions), ✓ fresh or ✗ stale (older than its own `stale_after_ms`: the host stopped exporting, the values
21
+ are its last), the delay-origin line (RT 16.3: client rendering, Lanes queueing, storage, holder, network, native
22
+ harness; each ok, incomplete when a signal of it is unobserved, warn or alert), the facet line (resources, custody,
23
+ owner sources), then exactly one line per signal in snapshot order: ✗ for an alert, ⚠ for a warning or a signal the
24
+ host did not sample (`not_sampled`), an information line for ok and a declared unavailable reason.
25
+
26
+ Every value is an integer and every line is built from the snapshot and the clock alone, so a snapshot and a `now`
27
+ render to the same bytes every time.
28
+
29
+ python3 libexec/doctor_lanes2.py [--snapshot PATH] [--now-ms MS]
30
+ print the lines as `lanes doctor` does; exit 1 when a line is ✗, else 0 (also when there is no snapshot)
31
+ """
32
+ import json
33
+ import os
34
+ import sys
35
+ import time
36
+ from pathlib import Path
37
+
38
+ SCHEMA = 'lanes2.signals.snapshot/2'
39
+ SNAPSHOT = Path('signals') / 'lanes2.json' # under $LANES_STATE: signals.json `snapshot.path`
40
+ MAX_BYTES = 131072 # signals.json `snapshot.max_bytes`
41
+ NOT_SAMPLED = 'not_sampled' # the registry's own reason: a producer the host did not run
42
+ STATES = ('ok', 'warn', 'alert', 'unavailable')
43
+ ORIGIN_STATES = ('ok', 'incomplete', 'warn', 'alert')
44
+ KINDS = ('gauge', 'counter', 'high_water', 'age', 'flag')
45
+ MARK = {'alert': '✗', 'warn': '⚠', 'ok': '', 'unavailable': ''}
46
+ CMP = {'at_least': '≥', 'above': '>', 'at_most': '≤'}
47
+ USAGE = 'usage: doctor_lanes2.py [--snapshot PATH] [--now-ms MS]'
48
+ KIB, MIB, GIB = 1 << 10, 1 << 20, 1 << 30
49
+
50
+
51
+ class Malformed(ValueError):
52
+ """The document is not a `lanes2.signals.snapshot/2` snapshot this renderer can show."""
53
+
54
+
55
+ def default_state():
56
+ """$LANES_STATE, else ~/.local/state/lanes (lanes_lib.STATE's rule)."""
57
+ return Path(os.environ.get('LANES_STATE', Path.home() / '.local/state/lanes'))
58
+
59
+
60
+ def is_int(value):
61
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
62
+
63
+
64
+ def present(mapping, key):
65
+ """Whether `mapping` is an object that carries `key` (null included): every field the renderer prints must be
66
+ there, a missing one is a malformed snapshot, never a KeyError."""
67
+ return isinstance(mapping, dict) and key in mapping
68
+
69
+
70
+ def tenths(value, unit):
71
+ """`value / unit` with one decimal, by integer arithmetic (no float formatting)."""
72
+ scaled = value * 10 // unit
73
+ return f'{scaled // 10}.{scaled % 10}'
74
+
75
+
76
+ def fmt(value, unit):
77
+ """One value in its unit: µs as ms (s from one second), bytes as B/KiB/MiB/GiB, a bool as yes/no."""
78
+ if unit == 'us':
79
+ return f'{tenths(value, 1000)} ms' if value < 1_000_000 else f'{tenths(value, 1_000_000)} s'
80
+ if unit == 'bytes':
81
+ if value < KIB:
82
+ return f'{value} B'
83
+ for size, name in ((MIB, 'KiB'), (GIB, 'MiB')):
84
+ if value < size:
85
+ return f'{tenths(value, size >> 10)} {name}'
86
+ return f'{tenths(value, GIB)} GiB'
87
+ if unit == 'bool':
88
+ return 'yes' if value else 'no'
89
+ if unit == 'count':
90
+ return str(value)
91
+ return f'{value} {unit}'
92
+
93
+
94
+ def sample_text(sample, unit):
95
+ """`[<label> ]<value>[, +<increase>][ <threshold note>]`, or `[<label> ]unavailable (<reason>)`: the bound it
96
+ crossed for warn/alert (a counter's bound applies to its increase), `of <cap>` for a cap it is under."""
97
+ label = sample['label']
98
+ head = f'{label} ' if label is not None else ''
99
+ if sample['state'] == 'unavailable':
100
+ return f"{head}unavailable ({sample['reason']})"
101
+ text = head + fmt(sample['value'], unit)
102
+ if sample['delta'] is not None:
103
+ text += f", +{fmt(sample['delta'], unit)}"
104
+ state, cmp = sample['state'], sample['cmp']
105
+ if state in ('warn', 'alert'):
106
+ bound = sample[state]
107
+ if unit == 'bool' or bound is None or cmp not in CMP:
108
+ return f'{text} ({state})'
109
+ return f'{text} ({state} {CMP[cmp]} {fmt(bound, unit)})'
110
+ if cmp == 'at_least' and sample['alert'] is not None:
111
+ return f'{text} of {fmt(sample["alert"], unit)}'
112
+ return text
113
+
114
+
115
+ def signal_line(signal):
116
+ """(mark, text) of one signal: ✗ alert, ⚠ warning or not sampled, else information."""
117
+ head = f"{signal['id']} — {signal['doctor']}: "
118
+ unsampled = signal['reason'] == NOT_SAMPLED or any(s['reason'] == NOT_SAMPLED for s in signal['samples'])
119
+ mark = MARK[signal['state']] or ('⚠' if unsampled else '')
120
+ if signal['reason'] is not None:
121
+ return mark, head + f"unavailable ({signal['reason']})"
122
+ return mark, head + '; '.join(sample_text(s, signal['unit']) for s in signal['samples'])
123
+
124
+
125
+ def origin_text(origin):
126
+ text = f"{origin['label']} {origin['state']}"
127
+ return text + (f" ({', '.join(origin['signals'])})" if origin['signals'] else '')
128
+
129
+
130
+ def check_snapshot(doc):
131
+ """Raise Malformed unless `doc` has every field the renderer reads, of the type it reads (never trusts a field it
132
+ then prints, and never meets a missing one)."""
133
+ def need(ok, what):
134
+ if not ok:
135
+ raise Malformed(what)
136
+
137
+ def has(mapping, key, test):
138
+ return present(mapping, key) and test(mapping[key])
139
+
140
+ def text(value):
141
+ return isinstance(value, str)
142
+
143
+ def optional_text(value):
144
+ return value is None or isinstance(value, str)
145
+
146
+ def optional_int(value):
147
+ return value is None or is_int(value)
148
+
149
+ def word_of(words):
150
+ # A word of `words`, tested as a string first: an unhashable value (a list, an object) is malformed, never
151
+ # a TypeError from the dict lookup.
152
+ return lambda value: isinstance(value, str) and value in words
153
+
154
+ need(isinstance(doc, dict), 'not a JSON object')
155
+ need(doc.get('schema') == SCHEMA and doc.get('v') == 2, f'not {SCHEMA}')
156
+ for key in ('manifest_revision', 'resources_revision', 'written_at_ms', 'refresh_ms', 'stale_after_ms'):
157
+ need(has(doc, key, is_int), f'`{key}` is not a non-negative integer')
158
+ for key in ('profile', 'runtime_version'):
159
+ need(has(doc, key, text), f'`{key}` is not a string')
160
+ for key in ('host_instance', 'source_revision', 'installed_version'):
161
+ need(has(doc, key, optional_text), f'`{key}` is not a string or null')
162
+ need(has(doc, 'attribution', lambda v: isinstance(v, list)) and has(doc, 'signals', lambda v: isinstance(v, list)),
163
+ 'no attribution or signals')
164
+ for origin in doc['attribution']:
165
+ need(has(origin, 'origin', text) and has(origin, 'label', text)
166
+ and has(origin, 'state', word_of(ORIGIN_STATES))
167
+ and has(origin, 'delay', lambda v: isinstance(v, bool))
168
+ and has(origin, 'signals', lambda v: isinstance(v, list) and all(isinstance(n, str) for n in v)),
169
+ 'a malformed attribution entry')
170
+ for signal in doc['signals']:
171
+ need(isinstance(signal, dict), 'a signal is not an object')
172
+ need(all(has(signal, key, text) for key in ('id', 'doctor', 'unit', 'kind', 'origin')),
173
+ 'a signal without id, doctor, unit, kind or origin')
174
+ sid = signal['id']
175
+ need(word_of(KINDS)(signal['kind']), f'{sid}: unknown kind')
176
+ need(has(signal, 'state', word_of(STATES)), f'{sid}: unknown state')
177
+ need(has(signal, 'reason', optional_text), f'{sid}: reason')
178
+ need(has(signal, 'samples', lambda v: isinstance(v, list)), f'{sid}: no samples')
179
+ if signal['reason'] is not None:
180
+ need(signal['state'] == 'unavailable' and not signal['samples'],
181
+ f'{sid}: an unavailable signal with samples')
182
+ else:
183
+ need(bool(signal['samples']), f'{sid}: a signal without samples or a reason')
184
+ for sample in signal['samples']:
185
+ need(isinstance(sample, dict)
186
+ and has(sample, 'label', optional_text)
187
+ and has(sample, 'value', optional_int)
188
+ and has(sample, 'delta', optional_int)
189
+ and has(sample, 'state', word_of(STATES))
190
+ and has(sample, 'reason', optional_text)
191
+ and has(sample, 'cmp', lambda v: v is None or word_of(CMP)(v))
192
+ and all(has(sample, key, optional_int) for key in ('warn', 'alert')), f'{sid}: a malformed sample')
193
+ unavailable = sample['state'] == 'unavailable'
194
+ need(unavailable == (sample['value'] is None) == (sample['reason'] is not None),
195
+ f'{sid}: a sample whose value, state and reason disagree')
196
+
197
+
198
+ def render(doc, now_ms, path):
199
+ """[(mark, text)] of a parsed snapshot `doc` read from `path` at `now_ms` (Unix ms)."""
200
+ check_snapshot(doc)
201
+ host = doc['host_instance'] or 'an unnamed host'
202
+ written, stale = doc['written_at_ms'], doc['stale_after_ms']
203
+ lines = [('', f"lanes2 runtime signals: {path}, from {host} (lanes-runtime {doc['runtime_version']}, "
204
+ f"source {doc['source_revision'] or 'unknown'}, installed {doc['installed_version'] or 'unknown'}, "
205
+ f"profile {doc['profile']} r{doc['resources_revision']}, manifest r{doc['manifest_revision']})")]
206
+ if written > now_ms:
207
+ lines.append(('⚠', f'lanes2 signals snapshot written {tenths(written - now_ms, 1000)} s in the future: '
208
+ 'a clock step or another host\'s clock; its age is unknown'))
209
+ elif now_ms - written > stale:
210
+ lines.append(('✗', f'lanes2 signals snapshot fresh — written {(now_ms - written) // 1000} s ago, stale after '
211
+ f'{stale // 1000} s: the host stopped exporting, so the values below are its last'))
212
+ else:
213
+ lines.append(('✓', f'lanes2 signals snapshot fresh — {(now_ms - written) // 1000} s old (stale after '
214
+ f'{stale // 1000} s)'))
215
+ delay = [origin for origin in doc['attribution'] if origin['delay']]
216
+ facets = [origin for origin in doc['attribution'] if not origin['delay']]
217
+ lines.append(('', 'delay origin: ' + (' · '.join(origin_text(o) for o in delay) or 'none attributed')))
218
+ if facets:
219
+ lines.append(('', 'facets: ' + ' · '.join(origin_text(o) for o in facets)))
220
+ lines.extend(signal_line(signal) for signal in doc['signals'])
221
+ return lines
222
+
223
+
224
+ def unreadable(path, why):
225
+ return [('✗', f'lanes2 signals snapshot readable — {why} ({path})')]
226
+
227
+
228
+ def read_snapshot(path, now_ms=None):
229
+ """[(mark, text)] of the snapshot file `path` at `now_ms` (Unix ms, default now); [] when the file is absent."""
230
+ now_ms = int(time.time() * 1000) if now_ms is None else now_ms
231
+ try:
232
+ with open(path, 'rb') as handle:
233
+ data = handle.read(MAX_BYTES + 1)
234
+ except FileNotFoundError:
235
+ return []
236
+ except OSError as error:
237
+ return unreadable(path, error.strerror or error)
238
+ if len(data) > MAX_BYTES:
239
+ return unreadable(path, f'larger than {MAX_BYTES} bytes')
240
+ try:
241
+ return render(json.loads(data.decode('utf-8')), now_ms, path)
242
+ except RecursionError: # a document nested deeper than the decoder recurses
243
+ return unreadable(path, 'nested too deeply')
244
+ except (UnicodeDecodeError, ValueError) as error: # json.JSONDecodeError and Malformed are ValueErrors
245
+ return unreadable(path, error)
246
+ except (KeyError, TypeError, IndexError) as error: # a field check_snapshot let through: still one problem line
247
+ return unreadable(path, f'{type(error).__name__} {error}')
248
+
249
+
250
+ def doctor_lines(state=None, now_ms=None):
251
+ """`lanes doctor`'s lines for the snapshot under `state` ($LANES_STATE); [] when there is none. Never raises: a
252
+ renderer fault is one ✗ line, so `lanes doctor` still prints its later checks."""
253
+ path = Path(state if state is not None else default_state()) / SNAPSHOT
254
+ try:
255
+ return read_snapshot(path, now_ms)
256
+ except Exception as error: # noqa: BLE001 — doctor must survive its own renderer
257
+ return unreadable(path, f'the renderer failed: {type(error).__name__}')
258
+
259
+
260
+ def print_lines(lines, out=None):
261
+ """Print `lines` the way `lanes doctor` prints checks, warnings and information; True when one is ✗."""
262
+ out = sys.stdout if out is None else out
263
+ for mark, text in lines:
264
+ out.write(f'{mark or " "} {text}\n')
265
+ return any(mark == '✗' for mark, _text in lines)
266
+
267
+
268
+ def main(argv):
269
+ snapshot, now_ms, rest = None, None, list(argv)
270
+ while rest:
271
+ word = rest.pop(0)
272
+ if word == '--snapshot' and rest:
273
+ snapshot = Path(rest.pop(0))
274
+ elif word == '--now-ms' and rest and rest[0].isdigit():
275
+ now_ms = int(rest.pop(0))
276
+ else:
277
+ print(USAGE, file=sys.stderr)
278
+ return 2
279
+ lines = doctor_lines(now_ms=now_ms) if snapshot is None else read_snapshot(snapshot, now_ms)
280
+ return 1 if print_lines(lines) else 0
281
+
282
+
283
+ if __name__ == '__main__':
284
+ sys.exit(main(sys.argv[1:]))
@@ -43,12 +43,23 @@ workspace container. `LANES_THROTTLE_CONTAINER=<name>` reads the log through tha
43
43
  namespace — a daemon bound to the container's 127.0.0.1 is not (DEF-1525). Why a source is down (`connection
44
44
  refused`, `timed out`, `HTTP 401`, `log dir missing`, ...) goes to stderr — the journal — each time it changes, and
45
45
  on every `--once`; it is never written into economy.json.
46
+
47
+ Reader mode (lanes2 E5, TI INT-12, BEY-6845): `LANES_THROTTLE_PROJECTION=<file>` makes the poller a compatibility READER
48
+ of the shared projection adapter (`throttle-rc` `studio_host::readers::projection`, `throttle.source-projection.v1`):
49
+ `/status` and `/sessions` come from the adapter's own entries for those routes, the daemon is never contacted, no bearer
50
+ is read and `LANES_THROTTLE_CONTROL` is not consulted (the adapter holds the explicitly selected instance's credential).
51
+ economy.json keeps its v1 shape. An entry the adapter did not read fresh in its last cycle is a failed source here (the
52
+ previous figures stay, marked `stale: true`; the stale value is never applied), and a projection that is absent, not a
53
+ v1 document, over PROJECTION_MAX, unbound to its instance, written more than PROJECTION_STALE seconds ago or more than
54
+ PROJECTION_SKEW seconds in the future fails both. `throttle-rc studio project --scope economy` is the writer.
55
+ The log fold is unchanged. The default stays the polling mode until the W19 agent daemon runs the adapter.
46
56
  """
47
57
  import argparse
48
58
  import copy
49
59
  import json
50
60
  import os
51
61
  import re
62
+ import stat
52
63
  import sys
53
64
  import time
54
65
  import urllib.error
@@ -85,6 +96,10 @@ FLEET_KEYS = ('overflow_spend_today_usd', 'overflow_budget_usd', 'spent_fraction
85
96
  'upstream_429_delta', 'paid_in_flight', 'sub_in_flight', 'fable_sustainable_rpm')
86
97
  LIVE_KEYS = ('model', 'requested_model', 'paid_share', 'usd_per_hour', 'tok_per_min', 'cache_read_ratio',
87
98
  'downgraded_5m', 'status_429', 'last_request_age_s')
99
+ PROJECTION_SCHEMA = 'throttle.source-projection.v1' # the shared adapter's document (reader mode)
100
+ PROJECTION_MAX = 96 << 20 # bytes: the adapter's MAX_PROJECTION_BYTES; a bigger file is not its document
101
+ PROJECTION_STALE = 30 # seconds: an older projection is not read
102
+ PROJECTION_SKEW = 5 # seconds: a projection written further in the future is not read (a clock step)
88
103
 
89
104
 
90
105
  def trace_key(trace):
@@ -520,6 +535,70 @@ def fetch_sessions(control, token=None, opener=None):
520
535
  return fetch_json(control, 'sessions', token, opener)
521
536
 
522
537
 
538
+ def read_projection(path, now):
539
+ """(the shared adapter's projection, None) or (None, why): a regular file (a link is not followed) of at most
540
+ PROJECTION_MAX bytes holding a throttle.source-projection.v1 document whose instance is bound and whose
541
+ `written_ms` is at most PROJECTION_STALE seconds before `now` (epoch s) and at most PROJECTION_SKEW after it: a
542
+ file stamped in the future (a clock step back, a skewed writer) would otherwise pass as fresh until the clock
543
+ caught up."""
544
+ try:
545
+ fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, 'O_CLOEXEC', 0))
546
+ except FileNotFoundError:
547
+ return None, f'projection absent ({path})'
548
+ except OSError as error:
549
+ return None, f'projection unreadable ({error.strerror or type(error).__name__})'
550
+ try:
551
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
552
+ return None, f'projection is not a regular file ({path})'
553
+ chunks, size = [], 0
554
+ while size <= PROJECTION_MAX:
555
+ chunk = os.read(fd, min(1 << 20, PROJECTION_MAX + 1 - size))
556
+ if not chunk:
557
+ break
558
+ chunks.append(chunk)
559
+ size += len(chunk)
560
+ except OSError as error:
561
+ return None, f'projection unreadable ({error.strerror or type(error).__name__})'
562
+ finally:
563
+ os.close(fd)
564
+ if size > PROJECTION_MAX:
565
+ return None, f'projection over {PROJECTION_MAX} bytes'
566
+ try:
567
+ doc = json.loads(b''.join(chunks))
568
+ except ValueError:
569
+ return None, 'projection is not JSON'
570
+ if not isinstance(doc, dict) or doc.get('schema') != PROJECTION_SCHEMA or doc.get('version') != 1:
571
+ return None, f'projection is not a {PROJECTION_SCHEMA} document'
572
+ if _get(doc, 'instance', 'bound') is not True:
573
+ return None, 'projection instance not bound'
574
+ written = doc.get('written_ms')
575
+ if not isinstance(written, int) or isinstance(written, bool):
576
+ return None, 'projection names no written_ms'
577
+ age = now - written / 1000
578
+ if age > PROJECTION_STALE:
579
+ return None, f'projection stale ({int(age)} s old)'
580
+ if age < -PROJECTION_SKEW:
581
+ return None, f'projection written in the future ({int(-age)} s)'
582
+ return doc, None
583
+
584
+
585
+ def projection_source(doc, why, route):
586
+ """(the JSON document the adapter last read FRESH from `route`, None) or (None, why). A stale entry's value is
587
+ never returned: the poller's own stale handling keeps the previous figures."""
588
+ if why:
589
+ return None, why
590
+ sources = doc.get('sources') if isinstance(doc, dict) else None
591
+ for entry in (sources.values() if isinstance(sources, dict) else ()):
592
+ if not isinstance(entry, dict) or entry.get('route') != route:
593
+ continue
594
+ if entry.get('fresh') is not True:
595
+ return None, f"projection: {str(entry.get('error') or 'not fresh')[:160]} ({route})"
596
+ if entry.get('http_status') != 200 or not isinstance(entry.get('document'), dict):
597
+ return None, f'projection: not a JSON object ({route})'
598
+ return entry['document'], None
599
+ return None, f'not in the projection ({route})'
600
+
601
+
523
602
  def _canonical(doc):
524
603
  return json.dumps(doc, sort_keys=True, separators=(',', ':'))
525
604
 
@@ -581,7 +660,10 @@ def poll_once(state_dir, env, opener=None, now=None, write=True, status_file=Non
581
660
  state_dir = Path(state_dir)
582
661
  now = int(time.time() if now is None else now)
583
662
  day = time.strftime('%Y-%m-%d', time.gmtime(now))
584
- control = control_url(env)
663
+ projection_file = env.get('LANES_THROTTLE_PROJECTION')
664
+ # Reader mode: the shared adapter's projection, never the daemon (no control URL, no bearer).
665
+ projection = read_projection(os.path.expanduser(projection_file), now) if projection_file else None
666
+ control = None if projection_file else control_url(env)
585
667
  token = read_token(env) if control else None
586
668
  previous = L.read_json(state_dir / ECONOMY)
587
669
  previous = previous if isinstance(previous, dict) and previous.get('v') == SCHEMA else {}
@@ -592,6 +674,8 @@ def poll_once(state_dir, env, opener=None, now=None, write=True, status_file=Non
592
674
  if path:
593
675
  doc = L.read_json(path)
594
676
  return (doc, None) if isinstance(doc, dict) else (None, f'fixture is not a JSON object: {path}')
677
+ if projection is not None:
678
+ return projection_source(*projection, f'/{name}')
595
679
  if not control:
596
680
  return None, 'not requested (LANES_THROTTLE_CONTROL=none)'
597
681
  return fetch(control, name, token, opener)
@@ -669,7 +753,8 @@ def main(argv=None):
669
753
  print(json.dumps(payload, indent=2, sort_keys=True))
670
754
  report(diagnostics, None, always=True)
671
755
  return 0
672
- control_url(env) # a malformed URL stops the unit at start, not once per tick
756
+ if not env.get('LANES_THROTTLE_PROJECTION'):
757
+ control_url(env) # a malformed URL stops the unit at start, not once per tick (reader mode reads no URL)
673
758
  L.record_tree('economy', state) # W9 U0: the unit's tree; `--once`/`--dry-run` (a person's diagnostic) never
674
759
  last = None
675
760
  while True: