okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
71e26e68f
main
1"""Versioned, owner-editable serving profiles separate from setup's run config. 2 3The source JSON belongs to setup.py; this small layer keeps operator overrides in 4the user's configuration directory so an installer update cannot silently erase 5them. It deliberately does not start processes or contact a network service. 6""" 7 8from __future__import annotations 9 10from strata_control .private_files import private_mkdir as _private_mkdir 11import hashlib 12import json 13import math 14import os 15import re 16import shlex 17import stat 18import subprocess 19import tempfile 20from strata_control import atomic as _atomic_mod 21from contextlib import contextmanager 22from pathlib import Path 23 24 25PROFILE_ID = re .compile (r"[a-z][a-z0-9_-]{0,63}\Z" ) 26OVERRIDE_KEYS = frozenset ({"host" ,"port" ,"parallel" ,"batch_groups" ,"max_queue" ,"queue_timeout" ,"offline" , 27"batch_telemetry" }) 28 29 30class ProfileError (ValueError ): 31"""A profile is missing, invalid or changed while it was being edited.""" 32 33def __init__ (self ,message :str ,exit_code :int = 2 ): 34super ().__init__ (message ) 35self .exit_code = exit_code 36 37 38def profile_dir ()-> Path : 39explicit = os .environ .get ("STRATA_PROFILE_DIR" ) 40if explicit : 41return Path (explicit ).expanduser () 42if os .name == "nt" : 43base = os .environ .get ("APPDATA" ) 44return (Path (base )if base else Path .home ()/ "AppData" / "Roaming" )/ "Strata" / "profiles" 45return Path (os .environ .get ("XDG_CONFIG_HOME" ,str (Path .home ()/ ".config" )))/ "strata" / "profiles" 46 47 48def _name (name :str )-> str : 49if not PROFILE_ID .fullmatch (name ): 50raise ProfileError ("profile name must start with a lowercase letter and use only a-z, 0-9, _ or -" ) 51return name 52 53 54def _path (name :str )-> Path : 55return profile_dir ()/ f" { _name ( name ) } .json" 56 57 58def _bytes (profile :dict )-> bytes : 59return (json .dumps (profile ,indent = 2 ,ensure_ascii = False ,sort_keys = True )+ "\n" ).encode ("utf-8" ) 60 61 62def _revision (data :bytes )-> str : 63return hashlib .sha256 (data ).hexdigest ()[:16 ] 64 65 66def parse_assignment (text :str )-> tuple [str ,object ]: 67key ,sep ,raw = text .partition ("=" ) 68if not sep or key not in OVERRIDE_KEYS : 69raise ProfileError (f"expected one of { ', ' . join ( sorted ( OVERRIDE_KEYS )) } as KEY=VALUE" ) 70if key in ("port" ,"parallel" ,"max_queue" ): 71try : 72value :object = int (raw ) 73except ValueError : 74raise ProfileError (f" { key } must be a whole number" )from None 75elif key == "queue_timeout" : 76try : 77value = float (raw ) 78except ValueError : 79raise ProfileError ("queue_timeout must be a number of seconds" )from None 80elif key == "batch_groups" : 81if raw == "auto" : 82value = raw 83else : 84try : 85value = int (raw ) 86except ValueError : 87raise ProfileError ("batch_groups must be auto or a positive whole number" )from None 88elif key in ("offline" ,"batch_telemetry" ): 89if raw not in ("true" ,"false" ): 90raise ProfileError (f" { key } must be true or false" ) 91value = raw == "true" 92else : 93value = raw 94validate_overrides ({key :value }) 95return key ,value 96 97 98def validate_overrides (overrides :object )-> dict : 99if not isinstance (overrides ,dict )or set (overrides )- OVERRIDE_KEYS : 100raise ProfileError ("overrides must contain only supported serving settings" ) 101for key ,value in overrides .items (): 102if key == "host" and (not isinstance (value ,str )or not value or any (c .isspace ()for c in value )): 103raise ProfileError ("host must be a nonempty address without whitespace" ) 104if key == "port" and (type (value )is not int or not 0 <= value <= 65535 ): 105raise ProfileError ("port must be in 0..65535" ) 106if key == "parallel" and (type (value )is not int or not 1 <= value <= 1024 ): 107raise ProfileError ("parallel must be in 1..1024" ) 108if key == "max_queue" and (type (value )is not int or not 0 <= value <= 4096 ): 109raise ProfileError ("max_queue must be in 0..4096" ) 110if key == "queue_timeout" and (type (value )not in (int ,float )or not math .isfinite (value ) 111or not 0.1 <= value <= 600 ): 112raise ProfileError ("queue_timeout must be finite seconds in 0.1..600" ) 113if key == "batch_groups" and value != "auto" and (type (value )is not int or not 1 <= value <= 1024 ): 114raise ProfileError ("batch_groups must be auto or in 1..1024" ) 115if key in ("offline" ,"batch_telemetry" )and type (value )is not bool : 116raise ProfileError (f" { key } must be true or false" ) 117return overrides 118 119 120def validate_profile (value :object ,* ,expected_name :str | None = None )-> dict : 121if not isinstance (value ,dict )or set (value )!= {"schema_version" ,"id" ,"source_config" ,"overrides" }: 122raise ProfileError ("profile needs schema_version, id, source_config and overrides" ) 123if type (value ["schema_version" ])is not int or value ["schema_version" ]!= 1 : 124raise ProfileError ("unsupported profile schema version" ) 125name = _name (value ["id" ]if isinstance (value ["id" ],str )else "" ) 126if expected_name is not None and name != expected_name : 127raise ProfileError ("profile ID does not match its filename" ) 128source = value ["source_config" ] 129if not isinstance (source ,str )or not Path (source ).is_absolute (): 130raise ProfileError ("source_config must be an absolute path" ) 131validate_overrides (value ["overrides" ]) 132return value 133 134 135def read_run_config (path :Path )-> dict : 136try : 137cfg = json .loads (path .read_text (encoding = "utf-8-sig" )) 138except (OSError ,ValueError )as exc : 139raise ProfileError (f"cannot read run config ( { type ( exc ). __name__ } )" ,5 )from None 140if isinstance (cfg ,dict ):# paths into a version folder of Strata's own that an update removed: the current one 141from strata_control import cfg_paths 142cfg = cfg_paths .resolve_config (cfg )[0 ] 143if not isinstance (cfg ,dict )or not isinstance (cfg .get ("args" ),list )or not all ( 144isinstance (arg ,str )for arg in cfg ["args" ] 145 ): 146raise ProfileError ("run config needs an args array of strings" ) 147for key in ("exe" ,"tokenizer" ): 148if not isinstance (cfg .get (key ),str )or not cfg [key ]: 149raise ProfileError (f"run config needs a nonempty { key } path" ) 150return cfg 151 152 153def load (name :str )-> tuple [dict ,str ]: 154path = _path (name ) 155try : 156if not stat .S_ISREG (path .lstat ().st_mode ): 157raise ProfileError ("profile must be a regular file" ,5 ) 158from strata_control import private_files 159data = private_files .read_bytes_repairing (path )# a profile an elevated run locked is repaired once, in place 160if len (data )> 1024 * 1024 : 161raise ProfileError ("profile is larger than 1 MiB" ,5 ) 162value = json .loads (data .decode ("utf-8-sig" )) 163except FileNotFoundError : 164raise ProfileError (f"profile { name !r } is not saved; use strata profile create" ,5 )from None 165except (OSError ,ValueError ,UnicodeError )as exc : 166if isinstance (exc ,ProfileError ): 167raise 168raise ProfileError (f"cannot read profile ( { type ( exc ). __name__ } )" ,5 )from None 169return validate_profile (value ,expected_name = name ),_revision (data ) 170 171 172def list_profiles ()-> list [dict ]: 173directory = profile_dir () 174if not directory .exists (): 175return [] 176result = [] 177for path in sorted (directory .glob ("*.json" )): 178if not PROFILE_ID .fullmatch (path .stem ): 179continue 180try : 181profile ,revision = load (path .stem ) 182result .append ({"id" :path .stem ,"revision" :revision ,"source_config" :profile ["source_config" ]}) 183except ProfileError as exc : 184result .append ({"id" :path .stem ,"error" :str (exc )}) 185return result 186 187 188@contextmanager 189def _lock (name :str ): 190directory = profile_dir () 191_private_mkdir (directory ,parents = True ,exist_ok = True ) 192lock = directory / f". { _name ( name ) } .lock" 193with open (lock ,"a+b" )as stream : 194if os .name == "nt" : 195import msvcrt 196stream .seek (0 ) 197if not stream .read (1 ): 198stream .write (b"0" ) 199stream .flush () 200stream .seek (0 ) 201msvcrt .locking (stream .fileno (),msvcrt .LK_LOCK ,1 ) 202try : 203yield 204finally : 205stream .seek (0 ) 206msvcrt .locking (stream .fileno (),msvcrt .LK_UNLCK ,1 ) 207else : 208import fcntl 209fcntl .flock (stream .fileno (),fcntl .LOCK_EX ) 210try : 211yield 212finally : 213fcntl .flock (stream .fileno (),fcntl .LOCK_UN ) 214 215 216def _atomic (path :Path ,data :bytes )-> None : 217fd ,temp_name = tempfile .mkstemp (prefix = f". { path . stem } -" ,suffix = ".tmp" ,dir = path .parent ) 218try : 219with os .fdopen (fd ,"wb" )as stream : 220stream .write (data ) 221stream .flush () 222os .fsync (stream .fileno ()) 223_atomic_mod .replace (temp_name ,path ) 224if os .name != "nt" : 225try : 226parent_fd = os .open (path .parent ,os .O_RDONLY ) 227try : 228os .fsync (parent_fd ) 229finally : 230os .close (parent_fd ) 231except OSError : 232# Replacement already succeeded; do not report a failed save after it changed the profile. 233pass 234finally : 235if os .path .exists (temp_name ): 236os .unlink (temp_name ) 237 238 239def create (name :str ,source_config :str )-> tuple [dict ,str ]: 240name = _name (name ) 241try : 242source = Path (source_config ).expanduser ().resolve (strict = True ) 243except OSError as exc : 244raise ProfileError (f"run config is unavailable ( { type ( exc ). __name__ } )" ,5 )from None 245read_run_config (source ) 246profile = {"schema_version" :1 ,"id" :name ,"source_config" :str (source ),"overrides" : {}} 247with _lock (name ): 248path = _path (name ) 249if path .exists ()or path .is_symlink (): 250raise ProfileError (f"profile { name !r } already exists" ) 251_atomic (path ,_bytes (profile )) 252return load (name ) 253 254 255def propose_source (name :str ,source_config :str )-> tuple [dict ,str ]: 256"""Select another installed run config without changing its contents.""" 257current ,revision = load (name ) 258try : 259source = Path (source_config ).expanduser ().resolve (strict = True ) 260except OSError as exc : 261raise ProfileError (f"run config is unavailable ( { type ( exc ). __name__ } )" ,5 )from None 262if not stat .S_ISREG (source .lstat ().st_mode ): 263raise ProfileError ("run config must be a regular file" ,5 ) 264read_run_config (source ) 265proposed = {** current ,"source_config" :str (source )} 266return validate_profile (proposed ,expected_name = name ),revision 267 268 269def save (name :str ,proposed :dict ,* ,expected_revision :str , 270expected_source_sha256 :str | None = None )-> tuple [dict ,str ]: 271name = _name (name ) 272validate_profile (proposed ,expected_name = name ) 273read_run_config (Path (proposed ["source_config" ])) 274with _lock (name ): 275current ,revision = load (name ) 276if revision != expected_revision : 277raise ProfileError ("profile changed during edit; reload it before saving" ,6 ) 278if expected_source_sha256 is not None : 279if not re .fullmatch (r"[0-9a-f]{64}" ,expected_source_sha256 ): 280raise ProfileError ("source digest must be a lowercase SHA-256" ) 281try : 282source = Path (proposed ["source_config" ]).read_bytes () 283except OSError : 284raise ProfileError ("run config changed after review; retry" ,6 )from None 285if len (source )> 1024 * 1024 or hashlib .sha256 (source ).hexdigest ()!= expected_source_sha256 : 286raise ProfileError ("run config changed after review; retry" ,6 ) 287if current == proposed : 288return current ,revision 289history = profile_dir ()/ ".history" / name 290_private_mkdir (history ,parents = True ,exist_ok = True ) 291old = _path (name ).read_bytes () 292if _revision (old )!= revision : 293raise ProfileError ("profile changed during edit; reload it before saving" ,6 ) 294old_path = history / f" { revision } .json" 295if not old_path .exists (): 296_atomic (old_path ,old ) 297_atomic (_path (name ),_bytes (proposed )) 298return load (name ) 299 300 301def set_values (name :str ,assignments :list [str ])-> tuple [dict ,str ,str ]: 302proposed ,revision = propose_values (name ,assignments ) 303saved ,new_revision = save (name ,proposed ,expected_revision = revision ) 304return saved ,revision ,new_revision 305 306 307def propose_values (name :str ,assignments :list [str ])-> tuple [dict ,str ]: 308current ,revision = load (name ) 309changed = {key :value for key ,value in (parse_assignment (item )for item in assignments )} 310proposed = {** current ,"overrides" : {** current ["overrides" ],** changed }} 311validate_profile (proposed ,expected_name = name ) 312return proposed ,revision 313 314 315def history (name :str )-> list [dict ]: 316_name (name ) 317directory = profile_dir ()/ ".history" / name 318entries = [] 319if directory .exists (): 320for path in directory .glob ("*.json" ): 321if re .fullmatch (r"[0-9a-f]{16}" ,path .stem )and path .is_file ()and not path .is_symlink (): 322entries .append ({"revision" :path .stem ,"saved_at" :path .stat ().st_mtime }) 323_ ,current = load (name ) 324return [{"revision" :current ,"current" :True }, 325* sorted ((item for item in entries if item ["revision" ]!= current ), 326key = lambda item :item ["saved_at" ],reverse = True )] 327 328 329def rollback (name :str ,target_revision :str )-> tuple [dict ,str ,str ]: 330_name (name ) 331if not re .fullmatch (r"[0-9a-f]{16}" ,target_revision ): 332raise ProfileError ("rollback target must be a full 16-character revision" ) 333_ ,current_revision = load (name ) 334path = profile_dir ()/ ".history" / name / f" { target_revision } .json" 335try : 336if not stat .S_ISREG (path .lstat ().st_mode ): 337raise ProfileError ("profile history must be a regular file" ,5 ) 338data = path .read_bytes () 339if _revision (data )!= target_revision : 340raise ProfileError ("profile history content does not match its revision" ,5 ) 341target = validate_profile (json .loads (data .decode ("utf-8" )),expected_name = name ) 342except FileNotFoundError : 343raise ProfileError (f"profile revision { target_revision } was not found" ,5 )from None 344except (OSError ,UnicodeError ,ValueError )as exc : 345if isinstance (exc ,ProfileError ): 346raise 347raise ProfileError (f"cannot read profile history ( { type ( exc ). __name__ } )" ,5 )from None 348saved ,new_revision = save (name ,target ,expected_revision = current_revision ) 349return saved ,current_revision ,new_revision 350 351 352def edit (name :str )-> tuple [dict ,str ,str ]: 353current ,revision = load (name ) 354editor = os .environ .get ("VISUAL" )or os .environ .get ("EDITOR" ) 355if not editor : 356raise ProfileError ("set VISUAL or EDITOR, or use strata profile set" ) 357command = shlex .split (editor ,posix = os .name != "nt" ) 358if not command : 359raise ProfileError ("VISUAL or EDITOR is empty" ) 360fd ,temp_name = tempfile .mkstemp (prefix = f". { name } -edit-" ,suffix = ".json" ,dir = profile_dir ()) 361keep_draft = False 362try : 363with os .fdopen (fd ,"wb" )as stream : 364stream .write (_bytes (current )) 365result = subprocess .run ([* command ,temp_name ],check = False ) 366if result .returncode : 367keep_draft = True 368raise ProfileError (f"editor exited with status { result . returncode } ; draft kept at { temp_name } " ,6 ) 369try : 370proposed = json .loads (Path (temp_name ).read_text (encoding = "utf-8-sig" )) 371except (OSError ,ValueError )as exc : 372keep_draft = True 373raise ProfileError (f"edited profile is not valid JSON ( { type ( exc ). __name__ } ); draft kept at { temp_name } " )from None 374try : 375saved ,new_revision = save (name ,proposed ,expected_revision = revision ) 376except ProfileError as exc : 377keep_draft = True 378raise ProfileError (f" { exc } ; draft kept at { temp_name } " ,exc .exit_code )from None 379return saved ,revision ,new_revision 380finally : 381if not keep_draft : 382Path (temp_name ).unlink (missing_ok = True ) 383 384 385def resolve (ref :str )-> tuple [Path ,dict | None ,str | None ]: 386"""A saved name or an explicit JSON path; path-like values never fall back to names.""" 387path = Path (ref ).expanduser () 388if path .suffix .lower ()== ".json" or path .is_absolute ()or "/" in ref or "\\" in ref : 389return path .resolve (),None ,None 390profile ,revision = load (ref ) 391return Path (profile ["source_config" ]),profile ,revision