@vibelord/lanes 1.7.3 → 1.7.4
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.
- package/README.md +9 -0
- package/package.json +1 -1
- package/payload/lanes/VERSION +1 -1
- package/payload/lanes/bin/lanes +97 -17
- package/payload/lanes/bin/lanes-site-serve +15 -0
- package/payload/lanes/bin-rs/BINARIES.json +5 -0
- package/payload/lanes/container/lane-mcp +105 -5
- package/payload/lanes/container/lane_core.py +110 -0
- package/payload/lanes/container/throttle-pulse +159 -14
- package/payload/lanes/docs/ARCHITECTURE.md +108 -11
- package/payload/lanes/docs/DESIGN.md +10 -8
- package/payload/lanes/docs/INSTALL.md +1 -1
- package/payload/lanes/docs/RUNBOOK.md +297 -5
- package/payload/lanes/docs/USERGUIDE.md +11 -6
- package/payload/lanes/install/host-install.sh +14 -3
- package/payload/lanes/libexec/adopt.py +325 -0
- package/payload/lanes/libexec/cutover.py +656 -0
- package/payload/lanes/libexec/docsd.py +12 -8
- package/payload/lanes/libexec/doctor_lanes2.py +213 -0
- package/payload/lanes/libexec/economy_poll.py +87 -2
- package/payload/lanes/libexec/lanes_lib.py +465 -2
- package/payload/lanes/libexec/native.sh +38 -0
- package/payload/lanes/libexec/native_bin.py +668 -0
- package/payload/lanes/libexec/shadow.py +1311 -0
- package/payload/lanes/libexec/sidebar.py +252 -30
- package/payload/lanes/libexec/sidebar_status.py +373 -25
- package/payload/lanes/libexec/statusd.py +67 -3
- package/payload/lanes/libexec/tokens.py +99 -131
- package/payload/lanes/libexec/tokens.sh +1 -1
- package/payload/lanes/libexec/update.py +48 -5
- package/payload/lanes/libexec/users.py +282 -0
- package/payload/lanes/site/README.md +9 -0
- package/payload/lanes/site/conformance.py +280 -0
- package/payload/lanes/site/protocol.py +368 -0
- package/payload/lanes/site/server.py +314 -0
- package/payload/lanes/tokens/README.md +156 -0
- package/payload/lanes/tokens/generate.py +930 -0
- package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
- package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
- package/payload/lanes/tokens/tokens.v1.json +763 -0
- package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
- package/payload/lanes/web/README.md +132 -4
- package/payload/lanes/web/directory.css +95 -0
- package/payload/lanes/web/directory.js +951 -0
- package/payload/lanes/web/generated/README.md +107 -0
- package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
- package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
- package/payload/lanes/web/mobile.js +17 -21
- package/payload/lanes/web/tokens.css +137 -0
- 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
|
-
|
|
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
|
-
|
|
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,213 @@
|
|
|
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/1`, the manifest docs/contracts/lanes2/manifests/
|
|
6
|
+
signals.json; DM-LANES2-RT16-SIGNALS). The snapshot is self-describing: every signal carries its doctor phrase, unit,
|
|
7
|
+
delay origin, state (ok, warn, alert or unavailable with a reason) and per label its value and the threshold the host
|
|
8
|
+
resolved from its resource manifest (lane G2) and benchmark.json (RT 14.1, 15.3). This module only renders it, so the
|
|
9
|
+
same text comes out wherever it runs (an installed tree has no docs/), and the Throttle monitor tab reads the same file.
|
|
10
|
+
|
|
11
|
+
`doctor_lines(state)` -> [(mark, text)] in `lanes doctor`'s protocol (`✓`/`✗` are checks, `⚠` a warning, `` an
|
|
12
|
+
information line):
|
|
13
|
+
|
|
14
|
+
- no snapshot file: nothing (no Lanes 2.0 host exports one before integration gate I1);
|
|
15
|
+
- a snapshot that cannot be read, is not one, or exceeds MAX_BYTES: one ✗ line and nothing else;
|
|
16
|
+
- otherwise a header, ✓ fresh or ✗ stale (older than its own `stale_after_ms`: the host stopped exporting, the values
|
|
17
|
+
are its last), the delay-origin line (RT 16.3: client rendering, Lanes queueing, storage, holder, network, native
|
|
18
|
+
harness), the facet line (resources, custody, owner sources), then exactly one line per signal in snapshot order:
|
|
19
|
+
✗ for an alert, ⚠ for a warning, an information line for ok and unavailable.
|
|
20
|
+
|
|
21
|
+
Every value is an integer and every line is built from the snapshot and the clock alone, so a snapshot and a `now`
|
|
22
|
+
render to the same bytes every time.
|
|
23
|
+
|
|
24
|
+
python3 libexec/doctor_lanes2.py [--snapshot PATH] [--now-ms MS]
|
|
25
|
+
print the lines as `lanes doctor` does; exit 1 when a line is ✗, else 0 (also when there is no snapshot)
|
|
26
|
+
"""
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import sys
|
|
30
|
+
import time
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
SCHEMA = 'lanes2.signals.snapshot/1'
|
|
34
|
+
SNAPSHOT = Path('signals') / 'lanes2.json' # under $LANES_STATE: signals.json `snapshot.path`
|
|
35
|
+
MAX_BYTES = 65536 # signals.json `snapshot.max_bytes`
|
|
36
|
+
STATES = ('ok', 'warn', 'alert', 'unavailable')
|
|
37
|
+
MARK = {'alert': '✗', 'warn': '⚠', 'ok': '', 'unavailable': ''}
|
|
38
|
+
CMP = {'at_least': '≥', 'above': '>', 'at_most': '≤'}
|
|
39
|
+
USAGE = 'usage: doctor_lanes2.py [--snapshot PATH] [--now-ms MS]'
|
|
40
|
+
KIB, MIB, GIB = 1 << 10, 1 << 20, 1 << 30
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Malformed(ValueError):
|
|
44
|
+
"""The document is not a `lanes2.signals.snapshot/1` snapshot this renderer can show."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def default_state():
|
|
48
|
+
"""$LANES_STATE, else ~/.local/state/lanes (lanes_lib.STATE's rule)."""
|
|
49
|
+
return Path(os.environ.get('LANES_STATE', Path.home() / '.local/state/lanes'))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_int(value):
|
|
53
|
+
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def tenths(value, unit):
|
|
57
|
+
"""`value / unit` with one decimal, by integer arithmetic (no float formatting)."""
|
|
58
|
+
scaled = value * 10 // unit
|
|
59
|
+
return f'{scaled // 10}.{scaled % 10}'
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def fmt(value, unit):
|
|
63
|
+
"""One value in its unit: µs as ms (s from one second), bytes as B/KiB/MiB/GiB, a bool as yes/no."""
|
|
64
|
+
if unit == 'us':
|
|
65
|
+
return f'{tenths(value, 1000)} ms' if value < 1_000_000 else f'{tenths(value, 1_000_000)} s'
|
|
66
|
+
if unit == 'bytes':
|
|
67
|
+
if value < KIB:
|
|
68
|
+
return f'{value} B'
|
|
69
|
+
for size, name in ((MIB, 'KiB'), (GIB, 'MiB')):
|
|
70
|
+
if value < size:
|
|
71
|
+
return f'{tenths(value, size >> 10)} {name}'
|
|
72
|
+
return f'{tenths(value, GIB)} GiB'
|
|
73
|
+
if unit == 'bool':
|
|
74
|
+
return 'yes' if value else 'no'
|
|
75
|
+
if unit == 'count':
|
|
76
|
+
return str(value)
|
|
77
|
+
return f'{value} {unit}'
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def sample_text(sample, unit):
|
|
81
|
+
"""`[<label> ]<value>[ <threshold note>]`: the bound it crossed for warn/alert, `of <cap>` for a cap it is under."""
|
|
82
|
+
label = sample['label']
|
|
83
|
+
text = (f'{label} ' if label is not None else '') + fmt(sample['value'], unit)
|
|
84
|
+
state, cmp = sample['state'], sample['cmp']
|
|
85
|
+
if state in ('warn', 'alert'):
|
|
86
|
+
bound = sample[state]
|
|
87
|
+
if unit == 'bool' or bound is None or cmp not in CMP:
|
|
88
|
+
return f'{text} ({state})'
|
|
89
|
+
return f'{text} ({state} {CMP[cmp]} {fmt(bound, unit)})'
|
|
90
|
+
if cmp == 'at_least' and sample['alert'] is not None:
|
|
91
|
+
return f'{text} of {fmt(sample["alert"], unit)}'
|
|
92
|
+
return text
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def signal_line(signal):
|
|
96
|
+
"""(mark, text) of one signal."""
|
|
97
|
+
head = f"{signal['id']} — {signal['doctor']}: "
|
|
98
|
+
if signal['state'] == 'unavailable':
|
|
99
|
+
return '', head + f"unavailable ({signal['reason'] or 'no reason given'})"
|
|
100
|
+
return MARK[signal['state']], head + '; '.join(sample_text(s, signal['unit']) for s in signal['samples'])
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def origin_text(origin):
|
|
104
|
+
text = f"{origin['label']} {origin['state']}"
|
|
105
|
+
return text + (f" ({', '.join(origin['signals'])})" if origin['signals'] else '')
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def check_snapshot(doc):
|
|
109
|
+
"""Raise Malformed unless `doc` has the shape the renderer reads (never trusts a field it then prints)."""
|
|
110
|
+
def need(ok, what):
|
|
111
|
+
if not ok:
|
|
112
|
+
raise Malformed(what)
|
|
113
|
+
|
|
114
|
+
need(isinstance(doc, dict), 'not a JSON object')
|
|
115
|
+
need(doc.get('schema') == SCHEMA and doc.get('v') == 1, f'not {SCHEMA}')
|
|
116
|
+
for key in ('manifest_revision', 'resources_revision', 'written_at_ms', 'refresh_ms', 'stale_after_ms'):
|
|
117
|
+
need(is_int(doc.get(key)), f'`{key}` is not a non-negative integer')
|
|
118
|
+
for key in ('profile', 'runtime_version'):
|
|
119
|
+
need(isinstance(doc.get(key), str), f'`{key}` is not a string')
|
|
120
|
+
need(doc.get('host_instance') is None or isinstance(doc.get('host_instance'), str), '`host_instance`')
|
|
121
|
+
need(isinstance(doc.get('attribution'), list) and isinstance(doc.get('signals'), list), 'no attribution or signals')
|
|
122
|
+
for origin in doc['attribution']:
|
|
123
|
+
need(isinstance(origin, dict) and isinstance(origin.get('label'), str) and origin.get('state') in STATES
|
|
124
|
+
and isinstance(origin.get('delay'), bool) and isinstance(origin.get('signals'), list)
|
|
125
|
+
and all(isinstance(name, str) for name in origin['signals']), 'a malformed attribution entry')
|
|
126
|
+
for signal in doc['signals']:
|
|
127
|
+
need(isinstance(signal, dict), 'a signal is not an object')
|
|
128
|
+
need(all(isinstance(signal.get(key), str) for key in ('id', 'doctor', 'unit', 'origin')),
|
|
129
|
+
'a signal without id, doctor, unit or origin')
|
|
130
|
+
need(signal.get('state') in STATES, f"{signal.get('id')}: unknown state")
|
|
131
|
+
need(signal.get('reason') is None or isinstance(signal.get('reason'), str), f"{signal['id']}: reason")
|
|
132
|
+
need(isinstance(signal.get('samples'), list), f"{signal['id']}: no samples")
|
|
133
|
+
for sample in signal['samples']:
|
|
134
|
+
need(isinstance(sample, dict) and is_int(sample.get('value')) and sample.get('state') in STATES
|
|
135
|
+
and (sample.get('label') is None or isinstance(sample.get('label'), str))
|
|
136
|
+
and all(sample.get(key) is None or is_int(sample.get(key)) for key in ('warn', 'alert'))
|
|
137
|
+
and (sample.get('cmp') is None or sample.get('cmp') in CMP), f"{signal['id']}: a malformed sample")
|
|
138
|
+
need(signal['state'] == 'unavailable' or signal['samples'], f"{signal['id']}: a state without samples")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def render(doc, now_ms, path):
|
|
142
|
+
"""[(mark, text)] of a parsed snapshot `doc` read from `path` at `now_ms` (Unix ms)."""
|
|
143
|
+
check_snapshot(doc)
|
|
144
|
+
host = doc['host_instance'] or 'an unnamed host'
|
|
145
|
+
written, stale = doc['written_at_ms'], doc['stale_after_ms']
|
|
146
|
+
lines = [('', f"lanes2 runtime signals: {path}, from {host} (lanes-runtime {doc['runtime_version']}, "
|
|
147
|
+
f"profile {doc['profile']} r{doc['resources_revision']}, manifest r{doc['manifest_revision']})")]
|
|
148
|
+
if written > now_ms:
|
|
149
|
+
lines.append(('⚠', f'lanes2 signals snapshot written {tenths(written - now_ms, 1000)} s in the future: '
|
|
150
|
+
'a clock step or another host\'s clock; its age is unknown'))
|
|
151
|
+
elif now_ms - written > stale:
|
|
152
|
+
lines.append(('✗', f'lanes2 signals snapshot fresh — written {(now_ms - written) // 1000} s ago, stale after '
|
|
153
|
+
f'{stale // 1000} s: the host stopped exporting, so the values below are its last'))
|
|
154
|
+
else:
|
|
155
|
+
lines.append(('✓', f'lanes2 signals snapshot fresh — {(now_ms - written) // 1000} s old (stale after '
|
|
156
|
+
f'{stale // 1000} s)'))
|
|
157
|
+
delay = [origin for origin in doc['attribution'] if origin['delay']]
|
|
158
|
+
facets = [origin for origin in doc['attribution'] if not origin['delay']]
|
|
159
|
+
lines.append(('', 'delay origin: ' + (' · '.join(origin_text(o) for o in delay) or 'none attributed')))
|
|
160
|
+
if facets:
|
|
161
|
+
lines.append(('', 'facets: ' + ' · '.join(origin_text(o) for o in facets)))
|
|
162
|
+
lines.extend(signal_line(signal) for signal in doc['signals'])
|
|
163
|
+
return lines
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def read_snapshot(path, now_ms=None):
|
|
167
|
+
"""[(mark, text)] of the snapshot file `path` at `now_ms` (Unix ms, default now); [] when the file is absent."""
|
|
168
|
+
now_ms = int(time.time() * 1000) if now_ms is None else now_ms
|
|
169
|
+
try:
|
|
170
|
+
with open(path, 'rb') as handle:
|
|
171
|
+
data = handle.read(MAX_BYTES + 1)
|
|
172
|
+
except FileNotFoundError:
|
|
173
|
+
return []
|
|
174
|
+
except OSError as error:
|
|
175
|
+
return [('✗', f'lanes2 signals snapshot readable — {error.strerror or error} ({path})')]
|
|
176
|
+
if len(data) > MAX_BYTES:
|
|
177
|
+
return [('✗', f'lanes2 signals snapshot readable — larger than {MAX_BYTES} bytes ({path})')]
|
|
178
|
+
try:
|
|
179
|
+
return render(json.loads(data.decode('utf-8')), now_ms, path)
|
|
180
|
+
except (UnicodeDecodeError, ValueError) as error: # json.JSONDecodeError and Malformed are ValueErrors
|
|
181
|
+
return [('✗', f'lanes2 signals snapshot readable — {error} ({path})')]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def doctor_lines(state=None, now_ms=None):
|
|
185
|
+
"""`lanes doctor`'s lines for the snapshot under `state` ($LANES_STATE); [] when there is none."""
|
|
186
|
+
return read_snapshot(Path(state if state is not None else default_state()) / SNAPSHOT, now_ms)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def print_lines(lines, out=None):
|
|
190
|
+
"""Print `lines` the way `lanes doctor` prints checks, warnings and information; True when one is ✗."""
|
|
191
|
+
out = sys.stdout if out is None else out
|
|
192
|
+
for mark, text in lines:
|
|
193
|
+
out.write(f'{mark or " "} {text}\n')
|
|
194
|
+
return any(mark == '✗' for mark, _text in lines)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def main(argv):
|
|
198
|
+
snapshot, now_ms, rest = None, None, list(argv)
|
|
199
|
+
while rest:
|
|
200
|
+
word = rest.pop(0)
|
|
201
|
+
if word == '--snapshot' and rest:
|
|
202
|
+
snapshot = Path(rest.pop(0))
|
|
203
|
+
elif word == '--now-ms' and rest and rest[0].isdigit():
|
|
204
|
+
now_ms = int(rest.pop(0))
|
|
205
|
+
else:
|
|
206
|
+
print(USAGE, file=sys.stderr)
|
|
207
|
+
return 2
|
|
208
|
+
lines = doctor_lines(now_ms=now_ms) if snapshot is None else read_snapshot(snapshot, now_ms)
|
|
209
|
+
return 1 if print_lines(lines) else 0
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
if __name__ == '__main__':
|
|
213
|
+
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
|
-
|
|
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
|
-
|
|
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:
|