okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""Independent, versioned components: manifests, safe unpacking, atomic activation, rollback. 2 3The application, the engine, the agent runtime, tuning and prepared data are separate deliverables 4with separate lifecycles, so they are separate *components* here. This module is the machinery they 5share: what a component is, whether it may be used on this machine, how it is verified before it is 6unpacked, how it is unpacked without escaping its directory, how it is cached, and how it is 7activated and rolled back. 8 9The design decisions that matter, and why: 10 11**Verification happens before anything is written.** A manifest names each artifact's SHA-256. An 12artifact whose digest does not match is refused and nothing is extracted — not extracted-then-checked, 13because a compromised archive can do damage during extraction. 14 15**Unpacking cannot escape its destination.** Archive members are validated: no absolute paths, no 16`..` segments, no symlinks or hard links pointing outside, no device or FIFO members, and on Windows 17no drive-relative or UNC paths. Every member's resolved destination is checked to be inside the 18target. This is the one place where a hostile input turns into arbitrary file writes, so it is 19checked rather than trusted, and the checks are tested with the actual attack shapes. 20 21**Installation is by content digest, not by version string.** The cache is keyed on the digest of the 22artifact bytes, so a rebuilt artifact with an unchanged version number is a different cache entry, 23and a compatible application update reuses components rather than re-downloading them. 24 25**Activation is a rename, and the previous target is kept.** A component version becomes active by 26renaming a directory into place, which is atomic within a filesystem; the version it replaced is 27moved aside rather than deleted, so rollback restores it exactly. Nothing is ever deleted on 28activation. 29 30**Interrupted transfers are the normal case, not the exception.** A partial download is kept with a 31digest of what is there, resumed when possible, and only promoted to the cache once complete and 32verified. A crash during activation leaves the store consistent because the rename either happened or 33it did not. 34""" 35 36from __future__import annotations 37 38import hashlib 39import json 40import re 41import shutil 42import stat 43import tarfile 44import time 45import zipfile 46from dataclasses import asdict ,dataclass 47from pathlib import Path ,PurePosixPath 48from typing import Any ,Iterable 49 50SCHEMA_VERSION = 1 51 52from strata_control .targets import BACKEND_MATRIX ,ComponentError ,backend_supported ,host_platform # noqa: E402,F401 53from strata_control import atomic as _atomic_mod 54#: Component kinds, so a manifest cannot claim a role the architecture does not have. 55KINDS = ("application" ,"runtime" ,"agent-runtime" ,"tuning" ,"engine" ,"prepared-data" ) 56 57 58class UnsafeArchive (ComponentError ): 59"""An archive member would escape the destination. Nothing was extracted.""" 60 61 62# --------------------------------------------------------------------------- manifests 63 64@dataclass 65class Artifact : 66"""One downloadable file, identified by content.""" 67 68name :str 69url :str | None 70sha256 :str 71bytes :int 72format :str = "tar.gz" # tar.gz | tar.xz | zip | file 73unpack_to :str | None = None # where inside the component the archive's root lands 74 75def verify_bytes (self ,payload :bytes )-> None : 76actual = hashlib .sha256 (payload ).hexdigest () 77if actual != self .sha256 : 78raise ComponentError ( 79f"the downloaded { self . name } does not match its manifest: expected " 80f" { self . sha256 [: 16 ] } …, got { actual [: 16 ] } …" ) 81if self .bytes and len (payload )!= self .bytes : 82raise ComponentError ( 83f" { self . name } is { len ( payload ) } bytes, the manifest declares { self . bytes } " ) 84 85def verify_file (self ,path :Path )-> None : 86digest = hashlib .sha256 () 87size = 0 88with Path (path ).open ("rb" )as fh : 89for block in iter (lambda :fh .read (1 << 20 ),b"" ): 90digest .update (block ) 91size += len (block ) 92if digest .hexdigest ()!= self .sha256 : 93raise ComponentError ( 94f" { path . name } does not match its manifest: expected { self . sha256 [: 16 ] } …, " 95f"got { digest . hexdigest ()[: 16 ] } …" ) 96if self .bytes and size != self .bytes : 97raise ComponentError (f" { path . name } is { size } bytes, the manifest declares { self . bytes } " ) 98 99 100@dataclass 101class Component : 102"""A versioned, independently installable piece of the product.""" 103 104id :str 105version :str 106kind :str 107backend :str | None 108platforms :tuple [str , ...] 109artifacts :tuple [Artifact , ...] 110requires :tuple [str , ...]= () 111provides :tuple [str , ...]= () 112license :str = "" 113notes :str = "" 114#: Where the payload must be on the PATH or on disk once active, relative to the component root. 115entrypoint :str | None = None 116 117@property 118def cache_key (self )-> str : 119"""The identity of this component's bytes, not its version label. 120 121A rebuilt artifact with the same version is a different key, so a cache hit is a statement 122about the bytes rather than about a string someone typed. 123""" 124joined = "|" .join (f" { a . name } : { a . sha256 } " for a in sorted (self .artifacts ,key = lambda a :a .name )) 125return hashlib .sha256 (f" { self . id } @ { self . version } | { joined } " .encode ()).hexdigest () 126 127def to_dict (self )-> dict [str ,Any ]: 128data = asdict (self ) 129data ["schema_version" ]= SCHEMA_VERSION 130data ["cache_key" ]= self .cache_key 131return data 132 133 134def parse_manifest (payload :str | bytes | dict )-> Component : 135"""Read a component manifest, refusing anything that is not one. 136 137A manifest is the input that decides what gets downloaded and unpacked, so it is parsed strictly: 138a missing digest or an unknown kind is an error, not a default. 139""" 140if isinstance (payload , (str ,bytes )): 141try : 142data = json .loads (payload ) 143except json .JSONDecodeError as e : 144raise ComponentError (f"the component manifest is not valid JSON: { e } " )from None 145else : 146data = payload 147if not isinstance (data ,dict ): 148raise ComponentError ("the component manifest must be a JSON object" ) 149if data .get ("schema_version" )!= SCHEMA_VERSION : 150raise ComponentError ( 151f"unsupported manifest schema_version { data . get ( 'schema_version' )!r } ; expected " 152f" { SCHEMA_VERSION } " ) 153 154for required in ("id" ,"version" ,"kind" ,"artifacts" ): 155if not data .get (required ): 156raise ComponentError (f"the component manifest has no { required !r } " ) 157if data ["kind" ]not in KINDS : 158raise ComponentError ( 159f"unknown component kind { data [ 'kind' ]!r } ; expected one of { ', ' . join ( KINDS ) } " ) 160if not re .fullmatch (r"[a-z0-9][a-z0-9._-]{0,63}" ,str (data ["id" ])): 161raise ComponentError (f"the component id { data [ 'id' ]!r } is not a plain lowercase name" ) 162 163artifacts :list [Artifact ]= [] 164for raw in data ["artifacts" ]: 165if not isinstance (raw ,dict ): 166raise ComponentError ("every artifact must be a JSON object" ) 167for required in ("name" ,"sha256" ,"bytes" ): 168if raw .get (required )in (None ,"" ): 169raise ComponentError (f"an artifact has no { required !r } : { raw . get ( 'name' )!r } " ) 170digest = str (raw ["sha256" ]).lower () 171if not re .fullmatch (r"[0-9a-f]{64}" ,digest ): 172raise ComponentError ( 173f"an artifact's sha256 is not a 64-character hex digest: { raw [ 'sha256' ]!r } " ) 174try : 175size = int (raw ["bytes" ]) 176except (TypeError ,ValueError ): 177raise ComponentError (f"an artifact's bytes is not a number: { raw [ 'bytes' ]!r } " )from None 178if size <= 0 : 179raise ComponentError (f"an artifact declares { size } bytes, which cannot be a real file" ) 180# A path-like name would be used as a filename later, so it must not be one. 181if "/" in str (raw ["name" ])or "\\" in str (raw ["name" ])or str (raw ["name" ])in ("." ,".." ): 182raise ComponentError (f"an artifact name is a path, which is not allowed: { raw [ 'name' ]!r } " ) 183artifacts .append (Artifact ( 184name = str (raw ["name" ]),url = raw .get ("url" ),sha256 = digest ,bytes = size , 185format = str (raw .get ("format" ,"tar.gz" )), 186unpack_to = raw .get ("unpack_to" ))) 187if not artifacts : 188raise ComponentError ("the component manifest lists no artifacts" ) 189 190platforms = data .get ("platforms" ) 191if platforms is None : 192raise ComponentError ( 193"the component manifest does not say which platforms it supports; an unstated platform " 194"would be treated as every platform" ) 195if not isinstance (platforms , (list ,tuple ))or not platforms : 196raise ComponentError ("the component's platforms must be a non-empty list" ) 197 198return Component ( 199id = str (data ["id" ]),version = str (data ["version" ]),kind = str (data ["kind" ]), 200backend = data .get ("backend" ),platforms = tuple (str (p )for p in platforms ), 201artifacts = tuple (artifacts ),requires = tuple (data .get ("requires" )or ()), 202provides = tuple (data .get ("provides" )or ()),license = str (data .get ("license" )or "" ), 203notes = str (data .get ("notes" )or "" ),entrypoint = data .get ("entrypoint" )) 204 205 206def check_compatible (component :Component ,* ,target :str | None = None , 207backend :str | None = None )-> list [str ]: 208"""Why this component cannot be used here. An empty list means it can. 209 210Compatibility is a refusal gate, not a warning: activating an engine built for another backend is 211the failure this exists to prevent, and the packet is explicit that unsupported combinations stay 212explicitly gated rather than attempted. 213""" 214target = target or host_platform () 215reasons :list [str ]= [] 216if target not in component .platforms : 217reasons .append ( 218f" { component . id } { component . version } supports { ', ' . join ( component . platforms ) } , not { target } " ) 219if component .backend and backend is not None and component .backend != backend : 220reasons .append ( 221f" { component . id } is built for the { component . backend } backend, not { backend } " ) 222if component .backend : 223supported ,why = backend_supported (component .backend ,target ) 224if not supported : 225reasons .append (why ) 226return reasons 227 228 229# --------------------------------------------------------------------------- safe unpacking 230 231def _is_unsafe_member (name :str )-> str | None : 232"""Why an archive member name is unsafe, or None if it is fine. 233 234The attack shapes are listed explicitly rather than relying on a single normalisation trick, 235because a name that survives normalisation on one platform can still be absolute on another. 236""" 237if not name or name in ("." ,"./" ): 238return "an empty member name" 239if "\x00" in name : 240return "a NUL byte in the name" 241# Windows separators are treated as separators on every platform: an archive built on Windows 242# must not be able to escape a destination on macOS, and vice versa. 243normalised = name .replace ("\\" ,"/" ) 244if normalised .startswith ("/" ): 245return "an absolute path" 246if re .match (r"^[A-Za-z]:" ,normalised ): 247return "a drive-letter path" 248if normalised .startswith ("//" ): 249return "a UNC path" 250parts = PurePosixPath (normalised ).parts 251if any (part == ".." for part in parts ): 252return "a '..' segment" 253return None 254 255 256def _check_member_within (destination :Path ,member_name :str )-> Path : 257"""The member's resolved destination, refusing anything outside `destination`. 258 259Both the lexical check above and this resolved check are performed: the lexical one catches the 260obvious shapes, and this one catches a path that is only outside after resolution. 261""" 262unsafe = _is_unsafe_member (member_name ) 263if unsafe : 264raise UnsafeArchive (f"the archive contains { unsafe } : { member_name !r } " ) 265target = (destination / member_name .replace ("\\" ,"/" )).resolve () 266root = destination .resolve () 267if target != root and root not in target .parents : 268raise UnsafeArchive (f"the archive member { member_name !r } would land outside the destination" ) 269return target 270 271 272def safe_extract (archive :Path ,destination :Path ,* ,fmt :str | None = None )-> list [str ]: 273"""Unpack an archive into `destination`, or refuse without writing. 274 275Validated before any member is written: every member's name and resolved destination is checked 276first, so a refusal leaves the destination untouched rather than half-populated. 277""" 278archive = Path (archive ) 279destination = Path (destination ) 280fmt = fmt or _format_of (archive ) 281members = _members (archive ,fmt ) 282 283# Validate everything first: a refusal must not leave a partial extraction behind. 284for name ,kind in members : 285_check_member_within (destination ,name ) 286if kind in ("symlink" ,"hardlink" ,"device" ,"fifo" ): 287# A link inside the archive can point anywhere, including outside; verifying where each 288# one points is more permissive than this product needs, so links are refused outright. 289raise UnsafeArchive ( 290f"the archive contains a { kind } member ( { name !r } ); links are not accepted because a " 291"link can point outside the destination" ) 292if kind == "other" : 293raise UnsafeArchive (f"the archive contains an unsupported member type ( { name !r } )" ) 294 295destination .mkdir (parents = True ,exist_ok = True ) 296written :list [str ]= [] 297if fmt in ("tar.gz" ,"tar.xz" ,"tar.bz2" ,"tar" ): 298with tarfile .open (archive ,_tar_mode (fmt ))as tar : 299for member in tar .getmembers (): 300target = _check_member_within (destination ,member .name ) 301if member .isdir (): 302target .mkdir (parents = True ,exist_ok = True ) 303continue 304target .parent .mkdir (parents = True ,exist_ok = True ) 305source = tar .extractfile (member ) 306if source is None : 307continue 308with target .open ("wb" )as out : 309shutil .copyfileobj (source ,out ) 310# Preserve the executable bit, which a bundled runtime or engine needs, and nothing 311# else: the archive's own permission bits are not trusted for setuid or setgid. 312mode = member .mode & 0o777 313if mode : 314target .chmod (mode | (stat .S_IXUSR if mode & 0o100 else 0 )) 315written .append (member .name ) 316elif fmt == "zip" : 317with zipfile .ZipFile (archive )as zf : 318for info in zf .infolist (): 319target = _check_member_within (destination ,info .filename ) 320if info .is_dir (): 321target .mkdir (parents = True ,exist_ok = True ) 322continue 323target .parent .mkdir (parents = True ,exist_ok = True ) 324with zf .open (info )as source ,target .open ("wb" )as out : 325shutil .copyfileobj (source ,out ) 326written .append (info .filename ) 327else : 328raise ComponentError (f"unsupported archive format { fmt !r } " ) 329return written 330 331 332def _format_of (archive :Path )-> str : 333name = archive .name .lower () 334for suffix ,fmt in ((".tar.gz" ,"tar.gz" ), (".tgz" ,"tar.gz" ), (".tar.xz" ,"tar.xz" ), 335 (".txz" ,"tar.xz" ), (".tar.bz2" ,"tar.bz2" ), (".zip" ,"zip" ), 336 (".tar" ,"tar" )): 337if name .endswith (suffix ): 338return fmt 339raise ComponentError (f"cannot tell the archive format of { archive . name !r } from its name" ) 340 341 342def _tar_mode (fmt :str )-> str : 343return {"tar.gz" :"r:gz" ,"tar.xz" :"r:xz" ,"tar.bz2" :"r:bz2" ,"tar" :"r:" }[fmt ] 344 345 346def _members (archive :Path ,fmt :str )-> list [tuple [str ,str ]]: 347"""Every member as (name, kind), used for validation before extraction.""" 348out :list [tuple [str ,str ]]= [] 349if fmt == "zip" : 350with zipfile .ZipFile (archive )as zf : 351for info in zf .infolist (): 352out .append ((info .filename ,"dir" if info .is_dir ()else "file" )) 353return out 354with tarfile .open (archive ,_tar_mode (fmt ))as tar : 355for member in tar .getmembers (): 356if member .isdir (): 357kind = "dir" 358elif member .isfile (): 359kind = "file" 360elif member .issym (): 361kind = "symlink" 362elif member .islnk (): 363kind = "hardlink" 364elif member .ischr ()or member .isblk (): 365kind = "device" 366elif member .isfifo (): 367kind = "fifo" 368else : 369kind = "other" 370out .append ((member .name ,kind )) 371return out 372 373 374# --------------------------------------------------------------------------- the store 375 376@dataclass 377class InstalledComponent : 378"""A component version present on disk, and whether it is the active one.""" 379 380id :str 381version :str 382cache_key :str 383path :str 384installed_at :float 385artifact_sha256 :tuple [str , ...]= () 386active :bool = False 387 388 389class ComponentStore : 390"""Installed components, a content-addressed cache, and atomic activation with rollback. 391 392Layout:: 393 394<root>/cache/<cache_key>/ unpacked payload, immutable once complete 395<root>/active/<component-id> a directory rename-linked to a cached version 396<root>/previous/<component-id> the version that was active before the last activation 397<root>/partial/<artifact-name> an interrupted transfer, kept for resume 398<root>/state.json what is installed and what is active 399""" 400 401def __init__ (self ,root :Path )-> None : 402self .root = Path (root ) 403for part in ("cache" ,"active" ,"previous" ,"partial" ): 404 (self .root / part ).mkdir (parents = True ,exist_ok = True ) 405 406# ------------------------------------------------------------------ state 407 408@property 409def state_path (self )-> Path : 410return self .root / "state.json" 411 412def state (self )-> dict [str ,Any ]: 413if not self .state_path .exists (): 414return {"schema_version" :SCHEMA_VERSION ,"components" : {}} 415try : 416data = json .loads (self .state_path .read_text (encoding = "utf-8" )) 417except json .JSONDecodeError : 418# A damaged state file must not make the store unusable; the cache on disk is the truth 419# about what is present, and the state file is rebuilt from it as things are activated. 420return {"schema_version" :SCHEMA_VERSION ,"components" : {}} 421if data .get ("schema_version" )!= SCHEMA_VERSION : 422return {"schema_version" :SCHEMA_VERSION ,"components" : {}} 423return data 424 425def _save_state (self ,data :dict [str ,Any ])-> None : 426temp = self .state_path .parent / (self .state_path .name + ".tmp" ) 427temp .write_text (json .dumps (data ,indent = 1 ,sort_keys = True )+ "\n" ,encoding = "utf-8" ) 428_atomic_mod .replace (temp ,self .state_path ) 429 430# ------------------------------------------------------------------ cache and installation 431 432def cached (self ,component :Component )-> Path | None : 433"""The cached payload for exactly these bytes, if it is complete.""" 434path = self .root / "cache" / component .cache_key 435marker = path / ".complete" 436return path if marker .exists ()else None 437 438def install (self ,component :Component ,* ,source :Path | None = None , 439payloads :dict [str ,bytes ]| None = None , 440target :str | None = None ,backend :str | None = None )-> Path : 441"""Verify and unpack a component into the cache, reusing it when the bytes are known. 442 443Every artifact is verified *before* unpacking, so a mismatch writes nothing. A component 444whose bytes are already cached is not downloaded or unpacked again, which is what makes a 445compatible application update free of engine re-downloads. 446""" 447reasons = check_compatible (component ,target = target ,backend = backend ) 448if reasons : 449raise ComponentError ("; " .join (reasons ),2 ) 450 451existing = self .cached (component ) 452if existing is not None and source is None and payloads is None : 453return existing 454 455destination = self .root / "cache" / component .cache_key 456if destination .exists ()and (destination / ".complete" ).exists (): 457return destination 458 459# A staging directory named for the cache key, so a crash leaves an incomplete directory that 460# is never mistaken for a complete one (the `.complete` marker is written last). 461staging = self .root / "cache" / f". { component . cache_key } .partial" 462if staging .exists (): 463shutil .rmtree (staging ,ignore_errors = True ) 464staging .mkdir (parents = True ) 465 466try : 467for artifact in component .artifacts : 468data = self ._obtain (artifact ,source = source ,payloads = payloads ) 469artifact .verify_bytes (data ) 470into = staging / (artifact .unpack_to or "" ) 471into .mkdir (parents = True ,exist_ok = True ) 472if artifact .format in ("tar.gz" ,"tar.xz" ,"tar.bz2" ,"tar" ,"zip" ): 473temp_archive = staging / f". { artifact . name } .archive" 474temp_archive .write_bytes (data ) 475try : 476safe_extract (temp_archive ,into ,fmt = artifact .format ) 477finally : 478temp_archive .unlink (missing_ok = True ) 479else : 480 (into / artifact .name ).write_bytes (data ) 481if artifact .name .endswith ((".sh" ,".bin" )): 482 (into / artifact .name ).chmod (0o755 ) 483 (staging / ".complete" ).write_text ( 484json .dumps ({"cache_key" :component .cache_key ,"id" :component .id , 485"version" :component .version ,"installed_at" :time .time ()}, 486indent = 1 )+ "\n" ,encoding = "utf-8" ) 487if destination .exists (): 488shutil .rmtree (destination ,ignore_errors = True ) 489_atomic_mod .replace (staging ,destination ) 490except BaseException : 491# Leave nothing that looks complete. 492shutil .rmtree (staging ,ignore_errors = True ) 493raise 494 495state = self .state () 496state ["components" ].setdefault (component .id , {})["installed" ]= ( 497state ["components" ].get (component .id , {}).get ("installed" )or {}) 498state ["components" ][component .id ]["installed" ][component .version ]= asdict (InstalledComponent ( 499id = component .id ,version = component .version ,cache_key = component .cache_key , 500path = str (destination ),installed_at = time .time (), 501artifact_sha256 = tuple (a .sha256 for a in component .artifacts ))) 502self ._save_state (state ) 503return destination 504 505def _obtain (self ,artifact :Artifact ,* ,source :Path | None , 506payloads :dict [str ,bytes ]| None )-> bytes : 507"""The artifact's bytes, from memory, from disk, or from its URL.""" 508if payloads and artifact .name in payloads : 509return payloads [artifact .name ] 510if source is not None : 511candidate = Path (source ) 512if candidate .is_dir (): 513candidate = candidate / artifact .name 514if not candidate .exists (): 515raise ComponentError (f"the artifact { artifact . name } is not at { candidate } " ) 516return candidate .read_bytes () 517if artifact .url : 518return self ._fetch (artifact ) 519raise ComponentError ( 520f" { artifact . name } has no url and no local source was given, so it cannot be obtained" ) 521 522def _fetch (self ,artifact :Artifact )-> bytes : 523"""Download with resume, keeping partial bytes for a later attempt. 524 525A single interrupted transfer is the normal case on a real connection, so the partial bytes 526are kept under `partial/` and a ranged request picks up where it stopped. The result is 527verified by the caller before anything is unpacked. 528""" 529from strata_control import acquisition 530acquisition .require (f"the download of { artifact . name } " ,"strata install" ) 531import urllib .error 532import urllib .request 533from strata_control import tls 534tls .install () 535partial = self .root / "partial" / artifact .name 536have = partial .stat ().st_size if partial .exists ()else 0 537if have > artifact .bytes : 538partial .unlink ()# a stale file from a different artifact 539have = 0 540headers = {"Range" :f"bytes= { have } -" }if have else {} 541request = urllib .request .Request (artifact .url ,headers = headers ) 542mode = "ab" if have else "wb" 543try : 544from strata_control import netpolicy # the network rule: 12 s, one retry with 30 s, clear failures at once; reads stall out after 60 s 545try : 546answer = netpolicy .open_url (netpolicy .urlopen ,request ) 547except netpolicy .NetFailure as failure : 548raise ComponentError (failure .headline ("the " + artifact .name )+ " " + failure .next_step ())from None 549with answer as response : 550if have and response .status != 206 : 551# The server ignored the range, so start again rather than appending to a prefix 552# and producing a corrupt file that would fail verification much later. 553have ,mode = 0 ,"wb" 554with partial .open (mode )as out : 555while True : 556block = response .read (1 << 20 ) 557if not block : 558break 559out .write (block ) 560except (urllib .error .URLError ,OSError )as e : 561if tls .is_certificate_error (e ): 562raise ComponentError (f"the download of { artifact . name } stopped. " + tls .explain (tls .host_of (artifact .url )))from e 563raise ComponentError ( 564f"the download of { artifact . name } was interrupted after " 565f" { partial . stat (). st_size if partial . exists () else 0 } of { artifact . bytes } bytes; " 566f"the partial file is kept and a later attempt resumes it ( { e } )" )from e 567data = partial .read_bytes () 568if len (data )!= artifact .bytes : 569raise ComponentError ( 570f"the download of { artifact . name } is { len ( data ) } bytes but the manifest declares " 571f" { artifact . bytes } ; the partial file is kept so a later attempt can resume it" ) 572partial .unlink (missing_ok = True ) 573return data 574 575# ------------------------------------------------------------------ activation and rollback 576 577def active_path (self ,component_id :str )-> Path : 578return self .root / "active" / component_id 579 580def activate (self ,component :Component ,* ,target :str | None = None , 581backend :str | None = None )-> dict [str ,Any ]: 582"""Make a cached version active, moving the previous one aside. 583 584The move is a rename, so it either happens or it does not. The version being replaced is 585moved to `previous/` rather than deleted, which is what makes `rollback` exact. 586""" 587reasons = check_compatible (component ,target = target ,backend = backend ) 588if reasons : 589raise ComponentError ("; " .join (reasons ),2 ) 590source = self .cached (component ) 591if source is None : 592raise ComponentError ( 593f" { component . id } { component . version } is not installed; install it before activating" ) 594active = self .active_path (component .id ) 595previous = self .root / "previous" / component .id 596 597moved_aside :str | None = None 598if active .exists (): 599if previous .exists (): 600shutil .rmtree (previous ,ignore_errors = True ) 601_atomic_mod .replace (active ,previous ) 602moved_aside = str (previous ) 603 604# Record what is being displaced BEFORE the activation, so a crash between the two leaves a 605# rollback record that points at the previous version rather than at the new one. 606state = self .state () 607entry = state ["components" ].setdefault (component .id , {}) 608displaced = dict (entry .get ("active" )or {}) 609if moved_aside and displaced : 610entry ["rollback" ]= {"version" :displaced .get ("version" ), 611"cache_key" :displaced .get ("cache_key" ),"path" :moved_aside } 612self ._save_state (state ) 613 614# The cache is never consumed: an application update that reuses an installed engine depends 615# on the cached payload still being there, so the active directory is a copy. The copy goes 616# in beside the target and is renamed into place, so the active path is never half-populated. 617active .parent .mkdir (parents = True ,exist_ok = True ) 618incoming = active .parent / f". { component . id } .incoming" 619if incoming .exists (): 620shutil .rmtree (incoming ,ignore_errors = True ) 621shutil .copytree (source ,incoming ,symlinks = False ) 622_atomic_mod .replace (incoming ,active ) 623 624state = self .state () 625entry = state ["components" ].setdefault (component .id , {}) 626entry ["active" ]= {"version" :component .version ,"cache_key" :component .cache_key , 627"activated_at" :time .time (),"from" :str (source )} 628self ._save_state (state ) 629return {"id" :component .id ,"version" :component .version ,"active" :str (active ), 630"moved_aside" :moved_aside } 631 632def rollback (self ,component_id :str )-> dict [str ,Any ]: 633"""Restore the version that was active before the last activation. 634 635Refuses when there is nothing to restore rather than leaving the component absent, because 636"rollback succeeded" and "the component is now missing" must not be the same outcome. 637""" 638previous = self .root / "previous" / component_id 639if not previous .exists (): 640raise ComponentError ( 641f"there is no previous version of { component_id } to restore" ,2 ) 642active = self .active_path (component_id ) 643if active .exists (): 644abandoned = self .root / "previous" / f" { component_id } .replaced" 645if abandoned .exists (): 646shutil .rmtree (abandoned ,ignore_errors = True ) 647_atomic_mod .replace (active ,abandoned ) 648_atomic_mod .replace (previous ,active ) 649state = self .state () 650entry = state ["components" ].get (component_id , {}) 651restored = entry .get ("rollback" , {}) 652entry ["active" ]= {"version" :restored .get ("version" ),"cache_key" :restored .get ("cache_key" ), 653"activated_at" :time .time (),"restored" :True } 654entry .pop ("rollback" ,None ) 655self ._save_state (state ) 656return {"id" :component_id ,"restored" :restored .get ("version" ),"active" :str (active )} 657 658def installed (self ,component_id :str )-> list [InstalledComponent ]: 659"""Every version of a component present in the cache.""" 660entry = self .state ().get ("components" , {}).get (component_id , {}) 661out :list [InstalledComponent ]= [] 662active = (entry .get ("active" )or {}).get ("cache_key" ) 663for version ,data in (entry .get ("installed" )or {}).items (): 664out .append (InstalledComponent ( 665id = component_id ,version = version ,cache_key = data .get ("cache_key" ,"" ), 666path = data .get ("path" ,"" ),installed_at = data .get ("installed_at" ,0.0 ), 667artifact_sha256 = tuple (data .get ("artifact_sha256" )or ()), 668active = data .get ("cache_key" )== active )) 669return sorted (out ,key = lambda c :c .installed_at ) 670 671def prune_cache (self ,* ,keep :Iterable [str ]= ())-> list [str ]: 672"""Delete cached payloads that nothing refers to. Never touches an active or previous one. 673 674A compatible application update must not download an engine again, so pruning keeps whatever 675the active and previous versions point at, plus anything the caller names. 676""" 677keep_keys = set (keep ) 678state = self .state () 679for entry in state .get ("components" , {}).values (): 680for key in (entry .get ("active" )or {},entry .get ("rollback" )or {}): 681if key .get ("cache_key" ): 682keep_keys .add (key ["cache_key" ]) 683removed :list [str ]= [] 684cache = self .root / "cache" 685for path in cache .iterdir ()if cache .exists ()else []: 686if not path .is_dir ()or path .name .startswith ("." ): 687continue 688if path .name not in keep_keys : 689shutil .rmtree (path ,ignore_errors = True ) 690removed .append (path .name ) 691return removed