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