datadouble 0.0.3__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.
datadouble/channels.py ADDED
@@ -0,0 +1,62 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Channels: named, movable pointers to an image's generations.
5
+
6
+ A channel lives in a store next to the images it points at, as
7
+ ``<spec>/<group>/<engine>-<version>/channels/<name>.json``. ``promote``
8
+ advances one in the export store, ``fetch`` one in staging, and ``activate``
9
+ moves one back. Each channel keeps the generations it pointed at before, newest
10
+ first, so a rollback knows where it came from.
11
+ """
12
+
13
+ import datetime as dt
14
+ from collections.abc import Callable
15
+
16
+ from pydantic import AwareDatetime, BaseModel, ConfigDict
17
+
18
+ from datadouble.names import Generation, check_name
19
+ from datadouble.storage import Store
20
+
21
+ _HISTORY = 20
22
+
23
+
24
+ class Channel(BaseModel):
25
+ """Where a channel points, and where it pointed before."""
26
+
27
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
28
+
29
+ name: str
30
+ generation: Generation
31
+ updated_at: AwareDatetime
32
+ previous: tuple[Generation, ...] = ()
33
+
34
+
35
+ def channel_key(prefix: str, name: str) -> str:
36
+ """The store key of a channel under an image line's prefix."""
37
+ return f"{prefix}/channels/{check_name('channel', name)}.json"
38
+
39
+
40
+ def read_channel(store: Store, prefix: str, name: str) -> Channel | None:
41
+ """A channel, or None if it has never been set."""
42
+ data = store.get_bytes(channel_key(prefix, name))
43
+ return None if data is None else Channel.model_validate_json(data)
44
+
45
+
46
+ def point_channel(
47
+ store: Store,
48
+ prefix: str,
49
+ name: str,
50
+ generation: Generation,
51
+ clock: Callable[[], dt.datetime] = lambda: dt.datetime.now(tz=dt.UTC),
52
+ ) -> Channel:
53
+ """Point a channel at ``generation``, remembering where it pointed before."""
54
+ current = read_channel(store, prefix, name)
55
+ previous: tuple[Generation, ...] = ()
56
+ if current is not None and current.generation != generation:
57
+ previous = (current.generation, *current.previous)[:_HISTORY]
58
+ elif current is not None:
59
+ previous = current.previous
60
+ channel = Channel(name=name, generation=generation, updated_at=clock(), previous=previous)
61
+ store.put_bytes(channel_key(prefix, name), channel.model_dump_json(indent=2).encode())
62
+ return channel