okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221terminal: strata_cli, strata_control, bin/strata and the terminal tests64a91dcdc

main
6.3 KiB151 linesraw
1"""Read-only, bounded request activity for the source and portable CLI."""
2
3from __future__ import annotations
4
5import json
6import sys
7import time
8from typing import Any
9
10from strata_cli.client import ClientError, Endpoint
11from strata_cli.render import activity_label
12
13
14def _emit(record: dict[str, Any], machine: bool) -> None:
15    if machine:
16        print(json.dumps({"schema_version": 1, **record}, ensure_ascii=False, allow_nan=False), flush=True)
17    elif record["type"] == "activity":
18        print(activity_label(record, 120), flush=True)
19    elif record["type"] == "gap":
20        print(f"Activity #{record['from_seq']}–#{record['to_seq']} is absent from this bounded feed", flush=True)
21    elif record["type"] == "instance_change":
22        print("Serving instance changed; activity sequence restarted", flush=True)
23
24
25def activity_delta(snapshot: dict, instance_id: str | None, cursor: int | None) -> tuple[list[dict], str, int]:
26    """Return new transitions and explicit sequence gaps from one sanitized snapshot."""
27    current_id = (snapshot.get("instance") or {}).get("id")
28    activity = snapshot.get("activity") or {}
29    if not current_id or not activity.get("available"):
30        raise ClientError("request activity is unavailable on this server", 5)
31    latest = activity["last_seq"]
32    if type(latest) is not int:
33        raise ClientError("invalid request activity sequence", 5)
34    rows = activity["events"]
35    changed = instance_id is not None and current_id != instance_id
36    if changed:
37        cursor = None
38    elif cursor is not None and latest < cursor:
39        raise ClientError("request activity sequence moved backwards without an instance change", 5)
40    out: list[dict] = []
41    if changed:
42        out.append({"type": "instance_change", "from_instance_id": instance_id,
43                    "instance_id": current_id})
44    next_seq = 1 if cursor is None else cursor + 1
45    for row in rows:
46        seq = row["seq"]
47        if seq < next_seq:
48            continue
49        if seq > next_seq:
50            out.append({"type": "gap", "instance_id": current_id,
51                        "from_seq": next_seq, "to_seq": seq - 1})
52        out.append({"type": "activity", "instance_id": current_id, **row})
53        next_seq = seq + 1
54    if latest >= next_seq:
55        out.append({"type": "gap", "instance_id": current_id,
56                    "from_seq": next_seq, "to_seq": latest})
57    return out, current_id, latest
58
59
60class ActivityContinuity:
61    """Track gaps seen by one monitor without retaining request history locally."""
62
63    def __init__(self) -> None:
64        self.instance_id: str | None = None
65        self.cursor: int | None = None
66        self.gap: dict[str, int] | None = None
67        self.restarted = False
68        self.regressed = False
69
70    def add(self, snapshot: dict) -> None:
71        instance_id = (snapshot.get("instance") or {}).get("id")
72        activity = snapshot.get("activity") or {}
73        if not isinstance(instance_id, str) or not instance_id or not activity.get("available"):
74            return
75        latest = activity.get("last_seq")
76        if type(latest) is not int:
77            return
78        if self.instance_id is None:
79            # Retention before attach is expected; only report gaps after observation starts.
80            self.instance_id, self.cursor = instance_id, latest
81            return
82        try:
83            events, current_id, cursor = activity_delta(snapshot, self.instance_id, self.cursor)
84        except ClientError:
85            self.regressed = True
86            return
87        if current_id != self.instance_id:
88            self.gap = None
89            self.restarted = True
90            self.regressed = False
91        gaps = [event for event in events if event["type"] == "gap"]
92        if gaps:
93            self.gap = {"from_seq": gaps[-1]["from_seq"], "to_seq": gaps[-1]["to_seq"]}
94        self.instance_id, self.cursor = current_id, cursor
95
96    def status(self) -> dict:
97        return {"gap": dict(self.gap) if self.gap else None,
98                "restarted": self.restarted, "regressed": self.regressed}
99
100
101def run(endpoint: Endpoint, *, follow: bool, output: str, interval: float,
102        quiet: bool = False) -> int:
103    """Display retained transitions, then poll one snapshot at a time if requested."""
104    machine = output != "human"
105    snapshot = endpoint.snapshot()
106    activity = snapshot.get("activity") or {}
107    if not activity.get("available"):
108        raise ClientError("request activity is unavailable on this server", 5)
109    instance_id = (snapshot.get("instance") or {}).get("id")
110    if not follow:
111        record = {"schema_version": 1, "ok": True, "source": "runtime_activity",
112                  "instance_id": instance_id, "last_seq": activity["last_seq"],
113                  "retained": len(activity["events"]), "events": activity["events"]}
114        if machine:
115            print(json.dumps(record, ensure_ascii=False, allow_nan=False))
116        else:
117            if not quiet:
118                print("Recent request activity (redacted; newest 32 only)")
119            if activity["events"]:
120                for row in activity["events"]:
121                    print(activity_label(row, 120))
122            elif not quiet:
123                print("No request transitions retained")
124        return 0
125    if not instance_id:
126        raise ClientError("request activity follow needs a serving instance ID", 5)
127    if not machine and not quiet:
128        print("Following redacted request activity (polling; Ctrl+C to detach)", flush=True)
129    events, current_id, cursor = activity_delta(snapshot, None, None)
130    for event in events:
131        _emit(event, machine)
132    failures = 0
133    while True:
134        try:
135            time.sleep(interval)
136            snapshot = endpoint.snapshot()
137            events, current_id, cursor = activity_delta(snapshot, current_id, cursor)
138        except ClientError as e:
139            if e.exit_code != 3:
140                raise
141            failures += 1
142            if failures >= 3:
143                raise ClientError("request activity connection failed after 3 attempts", 3) from e
144            if failures == 1 and not quiet:
145                print("strata: activity connection lost; retrying", file=sys.stderr)
146            continue
147        if failures and not quiet:
148            print("strata: activity connection restored", file=sys.stderr)
149        failures = 0
150        for event in events:
151            _emit(event, machine)