clusterio 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.
clusterio/__init__.py ADDED
@@ -0,0 +1,75 @@
1
+ """Build distributed applications with the Python you know.
2
+
3
+ import clusterio
4
+
5
+ users = clusterio.dict("users")
6
+ users["ada"] = {"lang": "python"}
7
+
8
+ The module functions use a cluster made from ``CLUSTERIO_NODE``,
9
+ ``CLUSTERIO_PEERS`` and ``CLUSTERIO_DATA`` on first use. A ``Cluster`` has
10
+ the same methods, for choosing the configuration in code.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import builtins
16
+ from collections.abc import Callable
17
+ from typing import ParamSpec, TypeVar
18
+
19
+ from .cluster import Cluster, Unavailable, default, now
20
+ from .data import Dict, File, List, Lock, Transaction, open_file
21
+
22
+ __all__ = [
23
+ "Cluster",
24
+ "Dict",
25
+ "List",
26
+ "Lock",
27
+ "Transaction",
28
+ "Unavailable",
29
+ "dict",
30
+ "list",
31
+ "listdir",
32
+ "lock",
33
+ "now",
34
+ "open",
35
+ "remove",
36
+ "transaction",
37
+ ]
38
+
39
+ P = ParamSpec("P")
40
+ R = TypeVar("R")
41
+
42
+
43
+ def dict(name: str) -> Dict:
44
+ """The dict called ``name``, shared by the cluster."""
45
+ return Dict(default, name)
46
+
47
+
48
+ def list(name: str) -> List:
49
+ """The list called ``name``, shared by the cluster."""
50
+ return List(default, name)
51
+
52
+
53
+ def open(path: str, mode: str = "r", encoding: str | None = None) -> File:
54
+ """Open the file at ``path``, shared by the cluster. Modes: r, w, a, each with or without b."""
55
+ return open_file(default, path, mode, encoding)
56
+
57
+
58
+ def listdir(path: str = "") -> builtins.list[str]:
59
+ """The names in the directory ``path``, as ``os.listdir``."""
60
+ return default().listdir(path)
61
+
62
+
63
+ def remove(path: str) -> None:
64
+ """Remove the file at ``path``, as ``os.remove``."""
65
+ default().remove(path)
66
+
67
+
68
+ def transaction(fn: Callable[P, R]) -> Transaction[P, R]:
69
+ """Make ``fn`` run atomically on every node, in log order. See ``Transaction``."""
70
+ return Transaction(fn, default)
71
+
72
+
73
+ def lock(name: str, ttl: float = 10.0) -> Lock:
74
+ """The lock called ``name``, held for ``ttl`` seconds unless renewed. See ``Lock``."""
75
+ return Lock(default, name, ttl)
clusterio/cli.py ADDED
@@ -0,0 +1,62 @@
1
+ """``clusterio run [APP]``: start a node, then run an app on it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import importlib
7
+ import importlib.util
8
+ import os
9
+ import sys
10
+ import threading
11
+ from collections.abc import Callable, Sequence
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from . import cluster
16
+
17
+
18
+ def load(app: str) -> Callable[[], Any]:
19
+ """``module:function`` or ``path/to/file.py:function``; the function defaults to ``main``."""
20
+ target, _, name = app.partition(":")
21
+ if target.endswith(".py"):
22
+ path = Path(target).resolve()
23
+ sys.path.insert(0, str(path.parent))
24
+ target = path.stem
25
+ else:
26
+ sys.path.insert(0, os.getcwd())
27
+ module = importlib.import_module(target)
28
+ fn = getattr(module, name or "main", None)
29
+ if not callable(fn):
30
+ raise SystemExit(f"clusterio: {target} has no function {name or 'main'!r}")
31
+ return fn # type: ignore[no-any-return]
32
+
33
+
34
+ def main(argv: Sequence[str] | None = None) -> int:
35
+ parser = argparse.ArgumentParser(prog="clusterio", description="Run clusterio nodes and apps.")
36
+ commands = parser.add_subparsers(dest="command", required=True)
37
+ run = commands.add_parser("run", help="start a node, then call APP's function on it")
38
+ run.add_argument("app", nargs="?", help="module:function or file.py:function (default function: main)")
39
+ run.add_argument("--node", help="this node's name (CLUSTERIO_NODE)")
40
+ run.add_argument("--peers", help="every node: a=host:port,b=host:port (CLUSTERIO_PEERS)")
41
+ run.add_argument("--data", help="directory for this node's database (CLUSTERIO_DATA)")
42
+ args = parser.parse_args(argv)
43
+
44
+ for option, variable in (("node", "CLUSTERIO_NODE"), ("peers", "CLUSTERIO_PEERS"), ("data", "CLUSTERIO_DATA")):
45
+ if getattr(args, option):
46
+ os.environ[variable] = getattr(args, option)
47
+ node = cluster.default()
48
+ print(f"clusterio: node {node.node} of {','.join(sorted(node.peers))}, data in {node.data}", file=sys.stderr)
49
+ try:
50
+ if args.app:
51
+ result = load(args.app)()
52
+ return result if isinstance(result, int) else 0
53
+ threading.Event().wait()
54
+ except KeyboardInterrupt:
55
+ pass
56
+ finally:
57
+ node.close()
58
+ return 0
59
+
60
+
61
+ if __name__ == "__main__":
62
+ sys.exit(main())
clusterio/cluster.py ADDED
@@ -0,0 +1,271 @@
1
+ """A Cluster: this process's node, run on a background thread, and the API on it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import builtins
7
+ import concurrent.futures
8
+ import itertools
9
+ import logging
10
+ import os
11
+ import secrets
12
+ import sqlite3
13
+ import threading
14
+ import time
15
+ from collections.abc import Callable, Mapping
16
+ from pathlib import Path
17
+ from typing import Any, ParamSpec, TypeVar
18
+
19
+ from . import store
20
+ from .data import Dict, File, List, Lock, Transaction, open_file
21
+ from .net import Transport
22
+ from .raft import Node
23
+ from .store import Store, dumps
24
+
25
+ log = logging.getLogger("clusterio")
26
+
27
+ P = ParamSpec("P")
28
+ R = TypeVar("R")
29
+
30
+ TICK = 0.01
31
+ RETRY = 0.5
32
+
33
+
34
+ class Unavailable(TimeoutError):
35
+ """A write was not applied in time: no majority could be reached. It may still be applied later."""
36
+
37
+
38
+ def parse_peers(text: str) -> dict[str, str]:
39
+ """``a=10.0.0.1:7000,b=10.0.0.2:7000`` as a dict."""
40
+ peers = {}
41
+ for item in text.split(","):
42
+ name, sep, address = item.strip().partition("=")
43
+ if not sep or not name or not address:
44
+ raise ValueError(f"CLUSTERIO_PEERS: expected name=host:port, got {item!r}")
45
+ peers[name] = address
46
+ return peers
47
+
48
+
49
+ class Cluster:
50
+ """This process's node of a cluster.
51
+
52
+ An argument left out falls back to ``CLUSTERIO_NODE``, ``CLUSTERIO_PEERS``
53
+ and ``CLUSTERIO_DATA``; with none, the cluster is this node alone.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ node: str | None = None,
59
+ peers: Mapping[str, str] | None = None,
60
+ data: str | os.PathLike[str] | None = None,
61
+ timeout: float = 5.0,
62
+ ):
63
+ self.node = node or os.environ.get("CLUSTERIO_NODE") or "local"
64
+ env_peers = os.environ.get("CLUSTERIO_PEERS")
65
+ self.peers = dict(peers) if peers is not None else parse_peers(env_peers) if env_peers else {self.node: ""}
66
+ if self.node not in self.peers:
67
+ raise ValueError(f"node {self.node!r} is not one of the peers {sorted(self.peers)}")
68
+ self.data = Path(data or os.environ.get("CLUSTERIO_DATA") or Path(".clusterio") / self.node)
69
+ self.timeout = timeout
70
+ self.data.mkdir(parents=True, exist_ok=True)
71
+ self.path = str(self.data / "clusterio.db")
72
+
73
+ self._boot = secrets.token_hex(6)
74
+ self._seq = itertools.count()
75
+ # Writes not applied yet: entry, future, when to send again, and the term this node appended it in as leader.
76
+ self._pending: dict[str, tuple[str, concurrent.futures.Future[Any], float, int | None]] = {}
77
+ self._readers = threading.local()
78
+ self._halted = False
79
+ self._loop = asyncio.new_event_loop()
80
+ self._started: concurrent.futures.Future[None] = concurrent.futures.Future()
81
+ self._thread = threading.Thread(target=self._run, name=f"clusterio-{self.node}", daemon=True)
82
+ self._thread.start()
83
+ self._started.result()
84
+
85
+ # The API.
86
+
87
+ def dict(self, name: str) -> Dict:
88
+ return Dict(self._self, name)
89
+
90
+ def list(self, name: str) -> List:
91
+ return List(self._self, name)
92
+
93
+ def open(self, path: str, mode: str = "r", encoding: str | None = None) -> File:
94
+ return open_file(self._self, path, mode, encoding)
95
+
96
+ def listdir(self, path: str = "") -> builtins.list[str]:
97
+ return self.read(store.file_names, path)
98
+
99
+ def remove(self, path: str) -> None:
100
+ self.write("file_remove", path)
101
+
102
+ def transaction(self, fn: Callable[P, R]) -> Transaction[P, R]:
103
+ return Transaction(fn, self._self)
104
+
105
+ def lock(self, name: str, ttl: float = 10.0) -> Lock:
106
+ return Lock(self._self, name, ttl)
107
+
108
+ def now(self) -> float:
109
+ return now()
110
+
111
+ def _self(self) -> Cluster:
112
+ return self
113
+
114
+ @property
115
+ def leader(self) -> str | None:
116
+ """The node this node follows, or None during an election."""
117
+ return self.raft.leader
118
+
119
+ def close(self) -> None:
120
+ if self._loop.is_running():
121
+ self._loop.call_soon_threadsafe(self._farewell)
122
+ self._loop.call_soon_threadsafe(self._loop.stop)
123
+ self._thread.join()
124
+
125
+ def __enter__(self) -> Cluster:
126
+ return self
127
+
128
+ def __exit__(self, *exc: object) -> None:
129
+ self.close()
130
+
131
+ def __repr__(self) -> str:
132
+ return f"<Cluster node={self.node!r} peers={sorted(self.peers)} data={str(self.data)!r}>"
133
+
134
+ # Reads and writes, for Dict, List and File.
135
+
136
+ def read(self, query: Callable[..., Any], *args: Any) -> Any:
137
+ """Run a read query on this node's copy, or on the transaction being applied."""
138
+ current = store.applying()
139
+ if current is not None:
140
+ return query(current[0], *args)
141
+ conn = getattr(self._readers, "conn", None)
142
+ if conn is None:
143
+ conn = self._readers.conn = store.connect(self.path, readonly=True)
144
+ return query(conn, *args)
145
+
146
+ def write(self, op: str, *args: Any) -> Any:
147
+ """Append an operation to the log and wait until this node applies it."""
148
+ current = store.applying()
149
+ if current is not None:
150
+ return store.OPS[op](current[0], *args)
151
+ if self._halted:
152
+ raise RuntimeError("this node stopped applying the log; see its log for why")
153
+ rid = f"{self.node}:{self._boot}:{next(self._seq)}"
154
+ entry = dumps({"id": rid, "now": time.time(), "op": [op, *args]})
155
+ future: concurrent.futures.Future[Any] = concurrent.futures.Future()
156
+ self._loop.call_soon_threadsafe(self._submit, rid, entry, future)
157
+ try:
158
+ applied: store.Applied = future.result(self.timeout)
159
+ except concurrent.futures.TimeoutError:
160
+ self._loop.call_soon_threadsafe(self._pending.pop, rid, None)
161
+ raise Unavailable(f"write not applied within {self.timeout}s; leader: {self.raft.leader}") from None
162
+ if applied.error:
163
+ store.raise_error(applied.error)
164
+ return applied.value
165
+
166
+ # The node's thread.
167
+
168
+ def _run(self) -> None:
169
+ asyncio.set_event_loop(self._loop)
170
+ try:
171
+ self.store = Store(self.path)
172
+ self.raft = Node(self.node, sorted(self.peers), self.store)
173
+ self.transport: Transport | None = None
174
+ if len(self.peers) > 1:
175
+ self.transport = Transport(self.node, self.peers, self._deliver)
176
+ self._loop.run_until_complete(self.transport.start())
177
+ self._send(self.raft.start(time.monotonic()))
178
+ self._apply()
179
+ ticker = self._loop.create_task(self._tick())
180
+ except BaseException as e:
181
+ self._started.set_exception(e)
182
+ return
183
+ self._started.set_result(None)
184
+ try:
185
+ self._loop.run_forever()
186
+ finally:
187
+ ticker.cancel()
188
+ if self.transport:
189
+ self._loop.run_until_complete(self.transport.stop())
190
+ self._loop.run_until_complete(self._loop.shutdown_asyncgens())
191
+ self._loop.close()
192
+ self.store.close()
193
+
194
+ async def _tick(self) -> None:
195
+ while True:
196
+ await asyncio.sleep(TICK)
197
+ now = time.monotonic()
198
+ self._send(self.raft.tick(now))
199
+ for rid, (entry, future, due, appended) in list(self._pending.items()):
200
+ if future.done():
201
+ del self._pending[rid]
202
+ elif now >= due and not (self.raft.role == "leader" and appended == self.raft.term):
203
+ self._forward(rid, entry, future)
204
+ self._apply()
205
+
206
+ def _farewell(self) -> None:
207
+ """A leader that leaves tells every peer how far the log is committed."""
208
+ if self.raft.role == "leader":
209
+ self.raft.waiting.clear()
210
+ self._send(self.raft.replicate())
211
+
212
+ def _deliver(self, message: builtins.dict[str, Any]) -> None:
213
+ if message["type"] == "forward":
214
+ if self.raft.propose([message["entry"]]):
215
+ self._send(self.raft.replicate())
216
+ else:
217
+ self._send(self.raft.receive(message))
218
+ self._apply()
219
+
220
+ def _submit(self, rid: str, entry: str, future: concurrent.futures.Future[Any]) -> None:
221
+ self._forward(rid, entry, future)
222
+ self._apply()
223
+
224
+ def _forward(self, rid: str, entry: str, future: concurrent.futures.Future[Any]) -> None:
225
+ """Send an entry to the leader, or append it if this node leads; try again after RETRY."""
226
+ appended = self.raft.propose([entry])
227
+ self._pending[rid] = (entry, future, time.monotonic() + RETRY, self.raft.term if appended else None)
228
+ if appended:
229
+ self._send(self.raft.replicate())
230
+ elif self.raft.leader and self.transport:
231
+ self.transport.send({"type": "forward", "term": self.raft.term, "dest": self.raft.leader, "entry": entry})
232
+
233
+ def _send(self, messages: builtins.list[builtins.dict[str, Any]]) -> None:
234
+ if self.transport:
235
+ for m in messages:
236
+ self.transport.send(m)
237
+
238
+ def _apply(self) -> None:
239
+ entries = self.raft.committed()
240
+ if not entries or self._halted:
241
+ return
242
+ try:
243
+ results = self.store.apply(self.raft.applied + 1, entries)
244
+ except (store.Missing, sqlite3.Error):
245
+ log.exception("node %s stopped applying the log at index %d", self.node, self.raft.applied + 1)
246
+ self._halted = True
247
+ return
248
+ self.raft.applied += len(entries)
249
+ for result in results:
250
+ pending = self._pending.pop(result.id, None) if result.id else None
251
+ if pending:
252
+ pending[1].set_result(result)
253
+
254
+
255
+ _default: Cluster | None = None
256
+ _default_lock = threading.Lock()
257
+
258
+
259
+ def default() -> Cluster:
260
+ """The cluster the module functions use, made from the environment on first use."""
261
+ global _default
262
+ with _default_lock:
263
+ if _default is None:
264
+ _default = Cluster()
265
+ return _default
266
+
267
+
268
+ def now() -> float:
269
+ """The time: inside a transaction, the time its entry was made, the same on every node."""
270
+ current = store.applying()
271
+ return current[1] if current is not None else time.time()