oracle7-slim / workbench /interactive_program.py
psiloceyeben's picture
Release 12.0 (slim): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 4)
2419253 verified
Raw History Blame Contribute Delete
61.4 kB
"""Typed state, named events and reusable action parts for local browser programs. This part receives an explicit program shape. It does not reinterpret unknown behavior as a table, run arbitrary code, or invent a missing event binding. """ import copy import hashlib import html import itertools import json import math import os from pathlib import Path import re import secrets import tempfile import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer class ProgramError(ValueError): def __init__(self, message, status=400): super().__init__(message) self.status = status class _StateFileLock: """Reentrant in-process ownership plus an OS lock shared by app processes. The persistent lock file is never removed. Ownership belongs to the open handle, so termination releases it without guessing whether a PID is alive. """ def __init__(self, path): self.path = Path(path) self.thread = threading.RLock() self.depth = 0 self.handle = None def __enter__(self): self.thread.acquire() try: if self.depth == 0: self.path.parent.mkdir(parents=True, exist_ok=True) self.handle = open(self.path, 'a+b', buffering=0) if os.fstat(self.handle.fileno()).st_size == 0: self.handle.write(b'\0') deadline = time.monotonic() + 30 while True: try: self.handle.seek(0) if os.name == 'nt': import msvcrt msvcrt.locking(self.handle.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(self.handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) break except OSError: if time.monotonic() >= deadline: raise ProgramError('saved state is busy in another process; refresh before retrying', 409) time.sleep(0.01) self.depth += 1 return self except BaseException: if self.depth == 0 and self.handle is not None: self.handle.close(); self.handle = None self.thread.release() raise def __exit__(self, *exc): try: self.depth -= 1 if self.depth == 0: try: self.handle.seek(0) if os.name == 'nt': import msvcrt msvcrt.locking(self.handle.fileno(), msvcrt.LK_UNLCK, 1) else: import fcntl fcntl.flock(self.handle.fileno(), fcntl.LOCK_UN) finally: self.handle.close(); self.handle = None finally: self.thread.release() _STATE_LOCKS = {} _STATE_LOCKS_GUARD = threading.Lock() def _state_file_lock(state_path, root): lock_path = Path(str(state_path) + '.lock').resolve() if Path(root).resolve() not in lock_path.parents: raise ProgramError('program state lock must stay inside the project folder') key = os.path.normcase(str(lock_path)) with _STATE_LOCKS_GUARD: return _STATE_LOCKS.setdefault(key, _StateFileLock(lock_path)) def _keys(value, allowed, required=(), where='shape'): if not isinstance(value, dict): raise ProgramError('%s must be a named shape' % where) extra, missing = set(value) - set(allowed), set(required) - set(value) if extra or missing: raise ProgramError('%s: unknown fields %s; missing fields %s' % (where, sorted(extra), sorted(missing))) def _name(name): if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{0,63}', name): raise ProgramError('names must be 1–64 letters, digits or underscores, starting with a letter') def _schema(schema, where, initial=False, depth=0): _keys(schema, ('type', 'initial', 'min', 'max', 'enum', 'items', 'label'), ('type', 'initial') if initial else ('type',), where) typ = schema['type'] if typ not in ('integer', 'number', 'string', 'boolean', 'array'): raise ProgramError('%s: type %r has no part yet' % (where, typ)) if depth > 2: raise ProgramError('%s: nested arrays beyond depth 2 need an explicit part' % where) if typ == 'array': if 'items' not in schema: raise ProgramError('%s needs the type of its items' % where) _schema(schema['items'], where + '.items', depth=depth + 1) elif 'items' in schema: raise ProgramError('%s: items belongs to an array' % where) for bound in ('min', 'max'): if bound in schema: val = schema[bound] if typ == 'boolean' or isinstance(val, bool) or not isinstance(val, (int, float)) or not math.isfinite(val): raise ProgramError('%s: invalid %s bound' % (where, bound)) if typ in ('array', 'string') and (not isinstance(val, int) or val < 0): raise ProgramError('%s: length bounds must be nonnegative integers' % where) if schema.get('min', -math.inf) > schema.get('max', math.inf): raise ProgramError('%s: minimum is greater than maximum' % where) if 'label' in schema and not isinstance(schema['label'], str): raise ProgramError('%s: label must be text' % where) if 'enum' in schema: if not isinstance(schema['enum'], list) or not schema['enum']: raise ProgramError('%s: enum must name at least one value' % where) plain = dict(schema); plain.pop('enum') for item in schema['enum']: _value(item, plain, where) if 'initial' in schema: _value(schema['initial'], schema, where) def _value(value, schema, where): typ = schema['type'] valid = {'integer': lambda: isinstance(value, int) and not isinstance(value, bool), 'number': lambda: isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value), 'string': lambda: isinstance(value, str), 'boolean': lambda: isinstance(value, bool), 'array': lambda: isinstance(value, list)}[typ]() if not valid: raise ProgramError('%s must be %s' % (where, typ)) size = len(value) if typ in ('array', 'string') else value if typ != 'boolean' and (size < schema.get('min', -math.inf) or size > schema.get('max', math.inf)): raise ProgramError('%s is outside its declared bounds' % where) if 'enum' in schema and value not in schema['enum']: raise ProgramError('%s must be one of %s' % (where, schema['enum'])) if typ == 'array': for i, item in enumerate(value): _value(item, schema['items'], '%s[%d]' % (where, i)) return copy.deepcopy(value) _OPS = {'add': (2, 2), 'subtract': (2, 2), 'multiply': (2, 2), 'divide': (2, 2), 'eq': (2, 2), 'ne': (2, 2), 'lt': (2, 2), 'le': (2, 2), 'gt': (2, 2), 'ge': (2, 2), 'and': (1, 16), 'or': (1, 16), 'not': (1, 1), 'concat': (1, 16), 'contains': (2, 2), 'length': (1, 1), 'if': (3, 3)} def _expr_shape(expr, fields, params, where, depth=0): if depth > 32: raise ProgramError('%s: expression exceeds 32 nested parts' % where) if not isinstance(expr, dict): if isinstance(expr, (str, bool, int, float)) or expr is None: if isinstance(expr, float) and not math.isfinite(expr): raise ProgramError('%s needs finite numbers' % where) return if isinstance(expr, list): for item in expr: _expr_shape(item, fields, params, where, depth + 1) return raise ProgramError('%s has an unknown expression' % where) if set(expr) in ({'state'}, {'param'}): kind = next(iter(expr)); names = fields if kind == 'state' else params if expr[kind] not in names: raise ProgramError('%s refers to undeclared %s %r' % (where, kind, expr[kind])) return _keys(expr, ('op', 'args'), ('op', 'args'), where) if expr['op'] not in _OPS or not isinstance(expr['args'], list): raise ProgramError('%s needs a declared expression part: %r' % (where, expr.get('op'))) low, high = _OPS[expr['op']] if not low <= len(expr['args']) <= high: raise ProgramError('%s: %s takes %s..%s arguments' % (where, expr['op'], low, high)) for arg in expr['args']: _expr_shape(arg, fields, params, where, depth + 1) def _bool(value): if not isinstance(value, bool): raise ProgramError('a condition must produce a boolean') return value def _number(value): if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): raise ProgramError('arithmetic needs finite numbers') return value def expression(expr, state, params): if isinstance(expr, list): return [expression(x, state, params) for x in expr] if not isinstance(expr, dict): return expr if 'state' in expr: return copy.deepcopy(state[expr['state']]) if 'param' in expr: return copy.deepcopy(params[expr['param']]) op, args = expr['op'], expr['args'] if op == 'if': return expression(args[1] if _bool(expression(args[0], state, params)) else args[2], state, params) vals = [expression(x, state, params) for x in args] if op in ('add', 'subtract', 'multiply', 'divide'): a, b = map(_number, vals) if op == 'divide' and b == 0: raise ProgramError('division needs a nonzero denominator') result = {'add': lambda: a + b, 'subtract': lambda: a - b, 'multiply': lambda: a * b, 'divide': lambda: a / b}[op]() return _number(result) if op in ('eq', 'ne'): same = type(vals[0]) == type(vals[1]) and vals[0] == vals[1] return same if op == 'eq' else not same if op in ('lt', 'le', 'gt', 'ge'): a, b = map(_number, vals) return {'lt': lambda: a < b, 'le': lambda: a <= b, 'gt': lambda: a > b, 'ge': lambda: a >= b}[op]() if op in ('and', 'or'): conditions = [_bool(x) for x in vals] return all(conditions) if op == 'and' else any(conditions) if op == 'not': return not _bool(vals[0]) if op == 'concat': if any(not isinstance(x, str) for x in vals): raise ProgramError('concat needs text values') return ''.join(vals) if op == 'contains': if not isinstance(vals[0], (str, list)): raise ProgramError('contains needs a list or text') return vals[1] in vals[0] if op == 'length': if not isinstance(vals[0], (str, list)): raise ProgramError('length needs a list or text') return len(vals[0]) raise ProgramError('unknown expression part %s' % op) def _params(schema, supplied, where): _keys(supplied, schema, schema, where) return {name: _value(supplied[name], spec, where + '.' + name) for name, spec in schema.items()} def _action_shapes(actions, contract, params, where, calls, depth=0): if depth > 32: raise ProgramError('%s: actions exceed 32 nested parts' % where) if not isinstance(actions, list) or len(actions) > 128: raise ProgramError('%s needs at most 128 ordered actions' % where) for action in actions: if not isinstance(action, dict): raise ProgramError('%s needs a named action' % where) op = action.get('op') if op in ('set', 'append', 'remove'): _keys(action, ('op', 'field', 'value'), ('op', 'field', 'value'), where) if action['field'] not in contract['state']: raise ProgramError('%s targets undeclared state %r' % (where, action['field'])) if op != 'set' and contract['state'][action['field']]['type'] != 'array': raise ProgramError('%s requires an array field' % op) _expr_shape(action['value'], contract['state'], params, where) elif op == 'if': _keys(action, ('op', 'condition', 'then', 'else'), ('op', 'condition', 'then'), where) _expr_shape(action['condition'], contract['state'], params, where) for branch in ('then', 'else'): _action_shapes(action.get(branch, []), contract, params, where, calls, depth + 1) elif op == 'assert': _keys(action, ('op', 'condition', 'message'), ('op', 'condition', 'message'), where) if not isinstance(action['message'], str): raise ProgramError('an assertion needs a text message') _expr_shape(action['condition'], contract['state'], params, where) elif op == 'call': _keys(action, ('op', 'part', 'args'), ('op', 'part', 'args'), where) part = action['part'] if part not in contract['parts']: raise ProgramError('%s needs declared action part %r' % (where, part)) _keys(action['args'], contract['parts'][part]['params'], contract['parts'][part]['params'], where) for expr in action['args'].values(): _expr_shape(expr, contract['state'], params, where) calls.add(part) else: raise ProgramError('%s: action %r has no part yet' % (where, op)) def validate(contract): """Return the fully checked shape; never discard unknown requirements.""" c = copy.deepcopy(contract) _keys(c, ('version', 'title', 'state', 'events', 'parts', 'views', 'controls', 'checks'), ('version', 'title', 'state', 'events', 'views', 'controls'), 'program') if c['version'] != 1 or isinstance(c['version'], bool): raise ProgramError('program version must be 1') if not isinstance(c['title'], str) or not c['title'].strip(): raise ProgramError('program needs a title') c.setdefault('parts', {}); c.setdefault('checks', []) for group in ('state', 'events', 'parts'): if not isinstance(c[group], dict) or len(c[group]) > 128: raise ProgramError('%s needs at most 128 named members' % group) for name in c[group]: _name(name) if not c['state'] or not c['events']: raise ProgramError('program needs state and events') for name, schema in c['state'].items(): _schema(schema, 'state.' + name, initial=True) for group in ('events', 'parts'): for name, spec in c[group].items(): if not isinstance(spec, dict): raise ProgramError('%s.%s needs a named handler shape' % (group, name)) spec.setdefault('params', {}) calls = {} for group in ('events', 'parts'): for name, spec in c[group].items(): _keys(spec, ('params', 'actions', 'guard') if group == 'events' else ('params', 'actions'), ('actions',), group + '.' + name) spec.setdefault('params', {}) if not isinstance(spec['params'], dict): raise ProgramError('%s parameters must be named' % name) for param, schema in spec['params'].items(): _name(param); _schema(schema, name + '.' + param) if 'guard' in spec: _expr_shape(spec['guard'], c['state'], spec['params'], name) targets = set(); _action_shapes(spec['actions'], c, spec['params'], name, targets) if group == 'parts': calls[name] = targets def visit(name, active): if name in active: raise ProgramError('action parts form a cycle through %s' % name) for child in calls[name]: visit(child, active | {name}) for name in calls: visit(name, set()) if not isinstance(c['views'], list) or not isinstance(c['controls'], list): raise ProgramError('views and controls must be ordered lists') for view in c['views']: _keys(view, ('kind', 'label', 'value', 'visible'), ('kind', 'label', 'value'), 'view') if view['kind'] not in ('text', 'list') or not isinstance(view['label'], str): raise ProgramError('view needs a text/list kind and a text label') _expr_shape(view['value'], c['state'], {}, 'view') if 'visible' in view: _expr_shape(view['visible'], c['state'], {}, 'view visibility') for control in c['controls']: _keys(control, ('kind', 'label', 'event', 'args', 'visible'), ('kind', 'label', 'event'), 'control') if control['kind'] not in ('button', 'form') or control['event'] not in c['events'] or not isinstance(control['label'], str): raise ProgramError('control needs a button/form kind, declared event and text label') params = c['events'][control['event']]['params'] control.setdefault('args', {}) _keys(control['args'], params, params if control['kind'] == 'button' else (), 'control arguments') for expr in control['args'].values(): _expr_shape(expr, c['state'], {}, 'control argument') if 'visible' in control: _expr_shape(control['visible'], c['state'], {}, 'control visibility') if not isinstance(c['checks'], list): raise ProgramError('checks must be event trajectories') for check in c['checks']: _keys(check, ('events', 'state'), ('events', 'state'), 'check') if not isinstance(check['events'], list): raise ProgramError('check events must be a list') for event in check['events']: _keys(event, ('event', 'args'), ('event',), 'check event') if event['event'] not in c['events']: raise ProgramError('check names undeclared event %r' % event['event']) event.setdefault('args', {}) _params(c['events'][event['event']]['params'], event['args'], event['event']) _params(c['state'], check['state'], 'expected state') return c def initial_state(contract): return {name: copy.deepcopy(spec['initial']) for name, spec in contract['state'].items()} def transition(contract, state, event, args): """Apply one event atomically to a copied state, validating each assignment.""" if event not in contract['events']: raise ProgramError('event %r has no handler' % event) working = _params(contract['state'], state, 'state') spec = contract['events'][event] params = _params(spec['params'], args, event) if 'guard' in spec and not _bool(expression(spec['guard'], working, params)): raise ProgramError('event %s is not available in the current state' % event, 409) budget = [2048] def actions(items, values): for action in items: budget[0] -= 1 if budget[0] < 0: raise ProgramError('event exceeds its 2048 action budget') op = action['op'] if op in ('set', 'append', 'remove'): value = expression(action['value'], working, values); field = action['field'] if op == 'append': value = working[field] + [value] elif op == 'remove': value = [item for item in working[field] if item != value] working[field] = _value(value, contract['state'][field], field) elif op == 'if': actions(action.get('then' if _bool(expression(action['condition'], working, values)) else 'else', []), values) elif op == 'assert': if not _bool(expression(action['condition'], working, values)): raise ProgramError(action['message'], 409) elif op == 'call': part = contract['parts'][action['part']] supplied = {k: expression(v, working, values) for k, v in action['args'].items()} actions(part['actions'], _params(part['params'], supplied, action['part'])) actions(spec['actions'], params) return working def _encoded(value): return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False).encode('utf-8') def _hash(value): return hashlib.sha256(value).hexdigest() def replay(contract, history, initial=None): state = initial_state(contract) if initial is None else _params(contract['state'], initial, 'epoch initial state') if not isinstance(history, list) or len(history) > 10000: raise ProgramError('event history must have at most 10000 events') for entry in history: _keys(entry, ('event', 'args', 'state_hash'), ('event', 'args', 'state_hash'), 'history event') state = transition(contract, state, entry['event'], entry['args']) if entry['state_hash'] != _hash(_encoded(state)): raise ProgramError('retained event history does not reproduce its state receipt', 409) return state def _same_state_schema(left, right): def shape(contract): return {name: {k: copy.deepcopy(v) for k, v in schema.items() if k not in ('initial', 'label')} for name, schema in contract['state'].items()} return shape(left) == shape(right) def _audit_document(doc, contract): """Replay each epoch under its own definition; never reinterpret old events.""" _keys(doc, ('contract', 'definition', 'state', 'history', 'base', 'epochs', 'source_sha256'), ('contract', 'state', 'history'), 'stored program') if doc['contract'] != _hash(_encoded(contract)): raise ProgramError('saved state belongs to a different program contract; name a migration before continuing', 409) if 'definition' in doc and validate(doc['definition']) != contract: raise ProgramError('saved definition does not match its contract receipt', 409) epochs = doc.get('epochs', []) if not isinstance(epochs, list) or len(epochs) > 128: raise ProgramError('saved program supports at most 128 checked revision epochs', 409) previous_state, previous_contract = None, None for epoch in epochs: _keys(epoch, ('contract', 'definition', 'base', 'history', 'state', 'state_hash', 'source_sha256', 'receipt_sha256'), ('contract', 'definition', 'base', 'history', 'state', 'state_hash', 'source_sha256', 'receipt_sha256'), 'revision epoch') definition = validate(epoch['definition']) if _hash(_encoded(definition)) != epoch['contract']: raise ProgramError('revision epoch definition does not match its contract receipt', 409) if previous_contract is None: if epoch['base'] != initial_state(definition): raise ProgramError('first revision epoch must start at its recorded initial state', 409) elif epoch['base'] != previous_state or not _same_state_schema(previous_contract, definition): raise ProgramError('revision epochs do not preserve compatible state continuously', 409) state = replay(definition, epoch['history'], epoch['base']) if state != epoch['state'] or _hash(_encoded(state)) != epoch['state_hash']: raise ProgramError('revision epoch does not reproduce its state receipt', 409) if not isinstance(epoch['receipt_sha256'], str) or not re.fullmatch('[0-9a-f]{64}', epoch['receipt_sha256']): raise ProgramError('revision epoch needs its prior saved-file receipt', 409) if epoch['source_sha256'] is not None and not re.fullmatch('[0-9a-f]{64}', str(epoch['source_sha256'])): raise ProgramError('revision epoch has an invalid source receipt', 409) previous_state, previous_contract = state, definition base = doc.get('base', initial_state(contract)) if epochs: if base != previous_state or not _same_state_schema(previous_contract, contract): raise ProgramError('current epoch does not continue the prior compatible state', 409) elif base != initial_state(contract): raise ProgramError('initial program state differs without a checked revision epoch', 409) if replay(contract, doc['history'], base) != doc['state']: raise ProgramError('saved state does not match replayed events', 409) _params(contract['state'], doc['state'], 'saved state') return doc class ProgramStore: def __init__(self, contract, root='.', filename='.oracle7/program-state.json', previous=None, source_sha256=None): self.contract = validate(contract); self.root = Path(root).resolve() self.path = (self.root / filename).resolve() if self.root not in self.path.parents: raise ProgramError('program state must stay inside the project folder') self.contract_hash = _hash(_encoded(self.contract)) self.previous = copy.deepcopy(previous or {}) self.source_sha256 = source_sha256 self.lock = _state_file_lock(self.path, self.root) def read(self): with self.lock: return self._read_locked() def _read_locked(self): if not self.path.exists(): return {'contract': self.contract_hash, 'definition': self.contract, 'state': initial_state(self.contract), 'history': [], 'base': initial_state(self.contract), 'epochs': [], 'source_sha256': self.source_sha256}, None data = self.path.read_bytes() try: doc = json.loads(data) if doc['contract'] != self.contract_hash: prior = self.previous.get(doc['contract']) if not prior: raise ProgramError('saved state belongs to a different program contract; name a migration before continuing', 409) old = validate(prior['contract']); _audit_document(doc, old) if not _same_state_schema(old, self.contract): raise ProgramError('saved state schema changed; name an explicit state migration before continuing', 409) _params(self.contract['state'], doc['state'], 'preserved state') epochs = copy.deepcopy(doc.get('epochs', [])) if len(epochs) >= 128: raise ProgramError('revision history reached 128 epochs; name an archival migration before continuing', 409) epochs.append({'contract': doc['contract'], 'definition': old, 'base': doc.get('base', initial_state(old)), 'history': copy.deepcopy(doc['history']), 'state': copy.deepcopy(doc['state']), 'state_hash': _hash(_encoded(doc['state'])), 'source_sha256': prior.get('source_sha256'), 'receipt_sha256': _hash(data)}) migrated = {'contract': self.contract_hash, 'definition': self.contract, 'state': copy.deepcopy(doc['state']), 'base': copy.deepcopy(doc['state']), 'history': [], 'epochs': epochs, 'source_sha256': self.source_sha256} _audit_document(migrated, self.contract) encoded = _encoded(migrated) self.snapshot(migrated, encoded) # new views must accept the preserved state before writing self._commit(encoded, data) return migrated, encoded _audit_document(doc, self.contract) return doc, data except (ValueError, TypeError, KeyError) as exc: if isinstance(exc, ProgramError): raise raise ProgramError('saved program state cannot be read: %s' % exc, 409) from exc def snapshot(self, doc=None, raw=None): if doc is None: doc, raw = self.read() state = doc['state']; views = []; controls = [] for view in self.contract['views']: if not _bool(expression(view.get('visible', True), state, {})): continue value = expression(view['value'], state, {}) if view['kind'] == 'list' and not isinstance(value, list): raise ProgramError('list view %s must produce a list' % view['label']) views.append({'kind': view['kind'], 'label': view['label'], 'value': value}) for i, control in enumerate(self.contract['controls']): if not _bool(expression(control.get('visible', True), state, {})): continue item = {k: control[k] for k in ('kind', 'label', 'event')} item['id'] = str(i); item['args'] = {k: expression(v, state, {}) for k, v in control['args'].items()} item['params'] = self.contract['events'][control['event']]['params']; controls.append(item) return {'title': self.contract['title'], 'version': _hash(raw if raw is not None else _encoded(doc)), 'state': copy.deepcopy(state), 'events': len(doc['history']) + sum(len(e['history']) for e in doc.get('epochs', [])), 'revision_epochs': len(doc.get('epochs', [])), 'views': views, 'controls': controls} def dispatch(self, payload): _keys(payload, ('version', 'event', 'args'), ('version', 'event', 'args'), 'event request') with self.lock: doc, before = self.read() if payload['version'] != self.snapshot(doc, before)['version']: raise ProgramError('state changed; refresh before sending this event again', 409) if len(doc['history']) >= 10000: raise ProgramError('event history reached 10000; a checkpoint part is needed', 409) state = transition(self.contract, doc['state'], payload['event'], payload['args']) next_doc = {'contract': self.contract_hash, 'definition': self.contract, 'state': state, 'base': doc.get('base', initial_state(self.contract)), 'epochs': doc.get('epochs', []), 'source_sha256': self.source_sha256, 'history': doc['history'] + [{'event': payload['event'], 'args': payload['args'], 'state_hash': _hash(_encoded(state))}]} encoded = _encoded(next_doc) result = self.snapshot(next_doc, encoded) # validate every view before any persistent change self._commit(encoded, before) return result def _commit(self, encoded, before): with self.lock: return self._commit_locked(encoded, before) def _commit_locked(self, encoded, before): self.path.parent.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(prefix='.program-', dir=str(self.path.parent)) try: with os.fdopen(fd, 'wb') as handle: handle.write(encoded); handle.flush(); os.fsync(handle.fileno()) current = self.path.read_bytes() if self.path.exists() else None if current != before: raise ProgramError('saved state changed during this event or revision; refresh before retrying', 409) os.replace(tmp, self.path) finally: if os.path.exists(tmp): os.unlink(tmp) _PAGE = r'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"> <title>__TITLE__</title><style>body{font:17px/1.6 system-ui,sans-serif;max-width:960px;margin:3rem auto;padding:0 1.3rem;color:#1f2933;background:#f8fafc}h1{font-size:2rem}section,form{margin:1rem 0;padding:1.1rem;border:1px solid #cbd5e1;border-radius:12px;background:white}h2{font-size:1rem;margin:0 0 .5rem}button,input,select,textarea{font:inherit;padding:.5rem .8rem;border:1px solid #94a3b8;border-radius:7px}button{background:#154f82;color:white;cursor:pointer;margin:.3rem .4rem .3rem 0}label{display:block;margin:.5rem 0}label>input,label>select,label>textarea{display:block;max-width:95%}output{display:block;font-size:1.4rem}#notice{min-height:1.6rem}#notice.error{color:#a32121}small{color:#52606d}:focus-visible{outline:3px solid #e8a12b;outline-offset:3px}</style> <main><h1>__TITLE__</h1><div id="views"></div><div id="controls"></div><p id="notice" role="status" aria-live="polite"></p><button id="refresh">Refresh</button><small id="receipt"></small></main> <script> const token=__TOKEN__;let current=null,busy=false; const node=(tag,text)=>{const e=document.createElement(tag);if(text!==undefined)e.textContent=text;return e;}; const display=value=>typeof value==='string'?value:JSON.stringify(value); function show(snapshot){current=snapshot;document.getElementById('receipt').textContent='Saved events: '+snapshot.events;const views=document.getElementById('views');views.replaceChildren();snapshot.views.forEach((view,i)=>{const box=node('section');box.dataset.view=String(i);box.append(node('h2',view.label));if(view.kind==='list'){const list=node('ul');view.value.forEach(value=>list.append(node('li',display(value))));box.append(list);}else box.append(node('output',display(view.value)));views.append(box);});const controls=document.getElementById('controls');controls.replaceChildren();snapshot.controls.forEach(control=>{const form=node('form');form.dataset.event=control.event;form.dataset.control=control.id;const inputs={};if(control.kind==='form')Object.entries(control.params).forEach(([name,spec])=>{if(Object.hasOwn(control.args,name))return;let input;if(spec.enum){input=node('select');spec.enum.forEach((value,index)=>{const option=node('option',display(value));option.value=String(index);input.append(option);});}else if(spec.type==='array')input=node('textarea');else{input=node('input');input.type=spec.type==='boolean'?'checkbox':spec.type==='integer'||spec.type==='number'?'number':'text';if(spec.type==='integer')input.step='1';if(spec.type==='number')input.step='any';if(spec.type==='integer'||spec.type==='number'){if(spec.min!==undefined)input.min=spec.min;if(spec.max!==undefined)input.max=spec.max;}else if(spec.type==='string'){if(spec.min!==undefined)input.minLength=spec.min;if(spec.max!==undefined)input.maxLength=spec.max;}}input.name=name;input.required=spec.type!=='boolean';if(spec.initial!==undefined&&!spec.enum){if(spec.type==='boolean')input.checked=spec.initial;else input.value=spec.type==='array'?JSON.stringify(spec.initial):String(spec.initial);}inputs[name]={input,spec};const label=node('label',spec.label||name);label.append(input);form.append(label);});const button=node('button',control.label);button.type='submit';form.append(button);form.onsubmit=async(event)=>{event.preventDefault();if(busy)return;try{const args={...control.args};Object.entries(inputs).forEach(([name,{input,spec}])=>{args[name]=spec.enum?spec.enum[Number(input.value)]:spec.type==='boolean'?input.checked:spec.type==='number'||spec.type==='integer'?Number(input.value):spec.type==='array'?JSON.parse(input.value):input.value;});await send(control.event,args);}catch(error){notice(error.message,true);}};controls.append(form);});} function notice(text,error=false){const n=document.getElementById('notice');n.textContent=text;n.className=error?'error':'';} async function get(){const response=await fetch('/_program/state');const body=await response.json();if(!response.ok)throw Error(body.error||'Cannot read the saved state');show(body);return body;} async function send(event,args){busy=true;try{const response=await fetch('/_program/event',{method:'POST',headers:{'Content-Type':'application/json','X-Oracle7-Token':token},body:JSON.stringify({event,args,version:current.version})});const body=await response.json();if(!response.ok)throw Error(body.error||'Event was not saved');show(body);notice('Saved.');return body;}finally{busy=false;}} document.getElementById('refresh').onclick=()=>get().then(()=>notice('Refreshed.')).catch(error=>notice(error.message,true)); window.__o7program={get state(){return current;},send,refresh:get};get().catch(error=>notice(error.message,true)); </script></html>''' def handler(store): token = secrets.token_urlsafe(32) page = _PAGE.replace('__TITLE__', html.escape(store.contract['title'])).replace('__TOKEN__', json.dumps(token)) class Handler(BaseHTTPRequestHandler): def log_message(self, *args): pass def answer(self, status, content, typ='application/json'): body = content.encode('utf-8') if isinstance(content, str) else _encoded(content) self.send_response(status); self.send_header('Content-Type', typ + '; charset=utf-8') self.send_header('Content-Length', str(len(body))); self.send_header('Cache-Control', 'no-store') self.send_header('X-Content-Type-Options', 'nosniff'); self.end_headers(); self.wfile.write(body) def local(self): expected = '127.0.0.1:%s' % self.server.server_address[1] if self.headers.get('Host') != expected: raise ProgramError('this local program requires its loopback host', 403) return 'http://' + expected def do_GET(self): try: self.local() if self.path == '/': self.answer(200, page, 'text/html') elif self.path == '/_program/state': self.answer(200, store.snapshot()) else: self.answer(404, {'error': 'unknown program route'}) except ProgramError as exc: self.answer(exc.status, {'error': str(exc)}) except (ValueError, TypeError, KeyError) as exc: self.answer(400, {'error': 'invalid saved view: %s' % exc}) def do_POST(self): try: origin = self.local() if self.path != '/_program/event': raise ProgramError('unknown program route', 404) if self.headers.get('Origin') != origin or self.headers.get('X-Oracle7-Token') != token: raise ProgramError('open the local program page before sending an event', 403) if self.headers.get('Content-Type', '').split(';')[0] != 'application/json': raise ProgramError('program events must use JSON', 415) size = int(self.headers.get('Content-Length', 0)) if not 0 < size <= 262144: raise ProgramError('event body must contain 1..262144 bytes', 413) data = json.loads(self.rfile.read(size)) self.answer(200, store.dispatch(data)) except ProgramError as exc: self.answer(exc.status, {'error': str(exc)}) except (ValueError, TypeError, KeyError) as exc: self.answer(400, {'error': 'invalid event: %s' % exc}) return Handler def serve(contract, port=8000, root='.', state_file='.oracle7/program-state.json', previous=None, source_sha256=None): store = ProgramStore(contract, root, state_file, previous, source_sha256) store.snapshot() ThreadingHTTPServer(('127.0.0.1', int(port)), handler(store)).serve_forever() # AUTHORING: the generated program contains the preceding self-contained part. def request_contract(text, root, reading=None): """Bind explicit state/event JSON or a grounded build request naming it. Return None for tables/discussion. Recognized requests with unsafe paths or unbound instructions raise ProgramError. Schema errors stay raw for validate. """ text = str(text or '').strip(); base = Path(root).resolve() def contract(value): if isinstance(value, dict) and set(value) == {'program'}: value = value['program'] return value if isinstance(value, dict) and isinstance(value.get('state'), dict) and isinstance(value.get('events'), dict) else None try: direct = contract(json.loads(text)) except (ValueError, TypeError): direct = None if direct is not None: return {'contract': direct, 'file': 'app.py'} inline = [] for fence in re.finditer(r'```(?:json|oracle7-program)?\s*\n([\s\S]*?)\n```', text, re.I): try: candidate = contract(json.loads(fence.group(1))) except (ValueError, TypeError): candidate = None if candidate is not None: inline.append((fence, candidate)) if len(inline) == 1 and inline[0][0].group(0) == text: return {'contract': inline[0][1], 'file': 'app.py'} # Reuse the head's full-prefix request envelope, preserving explanation and quotation. try: from language_bridge import request_reading, _ENVELOPE payload = request_reading(text)['reading'] envelope = _ENVELOPE.match(payload) if envelope: payload = payload[envelope.end():] except ImportError: _ENVELOPE = re.compile(r'(?i)^\s*please\s+') payload = re.sub(r'(?i)^\s*please\s+', '', text) lead = re.match(r'(?i)^\s*(build|create|make|emit)\b', payload) if not lead: return None if reading and reading.get('available'): if reading.get('intent') not in ('request', 'commitment'): return None clauses = reading.get('clauses') or reading.get('outcomes') or [] frames = [(c, c.get('frame') or {}) for c in clauses] if frames and not any(c.get('kind') == 'outcome' and not c.get('negative') and f.get('verb') in ('build', 'create', 'make', 'emit') and f.get('mood') in ('request', 'commitment') for c, f in frames): return None actions = [c for c in clauses if c.get('kind') != 'constraint' and c.get('text', '').strip()] if len(actions) == 1 and actions[0].get('kind') == 'outcome': payload = actions[0]['text'].strip() envelope = _ENVELOPE.match(payload) if envelope: payload = payload[envelope.end():] lead = re.match(r'(?i)^\s*(build|create|make|emit)\b', payload) if not lead: return None # File tokens and role words are request syntax, never a vocabulary of app data. token = re.compile(r'`([^`\r\n]+\.(?:json|py))`|"([^"\r\n]+\.(?:json|py))"|\'([^\'\r\n]+\.(?:json|py))\'|(?<![\w./\\:])([\w./\\:+~-]+\.(?:json|py))(?![\w])', re.I) body = payload[lead.end():] body = re.sub(r'```(?:json|oracle7-program)?\s*\n[\s\S]*?\n```', ' CONTRACT ', body, flags=re.I) tokens = [(m, next(x for x in m.groups() if x is not None)) for m in token.finditer(body)] sources = []; bad_sources = [] for match, name in tokens: if not name.lower().endswith('.json'): continue candidate_path = (base / name).resolve() if base not in candidate_path.parents: bad_sources.append(name); continue if not candidate_path.is_file(): continue try: candidate = contract(json.loads(candidate_path.read_text(encoding='utf-8-sig'))) except (OSError, ValueError, TypeError): candidate = None if candidate is not None: sources.append((name, candidate)) if bad_sources and (inline or sources or re.search(r'\b(?:program|contract|interactive)\b', body, re.I)): raise ProgramError('program contract %s must stay inside the opened project folder' % bad_sources[0]) candidates = [value for _, value in inline] + [value for _, value in sources] if not candidates: return None if len(candidates) != 1: raise ProgramError('name one program contract for this build') destinations = list(dict.fromkeys(name for _, name in tokens if name.lower().endswith('.py'))) if len(destinations) > 1: raise ProgramError('name one Python destination for this program') destination = destinations[0] if destinations else 'app.py' output = (base / destination).resolve() if base not in output.parents or output.suffix.lower() != '.py': raise ProgramError('program destination must be a Python file inside the opened project folder') # Additional requested behavior must be received elsewhere, not erased by a build. remaining = token.sub(' FILE ', body) words = re.findall(r'[A-Za-z]+', remaining.lower()) known = {'a', 'an', 'the', 'this', 'that', 'local', 'interactive', 'browser', 'web', 'program', 'app', 'application', 'contract', 'file', 'from', 'using', 'with', 'in', 'as', 'to', 'into', 'named', 'called', 'described', 'defined', 'specified', 'by', 'please'} unknown = [word for word in words if word not in known] nonwords = re.sub(r'[A-Za-z\s,.:!?`\'"()\-]', '', remaining) named_inputs = [name for _, name in tokens if name.lower().endswith('.json')] if unknown or nonwords or (not inline and named_inputs != [sources[0][0]]) or inline and named_inputs: raise ProgramError('program request retains an unbound instruction or input: %s' % (' '.join(unknown) or nonwords or ', '.join(named_inputs))) return {'contract': candidates[0], 'file': output.relative_to(base).as_posix()} def receive(value): """Receive a direct contract or JSON fence; surrounding unbound prose is a hole.""" try: if isinstance(value, str): text = value.strip() match = re.fullmatch(r'```(?:json|oracle7-program)?\s*\n([\s\S]*?)\n```', text) if match: text = match.group(1) value = json.loads(text) if isinstance(value, dict) and set(value) == {'program'}: value = value['program'] return {'kind': 'interactive_program', 'contract': validate(value), 'holes': []} except (ProgramError, ValueError, TypeError) as exc: return {'kind': 'interactive_program', 'contract': None, 'holes': [{'kind': 'program_binding', 'text': str(exc), 'needs': 'an explicit program shape naming state, events, actions, views and controls'}]} def runtime_source(): return Path(__file__).read_text(encoding='utf-8').split('# AUTHORING:')[0] def check_existing_state(root, contract, filename='app.py'): """Read-only revision preflight, including legacy saved states. The returned prior-definition receipt can be embedded in a staged candidate. It authorizes no schema change and never writes or migrates the live state. """ import ast contract = validate(contract) root = Path(root).resolve(); output = (root / filename).resolve() if root not in output.parents or output.suffix != '.py': raise ProgramError('name a Python program file inside the project folder') state = output.parent / '.oracle7' / (output.stem + '-state.json') if not state.exists(): return {} if root not in state.resolve().parents: raise ProgramError('program state must stay inside the project folder') try: data = state.read_bytes(); doc = json.loads(data) if not output.is_file(): raise ProgramError('saved state needs the prior generated source before a revision can be checked', 409) source = output.read_bytes(); tree = ast.parse(source.decode('utf-8-sig')) literals = {} for node in ast.walk(tree): if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): name = node.targets[0].id if name in ('_contract', '_previous') and isinstance(node.value, ast.Call): call = node.value if (isinstance(call.func, ast.Attribute) and isinstance(call.func.value, ast.Name) and call.func.value.id == 'json' and call.func.attr == 'loads' and len(call.args) == 1 and not call.keywords): if name in literals: raise ProgramError('prior source has several program definitions; name the intended migration', 409) literals[name] = json.loads(ast.literal_eval(call.args[0])) if '_contract' not in literals: raise ProgramError('saved state needs a readable prior program definition; name an explicit migration', 409) declared = validate(literals['_contract']) old_hash = doc.get('contract') if _hash(_encoded(declared)) == old_hash: old = declared; source_hash = _hash(source) else: prior = literals.get('_previous', {}).get(old_hash) if not prior: raise ProgramError('saved state has no checked prior definition in the current source; name a migration', 409) old = validate(prior['contract']); source_hash = prior.get('source_sha256') _audit_document(doc, old) if not _same_state_schema(old, contract): raise ProgramError('saved state schema changed; name an explicit migration before replacing this program', 409) _params(contract['state'], doc['state'], 'preserved state') if old_hash != _hash(_encoded(contract)) and len(doc.get('epochs', [])) >= 128: raise ProgramError('revision history reached 128 epochs; name an archival migration before replacing this program', 409) # View/visibility expressions must also accept the state we promise to keep. ProgramStore(contract, output.parent).snapshot({'state': doc['state'], 'history': []}, b'preflight') return {} if old_hash == _hash(_encoded(contract)) else {old_hash: {'contract': old, 'source_sha256': source_hash}} except (ValueError, TypeError, KeyError, SyntaxError, OSError) as error: if isinstance(error, ProgramError): raise raise ProgramError('saved program revision cannot be checked: %s' % error, 409) from error def build(root, contract, filename='app.py', previous=None): contract = validate(contract) root = Path(root).resolve(); output = (root / filename).resolve() if root not in output.parents or output.suffix != '.py': raise ProgramError('name a Python program file inside the project folder') previous = check_existing_state(root, contract, filename) if previous is None else copy.deepcopy(previous) for old_hash, prior in previous.items(): old = validate(prior['contract']) if old_hash != _hash(_encoded(old)) or not _same_state_schema(old, contract): raise ProgramError('prior definition receipt does not authorize this state migration', 409) state_file = '.oracle7/' + output.stem + '-state.json' source = runtime_source() + '\n\nif __name__ == "__main__":\n import sys\n _contract = json.loads(' + repr(json.dumps(contract, ensure_ascii=False)) + ')\n _previous = json.loads(' + repr(json.dumps(previous, ensure_ascii=False)) + ')\n serve(_contract, int(sys.argv[-1]) if len(sys.argv) > 1 else 8000, Path(__file__).resolve().parent, ' + repr(state_file) + ', _previous, _hash(Path(__file__).read_bytes()))\n' compile(source, filename, 'exec') output.parent.mkdir(parents=True, exist_ok=True); output.write_text(source, encoding='utf-8', newline='\n') return {'kind': 'interactive_program', 'file': filename, 'files': [filename], 'contract': contract, 'state_file': (output.parent.relative_to(root) / state_file).as_posix(), 'sha256': _hash(output.read_bytes()), 'state_revision': {'mode': 'compatible_on_open' if previous else 'current_or_new', 'prior_contracts': sorted(previous)}} def _reference(contract, old, event, args): """Independent transition judge: no production expression/transition calls.""" state = copy.deepcopy(old); params = args def value(e, bindings): if isinstance(e, list): return [value(x, bindings) for x in e] if not isinstance(e, dict): return e if 'state' in e: return copy.deepcopy(state[e['state']]) if 'param' in e: return copy.deepcopy(bindings[e['param']]) op = e['op'] if op == 'if': return value(e['args'][1 if value(e['args'][0], bindings) else 2], bindings) vs = [value(x, bindings) for x in e['args']] import operator binary = {'add': operator.add, 'subtract': operator.sub, 'multiply': operator.mul, 'divide': operator.truediv, 'lt': operator.lt, 'le': operator.le, 'gt': operator.gt, 'ge': operator.ge} if op in binary: return binary[op](*vs) if op == 'eq': return type(vs[0]) == type(vs[1]) and vs[0] == vs[1] if op == 'ne': return not (type(vs[0]) == type(vs[1]) and vs[0] == vs[1]) if op == 'and': return all(vs) if op == 'or': return any(vs) if op == 'not': return not vs[0] if op == 'concat': return ''.join(vs) if op == 'contains': return vs[1] in vs[0] if op == 'length': return len(vs[0]) raise AssertionError('reference has no expression ' + op) def execute(actions, bindings): for action in actions: op = action['op'] if op == 'set': state[action['field']] = value(action['value'], bindings) elif op == 'append': state[action['field']].append(value(action['value'], bindings)) elif op == 'remove': state[action['field']] = [x for x in state[action['field']] if x != value(action['value'], bindings)] elif op == 'if': execute(action.get('then' if value(action['condition'], bindings) else 'else', []), bindings) elif op == 'assert': if not value(action['condition'], bindings): raise ProgramError(action['message']) elif op == 'call': execute(contract['parts'][action['part']]['actions'], {k: value(v, bindings) for k, v in action['args'].items()}) else: raise AssertionError('reference has no action ' + op) spec = contract['events'][event] if not value(spec.get('guard', True), params): raise ProgramError('reference guard rejects event ' + event) execute(spec['actions'], params) return state def derive_checks(contract): """a check for each event no declared check exercises, derived from the contract itself: a declared check's events (or none) followed by that event, at the first point where the contract's own guard accepts it and its parameters need no value the contract does not give. The expected state is the independent reference's, so the generated program is still compared step by step against the contract's actions. Each derived check says it was derived (12.0 C27).""" seen = {e['event'] for check in contract['checks'] for e in check['events']} out = [] for name in sorted(set(contract['events']) - seen): if contract['events'][name].get('params'): continue # a parameter's value is not the contract's to choose found = [] # where the event changes the state shows it best for check in list(contract['checks']) + [{'events': []}]: state = initial_state(contract) try: for e in check['events']: state = _reference(contract, state, e['event'], e.get('args') or {}) after = _reference(contract, state, name, {}) except (ProgramError, KeyError, TypeError, ValueError, ZeroDivisionError): continue found.append((after == state, check, after)) if not found: continue _same, check, after = sorted(found, key=lambda x: x[0])[0] out.append({'events': list(check['events']) + [{'event': name, 'args': {}}], 'state': after, 'derived': 'from the contract: %s after %s' % (name, ', '.join(e['event'] for e in check['events']) or 'the initial state')}) return out def check_program(root, filename, contract, env=None): """Run emitted HTTP transitions in isolated copies; original state is untouched.""" import socket import subprocess import sys import time import urllib.request contract = validate(contract) derived = derive_checks(contract) seen = {e['event'] for check in contract['checks'] + derived for e in check['events']} missing = set(contract['events']) - seen if not contract['checks'] or missing: return False, 'provide behavioral checks that exercise every event; missing: ' + ', '.join(sorted(missing)) contract = dict(contract, checks=contract['checks'] + derived) base = Path(root).resolve(); candidate = (base / filename).resolve() if base not in candidate.parents: return False, 'checked program must stay inside the project folder' source = candidate.read_bytes(); n = 0 if env is None: # round-3 R2: the checked program runs in the run jail import runjail env = runjail.env(root=root) try: for check in contract['checks']: with tempfile.TemporaryDirectory(prefix='o7-program-check-') as temp: target = Path(temp) / 'app.py'; target.write_bytes(source) with socket.socket() as sock: sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1] process = subprocess.Popen([sys.executable, '-B', str(target), str(port)], cwd=temp, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=env) base = 'http://127.0.0.1:%s' % port def get(path): with urllib.request.urlopen(base + path, timeout=5) as response: return response.read() try: for _ in range(100): try: page = get('/').decode('utf-8'); break except OSError: if process.poll() is not None: raise ProgramError('generated program stopped: ' + process.stderr.read().decode('utf-8', errors='replace')[-1200:]) time.sleep(.05) else: raise ProgramError('generated program did not open its local page') token = json.loads(re.search(r'const token=("[^"]*")', page).group(1)) snapshot = json.loads(get('/_program/state')); state = initial_state(contract) if snapshot['state'] != state: raise ProgramError('generated initial state differs from the declared state') for event in check['events']: state = _reference(contract, state, event['event'], event['args']) payload = dict(event, version=snapshot['version']) request = urllib.request.Request(base + '/_program/event', data=_encoded(payload), headers={'Content-Type': 'application/json', 'Origin': base, 'X-Oracle7-Token': token}) with urllib.request.urlopen(request, timeout=5) as response: snapshot = json.load(response) if snapshot['state'] != state: raise ProgramError('event %s differs from the independent transition' % event['event']) kept = json.loads((Path(temp) / ('.oracle7/' + Path(filename).stem + '-state.json')).read_text(encoding='utf-8')) if kept['state'] != state or json.loads(get('/_program/state'))['state'] != state: raise ProgramError('event %s was not persisted and reread' % event['event']) n += 1 if state != check['state']: raise ProgramError('independent transitions differ from the declared expected final state') finally: process.terminate() try: process.wait(timeout=5) except subprocess.TimeoutExpired: process.kill(); process.wait(timeout=5) process.stderr.close() d = [c['derived'] for c in contract['checks'] if c.get('derived')] return True, ('%s HTTP transitions match independent actions and declared final states; persistence and replay checked' % n + ('; %d check%s derived (%s)' % (len(d), '' if len(d) == 1 else 's', '; '.join(d)) if d else '')) except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc: return False, str(exc)
"""Typed state, named events and reusable action parts for local browser programs.
This part receives an explicit program shape. It does not reinterpret unknown
behavior as a table, run arbitrary code, or invent a missing event binding.
"""
import copy
import hashlib
import html
import itertools
import json
import math
import os
from pathlib import Path
import re
import secrets
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class ProgramError(ValueError):
def __init__(self, message, status=400):
super().__init__(message)
self.status = status
class _StateFileLock:
"""Reentrant in-process ownership plus an OS lock shared by app processes.
The persistent lock file is never removed. Ownership belongs to the open
handle, so termination releases it without guessing whether a PID is alive.
"""
def __init__(self, path):
self.path = Path(path)
self.thread = threading.RLock()
self.depth = 0
self.handle = None
def __enter__(self):
self.thread.acquire()
try:
if self.depth == 0:
self.path.parent.mkdir(parents=True, exist_ok=True)
self.handle = open(self.path, 'a+b', buffering=0)
if os.fstat(self.handle.fileno()).st_size == 0:
self.handle.write(b'\0')
deadline = time.monotonic() + 30
while True:
try:
self.handle.seek(0)
if os.name == 'nt':
import msvcrt
msvcrt.locking(self.handle.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(self.handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except OSError:
if time.monotonic() >= deadline:
raise ProgramError('saved state is busy in another process; refresh before retrying', 409)
time.sleep(0.01)
self.depth += 1
return self
except BaseException:
if self.depth == 0 and self.handle is not None:
self.handle.close(); self.handle = None
self.thread.release()
raise
def __exit__(self, *exc):
try:
self.depth -= 1
if self.depth == 0:
try:
self.handle.seek(0)
if os.name == 'nt':
import msvcrt
msvcrt.locking(self.handle.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(self.handle.fileno(), fcntl.LOCK_UN)
finally:
self.handle.close(); self.handle = None
finally:
self.thread.release()
_STATE_LOCKS = {}
_STATE_LOCKS_GUARD = threading.Lock()
def _state_file_lock(state_path, root):
lock_path = Path(str(state_path) + '.lock').resolve()
if Path(root).resolve() not in lock_path.parents:
raise ProgramError('program state lock must stay inside the project folder')
key = os.path.normcase(str(lock_path))
with _STATE_LOCKS_GUARD:
return _STATE_LOCKS.setdefault(key, _StateFileLock(lock_path))