|
| 1 | +""" |
| 2 | +Orders state checkpoints after the resources they summarize. |
| 3 | +
|
| 4 | +When the CLI supports checkpoints, it persists the state rows a source sends as |
| 5 | +``Sync.MessageCheckpoint`` once every destination has committed the messages sent |
| 6 | +before them. A checkpoint must therefore go on the sync stream only after every |
| 7 | +resource its state covers: the resources produced, before the flush, by the table |
| 8 | +resolvers that changed its keys, and the relations those resources spawned. |
| 9 | +
|
| 10 | +The scheduler sends every message through a single queue, so a checkpoint put on |
| 11 | +the queue once those resources are on it is ordered after them on the stream. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import contextvars |
| 17 | +import queue |
| 18 | +import threading |
| 19 | +from contextlib import contextmanager |
| 20 | +from typing import Dict, Iterable, Iterator, List, Optional, Set, Tuple |
| 21 | + |
| 22 | +from cloudquery.sdk.message import SyncCheckpointMessage |
| 23 | + |
| 24 | + |
| 25 | +class Scope: |
| 26 | + """ |
| 27 | + A table resolver call and the relations its resources spawn. |
| 28 | +
|
| 29 | + A scope is finished once its resolver returned and every child scope it |
| 30 | + spawned is finished. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__(self, parent: Optional[Scope], sync: Optional[object]): |
| 34 | + self.parent = parent |
| 35 | + # the sync the scope belongs to, so that resolvers still running after it ended cannot checkpoint into the next one |
| 36 | + self.sync = sync |
| 37 | + # child scopes that are not finished yet |
| 38 | + self.open_children: Set[Scope] = set() |
| 39 | + self.resolving = True |
| 40 | + # checkpoints waiting for this scope to finish |
| 41 | + self.waiters: List[_Pending] = [] |
| 42 | + |
| 43 | + def finished(self) -> bool: |
| 44 | + return not self.resolving and not self.open_children |
| 45 | + |
| 46 | + |
| 47 | +class _Pending: |
| 48 | + """A checkpoint waiting for scopes to finish and for earlier checkpoints of its keys to be sent.""" |
| 49 | + |
| 50 | + def __init__(self, msg: SyncCheckpointMessage, keys: List[str], sync: object): |
| 51 | + self.msg = msg |
| 52 | + self.keys = keys |
| 53 | + self.sync = sync |
| 54 | + self.blockers = 0 |
| 55 | + self.dependents: List[_Pending] = [] |
| 56 | + |
| 57 | + |
| 58 | +class Checkpoints: |
| 59 | + """ |
| 60 | + Sends state checkpoints on the scheduler's queue after the resources they cover. |
| 61 | +
|
| 62 | + The scheduler owns an instance and passes it to the state client through |
| 63 | + :meth:`cloudquery.sdk.stateclient.StateClientBuilder.build`. |
| 64 | + """ |
| 65 | + |
| 66 | + def __init__(self): |
| 67 | + self._lock = threading.Lock() |
| 68 | + self._scope: contextvars.ContextVar[Optional[Scope]] = contextvars.ContextVar( |
| 69 | + "cloudquery_checkpoint_scope", default=None |
| 70 | + ) |
| 71 | + self._res: Optional[queue.Queue] = None |
| 72 | + # newest unsent checkpoint of each key |
| 73 | + self._unsent: Dict[str, _Pending] = {} |
| 74 | + self._sync: Optional[object] = None |
| 75 | + |
| 76 | + def start(self, res: queue.Queue) -> None: |
| 77 | + """Sends later checkpoints on res. Called by the scheduler when a sync starts.""" |
| 78 | + with self._lock: |
| 79 | + self._res = res |
| 80 | + self._sync = object() |
| 81 | + self._unsent = {} |
| 82 | + |
| 83 | + def stop(self) -> None: |
| 84 | + """Drops unsent checkpoints and rejects later ones. Called by the scheduler when a sync ends.""" |
| 85 | + with self._lock: |
| 86 | + self._res = None |
| 87 | + self._sync = None |
| 88 | + self._unsent = {} |
| 89 | + |
| 90 | + def new_scope(self, parent: Optional[Scope]) -> Scope: |
| 91 | + """Returns a scope for a table resolver call, before the call is submitted.""" |
| 92 | + scope = Scope(parent, parent.sync if parent is not None else self._sync) |
| 93 | + if parent is not None: |
| 94 | + with self._lock: |
| 95 | + parent.open_children.add(scope) |
| 96 | + return scope |
| 97 | + |
| 98 | + @contextmanager |
| 99 | + def entered(self, scope: Scope) -> Iterator[None]: |
| 100 | + """ |
| 101 | + Makes scope the current one in this context, for the state changes its resolver makes. |
| 102 | + To change state from other threads, run them in a copy of the context, e.g. with |
| 103 | + ``contextvars.copy_context().run``; asyncio tasks copy it already. |
| 104 | + """ |
| 105 | + token = self._scope.set(scope) |
| 106 | + try: |
| 107 | + yield |
| 108 | + finally: |
| 109 | + self._scope.reset(token) |
| 110 | + |
| 111 | + def current_scope(self) -> Optional[Scope]: |
| 112 | + """Returns the scope of the table resolver running in this context, or None outside table resolvers.""" |
| 113 | + return self._scope.get() |
| 114 | + |
| 115 | + def resolver_finished(self, scope: Scope) -> None: |
| 116 | + """ |
| 117 | + Marks the resolver of scope as returned, once every resource it produced is on the queue. |
| 118 | + """ |
| 119 | + with self._lock: |
| 120 | + scope.resolving = False |
| 121 | + ready: List[_Pending] = [] |
| 122 | + while scope is not None and scope.finished(): |
| 123 | + for pending in scope.waiters: |
| 124 | + pending.blockers -= 1 |
| 125 | + if pending.blockers == 0: |
| 126 | + ready.append(pending) |
| 127 | + scope.waiters = [] |
| 128 | + if scope.parent is not None: |
| 129 | + scope.parent.open_children.discard(scope) |
| 130 | + scope = scope.parent |
| 131 | + self._send(ready) |
| 132 | + |
| 133 | + def schedule( |
| 134 | + self, |
| 135 | + checkpoints: List[ |
| 136 | + Tuple[Iterable[Optional[Scope]], List[str], SyncCheckpointMessage] |
| 137 | + ], |
| 138 | + ) -> None: |
| 139 | + """ |
| 140 | + Sends each (scopes, keys, msg) once every resource the scopes produced so far is on the |
| 141 | + queue, including the relations spawned from them, and after every earlier unsent |
| 142 | + checkpoint of keys. A None scope stands for changes made outside table resolvers, which |
| 143 | + wait for nothing. Schedules all of them or, if it raises, none of them. |
| 144 | +
|
| 145 | + Raises: |
| 146 | + RuntimeError: if no sync is running, as the checkpoints could not be sent. |
| 147 | + """ |
| 148 | + with self._lock: |
| 149 | + if self._res is None: |
| 150 | + raise RuntimeError( |
| 151 | + "state checkpoints can only be flushed while the scheduler syncs, " |
| 152 | + "e.g. from a table resolver or the post-sync hook" |
| 153 | + ) |
| 154 | + for scopes, _, _ in checkpoints: |
| 155 | + if any(s is not None and s.sync is not self._sync for s in scopes): |
| 156 | + raise RuntimeError( |
| 157 | + "state checkpoints of a table resolver can only be flushed during its own sync" |
| 158 | + ) |
| 159 | + for scopes, keys, msg in checkpoints: |
| 160 | + self._schedule(scopes, keys, msg) |
| 161 | + |
| 162 | + def _schedule( |
| 163 | + self, |
| 164 | + scopes: Iterable[Optional[Scope]], |
| 165 | + keys: List[str], |
| 166 | + msg: SyncCheckpointMessage, |
| 167 | + ) -> None: |
| 168 | + pending = _Pending(msg, keys, self._sync) |
| 169 | + for scope in {s for s in scopes if s is not None}: |
| 170 | + # the scope's own resources are on the queue already: resolvers put each |
| 171 | + # resource on it before they resume, so only its relations can be in flight |
| 172 | + for child in scope.open_children: |
| 173 | + child.waiters.append(pending) |
| 174 | + pending.blockers += 1 |
| 175 | + earlier = set() |
| 176 | + for key in keys: |
| 177 | + previous = self._unsent.get(key) |
| 178 | + if previous is not None and previous not in earlier: |
| 179 | + earlier.add(previous) |
| 180 | + previous.dependents.append(pending) |
| 181 | + pending.blockers += 1 |
| 182 | + self._unsent[key] = pending |
| 183 | + if pending.blockers == 0: |
| 184 | + self._send([pending]) |
| 185 | + |
| 186 | + def _send(self, ready: List[_Pending]) -> None: |
| 187 | + """Puts ready checkpoints on the queue, then the ones that only waited for them. Called with the lock held.""" |
| 188 | + while ready: |
| 189 | + pending = ready.pop() |
| 190 | + if pending.sync is self._sync: |
| 191 | + self._res.put(pending.msg) |
| 192 | + for key in pending.keys: |
| 193 | + if self._unsent.get(key) is pending: |
| 194 | + del self._unsent[key] |
| 195 | + for dependent in pending.dependents: |
| 196 | + dependent.blockers -= 1 |
| 197 | + if dependent.blockers == 0: |
| 198 | + ready.append(dependent) |
| 199 | + pending.dependents = [] |
0 commit comments