Files
cbb-refresh-verify-795/src/cbb_refresh_verify/operation_queue.py
T

565 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Cooperative FIFO admission for this application's native operations."""
from contextlib import contextmanager, nullcontext
from dataclasses import dataclass, field
import ntpath
from threading import Condition, Event, RLock, Thread, local
import time
from uuid import uuid4
class QueueCancelled(RuntimeError):
pass
class QueueUnavailable(RuntimeError):
"""Admission failed before action dispatch; this task created no native session."""
def __init__(self, library, sessions=(), *, timed_out=False, detail=''):
self.library = str(library)
self.sessions = tuple(sessions)
self.timed_out = timed_out
details = []
for session in self.sessions:
block = session.get('block') or '当前库'
resources = '、'.join(map(str, session.get('blocked_resources') or ()))
details.append(' / '.join(filter(None, (block, session.get('operation_id'),
resources, session.get('path')))))
message = f'NATIVE_SESSION_PENDING: {self.library} 的已登记会话待释放,当前项未启动。'
if detail:
details.insert(0, detail)
super().__init__(message + (' ' + ';'.join(details) if details else ''))
class TaskHandoff(QueueCancelled):
"""The call is still observable; this is never a release receipt."""
def __init__(self, context, *, cancelled=False, result=None):
self.operation_id = context.operation_id
self.library = context.library
self.cancelled = cancelled
self.scope = context.scope
self.result = result
super().__init__('已交给后台观察;当前资源尚未确认释放。')
class _StopSignal:
def __init__(self):
self._event = Event()
def set(self):
with _tasks_guard:
self._event.set()
def is_set(self):
return self._event.is_set()
def wait(self, timeout=None):
return self._event.wait(timeout)
_local = local()
_tasks_guard = RLock()
_calls = {}
def _path_key(path):
# Identity was bound by the caller; queue predicates must never resolve a share.
return ntpath.normcase(ntpath.normpath(str(path)))
def request_library_keys(request, context=None):
library = str(getattr(request, 'lmc_file', getattr(request, 'library', '__injected_verifier_scope__')))
keys = {_path_key(library)}
drive, remote = getattr(request, 'mapped_drive', ''), getattr(request, 'mapped_remote_root', '')
if drive and remote and ntpath.splitdrive(library)[0].casefold() == drive.rstrip('\\/').casefold():
keys.add(_path_key(ntpath.join(remote, ntpath.splitdrive(library)[1].lstrip('\\/'))))
if context is not None:
aliases = {_path_key(v) for v in (context.library, *context.aliases)}
if keys.intersection(aliases):
keys.update(aliases)
return keys
@dataclass(eq=False)
class _Call:
context: object
external_stop: object = None
metadata_only: bool = False
done: Event = field(default_factory=Event)
abandoned: bool = False
native_depth: int = 0
commit_depth: int = 0
readonly_depth: int = 0
supervised_depth: int = 0
worker_sessions: list = field(default_factory=list)
shutdown_handoff: bool = False
native_handoff: str = ''
handoff_cancelled: bool = False
queue_pause: object = None
queued_for_slot: bool = False
phase_started: float = field(default_factory=time.monotonic)
result: object = None
last_result: object = None
error: BaseException | None = None
def is_set(self):
return (self.abandoned or self.context.stop.is_set()
or self.external_stop is not None and self.external_stop.is_set())
def current_context():
call = getattr(_local, 'call', None)
return call.context if call is not None else None
def task_stop(fallback=None):
return getattr(_local, 'call', None) or fallback
def allow_other_libraries():
call = getattr(_local, 'call', None)
return call.queue_pause() if call is not None and call.queue_pause is not None else nullcontext()
def check_active():
call = getattr(_local, 'call', None)
if call is not None and call.is_set():
raise QueueCancelled('任务已取消,未提交新的原生操作。')
def note_metadata_progress():
"""Renew inactivity only after completed I/O; never revive an abandoned call."""
call = getattr(_local, 'call', None)
if call is not None:
with _tasks_guard:
if not call.native_depth:
check_active()
call.phase_started = time.monotonic()
def remember_result(result):
call = getattr(_local, 'call', None)
if call is not None:
with _tasks_guard:
call.last_result = result
return result
def bind_supervised_worker(path, record):
"""Called only after the common launcher has durably registered its worker."""
call = getattr(_local, 'call', None)
if call is not None:
with _tasks_guard:
call.worker_sessions.append(dict(path=str(path), operation_id=record['operation_id'],
processes=record['processes'], worker_lease_handle=record.get('worker_lease_handle'),
worker_protection=record.get('worker_protection'), resource_scope=record.get('resource_scope')))
def check_worker_admission(job):
check_active()
call = getattr(_local, 'call', None)
if (call is not None and call.readonly_depth and job.get('inspection_only') is not True
and not (job.get('operation') == 'catalog' and job.get('worker_role') == 'catalog_readonly')):
raise RuntimeError('NATIVE_ROLE_REQUIRED: 只读观察不能启动原生写入进程。')
def commit_worker_start(worker, job):
"""Prepare evidence outside the shutdown fence; only SetEvent grants admission."""
from pathlib import Path
import win32event
try:
check_worker_admission(job)
event = getattr(worker, '_start_event', None)
context = current_context()
if context is not None and context.native_policy == 'external' and event is None:
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少已登记的启动事件。')
if event is not None and worker._start_binding != (
str(job['session_record_path']), job['operation_id'], job['start_gate']):
raise RuntimeError('WORKER_ADMISSION_IDENTITY_CHANGED')
Path(job['start_gate']).touch()
with _tasks_guard:
check_worker_admission(job)
if event is not None:
win32event.SetEvent(event)
except BaseException:
# A stalled evidence volume cannot delay shutdown or grant admission.
if job.get('cancel_signal'):
Path(job['cancel_signal']).touch()
raise
def hold_native_handoff(process, session_record_path):
"""Yield parent admission to controls; the gated worker retains write exclusion.
The caller registers the exact worker observer first. Its writer barrier and
inherited sidecar survive this supervisor, including while a user answers Save.
"""
call = getattr(_local, 'call', None)
if call is not None:
with _tasks_guard:
call.handoff_cancelled = call.is_set()
call.native_handoff = str(session_record_path)
call.abandoned = True
raise TaskHandoff(call.context, cancelled=call.handoff_cancelled, result=call.last_result)
@contextmanager
def local_commit():
"""Finish an admitted filesystem rename/rollback without native ownership claims."""
call = getattr(_local, 'call', None)
with _tasks_guard:
check_active()
if call is not None:
if call.metadata_only or call.readonly_depth:
raise RuntimeError('Read-only metadata cannot commit filesystem changes')
call.commit_depth += 1
try:
yield
finally:
if call is not None:
with _tasks_guard:
call.commit_depth -= 1
call.phase_started = time.monotonic()
@contextmanager
def native_phase(*, read_only=False, supervised=False):
"""Never abandon a transaction between native writes (including Remove/Add)."""
call = getattr(_local, 'call', None)
if call is not None and call.metadata_only:
raise RuntimeError('A metadata-only call cannot enter native work')
if call is not None:
if call.readonly_depth and not read_only:
raise RuntimeError('NATIVE_ROLE_REQUIRED: 只读观察不能提交原生写入。')
if not read_only and (call.context.native_policy == 'restricted'
or call.context.native_policy == 'external' and not supervised):
raise RuntimeError('NATIVE_ROLE_REQUIRED: 界面写入必须通过已登记的独立工作进程。')
with _tasks_guard:
check_active()
if call is not None:
call.native_depth += 1
call.readonly_depth += int(read_only)
call.supervised_depth += int(supervised)
try:
yield
finally:
if call is not None:
with _tasks_guard:
call.native_depth -= 1
call.readonly_depth -= int(read_only)
call.supervised_depth -= int(supervised)
call.phase_started = time.monotonic()
@contextmanager
def native_channel(*, inspection_only=False, read_only=False):
"""Shared by Verify, Repair and backup native clients; reentrant per thread."""
import win32con, win32event
with native_phase(read_only=read_only or inspection_only, supervised=True):
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
try:
check_active()
acquired = win32event.WaitForSingleObject(mutex, 0) in (
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
raise RuntimeError('NATIVE_CHANNEL_BUSY: 另一个原生操作仍在运行。')
from .desktop_worker import assert_native_writer_idle
if inspection_only is not True:
assert_native_writer_idle()
yield
finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
@dataclass(frozen=True)
class BatchTaskContext:
library: str
aliases: tuple[str, ...] = ()
targets: tuple[str, ...] = ()
resources: tuple[str, ...] = ()
operation_id: str = field(default_factory=lambda: uuid4().hex)
stop: _StopSignal = field(default_factory=_StopSignal, repr=False, compare=False)
_closed: Event = field(default_factory=Event, repr=False, compare=False)
native_policy: str = field(default='legacy', kw_only=True)
# Only queue/batch boundaries consume this; the current item retains hard-stop semantics.
stop_after_current: _StopSignal = field(default_factory=_StopSignal, repr=False, compare=False, kw_only=True)
def __post_init__(self):
if self.native_policy not in ('legacy', 'restricted', 'external'):
raise ValueError('Unknown native task role')
object.__setattr__(self, 'library', str(self.library))
for name in ('aliases', 'targets', 'resources'):
object.__setattr__(self, name, tuple(str(v) for v in getattr(self, name)))
@property
def scope(self):
return dict(scope_state='DECLARED', library=self.library, aliases=list(self.aliases),
block_names=list(self.targets), resources=list(self.resources),
operation_ids=[self.operation_id])
@property
def state(self):
return self.snapshot()['state']
def snapshot(self):
with _tasks_guard:
calls = [call for call in _calls.values() if call.context is self]
pending = sum(not call.done.is_set() for call in calls)
return dict(operation_id=self.operation_id, resource_scope=self.scope,
state='CLOSED' if self._closed.is_set() else
'CANCELLED' if self.stop.is_set() else
'HANDED_OFF' if any(c.abandoned for c in calls) else
'RUNNING' if pending else 'IDLE', pending=pending,
pending_native=any(c.native_depth or c.commit_depth for c in calls))
def shutdown(self):
"""Yield UI supervision, never a native worker's write/lease ownership.
External workers commit their kernel start event under this same fence.
Registration and all filesystem preparation remain outside the fence.
Legacy in-process transactions cannot opt in.
"""
with _tasks_guard:
self._closed.set()
self.cancel()
calls = [c for c in _calls.values() if c.context is self and not c.done.is_set()]
for call in calls:
readonly = call.native_depth and call.readonly_depth == call.native_depth
external = (self.native_policy == 'external' and
call.supervised_depth == call.native_depth and
all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly')
for s in call.worker_sessions))
if not call.commit_depth and (not call.native_depth or readonly or external):
call.shutdown_handoff = call.abandoned = True
return {**self.snapshot(), 'safe_to_continue': False,
'shutdown_handoff': all(c.shutdown_handoff for c in calls),
'worker_sessions': [s for c in calls for s in c.worker_sessions]}
def cancel(self):
self.stop.set()
def check_active(self):
if self.stop.is_set() or self._closed.is_set():
raise QueueCancelled('任务已取消,未提交新的原生操作。')
check_active()
def guard_callback(self, callback, *, current=None):
call = getattr(_local, 'call', None)
def guarded(*args, **kwargs):
# Cancellation still gets its own terminal result; closing or an
# abandoned invocation cannot update a newer task/library.
if (not self._closed.is_set() and not (call and call.abandoned)
and (current is None or current() is self)):
return callback(*args, **kwargs)
return guarded
def close(self, *, timeout_seconds=30):
self._closed.set()
self.cancel()
deadline = time.monotonic() + min(30, max(0, timeout_seconds))
with _tasks_guard:
calls = [c for c in _calls.values() if c.context is self]
for call in calls:
call.done.wait(max(0, deadline-time.monotonic()))
with _tasks_guard:
for call in calls:
if not call.done.is_set() and not call.native_depth and not call.commit_depth:
call.abandoned = True
return self.snapshot()
def run(self, action, *, stop=None, timeout_seconds=10, metadata_only=False):
self.check_active()
if current_context() is self:
return action() # Preserve nested lease and mutex thread identity.
aliases = {_path_key(v) for v in (self.library, *self.aliases)}
call = _Call(self, stop, metadata_only=metadata_only)
with _tasks_guard:
if not metadata_only and self.native_policy != 'restricted' and any(c.abandoned and not c.metadata_only and aliases.intersection(
_path_key(v) for v in (c.context.library, *c.context.aliases))
for c in _calls.values()):
raise TaskHandoff(self)
_calls[id(call)] = call
def execute():
_local.call = call
try:
check_active()
call.result = action()
except BaseException as error:
call.error = error
finally:
with _tasks_guard:
call.done.set()
_calls.pop(id(call), None)
del _local.call
Thread(target=execute, name='cbb-task-'+self.operation_id[:12], daemon=True).start()
while not call.done.wait(.02):
with _tasks_guard:
if call.shutdown_handoff:
raise TaskHandoff(self, cancelled=True, result=call.last_result)
if call.native_handoff:
cancelled = call.handoff_cancelled
call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
elapsed = time.monotonic()-call.phase_started
expired = not call.queued_for_slot and elapsed >= timeout_seconds
if not call.native_depth and not call.commit_depth and (call.abandoned or expired):
cancelled = call.is_set()
call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
if call.error is not None:
raise call.error
return call.result
@dataclass(eq=False)
class _Ticket:
roots: frozenset
ready: bool = False
paused: bool = False
class NativeQueue:
def __init__(self):
self.condition = Condition()
self.pending = []
self.active = False
self.closed = False
self.contexts = {}
def wake(self):
with self.condition: self.condition.notify_all()
def close(self, *, timeout_seconds=30):
deadline = time.monotonic()+min(30, max(0, timeout_seconds))
with self.condition:
self.closed = True
contexts = tuple(self.contexts.values())
for context in contexts:
context.cancel()
self.condition.notify_all()
return tuple(context.close(timeout_seconds=max(0, deadline-time.monotonic()))
for context in contexts)
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None,
context=None, timeout_seconds=10, skip_unavailable=False, wait_for_release_seconds=None):
release_deadline = None
def available_now():
nonlocal release_deadline
if not ready():
return False
if context is None:
return True # Explicit recovery controls must still reach their retained clients.
from .session_record import _live_library_available
for path in (context.library, *context.aliases):
if not _live_library_available(path):
if skip_unavailable and wait_for_release_seconds is None:
raise QueueUnavailable(path)
if wait_for_release_seconds is not None:
now = time.monotonic()
if release_deadline is None:
release_deadline = now + wait_for_release_seconds
if now >= release_deadline:
from .session_record import retained_session_states
raise QueueUnavailable(path, retained_session_states(path), timed_out=True)
return False
return True
roots = frozenset(ntpath.dirname(_path_key(path))
for path in (context.library, *context.aliases)) if context is not None else frozenset()
ticket = _Ticket(roots)
acquired, notified = False, False
previous_state = None
def first_ready():
paused = [entry for entry in self.pending if entry.paused]
return next((entry for entry in self.pending if entry.ready and not any(
owner is not entry and (not entry.roots or owner.roots & entry.roots)
for owner in paused)), None)
@contextmanager
def pause():
nonlocal acquired
call = _local.call
with self.condition:
can_pause = acquired and not call.native_depth and not call.commit_depth
if can_pause:
ticket.ready, ticket.paused = False, True
self.active = acquired = False
self.condition.notify_all()
if not can_pause:
# Nested Verify may still be part of a management transaction.
yield
return
try:
yield
finally:
with _tasks_guard:
call.queued_for_slot = True
try:
with self.condition:
ticket.ready = True
while ticket in self.pending and not self.closed and not call.is_set():
if not self.active and first_ready() is ticket:
self.active = acquired = True
break
self.condition.wait(.1)
ticket.paused = ticket.ready = False
self.condition.notify_all()
if not acquired:
raise QueueCancelled('已取消等待原生通道,未提交新的调用。')
finally:
with _tasks_guard:
call.queued_for_slot = False
call.phase_started = time.monotonic()
def run_admitted():
call = _local.call
previous_pause, call.queue_pause = call.queue_pause, pause
try:
return action()
finally:
call.queue_pause = previous_pause
with self.condition:
if self.closed:
raise QueueCancelled('队列已关闭,未启动新的操作。')
if context is not None:
self.contexts[id(context)] = context
self.pending.append(ticket)
try:
while not acquired:
if (self.closed or stop is not None and stop.is_set()
or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())):
raise QueueCancelled('已取消排队,未启动原生操作。')
available = available_now() # Cached predicates only, outside the queue lock.
with self.condition:
if (self.closed or stop is not None and stop.is_set()
or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())):
raise QueueCancelled('已取消排队,未启动原生操作。')
ticket.ready = bool(available)
if not self.active and first_ready() is ticket:
self.active = acquired = True
else:
self.condition.wait(.1)
if acquired and not available_now():
with self.condition:
ticket.ready = self.active = acquired = False
self.condition.notify_all()
if not acquired and waiting is not None:
try:
current_state = wait_state() if wait_state is not None else None
if not notified or current_state != previous_state:
waiting()
notified, previous_state = True, current_state
except Exception:
pass
if (stop is not None and stop.is_set()
or context is not None and context.stop_after_current.is_set()):
raise QueueCancelled('已取消排队,未启动原生操作。')
return context.run(run_admitted, stop=stop, timeout_seconds=timeout_seconds) if context else action()
finally:
with self.condition:
self.pending = [entry for entry in self.pending if entry is not ticket]
if acquired: self.active = False
self.condition.notify_all()