calendaring-sync 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,572 @@
1
+ # SPDX-FileCopyrightText: 2026 calendaring-sync contributors
2
+ # SPDX-License-Identifier: AGPL-3.0-or-later
3
+
4
+ """The base classes every :term:`adapter` is built on.
5
+
6
+ :class:`Adapter` holds the order of a sync, written once for every
7
+ protocol: open a :term:`session`, read and :term:`ingest` what changed,
8
+ then :term:`push` the pending edits. An adapter subclasses it, fills in
9
+ how its protocol reads and sends, and adds :class:`SyncAdapter` or
10
+ :class:`AsyncAdapter` for the public methods.
11
+
12
+ Both variants run the same steps. A step is a generator that yields what
13
+ a client call returned, the answer itself from a synchronous client or a
14
+ coroutine from an asynchronous one, or an :class:`InStore` for a call into
15
+ the :term:`store`, and gets each result sent back. :class:`SyncAdapter`
16
+ runs the steps as they come; :class:`AsyncAdapter` awaits the coroutines
17
+ and runs the store calls as its description says.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import asyncio
23
+ import concurrent.futures
24
+ import contextvars
25
+ import enum
26
+ import inspect
27
+ from abc import ABC, abstractmethod
28
+ from collections.abc import Callable, Generator, Mapping
29
+ from dataclasses import dataclass, field
30
+ from typing import Any, TypeVar
31
+ from urllib.parse import urlsplit, urlunsplit
32
+
33
+ from calendaring_sync._checks import check_argument_types
34
+ from calendaring_sync.error import OtherScopeError, ScopeGoneError
35
+ from calendaring_sync.objects.edit import EditFields
36
+ from calendaring_sync.objects.push import PushOutcome, Rejected
37
+ from calendaring_sync.objects.record import Record, RecordState
38
+ from calendaring_sync.objects.scope import Scope
39
+ from calendaring_sync.replica import Replica
40
+ from calendaring_sync.session import Session
41
+
42
+ _T = TypeVar("_T")
43
+
44
+ # The records whose edit is waiting to be sent.
45
+ _PENDING = frozenset({RecordState.PENDING})
46
+
47
+
48
+ def _run(steps: Steps[_T]) -> _T:
49
+ """Drive the steps of a sync for a synchronous client."""
50
+ sent: Any = None
51
+ failure: BaseException | None = None
52
+ while True:
53
+ try:
54
+ step = steps.send(sent) if failure is None else steps.throw(failure)
55
+ except StopIteration as done:
56
+ return done.value # type: ignore[no-any-return]
57
+ sent, failure = None, None
58
+ try:
59
+ sent = step.run() if isinstance(step, InStore) else step
60
+ except BaseException as exc: # noqa: BLE001, thrown back into the steps
61
+ failure = exc
62
+
63
+
64
+ async def _arun(steps: Steps[_T]) -> _T:
65
+ """Drive the steps of a sync for an asynchronous client.
66
+
67
+ A store call runs to its end in its worker thread before the steps hear
68
+ of a cancellation or of the driver being closed, so a session never ends
69
+ while one of its calls is still running.
70
+ """
71
+ sent: Any = None
72
+ failure: BaseException | None = None
73
+ while True:
74
+ try:
75
+ step = steps.send(sent) if failure is None else steps.throw(failure)
76
+ except StopIteration as done:
77
+ return done.value # type: ignore[no-any-return]
78
+ sent, failure = None, None
79
+ call: concurrent.futures.Future[Any] | None = None
80
+ try:
81
+ if isinstance(step, InStore):
82
+ call = _in_thread(step)
83
+ running = asyncio.wrap_future(call)
84
+ try:
85
+ sent = await asyncio.shield(running)
86
+ except asyncio.CancelledError:
87
+ await asyncio.wait([running])
88
+ raise
89
+ else:
90
+ sent = await step
91
+ except GeneratorExit:
92
+ # Nothing can be awaited while closing, so the call is waited for here.
93
+ if call is not None:
94
+ _hand_over(steps, call)
95
+ steps.close()
96
+ raise
97
+ except BaseException as exc: # noqa: BLE001, thrown back into the steps
98
+ failure = exc
99
+
100
+
101
+ def _in_thread(step: InStore) -> concurrent.futures.Future[Any]:
102
+ """Start a store call in a worker thread of the running loop."""
103
+ result: concurrent.futures.Future[Any] = concurrent.futures.Future()
104
+ context = contextvars.copy_context()
105
+
106
+ def run() -> None:
107
+ try:
108
+ result.set_result(context.run(step.run))
109
+ except BaseException as exc: # noqa: BLE001, kept for the driver
110
+ result.set_exception(exc)
111
+
112
+ asyncio.get_running_loop().run_in_executor(None, run)
113
+ return result
114
+
115
+
116
+ def _hand_over(steps: Steps[Any], call: concurrent.futures.Future[Any]) -> None:
117
+ """Give the steps what a store call they were waiting for ended with, when closing.
118
+
119
+ The steps then know whether, for example, a session was entered and has
120
+ to end. Whatever they do next goes nowhere, since the driver is closing.
121
+ """
122
+ try:
123
+ try:
124
+ outcome = call.result()
125
+ except BaseException as exc: # noqa: BLE001, thrown into the steps
126
+ following = steps.throw(exc)
127
+ else:
128
+ following = steps.send(outcome)
129
+ except BaseException: # noqa: BLE001, nobody is left to receive it
130
+ return
131
+ if inspect.iscoroutine(following):
132
+ following.close()
133
+
134
+
135
+ def _end(session_manager: Any, exc_info: tuple[Any, Any, Any]) -> Steps[None]:
136
+ """End a session as a store step, or right away when the driver closes first.
137
+
138
+ A closing driver drops the step that follows the call it waited for, and
139
+ that step can be this one.
140
+ """
141
+ try:
142
+ yield InStore(session_manager.__exit__, exc_info)
143
+ except GeneratorExit:
144
+ session_manager.__exit__(*exc_info)
145
+ raise
146
+
147
+
148
+ def _url_id(url: str) -> str:
149
+ """A server URL in one spelling, for a default scope id.
150
+
151
+ Scheme and host are case-insensitive (RFC 3986 section 6.2.2.1), so
152
+ they're lowercased, and a login is left out, so it never reaches a
153
+ store. An explicit port is kept as a number, even the scheme's default.
154
+ """
155
+ parts = urlsplit(url)
156
+ host = parts.hostname or ""
157
+ if ":" in host:
158
+ host = f"[{host}]"
159
+ netloc = host if parts.port is None else f"{host}:{parts.port}"
160
+ return urlunsplit(parts._replace(scheme=parts.scheme.lower(), netloc=netloc))
161
+
162
+
163
+ @check_argument_types
164
+ class Adapter(ABC):
165
+ """Syncs one :term:`scope` with a :class:`~calendaring_sync.replica.Replica`, for any protocol.
166
+
167
+ A sync opens a :term:`session`, reads what changed on the server and
168
+ ingests it, then pushes the pending edits one at a time: claimed, sent,
169
+ settled. When the server refuses the scope's :term:`sync token`, the
170
+ scope is :term:`reset` and listed in full in a new session. An adapter
171
+ subclasses it together with :class:`SyncAdapter` or
172
+ :class:`AsyncAdapter`, which add the public methods.
173
+
174
+ A subclass sets these class attributes, which open each session:
175
+
176
+ - ``_fingerprint_scheme``: the name of the adapter's :term:`fingerprint scheme`.
177
+ - ``_media_type``: the media type of the scope's :term:`content`.
178
+ - ``_guarded_by_version``: ``True`` if a push applies only while the
179
+ object still has the :term:`version` the edit was based on.
180
+ - ``_unique_logical_key``: ``True`` if no two objects in the scope can
181
+ share a :term:`logical key`.
182
+ - ``_guard_covers_scope``: ``True`` if the server checks a push against
183
+ the whole scope rather than the object, so after one rejection every
184
+ later push would be rejected too, and they wait for the next sync.
185
+
186
+ It writes these methods for its protocol, each a generator of
187
+ :data:`Steps` except :meth:`_waits`, :meth:`_new_object_id` and
188
+ :meth:`_edit_fields`:
189
+
190
+ - :meth:`_read` fetches what changed and ingests it.
191
+ - :meth:`_send` sends one claimed edit.
192
+ - :meth:`_waits` says whether a pending edit can't be sent yet.
193
+ - :meth:`_new_object_id` picks the :term:`object id` of a create.
194
+ - :meth:`_edit_fields` reads an edit's fields from its content.
195
+
196
+ It may also write :meth:`_gone`, which says whether an error from the
197
+ server means the scope is gone; a request made through :meth:`_ask`
198
+ then raises :class:`~calendaring_sync.error.ScopeGoneError` for it.
199
+
200
+ These names start with an underscore because your application calls
201
+ the adapter's public methods: a read or a send called on its own would
202
+ skip the session that orders them.
203
+
204
+ Args:
205
+ replica: Where the sync state is kept.
206
+ scope_id: The scope's id.
207
+ """
208
+
209
+ _fingerprint_scheme: str
210
+ _media_type: str
211
+ _guarded_by_version: bool
212
+ _unique_logical_key: bool
213
+ _guard_covers_scope: bool
214
+
215
+ def __init__(self, replica: Replica, scope_id: str) -> None:
216
+ self._replica = replica
217
+ self._scope_id = scope_id
218
+
219
+ @property
220
+ def scope_id(self) -> str:
221
+ """The :term:`scope` this adapter syncs."""
222
+ return self._scope_id
223
+
224
+ @property
225
+ def needs_full_listings(self) -> bool:
226
+ """Whether the server can lose changes without refusing the scope's token.
227
+
228
+ If it's ``True``, an incremental sync may miss a change or a
229
+ removal, so schedule a sync with ``full_listing=True`` now and then,
230
+ such as once a day. ``False`` by default; an adapter whose server
231
+ can lose changes says so.
232
+ """
233
+ return False
234
+
235
+ def edit_fields(self, content: bytes) -> EditFields:
236
+ """Read an object's fields from its content, the same way a sync reads the server's copy.
237
+
238
+ Use it for content your application made itself, such as a
239
+ :class:`~calendaring_sync.objects.resolution.Merge`. Reads nothing
240
+ from the store or the server.
241
+
242
+ Raises:
243
+ ValueError: If the content can't be an object of the scope, as
244
+ for a create.
245
+ """
246
+ return self._edit_fields(content, create=True)
247
+
248
+ def _create(self, content: bytes) -> Steps[int]:
249
+ """Record a create of an object with this content, and return its local key."""
250
+ fields = self._edit_fields(content, create=True)
251
+ key: int = yield InStore(
252
+ self._replica.create,
253
+ (self._scope_id, content),
254
+ {**vars(fields), "object_id": self._new_object_id()},
255
+ )
256
+ return key
257
+
258
+ def _change(self, local_key: int, content: bytes) -> Steps[None]:
259
+ """Record a change of a record in the scope to this content.
260
+
261
+ A change to a create that wasn't sent stays a create, so its content
262
+ must pass what a create's does.
263
+ """
264
+ fields = self._edit_fields(content, create=False)
265
+ # A record never changes scope or stops being a create before it's
266
+ # sent, so these hold when the change runs.
267
+ record: Record | None = yield InStore(self._replica.record, (local_key,))
268
+ if record is not None and record.scope != self._scope_id:
269
+ raise OtherScopeError(f"Record {local_key} is in scope {record.scope!r}, not this one")
270
+ if record is not None and record.is_create:
271
+ fields = self._edit_fields(content, create=True)
272
+ yield InStore(self._replica.change, (local_key, content), vars(fields))
273
+
274
+ def _waiting(self) -> Steps[list[Record]]:
275
+ """The pending edits the adapter won't send yet."""
276
+ pending: list[Record] = yield InStore(
277
+ self._replica.records, (self._scope_id,), {"states": _PENDING}
278
+ )
279
+ return [r for r in pending if self._waits(r)]
280
+
281
+ def _sync(self, *, full_listing: bool) -> Steps[None]:
282
+ """One sync: read and ingest, then push; a refused token resets and lists."""
283
+ read = yield from self._in_session(
284
+ lambda session: self._sync_session(session, full_listing=full_listing)
285
+ )
286
+ if read is ReadResult.INVALID_TOKEN:
287
+ yield InStore(self._replica.reset, (self._scope_id,))
288
+ yield from self._in_session(
289
+ lambda session: self._sync_session(session, full_listing=True)
290
+ )
291
+
292
+ def _sync_session(self, session: Session, *, full_listing: bool) -> Steps[ReadResult]:
293
+ scope: Scope = yield InStore(self._replica.scope, (self._scope_id,))
294
+ read = yield from self._read(session, scope, full_listing=full_listing)
295
+ if read is ReadResult.COMPLETE:
296
+ yield from self._push(session)
297
+ return read
298
+
299
+ def _in_session(self, steps: Callable[[Session], Steps[_T]]) -> Steps[_T]:
300
+ """Run ``steps`` inside a session of the scope, which ends whatever happens."""
301
+ session_manager = self._replica.session(
302
+ self._scope_id,
303
+ fingerprint_scheme=self._fingerprint_scheme,
304
+ media_type=self._media_type,
305
+ guarded_by_version=self._guarded_by_version,
306
+ unique_logical_key=self._unique_logical_key,
307
+ )
308
+ session: Session = yield InStore(session_manager.__enter__)
309
+ try:
310
+ result = yield from steps(session)
311
+ except GeneratorExit:
312
+ # A closing driver runs no more steps, so the session ends here.
313
+ session_manager.__exit__(None, None, None)
314
+ raise
315
+ except BaseException as exc:
316
+ yield from _end(session_manager, (type(exc), exc, exc.__traceback__))
317
+ raise
318
+ yield from _end(session_manager, (None, None, None))
319
+ return result
320
+
321
+ def _push(self, session: Session) -> Steps[None]:
322
+ """Push every pending edit, each claimed, sent and settled on its own.
323
+
324
+ Where the server checks a push against the whole scope, the pushes
325
+ stop at the first rejection, and the rest stay pending, unclaimed.
326
+ """
327
+ records: list[Record] = yield InStore(session.to_push)
328
+ for record in records:
329
+ if self._waits(record):
330
+ continue
331
+ object_id = self._new_object_id() if record.object_id is None else None
332
+ claimed: Record | None = yield InStore(
333
+ session.claim, (record.local_key,), {"object_id": object_id}
334
+ )
335
+ if claimed is None:
336
+ continue
337
+ outcome = yield from self._send(claimed)
338
+ yield InStore(session.settle, (claimed, outcome))
339
+ if self._guard_covers_scope and isinstance(outcome, Rejected):
340
+ return
341
+
342
+ def _ask(self, request: Callable[[], Any]) -> Steps[Any]:
343
+ """Make one request about the scope, and return the server's answer.
344
+
345
+ ``request`` is a function making the call, so a synchronous client's
346
+ error is raised inside this step too.
347
+
348
+ Raises:
349
+ ScopeGoneError: If :meth:`_gone` says the request's error means
350
+ the server no longer has the scope.
351
+ """
352
+ try:
353
+ return (yield request())
354
+ except Exception as exc:
355
+ gone = self._gone(exc)
356
+ if gone is None:
357
+ raise
358
+ raise ScopeGoneError(gone) from exc
359
+
360
+ def _gone(self, error: Exception) -> str | None:
361
+ """Say why the scope is gone, if ``error`` means the server no longer has it.
362
+
363
+ Returns:
364
+ The :class:`~calendaring_sync.error.ScopeGoneError` message, or
365
+ ``None`` for any other error, which is raised unchanged. The
366
+ base class returns ``None``.
367
+ """
368
+ return None
369
+
370
+ @abstractmethod
371
+ def _read(self, session: Session, scope: Scope, *, full_listing: bool) -> Steps[ReadResult]:
372
+ """Fetch what changed in the scope, ingest it, and say how the read ended.
373
+
374
+ Without a token in ``scope.token``, or with ``full_listing``, list
375
+ every object; otherwise ask for the changes since the token. Ingest
376
+ each :class:`~calendaring_sync.objects.change_set.ChangeSet` with
377
+ ``yield InStore(session.ingest, (change_set,))``.
378
+
379
+ Args:
380
+ session: The open session to ingest into.
381
+ scope: The scope as the store holds it.
382
+ full_listing: Whether the caller asked for a full listing.
383
+
384
+ Returns:
385
+ :attr:`ReadResult.INVALID_TOKEN` if the server refused the
386
+ token, before anything was ingested; :attr:`ReadResult.TRUNCATED`
387
+ if the server cut the changes short; :attr:`ReadResult.COMPLETE`
388
+ otherwise.
389
+ """
390
+
391
+ @abstractmethod
392
+ def _send(self, claimed: Record) -> Steps[PushOutcome]:
393
+ """Send one claimed edit and return how it ended.
394
+
395
+ An error raised here reaches the caller and leaves the push in
396
+ flight, since the request may have reached the server; the next
397
+ complete ingest settles it.
398
+
399
+ Args:
400
+ claimed: The record :meth:`~calendaring_sync.session.Session.claim`
401
+ returned, holding the edit to send.
402
+ """
403
+
404
+ @abstractmethod
405
+ def _waits(self, record: Record) -> bool:
406
+ """Whether a pending edit can't be sent yet, so it waits for a later sync.
407
+
408
+ Args:
409
+ record: A record with a pending edit.
410
+ """
411
+
412
+ @abstractmethod
413
+ def _new_object_id(self) -> str | None:
414
+ """Return an object id for a create, or ``None`` if the server picks it."""
415
+
416
+ @abstractmethod
417
+ def _edit_fields(self, content: bytes, *, create: bool) -> EditFields:
418
+ """Read an edit's fields from its content, the same way a sync reads the server's copy.
419
+
420
+ Args:
421
+ content: The edit's content.
422
+ create: Whether the edit is a create, which may need more of
423
+ the content, such as a logical key.
424
+
425
+ Raises:
426
+ ValueError: If the content can't be an object of the scope.
427
+ """
428
+
429
+
430
+ @check_argument_types
431
+ class SyncAdapter(Adapter):
432
+ """The public methods of an adapter for a synchronous client.
433
+
434
+ Your application calls :meth:`sync` when it decides to sync, and
435
+ records its edits with :meth:`create` and :meth:`change`. Deletes and
436
+ discards need nothing from the content, so they go to
437
+ :meth:`~calendaring_sync.replica.Replica.delete` and
438
+ :meth:`~calendaring_sync.replica.Replica.discard`. The adapter's class
439
+ says what content it takes and which of its client's errors reach you;
440
+ the next sync settles a push such an error interrupted. Every method
441
+ also raises the store's errors, as
442
+ :class:`~calendaring_sync.replica.Replica` describes.
443
+ """
444
+
445
+ def sync(self, *, full_listing: bool = False) -> None:
446
+ """Sync the scope: ingest what changed on the server, then push your edits.
447
+
448
+ A scope with no token is listed in full. When the server refuses the
449
+ token, the scope is :term:`reset` and listed in full. Your edits are
450
+ pushed only once everything the server reported was ingested. Each
451
+ step runs in a store transaction of its own.
452
+
453
+ Args:
454
+ full_listing: List every object instead of asking for changes.
455
+
456
+ Raises:
457
+ ScopeGoneError: If the server no longer has the scope.
458
+ IncompleteListingError: If the server cut a full listing short.
459
+ StaleChangeSetError: If another process ingested the scope first.
460
+ SessionError: If this replica already has a session open for the scope.
461
+ ScopeMismatchError: If the scope's content has another media type.
462
+ TransactionError: If a store transaction is open in this thread.
463
+ """
464
+ _run(self._sync(full_listing=full_listing))
465
+
466
+ def create(self, content: bytes) -> int:
467
+ """Record a create of an object with this content, and return its local key.
468
+
469
+ The next :meth:`sync` sends it. Runs in a write transaction.
470
+
471
+ Raises:
472
+ ValueError: If the content can't be an object of the scope.
473
+ UnknownScopeError: If the scope was never synced.
474
+ TransactionError: If a store transaction is open in this thread.
475
+ """
476
+ return _run(self._create(content))
477
+
478
+ def change(self, local_key: int, content: bytes) -> None:
479
+ """Record a change of an object to this content; the next :meth:`sync` sends it.
480
+
481
+ Reads the record, then writes the change, each in a transaction of
482
+ its own. A change to a create that wasn't sent yet stays a create,
483
+ so the content must pass what a create's does.
484
+
485
+ Raises:
486
+ ValueError: If the content can't be an object of the scope.
487
+ OtherScopeError: If the record is in another scope.
488
+ UnknownRecordError: If no record has this local key.
489
+ EditRefusedError: If the record can't take an edit, such as one
490
+ with an open conflict.
491
+ TransactionError: If a store transaction is open in this thread.
492
+ """
493
+ _run(self._change(local_key, content))
494
+
495
+ def waiting(self) -> list[Record]:
496
+ """Return the pending edits the next :meth:`sync` won't send, because it can't yet.
497
+
498
+ Runs in a read transaction.
499
+
500
+ Raises:
501
+ UnknownScopeError: If the scope was never synced.
502
+ TransactionError: If a store transaction is open in this thread.
503
+ """
504
+ return _run(self._waiting())
505
+
506
+
507
+ @check_argument_types
508
+ class AsyncAdapter(Adapter):
509
+ """The public methods of an adapter for an asynchronous client.
510
+
511
+ The same as :class:`SyncAdapter`'s, as coroutines. Each store call runs
512
+ in a worker thread, so a long ingest doesn't block the event loop.
513
+ """
514
+
515
+ async def sync(self, *, full_listing: bool = False) -> None:
516
+ """See :meth:`~calendaring_sync.adapters.base.SyncAdapter.sync`."""
517
+ await _arun(self._sync(full_listing=full_listing))
518
+
519
+ async def create(self, content: bytes) -> int:
520
+ """See :meth:`~calendaring_sync.adapters.base.SyncAdapter.create`."""
521
+ return await _arun(self._create(content))
522
+
523
+ async def change(self, local_key: int, content: bytes) -> None:
524
+ """See :meth:`~calendaring_sync.adapters.base.SyncAdapter.change`."""
525
+ await _arun(self._change(local_key, content))
526
+
527
+ async def waiting(self) -> list[Record]:
528
+ """See :meth:`~calendaring_sync.adapters.base.SyncAdapter.waiting`."""
529
+ return await _arun(self._waiting())
530
+
531
+
532
+ #: The steps of a sync, as a generator that yields client answers or
533
+ #: :class:`InStore` calls, is sent back what each one returned, and returns
534
+ #: its result.
535
+ Steps = Generator[Any, Any, _T]
536
+
537
+
538
+ @dataclass(frozen=True)
539
+ class InStore:
540
+ """A call into the store, which an asynchronous adapter runs in a worker thread.
541
+
542
+ Attributes:
543
+ call: The function to call, such as ``session.ingest``.
544
+ args: Its positional arguments.
545
+ kwargs: Its keyword arguments.
546
+
547
+ Examples:
548
+ A step that ingests a change set::
549
+
550
+ yield InStore(session.ingest, (change_set,))
551
+ """
552
+
553
+ call: Callable[..., Any]
554
+ args: tuple[Any, ...] = ()
555
+ kwargs: Mapping[str, Any] = field(default_factory=dict)
556
+
557
+ def run(self) -> Any:
558
+ """Make the call and return what it returned."""
559
+ return self.call(*self.args, **self.kwargs)
560
+
561
+
562
+ class ReadResult(enum.Enum):
563
+ """How the read part of a sync ended, which decides what the sync does next."""
564
+
565
+ #: Every change was ingested, so the pushes go out.
566
+ COMPLETE = "complete"
567
+ #: The server cut the changes short. The pushes wait, and the next sync
568
+ #: continues from the :term:`checkpoint`.
569
+ TRUNCATED = "truncated"
570
+ #: The server refused the scope's :term:`sync token`, so the scope is
571
+ #: :term:`reset` and listed in full.
572
+ INVALID_TOKEN = "invalid token"