chickinfry 0.5.0.dev1__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.
chickinfry/postgres.py ADDED
@@ -0,0 +1,281 @@
1
+ """Generated applications create and close a PostgresPort per request.
2
+
3
+ The asyncpg dependency of chickinfry[server] is imported only on the first
4
+ query. The text codecs for date and timestamp reject infinity instead of
5
+ mapping it to calendar boundary values.
6
+ """
7
+
8
+ import asyncio
9
+ import ssl
10
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
11
+ from contextvars import ContextVar
12
+ from datetime import date, datetime
13
+ from importlib import import_module
14
+ from typing import Protocol, TypeVar, cast
15
+ from urllib.parse import parse_qsl, unquote, urlencode, urlsplit
16
+
17
+ from .orm import DatabasePort, format_timestamp, parse_date, parse_timestamp
18
+
19
+ T = TypeVar("T")
20
+ _CLEANUP_SECONDS = 5.0
21
+ _ACTIVE: ContextVar[frozenset[int]] = ContextVar(
22
+ "chickinfry_transactions", default=frozenset()
23
+ )
24
+
25
+
26
+ class CommitOutcomeUnknown(Exception):
27
+ """A work unit is never retried automatically when the COMMIT response is ambiguous."""
28
+
29
+ outcome_unknown = True
30
+
31
+ def __init__(self) -> None:
32
+ super().__init__("Transaction commit outcome is unknown.")
33
+
34
+
35
+ class _Connection(Protocol):
36
+ _transport: asyncio.Transport
37
+
38
+ async def fetch(
39
+ self, query: str, *args: object
40
+ ) -> Sequence[Mapping[str, object]]: ...
41
+ async def execute(self, query: str) -> str: ...
42
+ async def close(self, *, timeout: float) -> None: ...
43
+ def terminate(self) -> None: ...
44
+ async def set_type_codec(
45
+ self,
46
+ typename: str,
47
+ *,
48
+ schema: str,
49
+ encoder: Callable[[object], str],
50
+ decoder: Callable[[str], object],
51
+ format: str,
52
+ ) -> None: ...
53
+
54
+
55
+ class _Asyncpg(Protocol):
56
+ async def connect(
57
+ self,
58
+ dsn: str,
59
+ *,
60
+ timeout: float,
61
+ server_settings: Mapping[str, str],
62
+ ssl: ssl.SSLContext | bool,
63
+ ) -> _Connection: ...
64
+
65
+
66
+ def _date_text(value: object) -> str:
67
+ if type(value) is not date:
68
+ raise ValueError("A date parameter is required.")
69
+ return value.isoformat()
70
+
71
+
72
+ def _timestamp_text(value: object) -> str:
73
+ if not isinstance(value, datetime):
74
+ raise ValueError("A datetime parameter is required.")
75
+ return format_timestamp(value)
76
+
77
+
78
+ def _validate_url(dsn: str) -> None:
79
+ try:
80
+ url = urlsplit(dsn)
81
+ if (
82
+ url.scheme not in ("postgres", "postgresql")
83
+ or not url.hostname
84
+ or not url.username
85
+ or not url.password
86
+ or not url.path[1:]
87
+ or url.fragment
88
+ or (url.port is not None and not 1 <= url.port <= 65535)
89
+ ):
90
+ raise ValueError
91
+ if any(
92
+ any(ord(c) < 32 or ord(c) == 127 for c in unquote(part))
93
+ for part in (url.hostname, url.username, url.password, url.path)
94
+ ):
95
+ raise ValueError
96
+ options = parse_qsl(url.query, keep_blank_values=True)
97
+ if len({key for key, _ in options}) != len(options):
98
+ raise ValueError
99
+ for key, value in options:
100
+ if key == "channel_binding":
101
+ if value not in ("require", "prefer", "disable"):
102
+ raise ValueError
103
+ elif key != "sslmode" or value not in (
104
+ "disable",
105
+ "prefer",
106
+ "require",
107
+ "verify-ca",
108
+ "verify-full",
109
+ "no-verify",
110
+ ):
111
+ raise ValueError
112
+ except ValueError:
113
+ raise ValueError("A complete, supported PostgreSQL URL is required.") from None
114
+
115
+
116
+ class PostgresPort:
117
+ """Lazily creates one connection and gives transaction callbacks a scoped DatabasePort."""
118
+
119
+ def __init__(self, dsn: str) -> None:
120
+ _validate_url(dsn)
121
+ url = urlsplit(dsn)
122
+ options = dict(parse_qsl(url.query, keep_blank_values=True))
123
+ if options.get("channel_binding") == "require":
124
+ raise ValueError(
125
+ "channel_binding=require is not supported by this runtime. "
126
+ "Remove channel_binding from the database URL; the connection "
127
+ "still verifies TLS with sslmode=verify-full."
128
+ )
129
+ # The pinned asyncpg offers no PLUS mechanism, so prefer may use plain SCRAM.
130
+ options.pop("channel_binding", None)
131
+ self._dsn = url._replace(query=urlencode(options)).geturl()
132
+ self._connection: _Connection | None = None
133
+ self._lock = asyncio.Lock()
134
+ self._close_lock = asyncio.Lock()
135
+ self._closed = False
136
+
137
+ def _check(self) -> None:
138
+ if self._closed:
139
+ raise RuntimeError("The database connection is closed.")
140
+ if id(self) in _ACTIVE.get():
141
+ raise RuntimeError(
142
+ "Root database reentry inside a transaction is not supported."
143
+ )
144
+
145
+ async def _connect(self) -> _Connection:
146
+ if self._closed:
147
+ raise RuntimeError("The database connection is closed.")
148
+ if self._connection is None:
149
+ driver = cast(_Asyncpg, import_module("asyncpg"))
150
+ mode = dict(parse_qsl(urlsplit(self._dsn).query)).get("sslmode")
151
+ tls: ssl.SSLContext | bool = False
152
+ if mode is not None and mode != "disable":
153
+ # prefer/require/verify-* all require verified TLS, matching the TS runtime.
154
+ tls = ssl.create_default_context()
155
+ if mode == "no-verify":
156
+ tls.check_hostname = False
157
+ tls.verify_mode = ssl.CERT_NONE
158
+ connection = await driver.connect(
159
+ self._dsn,
160
+ timeout=10,
161
+ server_settings={"DateStyle": "ISO", "TimeZone": "UTC"},
162
+ ssl=tls,
163
+ )
164
+ self._connection = connection
165
+ try:
166
+ if self._closed:
167
+ raise RuntimeError("The database connection is closed.")
168
+ await connection.set_type_codec(
169
+ "date",
170
+ schema="pg_catalog",
171
+ format="text",
172
+ encoder=_date_text,
173
+ decoder=parse_date,
174
+ )
175
+ await connection.set_type_codec(
176
+ "timestamptz",
177
+ schema="pg_catalog",
178
+ format="text",
179
+ encoder=_timestamp_text,
180
+ decoder=parse_timestamp,
181
+ )
182
+ except BaseException:
183
+ self.terminate()
184
+ raise
185
+ return self._connection
186
+
187
+ async def _execute(self, sql: str) -> None:
188
+ await (await self._connect()).execute(sql)
189
+
190
+ async def query(
191
+ self, sql: str, parameters: Sequence[object]
192
+ ) -> Sequence[Mapping[str, object]]:
193
+ self._check()
194
+ async with self._lock:
195
+ self._check()
196
+ try:
197
+ return await (await self._connect()).fetch(sql, *parameters)
198
+ except asyncio.CancelledError:
199
+ self.terminate()
200
+ raise
201
+
202
+ async def transaction(self, work: Callable[[DatabasePort], Awaitable[T]]) -> T:
203
+ self._check()
204
+ async with self._lock:
205
+ self._check()
206
+ tx = _TransactionPort(self)
207
+ begun = committing = False
208
+ marker = _ACTIVE.set(_ACTIVE.get() | {id(self)})
209
+ try:
210
+ await self._execute("begin")
211
+ begun = True
212
+ value = await work(tx)
213
+ tx.active = False
214
+ committing = True
215
+ await self._execute("commit")
216
+ return value
217
+ except BaseException as error:
218
+ tx.active = False
219
+ if committing:
220
+ try:
221
+ await self.close()
222
+ except BaseException:
223
+ pass
224
+ raise CommitOutcomeUnknown() from None
225
+ if isinstance(error, asyncio.CancelledError):
226
+ # No driver query or rollback waits for the cancellation acknowledgement.
227
+ self.terminate()
228
+ raise
229
+ if begun:
230
+ try:
231
+ async with asyncio.timeout(_CLEANUP_SECONDS):
232
+ await self._execute("rollback")
233
+ except BaseException:
234
+ self.terminate()
235
+ else:
236
+ self.terminate()
237
+ raise
238
+ finally:
239
+ tx.active = False
240
+ _ACTIVE.reset(marker)
241
+
242
+ async def close(self) -> None:
243
+ self._closed = True
244
+ try:
245
+ # The driver close timeout does not cover waiting for a pending cancel.
246
+ async with asyncio.timeout(_CLEANUP_SECONDS):
247
+ async with self._close_lock:
248
+ if self._connection is not None:
249
+ await self._connection.close(timeout=_CLEANUP_SECONDS)
250
+ finally:
251
+ self.terminate()
252
+
253
+ def terminate(self) -> None:
254
+ """Reclaims the real connection and cancel work after a timeout or cancellation."""
255
+ self._closed = True
256
+ connection, self._connection = self._connection, None
257
+ if connection is not None:
258
+ transport = connection._transport
259
+ try:
260
+ connection.terminate()
261
+ finally:
262
+ # asyncpg 0.31 skips the transport abort while its closing flag is set.
263
+ transport.abort()
264
+
265
+
266
+ class _TransactionPort:
267
+ def __init__(self, root: PostgresPort) -> None:
268
+ self.root = root
269
+ self.active = True
270
+ self._lock = asyncio.Lock()
271
+
272
+ async def query(
273
+ self, sql: str, parameters: Sequence[object]
274
+ ) -> Sequence[Mapping[str, object]]:
275
+ async with self._lock:
276
+ if not self.active:
277
+ raise RuntimeError("The transaction is no longer active.")
278
+ return await (await self.root._connect()).fetch(sql, *parameters)
279
+
280
+ async def transaction(self, work: Callable[[DatabasePort], Awaitable[T]]) -> T:
281
+ raise RuntimeError("Nested transactions are not supported.")
chickinfry/py.typed ADDED
File without changes