nabedra 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.
nabedra/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """Nabedra Database public types, errors, table handles and query builders."""
2
+ from .errors import (
3
+ AuthenticationError,
4
+ ConflictError,
5
+ LimitExceededError,
6
+ NabedraError,
7
+ NotFoundError,
8
+ OverloadedError,
9
+ ProtocolError,
10
+ StorageError,
11
+ TransportError,
12
+ UnknownOutcomeError,
13
+ ValidationError,
14
+ )
15
+ from .validation import Key, Row, Scalar, Schema
16
+ from .expr import Expr, col
17
+ from .query import Query
18
+ from .table import Table
19
+ from .client import Database, DB, RequestReceipt
20
+ from .cluster import Cluster
21
+
22
+ __all__ = [
23
+ "Scalar", "Key", "Row", "Schema",
24
+ "Database", "DB", "RequestReceipt", "Cluster", "Expr", "col", "Query", "Table",
25
+ "NabedraError", "ValidationError", "AuthenticationError", "NotFoundError",
26
+ "ConflictError", "LimitExceededError", "OverloadedError", "StorageError",
27
+ "TransportError", "ProtocolError", "UnknownOutcomeError",
28
+ ]
29
+
30
+ from .serve import serve
31
+ from .providers import KubernetesProvider, ProviderError
32
+ __all__ += ["serve", "KubernetesProvider", "ProviderError"]
33
+
34
+ from .aws import AwsCredentials
35
+ from .gateway import Gateway, GatewayContext, HTTPResponse, S3
36
+ __all__ += ["AwsCredentials", "Gateway", "GatewayContext", "HTTPResponse", "S3"]
nabedra/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ """Run the Nabedra command line interface with python -m nabedra."""
2
+ from .cli import main
3
+
4
+ raise SystemExit(main())
nabedra/_binary.py ADDED
@@ -0,0 +1,56 @@
1
+ """Private, on-demand resolution of the installed Rust executable."""
2
+ import os
3
+ from pathlib import Path
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+
10
+ CLI_VERSION = '0.1.0'
11
+ CONFIG_VERSION = 2
12
+ PROTOCOL_VERSION = 1
13
+ BINARY_FAILURE = (
14
+ 'Cannot launch compatible nabedra-database-server. Set NABEDRA_SERVER_BINARY to an '
15
+ 'executable file path or put nabedra-database-server on PATH.'
16
+ )
17
+
18
+
19
+ def binary_version(path):
20
+ # File-backed output avoids allocating unlimited diagnostics from a bad binary.
21
+ try:
22
+ with tempfile.TemporaryFile() as output:
23
+ result = subprocess.run([path, '--version'], stdin=subprocess.DEVNULL,
24
+ stdout=output, stderr=subprocess.DEVNULL, timeout=5)
25
+ output.seek(0)
26
+ data = output.read(257)
27
+ match = re.fullmatch(rb'nabedra-database-server (0\.1\.\d+)\s*', data)
28
+ if result.returncode == 0 and match:
29
+ return match[1].decode('ascii')
30
+ except (OSError, ValueError, subprocess.TimeoutExpired):
31
+ pass
32
+ raise RuntimeError(BINARY_FAILURE) from None
33
+
34
+
35
+ def resolve_server_binary(*, check=False):
36
+ """Explicit overrides are errors; search the active environment before PATH.
37
+
38
+ Launchers set check=True to probe compatibility. Resolution alone remains
39
+ inert for callers that only need to inspect the executable path.
40
+ """
41
+ explicit = 'NABEDRA_SERVER_BINARY' in os.environ
42
+ candidates = [os.environ['NABEDRA_SERVER_BINARY']] if explicit else [
43
+ str(Path(sys.prefix) / 'bin' / 'nabedra-database-server'), shutil.which('nabedra-database-server')]
44
+ for candidate in candidates:
45
+ if candidate:
46
+ path = os.path.abspath(candidate)
47
+ try:
48
+ if os.path.isfile(path) and os.access(path, os.X_OK):
49
+ if check:
50
+ binary_version(path)
51
+ return path
52
+ except (OSError, ValueError, RuntimeError):
53
+ pass
54
+ if explicit:
55
+ break
56
+ raise RuntimeError(BINARY_FAILURE) from None
@@ -0,0 +1,233 @@
1
+ """Private bounded single-request HTTP ingress around the reviewed callback pool."""
2
+ from __future__ import annotations
3
+
4
+ from collections import deque
5
+ import hmac
6
+ import re
7
+ import socket
8
+ import threading
9
+ import time
10
+
11
+ from ._callback_pool import _CallbackPool
12
+ from ._callback_protocol import (
13
+ _CallbackProtocolError, _MAX_BODY, _MAX_HEADERS, _bounded_json, _decode_command,
14
+ )
15
+
16
+ _IO_TIMEOUT = 2.0
17
+
18
+
19
+ def _close_socket(peer):
20
+ try:
21
+ peer.shutdown(socket.SHUT_RDWR)
22
+ except OSError:
23
+ pass
24
+ peer.close()
25
+
26
+
27
+ def _budget(peer, deadline):
28
+ remaining = deadline - time.monotonic()
29
+ if remaining <= 0:
30
+ raise TimeoutError
31
+ peer.settimeout(remaining)
32
+
33
+
34
+ def _reject(code='invalid_command'):
35
+ raise _CallbackProtocolError(code)
36
+
37
+
38
+ class _CallbackBridge:
39
+ """Own one port-zero listener, eight handlers and one _CallbackPool.
40
+
41
+ Inputs are already validated callbacks and independent lifetime tokens.
42
+ url is the actual startup callback address. activate takes prepared, validated
43
+ cluster/authority bindings. stop_admission is terminal and does no joins.
44
+ close joins ingress for <=1s total then calls pool.close exactly once, whose
45
+ callback joins total <=2s. alive covers all original threads after any close.
46
+ The future process guard must retain this owner while alive is true.
47
+ """
48
+
49
+ def __init__(self, callbacks, callback_token, authorize_token, *, _register_owner=None):
50
+ self.__callback_token = ('Bearer ' + callback_token).encode('ascii')
51
+ self._condition = threading.Condition()
52
+ self._stopping = False
53
+ self._pending = deque()
54
+ self._sockets = set()
55
+ self._threads = []
56
+ self._pool = None
57
+ self._listener = None
58
+ if _register_owner is not None:
59
+ _register_owner(self)
60
+ failed = False
61
+ try:
62
+ self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
63
+ self._listener.bind(('127.0.0.1', 0))
64
+ self._listener.listen(8)
65
+ self._listener.settimeout(.1)
66
+ port = self._listener.getsockname()[1]
67
+ self._host = f'127.0.0.1:{port}'.encode('ascii')
68
+ self.url = f'http://127.0.0.1:{port}/private/v1/callback'
69
+ _CallbackPool(callbacks, authorize_token, _register_owner=self._retain_pool)
70
+ for index in range(8):
71
+ self._start(self._run, f'nabedra-callback-http-{index}')
72
+ self._start(self._accept, 'nabedra-callback-accept')
73
+ except BaseException:
74
+ failed = True
75
+ if failed:
76
+ self.close()
77
+ # Outside the exception handler: no raw OS/secret exception context.
78
+ raise RuntimeError('Callback bridge startup failed') from None
79
+
80
+ def _retain_pool(self, pool):
81
+ # Retain before startup: a raising constructor never returns its owner.
82
+ self._pool = pool
83
+
84
+ def _start(self, target, name):
85
+ thread = threading.Thread(target=target, name=name, daemon=True)
86
+ self._threads.append(thread)
87
+ thread.start()
88
+
89
+ @property
90
+ def alive(self):
91
+ return (any(thread.is_alive() for thread in self._threads) or
92
+ (self._pool is not None and self._pool.alive))
93
+
94
+ def activate(self, cluster_id, authorize_url):
95
+ self._pool.activate(cluster_id, authorize_url)
96
+
97
+ def stop_admission(self):
98
+ if self._pool is not None:
99
+ self._pool.stop_admission()
100
+ with self._condition:
101
+ self._stopping = True
102
+ if self._listener is not None:
103
+ _close_socket(self._listener)
104
+ for peer in self._sockets:
105
+ _close_socket(peer)
106
+ self._sockets.clear()
107
+ self._pending.clear()
108
+ self._condition.notify_all()
109
+
110
+ def close(self):
111
+ self.stop_admission()
112
+ deadline = time.monotonic() + 1.0
113
+ try:
114
+ for thread in self._threads:
115
+ if thread.ident is not None and thread is not threading.current_thread():
116
+ thread.join(max(0, deadline-time.monotonic()))
117
+ finally:
118
+ if self._pool is not None:
119
+ self._pool.close()
120
+
121
+ def _accept(self):
122
+ while True:
123
+ try:
124
+ peer, address = self._listener.accept()
125
+ deadline = time.monotonic() + _IO_TIMEOUT
126
+ except socket.timeout:
127
+ continue
128
+ except OSError:
129
+ return
130
+ with self._condition:
131
+ if self._stopping or address[0] != '127.0.0.1' or len(self._pending) == 8:
132
+ _close_socket(peer)
133
+ else:
134
+ self._sockets.add(peer)
135
+ self._pending.append((peer, deadline))
136
+ self._condition.notify()
137
+ if self._stopping:
138
+ return
139
+
140
+ def _run(self):
141
+ while True:
142
+ with self._condition:
143
+ while not self._pending and not self._stopping:
144
+ self._condition.wait()
145
+ if self._stopping:
146
+ return
147
+ peer, deadline = self._pending.popleft()
148
+ try:
149
+ self._handle(peer, deadline)
150
+ except (OSError, ValueError):
151
+ # Lost sockets never cancel an entered pool call.
152
+ pass
153
+ finally:
154
+ with self._condition:
155
+ self._sockets.discard(peer)
156
+ _close_socket(peer)
157
+
158
+ def _headers(self, peer, deadline):
159
+ received = bytearray()
160
+ while b'\r\n\r\n' not in received:
161
+ if len(received) == _MAX_HEADERS:
162
+ _reject('limit_exceeded')
163
+ _budget(peer, deadline)
164
+ # Do not consume even a coalesced body before credential comparison.
165
+ chunk = peer.recv(1)
166
+ if not chunk:
167
+ _reject()
168
+ received.extend(chunk)
169
+ head, initial = bytes(received).split(b'\r\n\r\n', 1)
170
+ lines = head.split(b'\r\n')
171
+ if lines[0] != b'POST /private/v1/callback HTTP/1.1':
172
+ _reject()
173
+ headers = {}
174
+ for line in lines[1:]:
175
+ key, colon, value = line.partition(b':')
176
+ if (not colon or re.fullmatch(rb"[!#$%&'*+.^_`|~0-9A-Za-z-]+", key) is None or
177
+ any(c < 32 and c != 9 or c == 127 for c in value)):
178
+ _reject()
179
+ key = key.lower()
180
+ if key in headers:
181
+ _reject()
182
+ headers[key] = value.strip(b' \t')
183
+ if not hmac.compare_digest(headers.get(b'authorization', b''), self.__callback_token):
184
+ _reject('unauthorized')
185
+ if (headers.get(b'host') != self._host or
186
+ headers.get(b'content-type', b'').lower() != b'application/json' or
187
+ any(key in headers for key in (b'transfer-encoding', b'content-encoding',
188
+ b'expect', b'upgrade')) or
189
+ headers.get(b'connection', b'close').lower() not in (b'close', b'keep-alive')):
190
+ _reject()
191
+ length = headers.get(b'content-length', b'')
192
+ if re.fullmatch(rb'0|[1-9][0-9]{0,6}', length) is None:
193
+ _reject()
194
+ length = int(length)
195
+ if length > _MAX_BODY:
196
+ _reject('limit_exceeded')
197
+ # Extra buffered bytes are discarded; never parse a second request.
198
+ return length, initial[:length]
199
+
200
+ def _handle(self, peer, deadline):
201
+ try:
202
+ length, initial = self._headers(peer, deadline)
203
+ body = bytearray(initial)
204
+ while len(body) < length:
205
+ _budget(peer, deadline)
206
+ chunk = peer.recv(min(65536, length-len(body)))
207
+ if not chunk:
208
+ _reject()
209
+ body.extend(chunk)
210
+ # Even a completely queued request must satisfy its acceptance budget.
211
+ _budget(peer, deadline)
212
+ command = _decode_command(bytes(body))
213
+ except (_CallbackProtocolError, TimeoutError) as exc:
214
+ code = exc.code if isinstance(exc, _CallbackProtocolError) else 'invalid_command'
215
+ status = {'unauthorized': 401, 'limit_exceeded': 413}.get(code, 400)
216
+ raw = _bounded_json(dict(version=1, invocation_id=None,
217
+ error=dict(code=code, outcome='not_invoked')))
218
+ else:
219
+ status, raw = self._pool.wait(self._pool.submit(command))
220
+ self._write(peer, status, raw)
221
+
222
+ def _write(self, peer, status, raw):
223
+ deadline = time.monotonic() + _IO_TIMEOUT
224
+ header = (f'HTTP/1.1 {status} Reply\r\nContent-Type: application/json\r\n'
225
+ f'Content-Length: {len(raw)}\r\nConnection: close\r\n\r\n').encode('ascii')
226
+ for part in (header, raw):
227
+ view = memoryview(part)
228
+ while view:
229
+ _budget(peer, deadline)
230
+ count = peer.send(view[:65536])
231
+ if not count:
232
+ return
233
+ view = view[count:]
@@ -0,0 +1,205 @@
1
+ """Private finite callback ownership. No listener or process-global runtime guard."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ from dataclasses import dataclass
6
+ import json
7
+ import threading
8
+ import time
9
+
10
+ from ._callback_protocol import (
11
+ _Command, _CallbackProtocolError, _authorize, _bounded_json, _decode_command, _encode_result,
12
+ )
13
+
14
+
15
+ @dataclass(eq=False, repr=False)
16
+ class _Call:
17
+ command: _Command
18
+ deadline: float
19
+ key: tuple | None = None
20
+ identity: str | None = None
21
+ entered: bool = False
22
+ response: tuple[int, bytes] | None = None
23
+
24
+
25
+ def _failure(call, status, code):
26
+ # Inventory failure never supplies a usable observation of external state.
27
+ outcome = ('unknown' if code == 'callback_in_progress' or
28
+ (call.entered and call.command.value['action'] != 'inventory') else 'not_invoked')
29
+ return status, _bounded_json(dict(
30
+ version=1, invocation_id=call.command.value['invocation_id'],
31
+ error=dict(code=code, outcome=outcome)))
32
+
33
+
34
+ class _CallbackPool:
35
+ """Accept validated _Commands and a validated (start, stop, list) tuple.
36
+
37
+ submit returns an opaque observation handle; wait returns (status, body).
38
+ Admission requires activate(cluster_id, exact_authorize_url). stop_admission
39
+ is terminal. close joins the original threads for at most two seconds total.
40
+ alive reports whether any original thread still lives. A later runtime guard
41
+ must retain this owner while alive, including after close returns.
42
+ """
43
+
44
+ def __init__(self, callbacks, token, *, _observation_timeout=30.0, _register_owner=None):
45
+ self._callbacks = callbacks
46
+ self.__token = token
47
+ self._observation_timeout = _observation_timeout
48
+ self._condition = threading.Condition()
49
+ self._cluster = None
50
+ self._url = None
51
+ self._stopping = False
52
+ self._active = {}
53
+ # Each mailbox remains occupied until actual work and validation finish.
54
+ self._mailboxes = [None] * 4
55
+ self._threads = []
56
+ if _register_owner is not None:
57
+ _register_owner(self)
58
+ failed = False
59
+ try:
60
+ for index in range(4):
61
+ thread = threading.Thread(target=self._run, args=(index,),
62
+ name=f'nabedra-callback-{index}', daemon=True)
63
+ self._threads.append(thread)
64
+ thread.start()
65
+ except BaseException:
66
+ failed = True
67
+ if failed:
68
+ self.close()
69
+ raise RuntimeError('Callback pool startup failed') from None
70
+
71
+ @property
72
+ def alive(self):
73
+ return any(thread.is_alive() for thread in self._threads)
74
+
75
+ def activate(self, cluster_id, authorize_url):
76
+ """Set prepared, already-validated lifetime binding exactly once."""
77
+ with self._condition:
78
+ if self._stopping or self._cluster is not None:
79
+ raise RuntimeError('Callback pool activation rejected')
80
+ self._cluster, self._url = cluster_id, authorize_url
81
+
82
+ def submit(self, command):
83
+ """Reserve an idle worker immediately; never enqueue behind busy work."""
84
+ deadline = time.monotonic() + self._observation_timeout
85
+ # Re-decode the immutable bytes that authorization will receive; the
86
+ # caller's decoded dictionary may have changed since validation.
87
+ # Snapshot outside the admission lock. JSON's
88
+ # sorted keys ignore dict order and preserve bool/int/float distinctions.
89
+ # Both copies/representation are bounded by the 1 MiB command source.
90
+ snapshot = _decode_command(command.original_bytes)
91
+ value = snapshot.value
92
+ identity = json.dumps([value['target'], value['payload']], sort_keys=True,
93
+ ensure_ascii=False, separators=(',', ':'), allow_nan=False)
94
+ key = (value['cluster_id'], value['action'],
95
+ value['invocation_id'] if value['action'] == 'inventory' else value['intent_id'])
96
+ call = _Call(snapshot, deadline, key, identity)
97
+ with self._condition:
98
+ if self._stopping or self._cluster is None:
99
+ call.response = _failure(call, 503, 'bridge_not_active')
100
+ elif value['cluster_id'] != self._cluster:
101
+ call.response = _failure(call, 400, 'invalid_command')
102
+ elif key in self._active:
103
+ original = self._active[key]
104
+ if identity != original.identity:
105
+ call.response = _failure(call, 409, 'identity_conflict')
106
+ else:
107
+ call.response = _failure(call, 409, 'callback_in_progress')
108
+ else:
109
+ indices = (3,) if value['action'] == 'inventory' else range(3)
110
+ index = next((i for i in indices if self._mailboxes[i] is None), None)
111
+ if index is None:
112
+ call.response = _failure(call, 429, 'callback_capacity')
113
+ else:
114
+ self._active[key] = call
115
+ self._mailboxes[index] = call
116
+ self._condition.notify_all()
117
+ return call
118
+
119
+ def wait(self, call):
120
+ """Observe until the admission deadline; never transfer worker ownership."""
121
+ with self._condition:
122
+ while call.response is None:
123
+ remaining = call.deadline - time.monotonic()
124
+ if remaining <= 0:
125
+ call.response = _failure(call, 504, 'callback_timeout')
126
+ break
127
+ self._condition.wait(remaining)
128
+ return call.response
129
+
130
+ def stop_admission(self):
131
+ """Stop permanently, wake idle workers and resolve outstanding waiters."""
132
+ with self._condition:
133
+ self._stopping = True
134
+ for call in self._active.values():
135
+ if call.response is None:
136
+ expired = time.monotonic() >= call.deadline
137
+ call.response = _failure(call, 504 if expired else 503,
138
+ 'callback_timeout' if expired else 'bridge_not_active')
139
+ self._condition.notify_all()
140
+
141
+ def close(self):
142
+ self.stop_admission()
143
+ deadline = time.monotonic() + 2.0
144
+ for thread in self._threads:
145
+ if thread.ident is not None and thread is not threading.current_thread():
146
+ thread.join(max(0, deadline-time.monotonic()))
147
+
148
+ def _execute(self, call):
149
+ value = call.command.value
150
+ # Prepare the provider-owned copy before the fresh authorization read.
151
+ argument = copy.deepcopy(value['payload']) if value['action'] == 'start' else None
152
+ try:
153
+ _authorize(self._url, self.__token, call.command.original_bytes,
154
+ invocation_id=value['invocation_id'], deadline=call.deadline)
155
+ except _CallbackProtocolError as exc:
156
+ if exc.status_code is not None and exc.code != 'authorization_denied':
157
+ return _failure(call, exc.status_code, exc.code)
158
+ return _failure(call, 503, 'ownership_unavailable')
159
+ except BaseException:
160
+ return _failure(call, 503, 'ownership_unavailable')
161
+ with self._condition:
162
+ if call.response is not None:
163
+ return call.response
164
+ if time.monotonic() >= call.deadline:
165
+ return _failure(call, 504, 'callback_timeout')
166
+ if self._stopping:
167
+ return _failure(call, 503, 'bridge_not_active')
168
+ call.entered = True
169
+ try:
170
+ if value['action'] == 'start':
171
+ result = self._callbacks[0](argument)
172
+ elif value['action'] == 'stop':
173
+ result = self._callbacks[1](value['payload']['resource_id'])
174
+ else:
175
+ result = self._callbacks[2]()
176
+ except BaseException:
177
+ return _failure(call, 502, 'callback_failed')
178
+ try:
179
+ return 200, _encode_result(call.command, result)
180
+ except _CallbackProtocolError as exc:
181
+ if exc.code == 'limit_exceeded':
182
+ return _failure(call, 413, 'limit_exceeded')
183
+ return _failure(call, 502, 'invalid_callback_result')
184
+ except BaseException:
185
+ return _failure(call, 502, 'invalid_callback_result')
186
+
187
+ def _run(self, index):
188
+ while True:
189
+ with self._condition:
190
+ while self._mailboxes[index] is None and not self._stopping:
191
+ self._condition.wait()
192
+ call = self._mailboxes[index]
193
+ if call is None:
194
+ return
195
+ response = self._execute(call)
196
+ with self._condition:
197
+ if call.response is None:
198
+ call.response = (_failure(call, 504, 'callback_timeout')
199
+ if time.monotonic() >= call.deadline else response)
200
+ del self._active[call.key]
201
+ self._mailboxes[index] = None
202
+ del call, response
203
+ self._condition.notify_all()
204
+ if self._stopping:
205
+ return