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.
- calendaring_sync/__init__.py +153 -0
- calendaring_sync/_checks.py +328 -0
- calendaring_sync/_classify.py +135 -0
- calendaring_sync/_version.py +24 -0
- calendaring_sync/adapters/__init__.py +10 -0
- calendaring_sync/adapters/base.py +572 -0
- calendaring_sync/adapters/caldav.py +544 -0
- calendaring_sync/adapters/jmap.py +603 -0
- calendaring_sync/constants.py +21 -0
- calendaring_sync/error.py +246 -0
- calendaring_sync/objects/__init__.py +4 -0
- calendaring_sync/objects/_data.py +31 -0
- calendaring_sync/objects/change.py +68 -0
- calendaring_sync/objects/change_set.py +59 -0
- calendaring_sync/objects/conflict.py +97 -0
- calendaring_sync/objects/dropped_scope.py +26 -0
- calendaring_sync/objects/edit.py +81 -0
- calendaring_sync/objects/feed.py +60 -0
- calendaring_sync/objects/push.py +223 -0
- calendaring_sync/objects/record.py +262 -0
- calendaring_sync/objects/resolution.py +216 -0
- calendaring_sync/objects/scope.py +38 -0
- calendaring_sync/py.typed +0 -0
- calendaring_sync/replica.py +1369 -0
- calendaring_sync/session.py +294 -0
- calendaring_sync/store/__init__.py +7 -0
- calendaring_sync/store/base.py +683 -0
- calendaring_sync/store/memory.py +263 -0
- calendaring_sync/store/sqlite.py +618 -0
- calendaring_sync-0.1.0.dist-info/METADATA +111 -0
- calendaring_sync-0.1.0.dist-info/RECORD +33 -0
- calendaring_sync-0.1.0.dist-info/WHEEL +4 -0
- calendaring_sync-0.1.0.dist-info/licenses/LICENSE +235 -0
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 calendaring-sync contributors
|
|
2
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
"""Calendar sync state: sync tokens, object versions, change tracking, and conflict detection.
|
|
5
|
+
|
|
6
|
+
An application starts from :class:`~calendaring_sync.replica.Replica`
|
|
7
|
+
and a :term:`store`; an :term:`adapter`, or code of your own, tells them
|
|
8
|
+
what changed.
|
|
9
|
+
Import every public name from ``calendaring_sync`` itself, such as
|
|
10
|
+
``from calendaring_sync import Replica, SQLiteStore``, except the
|
|
11
|
+
adapters, which each come from their own module.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from calendaring_sync._version import __version__
|
|
15
|
+
from calendaring_sync.error import (
|
|
16
|
+
CalendaringSyncError,
|
|
17
|
+
DuplicateObjectError,
|
|
18
|
+
EditRefusedError,
|
|
19
|
+
FeedRangeError,
|
|
20
|
+
IncompleteListingError,
|
|
21
|
+
ListingRequiredError,
|
|
22
|
+
LoneSurrogateError,
|
|
23
|
+
ObjectIdAssignedError,
|
|
24
|
+
OpenConflictError,
|
|
25
|
+
OtherScopeError,
|
|
26
|
+
PendingEditError,
|
|
27
|
+
PushInFlightError,
|
|
28
|
+
RecordValueError,
|
|
29
|
+
RemovedRecordError,
|
|
30
|
+
ScopeGoneError,
|
|
31
|
+
ScopeMismatchError,
|
|
32
|
+
SessionError,
|
|
33
|
+
StaleChangeSetError,
|
|
34
|
+
StaleConflictError,
|
|
35
|
+
StoreBusyError,
|
|
36
|
+
StoreError,
|
|
37
|
+
StoreVersionError,
|
|
38
|
+
TransactionError,
|
|
39
|
+
TransactionPermissionError,
|
|
40
|
+
TransactionRequiredError,
|
|
41
|
+
TrimmedFeedError,
|
|
42
|
+
UnexpectedStoreError,
|
|
43
|
+
UnknownHolderError,
|
|
44
|
+
UnknownRecordError,
|
|
45
|
+
UnknownScopeError,
|
|
46
|
+
UnknownVersionError,
|
|
47
|
+
)
|
|
48
|
+
from calendaring_sync.objects.change import Change, Changed, Removed, Unchanged
|
|
49
|
+
from calendaring_sync.objects.change_set import ChangeSet
|
|
50
|
+
from calendaring_sync.objects.conflict import Conflict, ConflictKind
|
|
51
|
+
from calendaring_sync.objects.dropped_scope import DroppedScope
|
|
52
|
+
from calendaring_sync.objects.edit import EditFields, EditKind, LocalEdit
|
|
53
|
+
from calendaring_sync.objects.feed import FeedEntry, FeedEntryKind
|
|
54
|
+
from calendaring_sync.objects.push import (
|
|
55
|
+
Applied,
|
|
56
|
+
Gone,
|
|
57
|
+
LogicalKeyTaken,
|
|
58
|
+
NotAllowed,
|
|
59
|
+
PushOutcome,
|
|
60
|
+
Rejected,
|
|
61
|
+
Unknown,
|
|
62
|
+
)
|
|
63
|
+
from calendaring_sync.objects.record import Record, RecordState
|
|
64
|
+
from calendaring_sync.objects.resolution import (
|
|
65
|
+
Delete,
|
|
66
|
+
KeepLocal,
|
|
67
|
+
KeepServer,
|
|
68
|
+
Merge,
|
|
69
|
+
Resolution,
|
|
70
|
+
ResolvedConflicts,
|
|
71
|
+
UpdateHolder,
|
|
72
|
+
)
|
|
73
|
+
from calendaring_sync.objects.scope import Scope
|
|
74
|
+
from calendaring_sync.replica import Replica
|
|
75
|
+
from calendaring_sync.session import Session, SessionState
|
|
76
|
+
from calendaring_sync.store.base import StateStore, Storage, StorageTransaction
|
|
77
|
+
from calendaring_sync.store.memory import MemoryData, MemoryKeeper, MemoryStore
|
|
78
|
+
from calendaring_sync.store.sqlite import SQLiteStore
|
|
79
|
+
|
|
80
|
+
__all__ = [
|
|
81
|
+
"Applied",
|
|
82
|
+
"CalendaringSyncError",
|
|
83
|
+
"Change",
|
|
84
|
+
"ChangeSet",
|
|
85
|
+
"Changed",
|
|
86
|
+
"Conflict",
|
|
87
|
+
"ConflictKind",
|
|
88
|
+
"Delete",
|
|
89
|
+
"DroppedScope",
|
|
90
|
+
"DuplicateObjectError",
|
|
91
|
+
"EditFields",
|
|
92
|
+
"EditKind",
|
|
93
|
+
"EditRefusedError",
|
|
94
|
+
"FeedEntry",
|
|
95
|
+
"FeedEntryKind",
|
|
96
|
+
"FeedRangeError",
|
|
97
|
+
"Gone",
|
|
98
|
+
"IncompleteListingError",
|
|
99
|
+
"KeepLocal",
|
|
100
|
+
"KeepServer",
|
|
101
|
+
"ListingRequiredError",
|
|
102
|
+
"LocalEdit",
|
|
103
|
+
"LogicalKeyTaken",
|
|
104
|
+
"LoneSurrogateError",
|
|
105
|
+
"MemoryData",
|
|
106
|
+
"MemoryKeeper",
|
|
107
|
+
"MemoryStore",
|
|
108
|
+
"Merge",
|
|
109
|
+
"NotAllowed",
|
|
110
|
+
"ObjectIdAssignedError",
|
|
111
|
+
"OpenConflictError",
|
|
112
|
+
"OtherScopeError",
|
|
113
|
+
"PendingEditError",
|
|
114
|
+
"PushInFlightError",
|
|
115
|
+
"PushOutcome",
|
|
116
|
+
"Record",
|
|
117
|
+
"RecordState",
|
|
118
|
+
"RecordValueError",
|
|
119
|
+
"Rejected",
|
|
120
|
+
"Removed",
|
|
121
|
+
"RemovedRecordError",
|
|
122
|
+
"Replica",
|
|
123
|
+
"Resolution",
|
|
124
|
+
"ResolvedConflicts",
|
|
125
|
+
"SQLiteStore",
|
|
126
|
+
"Scope",
|
|
127
|
+
"ScopeGoneError",
|
|
128
|
+
"ScopeMismatchError",
|
|
129
|
+
"Session",
|
|
130
|
+
"SessionError",
|
|
131
|
+
"SessionState",
|
|
132
|
+
"StaleChangeSetError",
|
|
133
|
+
"StaleConflictError",
|
|
134
|
+
"StateStore",
|
|
135
|
+
"Storage",
|
|
136
|
+
"StorageTransaction",
|
|
137
|
+
"StoreBusyError",
|
|
138
|
+
"StoreError",
|
|
139
|
+
"StoreVersionError",
|
|
140
|
+
"TransactionError",
|
|
141
|
+
"TransactionPermissionError",
|
|
142
|
+
"TransactionRequiredError",
|
|
143
|
+
"TrimmedFeedError",
|
|
144
|
+
"Unchanged",
|
|
145
|
+
"UnexpectedStoreError",
|
|
146
|
+
"Unknown",
|
|
147
|
+
"UnknownHolderError",
|
|
148
|
+
"UnknownRecordError",
|
|
149
|
+
"UnknownScopeError",
|
|
150
|
+
"UnknownVersionError",
|
|
151
|
+
"UpdateHolder",
|
|
152
|
+
"__version__",
|
|
153
|
+
]
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 calendaring-sync contributors
|
|
2
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
"""The checks on what enters the core: argument types, and strings every store can keep.
|
|
5
|
+
|
|
6
|
+
A value's type is checked where it enters the library, so a wrong type fails
|
|
7
|
+
the same way on every store instead of being stored as it is by one and
|
|
8
|
+
converted by another. The checks are built from the annotations the first
|
|
9
|
+
time they're needed, as one plain function each, since they run on every
|
|
10
|
+
call.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import dataclasses
|
|
16
|
+
import enum
|
|
17
|
+
import inspect
|
|
18
|
+
import types
|
|
19
|
+
import typing
|
|
20
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
21
|
+
from functools import wraps
|
|
22
|
+
from typing import Any, TypeVar
|
|
23
|
+
|
|
24
|
+
from calendaring_sync.error import LoneSurrogateError
|
|
25
|
+
|
|
26
|
+
_T = TypeVar("_T")
|
|
27
|
+
|
|
28
|
+
#: Built-in types a value must be exactly, not a subclass of: ``True`` is
|
|
29
|
+
#: no local key, and a ``str`` subclass could change how two values compare.
|
|
30
|
+
_EXACT = (str, int, bytes, bool)
|
|
31
|
+
|
|
32
|
+
#: Value dataclasses that check their own fields when built. Being frozen,
|
|
33
|
+
#: one inside another value only needs to be of its class.
|
|
34
|
+
_CHECKED_WHEN_BUILT: set[type] = set()
|
|
35
|
+
|
|
36
|
+
# Marks an argument the caller left to its default.
|
|
37
|
+
_MISSING = object()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _Kind(enum.Enum):
|
|
41
|
+
"""The kinds of type hint the checks can read."""
|
|
42
|
+
|
|
43
|
+
NONE = enum.auto()
|
|
44
|
+
UNION = enum.auto()
|
|
45
|
+
EXACT = enum.auto()
|
|
46
|
+
NUMBER = enum.auto()
|
|
47
|
+
FROZENSET = enum.auto()
|
|
48
|
+
MAPPING = enum.auto()
|
|
49
|
+
CALLABLE = enum.auto()
|
|
50
|
+
#: A dataclass whose fields are checked one by one.
|
|
51
|
+
FIELDS = enum.auto()
|
|
52
|
+
#: Any other class, checked with ``isinstance``.
|
|
53
|
+
INSTANCE = enum.auto()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _kind(hint: Any) -> tuple[_Kind, tuple[Any, ...]]:
|
|
57
|
+
"""What kind of type a hint asks for, and the hints or class inside it.
|
|
58
|
+
|
|
59
|
+
Raises:
|
|
60
|
+
TypeError: If the checks can't read the hint.
|
|
61
|
+
"""
|
|
62
|
+
origin = typing.get_origin(hint)
|
|
63
|
+
if hint is type(None):
|
|
64
|
+
return _Kind.NONE, ()
|
|
65
|
+
if origin in (typing.Union, types.UnionType):
|
|
66
|
+
return _Kind.UNION, typing.get_args(hint)
|
|
67
|
+
if hint in _EXACT:
|
|
68
|
+
return _Kind.EXACT, (hint,)
|
|
69
|
+
if hint is float:
|
|
70
|
+
return _Kind.NUMBER, ()
|
|
71
|
+
if origin is frozenset:
|
|
72
|
+
return _Kind.FROZENSET, typing.get_args(hint)
|
|
73
|
+
if isinstance(origin, type) and issubclass(origin, Mapping):
|
|
74
|
+
return _Kind.MAPPING, typing.get_args(hint)
|
|
75
|
+
if origin is not None and getattr(origin, "__name__", "") == "Callable":
|
|
76
|
+
return _Kind.CALLABLE, ()
|
|
77
|
+
cls = origin if isinstance(origin, type) else hint
|
|
78
|
+
if not isinstance(cls, type):
|
|
79
|
+
raise TypeError(f"Can't check a value against {hint!r}")
|
|
80
|
+
if dataclasses.is_dataclass(cls) and cls not in _CHECKED_WHEN_BUILT:
|
|
81
|
+
return _Kind.FIELDS, (cls,)
|
|
82
|
+
return _Kind.INSTANCE, (cls,)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _describe(hint: Any) -> str:
|
|
86
|
+
"""The type a hint asks for, as an error message names it."""
|
|
87
|
+
kind, inner = _kind(hint)
|
|
88
|
+
match kind:
|
|
89
|
+
case _Kind.NONE:
|
|
90
|
+
return "None"
|
|
91
|
+
case _Kind.UNION:
|
|
92
|
+
names = [_describe(part) for part in inner]
|
|
93
|
+
return ", ".join(names[:-1]) + " or " + names[-1]
|
|
94
|
+
case _Kind.NUMBER:
|
|
95
|
+
return "float or int"
|
|
96
|
+
case _Kind.FROZENSET:
|
|
97
|
+
return f"frozenset of {_describe(inner[0])}"
|
|
98
|
+
case _Kind.MAPPING:
|
|
99
|
+
return f"mapping of {_describe(inner[0])} to {_describe(inner[1])}"
|
|
100
|
+
case _Kind.CALLABLE:
|
|
101
|
+
return "callable"
|
|
102
|
+
# A class, exact or not.
|
|
103
|
+
return str(inner[0].__name__)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _test(hint: Any, value: str, env: dict[str, object]) -> str:
|
|
107
|
+
"""Python source that's true when ``value`` matches ``hint``.
|
|
108
|
+
|
|
109
|
+
Names the source needs go into ``env``.
|
|
110
|
+
"""
|
|
111
|
+
kind, inner = _kind(hint)
|
|
112
|
+
match kind:
|
|
113
|
+
case _Kind.NONE:
|
|
114
|
+
return f"{value} is None"
|
|
115
|
+
case _Kind.UNION:
|
|
116
|
+
return "(" + " or ".join(_test(part, value, env) for part in inner) + ")"
|
|
117
|
+
case _Kind.EXACT:
|
|
118
|
+
return f"type({value}) is {inner[0].__name__}"
|
|
119
|
+
case _Kind.NUMBER:
|
|
120
|
+
return f"type({value}) in (float, int)"
|
|
121
|
+
case _Kind.FROZENSET:
|
|
122
|
+
items = f"all({_test(inner[0], '_i', env)} for _i in {value})"
|
|
123
|
+
return f"(type({value}) is frozenset and {items})"
|
|
124
|
+
case _Kind.MAPPING:
|
|
125
|
+
env["Mapping"] = Mapping
|
|
126
|
+
pairs = f"{_test(inner[0], '_k', env)} and {_test(inner[1], '_v', env)}"
|
|
127
|
+
return f"(isinstance({value}, Mapping) and all({pairs} for _k, _v in {value}.items()))"
|
|
128
|
+
case _Kind.CALLABLE:
|
|
129
|
+
return f"callable({value})"
|
|
130
|
+
cls = inner[0]
|
|
131
|
+
name = f"_{cls.__module__.replace('.', '_')}_{cls.__qualname__.replace('.', '_')}"
|
|
132
|
+
env[name] = cls
|
|
133
|
+
if kind is _Kind.FIELDS:
|
|
134
|
+
env[f"{name}_fields"] = _fields(cls)
|
|
135
|
+
return f"(isinstance({value}, {name}) and {name}_fields({value}))"
|
|
136
|
+
return f"isinstance({value}, {name})"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _compile(source: str, env: dict[str, object]) -> Callable[..., Any]:
|
|
140
|
+
"""Run the source of one function named ``check`` and return it."""
|
|
141
|
+
exec(source, env) # noqa: S102, the source is built above from annotations only
|
|
142
|
+
return env["check"] # type: ignore[return-value]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
_FIELDS: dict[type, Callable[[object], bool]] = {}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _fields(cls: type) -> Callable[[object], bool]:
|
|
149
|
+
"""A function that's true when every field of a dataclass instance has its declared type."""
|
|
150
|
+
if cls not in _FIELDS:
|
|
151
|
+
env: dict[str, object] = {}
|
|
152
|
+
hints = typing.get_type_hints(cls)
|
|
153
|
+
tests = [_test(hints[f.name], f"o.{f.name}", env) for f in dataclasses.fields(cls)]
|
|
154
|
+
_FIELDS[cls] = _compile("def check(o):\n return " + " and ".join(tests or ["True"]), env)
|
|
155
|
+
return _FIELDS[cls]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _field_mismatch(cls: type, value: object, prefix: str) -> str | None:
|
|
159
|
+
"""The message for the first field of a dataclass instance that has the wrong type."""
|
|
160
|
+
hints = typing.get_type_hints(cls)
|
|
161
|
+
found = (
|
|
162
|
+
_mismatch(prefix + f.name, hints[f.name], getattr(value, f.name))
|
|
163
|
+
for f in dataclasses.fields(cls)
|
|
164
|
+
)
|
|
165
|
+
return next((message for message in found if message is not None), None)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _inner_mismatch(name: str, hint: Any, value: object) -> str | None:
|
|
169
|
+
"""For a value of the kind ``hint`` holds, the message naming what inside it is wrong."""
|
|
170
|
+
kind, inner = _kind(hint)
|
|
171
|
+
if kind is _Kind.FIELDS and isinstance(value, inner[0]):
|
|
172
|
+
return _field_mismatch(inner[0], value, f"{name}.")
|
|
173
|
+
if kind is _Kind.FROZENSET and type(value) is frozenset:
|
|
174
|
+
bad = next((each for each in value if _mismatch("item", inner[0], each) is not None), None)
|
|
175
|
+
return f"{name} must be {_describe(hint)}, but holds {type(bad).__name__}"
|
|
176
|
+
if kind is _Kind.MAPPING and isinstance(value, Mapping):
|
|
177
|
+
key, item = inner
|
|
178
|
+
found = (
|
|
179
|
+
_mismatch(f"{name}[{k!r}]", item, v) or _mismatch(f"{name} key", key, k)
|
|
180
|
+
for k, v in value.items()
|
|
181
|
+
)
|
|
182
|
+
return next((message for message in found if message is not None), None)
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _mismatch(name: str, hint: Any, value: object) -> str | None:
|
|
187
|
+
"""The message for a value that doesn't match its hint, naming the part of it that's wrong."""
|
|
188
|
+
env: dict[str, object] = {}
|
|
189
|
+
if _compile(f"def check(v):\n return {_test(hint, 'v', env)}", env)(value):
|
|
190
|
+
return None
|
|
191
|
+
kind, inner_hints = _kind(hint)
|
|
192
|
+
parts = inner_hints if kind is _Kind.UNION else (hint,)
|
|
193
|
+
inner = (_inner_mismatch(name, part, value) for part in parts)
|
|
194
|
+
found = next((message for message in inner if message is not None), None)
|
|
195
|
+
return found or f"{name} must be {_describe(hint)}, not {type(value).__name__}"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def check_types(obj: object) -> None:
|
|
199
|
+
"""Raise ``TypeError`` unless every field of a dataclass instance has its declared type.
|
|
200
|
+
|
|
201
|
+
Fields holding a dataclass are checked in turn, unless that class checks
|
|
202
|
+
its own fields when built.
|
|
203
|
+
"""
|
|
204
|
+
if not _fields(type(obj))(obj):
|
|
205
|
+
raise TypeError(_field_mismatch(type(obj), obj, ""))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def checked_when_built(cls: type[_T]) -> type[_T]:
|
|
209
|
+
"""Check a value dataclass's field types every time one is built, before its own checks.
|
|
210
|
+
|
|
211
|
+
The class's own ``__post_init__``, if it has one, runs after the check.
|
|
212
|
+
"""
|
|
213
|
+
original = cls.__dict__.get("__post_init__")
|
|
214
|
+
if original is None:
|
|
215
|
+
# A dataclass calls __post_init__ only if it had one when built.
|
|
216
|
+
init: Callable[..., None] = cls.__init__
|
|
217
|
+
|
|
218
|
+
def __init__(self: object, *args: Any, **kwargs: Any) -> None:
|
|
219
|
+
init(self, *args, **kwargs)
|
|
220
|
+
check_types(self)
|
|
221
|
+
|
|
222
|
+
cls.__init__ = wraps(init)(__init__) # type: ignore[method-assign]
|
|
223
|
+
else:
|
|
224
|
+
|
|
225
|
+
def __post_init__(self: object) -> None:
|
|
226
|
+
check_types(self)
|
|
227
|
+
original(self)
|
|
228
|
+
|
|
229
|
+
cls.__post_init__ = __post_init__ # type: ignore[attr-defined]
|
|
230
|
+
_CHECKED_WHEN_BUILT.add(cls)
|
|
231
|
+
return cls
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
#: Checks one call's positional and keyword arguments.
|
|
235
|
+
_ArgumentCheck = Callable[[tuple[Any, ...], dict[str, Any]], None]
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def argument_check(func: Callable[..., object]) -> _ArgumentCheck:
|
|
239
|
+
"""Build the function that checks a call's arguments against ``func``'s annotations."""
|
|
240
|
+
hints = typing.get_type_hints(func)
|
|
241
|
+
env: dict[str, object] = {"_MISSING": _MISSING, "_fail": _fail}
|
|
242
|
+
lines = ["def check(args, kwargs):", " n = len(args)"]
|
|
243
|
+
for i, param in enumerate(inspect.signature(func).parameters.values()):
|
|
244
|
+
if param.name in ("self", "cls"):
|
|
245
|
+
continue
|
|
246
|
+
if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
|
|
247
|
+
raise TypeError(f"{func.__qualname__} takes *{param.name}, which isn't checked")
|
|
248
|
+
if param.name not in hints:
|
|
249
|
+
raise TypeError(f"{func.__qualname__} takes {param.name} without a type to check")
|
|
250
|
+
env[f"_h_{param.name}"] = hints[param.name]
|
|
251
|
+
if param.kind is param.KEYWORD_ONLY:
|
|
252
|
+
lines.append(f" v = kwargs.get({param.name!r}, _MISSING)")
|
|
253
|
+
else:
|
|
254
|
+
lines.append(f" v = args[{i}] if n > {i} else kwargs.get({param.name!r}, _MISSING)")
|
|
255
|
+
test = _test(hints[param.name], "v", env)
|
|
256
|
+
lines.append(f" if v is not _MISSING and not ({test}):")
|
|
257
|
+
lines.append(f" _fail({param.name!r}, _h_{param.name}, v)")
|
|
258
|
+
return _compile("\n".join(lines), env)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _fail(name: str, hint: Any, value: object) -> typing.NoReturn:
|
|
262
|
+
raise TypeError(_mismatch(name, hint, value))
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def check_argument_types(cls: type[_T]) -> type[_T]:
|
|
266
|
+
"""Check the argument types of every public method and ``__init__`` a class defines.
|
|
267
|
+
|
|
268
|
+
Each check is built from the method's annotations on its first call, so
|
|
269
|
+
an annotation may name a class defined later in the module.
|
|
270
|
+
"""
|
|
271
|
+
for name, func in list(vars(cls).items()):
|
|
272
|
+
if inspect.isfunction(func) and (not name.startswith("_") or name == "__init__"):
|
|
273
|
+
setattr(cls, name, _checking(func))
|
|
274
|
+
return cls
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _checking(func: Callable[..., _T]) -> Callable[..., _T]:
|
|
278
|
+
check: _ArgumentCheck | None = None
|
|
279
|
+
|
|
280
|
+
@wraps(func)
|
|
281
|
+
def wrapper(*args: Any, **kwargs: Any) -> _T:
|
|
282
|
+
nonlocal check
|
|
283
|
+
if check is None:
|
|
284
|
+
check = argument_check(func)
|
|
285
|
+
check(args, kwargs)
|
|
286
|
+
return func(*args, **kwargs)
|
|
287
|
+
|
|
288
|
+
wrapper._checks_arguments = True # type: ignore[attr-defined]
|
|
289
|
+
return wrapper
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def check_text(**values: str | Iterable[str] | None) -> None:
|
|
293
|
+
"""Raise :class:`~calendaring_sync.error.LoneSurrogateError` if a string holds a lone surrogate.
|
|
294
|
+
|
|
295
|
+
The design page's lone surrogates section says why no store can keep
|
|
296
|
+
one; refusing it where the string comes in keeps every store the same.
|
|
297
|
+
|
|
298
|
+
Args:
|
|
299
|
+
values: Each value by its argument's name: a string, strings, or
|
|
300
|
+
``None``.
|
|
301
|
+
"""
|
|
302
|
+
for name, value in values.items():
|
|
303
|
+
if value is None:
|
|
304
|
+
continue
|
|
305
|
+
for text in [value] if isinstance(value, str) else value:
|
|
306
|
+
try:
|
|
307
|
+
text.encode()
|
|
308
|
+
except UnicodeEncodeError as exc:
|
|
309
|
+
raise LoneSurrogateError(
|
|
310
|
+
f"{name} holds a lone surrogate at {exc.start}, which can't be stored"
|
|
311
|
+
) from exc
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def check_data(
|
|
315
|
+
fingerprint: str | None,
|
|
316
|
+
containers: frozenset[str],
|
|
317
|
+
logical_key: str | None,
|
|
318
|
+
**values: str | None,
|
|
319
|
+
) -> None:
|
|
320
|
+
"""Check the strings of a copy of an object with :func:`check_text`.
|
|
321
|
+
|
|
322
|
+
Args:
|
|
323
|
+
fingerprint: The copy's fingerprint.
|
|
324
|
+
containers: The copy's containers.
|
|
325
|
+
logical_key: The copy's logical key.
|
|
326
|
+
values: Any other strings that come with the copy, by name.
|
|
327
|
+
"""
|
|
328
|
+
check_text(fingerprint=fingerprint, containers=containers, logical_key=logical_key, **values)
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 calendaring-sync contributors
|
|
2
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
"""How a remote change meets a local edit, worked out from the three sides alone."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
from typing import TypeAlias
|
|
10
|
+
|
|
11
|
+
from calendaring_sync.objects._data import REMOTE, data
|
|
12
|
+
from calendaring_sync.objects.change import Changed, Removed
|
|
13
|
+
from calendaring_sync.objects.conflict import Conflict, ConflictKind
|
|
14
|
+
from calendaring_sync.objects.edit import EditKind, LocalEdit
|
|
15
|
+
from calendaring_sync.objects.record import Record
|
|
16
|
+
|
|
17
|
+
#: A copy of an object: the synced copy, a server's change, or a local edit.
|
|
18
|
+
Copy: TypeAlias = Record | Changed | LocalEdit
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ChangeClass(StrEnum):
|
|
22
|
+
"""What an :term:`ingest` does with one object."""
|
|
23
|
+
|
|
24
|
+
#: Nothing to do: no change, a version-only change, or both sides
|
|
25
|
+
#: arrived at the same content.
|
|
26
|
+
UNCHANGED = "unchanged"
|
|
27
|
+
#: The server changed or created the object, with no local edit.
|
|
28
|
+
REMOTE_ONLY = "remote_only"
|
|
29
|
+
#: There's a local edit, and the server didn't change the object.
|
|
30
|
+
LOCAL_ONLY = "local_only"
|
|
31
|
+
#: The server removed the object with no local edit, or both sides
|
|
32
|
+
#: deleted it.
|
|
33
|
+
DELETED_REMOTE = "deleted_remote"
|
|
34
|
+
#: The object was deleted locally, and the server didn't change it.
|
|
35
|
+
DELETED_LOCAL = "deleted_local"
|
|
36
|
+
#: Both sides acted on the object.
|
|
37
|
+
CONFLICT = "conflict"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _same(a: tuple[object, ...], b: tuple[object, ...]) -> bool:
|
|
41
|
+
"""Whether two copies' data match.
|
|
42
|
+
|
|
43
|
+
Fingerprints decide when both copies have one; after a fingerprint
|
|
44
|
+
scheme change one of them has none, and the content is compared instead.
|
|
45
|
+
"""
|
|
46
|
+
(fingerprint_a, content_a, *rest_a), (fingerprint_b, content_b, *rest_b) = a, b
|
|
47
|
+
if fingerprint_a is None or fingerprint_b is None:
|
|
48
|
+
same_content = content_a == content_b
|
|
49
|
+
else:
|
|
50
|
+
same_content = fingerprint_a == fingerprint_b
|
|
51
|
+
return same_content and rest_a == rest_b
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def same_data(a: Copy, b: Copy) -> bool:
|
|
55
|
+
"""Whether two copies of an object hold the same data."""
|
|
56
|
+
return _same(data(a), data(b))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def same_remote(conflict: Conflict, change: Changed | Removed) -> bool:
|
|
60
|
+
"""Whether the server reports again what an open conflict already holds."""
|
|
61
|
+
if conflict.remote_content is None or isinstance(change, Removed):
|
|
62
|
+
return conflict.remote_content is None and isinstance(change, Removed)
|
|
63
|
+
return _same(data(conflict, REMOTE), data(change))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def same_conflict(a: Conflict, b: Conflict) -> bool:
|
|
67
|
+
"""Whether two copies of a conflict say the same thing, whatever their versions."""
|
|
68
|
+
if (a.kind, a.holder) != (b.kind, b.holder):
|
|
69
|
+
return False
|
|
70
|
+
return _same(data(a, REMOTE), data(b, REMOTE))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def classify(
|
|
74
|
+
synced: Record | None,
|
|
75
|
+
remote: Changed | Removed | None,
|
|
76
|
+
local: LocalEdit | None,
|
|
77
|
+
) -> tuple[ChangeClass, ConflictKind | None]:
|
|
78
|
+
"""Classify one object from its synced copy, the server's report and the local edit.
|
|
79
|
+
|
|
80
|
+
Each case below is one kind of local edit meeting one kind of report
|
|
81
|
+
from the server. A change that holds the synced data counts as no
|
|
82
|
+
change, and one that holds the edit's data means both sides arrived at
|
|
83
|
+
the same object.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
synced: The record's :term:`synced copy`, ``None`` for an object
|
|
87
|
+
the store doesn't hold, one it holds as removed, or a create.
|
|
88
|
+
remote: The server's new copy, ``Removed`` if the server removed it,
|
|
89
|
+
or ``None`` if the server reported nothing new.
|
|
90
|
+
local: The record's :term:`pending edit`, or ``None``.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
The class, and the conflict's kind when the class is ``CONFLICT``.
|
|
94
|
+
|
|
95
|
+
Raises:
|
|
96
|
+
ValueError: If no object could have these sides: nothing at all,
|
|
97
|
+
a create of an object the server has, or a change or delete of
|
|
98
|
+
one it doesn't.
|
|
99
|
+
"""
|
|
100
|
+
if synced is None and remote is None and local is None:
|
|
101
|
+
raise ValueError("Nothing to classify: no synced copy, remote change or local edit")
|
|
102
|
+
if local is not None and (local.kind is EditKind.CREATE) != (synced is None):
|
|
103
|
+
has = "without" if synced is None else "with"
|
|
104
|
+
raise ValueError(f"A {local.kind} edit can't meet an object {has} a synced copy")
|
|
105
|
+
kept = isinstance(remote, Changed) and synced is not None and same_data(remote, synced)
|
|
106
|
+
match local and local.kind, remote:
|
|
107
|
+
case None, None:
|
|
108
|
+
return ChangeClass.UNCHANGED, None
|
|
109
|
+
case None, Changed() if kept:
|
|
110
|
+
return ChangeClass.UNCHANGED, None
|
|
111
|
+
case None, Changed():
|
|
112
|
+
return ChangeClass.REMOTE_ONLY, None
|
|
113
|
+
case None, Removed():
|
|
114
|
+
# Removing an object the store doesn't hold changes nothing.
|
|
115
|
+
return (ChangeClass.UNCHANGED if synced is None else ChangeClass.DELETED_REMOTE), None
|
|
116
|
+
case EditKind.CHANGE | EditKind.CREATE, Changed() if local and same_data(remote, local):
|
|
117
|
+
return ChangeClass.UNCHANGED, None
|
|
118
|
+
case EditKind.CHANGE, None | Changed() if remote is None or kept:
|
|
119
|
+
return ChangeClass.LOCAL_ONLY, None
|
|
120
|
+
case EditKind.DELETE, None | Changed() if remote is None or kept:
|
|
121
|
+
return ChangeClass.DELETED_LOCAL, None
|
|
122
|
+
case EditKind.CHANGE, Changed():
|
|
123
|
+
return ChangeClass.CONFLICT, ConflictKind.BOTH_CHANGED
|
|
124
|
+
case EditKind.CHANGE, Removed():
|
|
125
|
+
return ChangeClass.CONFLICT, ConflictKind.REMOVED_REMOTELY
|
|
126
|
+
case EditKind.DELETE, Changed():
|
|
127
|
+
return ChangeClass.CONFLICT, ConflictKind.DELETED_LOCALLY
|
|
128
|
+
case EditKind.DELETE, Removed():
|
|
129
|
+
# Both sides deleted the object.
|
|
130
|
+
return ChangeClass.DELETED_REMOTE, None
|
|
131
|
+
case EditKind.CREATE, Changed():
|
|
132
|
+
return ChangeClass.CONFLICT, ConflictKind.BOTH_CREATED
|
|
133
|
+
case _:
|
|
134
|
+
# A create the server has nothing at, or nothing anymore.
|
|
135
|
+
return ChangeClass.LOCAL_ONLY, None
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.1.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 1, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 calendaring-sync contributors
|
|
2
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
"""The adapter base classes, and the adapters that ship with calendaring-sync.
|
|
5
|
+
|
|
6
|
+
Each shipped adapter is a module of its own that needs the extra of the
|
|
7
|
+
same name. Importing this package imports no protocol's client library;
|
|
8
|
+
import the adapter's module, such as :mod:`calendaring_sync.adapters.caldav`,
|
|
9
|
+
to use it.
|
|
10
|
+
"""
|