"""State-driven Project Integration refresh; no UI or COM creation here.""" import time from .mentor_adapter import ActivityDeadline from .defaults import DEFAULT_TIMEOUT_SECONDS ACTIONS = ( ('ForwardAnnotation', 'ForwardAnnotate'), ('SynchCES', 'SynchCES'), ('LoadCES', 'LoadCES'), ('BackAnnotation', 'BackAnnotate'), ) class IntegrationError(RuntimeError): pass def value(obj, name): result = getattr(obj, name) return result() if callable(result) else result def statuses(pi): return {name: int(value(pi, name + 'Status')) for name, _ in ACTIONS} def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, timeout_seconds=DEFAULT_TIMEOUT_SECONDS, error_reader=None, sleep=time.sleep, clock=None): clock = clock or time.monotonic def check_error(): if error_reader is None: return detail = error_reader() if detail: emit(stage='integration_error', detail=detail) raise IntegrationError(f'Project Integration error: {detail}') deadline = ActivityDeadline(timeout_seconds, clock=clock) if timeout_seconds is not None else None in_flight = {} executed = set() protected_green = set() action_history = [] green_entry = None previous_state = None while True: check_error() state = statuses(pi) if state != previous_state: emit(stage='integration_status', statuses=state) if green_entry is None: green_entry = all(status == 2 for status in state.values()) if green_entry and not bool(value(pi, 'IsForwardAnnotationAllowed')): # Verified blocks can forbid another ForwardAnnotate despite # all four statuses being InSynch. Respect the native gate; # the caller still requires Save/Close and authoritative READY. emit(stage='integration_complete', statuses=state, actions=[], policy='already_synchronized_native_action_disallowed') return state if previous_state is not None and state != previous_state and deadline is not None: deadline.touch() previous_state = state for name, status in state.items(): # NoCES=3 is recorded as unsupported, never claimed green. if status not in (1, 2): raise IntegrationError(f'{name}: unsupported status {status}') if status != 2: protected_green.discard(name) for name in tuple(in_flight): if state[name] == 2: started, call_elapsed = in_flight.pop(name) emit(stage='integration_action_complete', action=dict(ACTIONS)[name], status=2, elapsed_seconds=round(clock() - started, 6), call_elapsed_seconds=round(call_elapsed, 6)) # When all four lamps start green, mirror the manual refresh: one # ForwardAnnotate, then only repair statuses that actually become Required. # Non-green entry keeps the previously validated four-action route. checked = executed | protected_green refreshed = ('ForwardAnnotation' in checked if green_entry else len(checked) == len(ACTIONS)) if refreshed and not in_flight and all(status == 2 for status in state.values()): emit(stage='integration_complete', statuses=state, actions=action_history, policy='green_first_only' if green_entry else 'required_with_native_gates' if protected_green else 'required_full_sequence', skipped_synchronized=sorted(protected_green)) return state if deadline is not None and deadline.expired(): raise IntegrationError('Project Integration timeout') if in_flight: sleep(.2) continue action_started = False for name, method in ACTIONS: if state[name] == 2 and (name in checked or (green_entry and name != 'ForwardAnnotation')): continue allowed = bool(value(pi, 'Is' + name + 'Allowed')) # Restored, previously verified CBBs can forbid a synchronized # action even while another action is Required. Do not invoke a # native-prohibited method or misreport the skip as a performed call. if state[name] == 2 and not allowed: protected_green.add(name) emit(stage='integration_action_skipped', action=method, initial_status=2, reason='synchronized_native_action_disallowed') continue if not allowed: emit(stage='integration_action_unavailable', action=method, initial_status=state[name], reason='mentor_not_allowed') raise IntegrationError(f'{name}: required but not allowed') check_error() # The permission getter itself can block past cancellation. emit(stage='integration_action', action=method, initial_status=state[name], reason='required_verification' if name not in executed else 'resynchronize') started = clock() try: action_result = value(pi, method) except Exception as error: emit(stage='integration_error', action=method, detail=str(error), elapsed_seconds=round(clock() - started, 6)) raise IntegrationError(f'{method}: {error}') from error if not action_result: raise IntegrationError(f'{method} returned false') in_flight[name] = (started, clock() - started) executed.add(name) action_history.append(method) action_started = True if deadline is not None: deadline.touch() until = clock() + settle_seconds previous = state while statuses(pi) == state and clock() < until: check_error() sleep(.2) if statuses(pi) != previous: if deadline is not None: deadline.touch() break # Every operation may change other statuses; always reread. if not action_started: sleep(.2)