netherframe.backends.postgresql 0.2.1__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.
- netherframe/backends/postgresql/__init__.py +59 -0
- netherframe/backends/postgresql/connection_settings.py +40 -0
- netherframe/backends/postgresql/graph.py +2511 -0
- netherframe/backends/postgresql/graph_authorization.py +102 -0
- netherframe/backends/postgresql/graph_checkpoints.py +239 -0
- netherframe/backends/postgresql/graph_completion.py +66 -0
- netherframe/backends/postgresql/graph_convergence.py +103 -0
- netherframe/backends/postgresql/graph_invalidation.py +115 -0
- netherframe/backends/postgresql/graph_lease_queue.py +236 -0
- netherframe/backends/postgresql/graph_planning_reads.py +97 -0
- netherframe/backends/postgresql/graph_publication.py +373 -0
- netherframe/backends/postgresql/graph_retention.py +141 -0
- netherframe/backends/postgresql/graph_reverse_edges.py +143 -0
- netherframe/backends/postgresql/graph_schema.py +2038 -0
- netherframe/backends/postgresql/graph_transfers.py +128 -0
- netherframe/backends/postgresql/postgresql.py +1207 -0
- netherframe/backends/postgresql/postgresql_backend_bootstrap.py +139 -0
- netherframe/backends/postgresql/py.typed +0 -0
- netherframe_backends_postgresql-0.2.1.dist-info/METADATA +138 -0
- netherframe_backends_postgresql-0.2.1.dist-info/RECORD +40 -0
- netherframe_backends_postgresql-0.2.1.dist-info/WHEEL +4 -0
- netherframe_backends_postgresql-0.2.1.dist-info/licenses/LICENSE +21 -0
- nf/backends/postgresql/__init__.py +4 -0
- nf/backends/postgresql/connection_settings.py +4 -0
- nf/backends/postgresql/graph.py +4 -0
- nf/backends/postgresql/graph_authorization.py +4 -0
- nf/backends/postgresql/graph_checkpoints.py +4 -0
- nf/backends/postgresql/graph_completion.py +4 -0
- nf/backends/postgresql/graph_convergence.py +4 -0
- nf/backends/postgresql/graph_invalidation.py +4 -0
- nf/backends/postgresql/graph_lease_queue.py +4 -0
- nf/backends/postgresql/graph_planning_reads.py +4 -0
- nf/backends/postgresql/graph_publication.py +4 -0
- nf/backends/postgresql/graph_retention.py +4 -0
- nf/backends/postgresql/graph_reverse_edges.py +4 -0
- nf/backends/postgresql/graph_schema.py +4 -0
- nf/backends/postgresql/graph_transfers.py +4 -0
- nf/backends/postgresql/postgresql.py +4 -0
- nf/backends/postgresql/postgresql_backend_bootstrap.py +4 -0
- nf/backends/postgresql/py.typed +0 -0
|
@@ -0,0 +1,1207 @@
|
|
|
1
|
+
"""PostgreSQL backend implementation for Netherframe with resource-level locking."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from netherframe.backends.postgresql import connection_settings as connection
|
|
7
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
8
|
+
import os
|
|
9
|
+
import ssl
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from contextlib import ExitStack, asynccontextmanager, suppress
|
|
14
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
15
|
+
|
|
16
|
+
import asyncpg
|
|
17
|
+
import anyio
|
|
18
|
+
from netherframe.core.backends.state_backend import stale_checkpoints, state_conflict
|
|
19
|
+
from netherframe.core.backends.state_engine import State, StateBackend
|
|
20
|
+
from netherframe.core.backends.state_models import StateVersion
|
|
21
|
+
from netherframe.core.backends.state_lock import LockInfo
|
|
22
|
+
from netherframe.core.constructs.backend_base import Backend
|
|
23
|
+
from netherframe.core.constructs.framework_settings import BackendSettings
|
|
24
|
+
from netherframe.core.exceptions import StateLockError
|
|
25
|
+
from netherframe.core.logging import get_logger
|
|
26
|
+
from collections.abc import AsyncGenerator
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from collections.abc import Callable
|
|
30
|
+
|
|
31
|
+
from netherframe.core.backends.backend_bootstrap import BackendBootstrapper
|
|
32
|
+
from netherframe.core.constructs.app_stack import Stack
|
|
33
|
+
|
|
34
|
+
logger = get_logger(__name__)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _loop_key() -> Any:
|
|
38
|
+
get_running_loop = getattr(anyio, "get_running_loop", None)
|
|
39
|
+
if callable(get_running_loop):
|
|
40
|
+
return get_running_loop()
|
|
41
|
+
lowlevel = cast("Any", anyio.lowlevel)
|
|
42
|
+
return lowlevel.current_token()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class PostgreSQLBackend(Backend, StateBackend):
|
|
46
|
+
"""PostgreSQL backend for both Terraform synthesis and hybrid execution.
|
|
47
|
+
|
|
48
|
+
This backend provides:
|
|
49
|
+
- State storage in PostgreSQL with JSONB columns
|
|
50
|
+
- Resource-level locking for granular concurrency control
|
|
51
|
+
- ACID transaction guarantees
|
|
52
|
+
- Built-in deadlock detection
|
|
53
|
+
- Connection pooling for performance
|
|
54
|
+
|
|
55
|
+
The backend adapts its behavior based on execution mode:
|
|
56
|
+
- In synthesis mode: Generates Terraform backend configuration
|
|
57
|
+
- In hybrid mode: Directly manages state in PostgreSQL with advanced locking
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
conditional_writes = True
|
|
61
|
+
|
|
62
|
+
# Prevent concurrent schema initialization collisions across threads/processes
|
|
63
|
+
_schema_init_lock: threading.Lock = threading.Lock()
|
|
64
|
+
|
|
65
|
+
# SQL schema for state and locking tables
|
|
66
|
+
SCHEMA_SQL = """
|
|
67
|
+
-- Main state storage table
|
|
68
|
+
CREATE TABLE IF NOT EXISTS {schema}.{prefix}states (
|
|
69
|
+
state_id VARCHAR(255) PRIMARY KEY,
|
|
70
|
+
state_data JSONB NOT NULL,
|
|
71
|
+
version INTEGER NOT NULL DEFAULT 1,
|
|
72
|
+
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
|
73
|
+
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
|
74
|
+
metadata JSONB DEFAULT '{{}}'::jsonb
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
-- Global state locks table
|
|
78
|
+
CREATE TABLE IF NOT EXISTS {schema}.{prefix}locks (
|
|
79
|
+
state_id VARCHAR(255) PRIMARY KEY,
|
|
80
|
+
lock_info JSONB NOT NULL,
|
|
81
|
+
acquired_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
|
82
|
+
expires_at TIMESTAMP WITH TIME ZONE,
|
|
83
|
+
holder_id VARCHAR(255) NOT NULL,
|
|
84
|
+
operation VARCHAR(100),
|
|
85
|
+
FOREIGN KEY (state_id) REFERENCES {schema}.{prefix}states(state_id) ON DELETE CASCADE
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
-- Resource-level locks table
|
|
89
|
+
CREATE TABLE IF NOT EXISTS {schema}.{prefix}resource_locks (
|
|
90
|
+
id SERIAL PRIMARY KEY,
|
|
91
|
+
resource_id VARCHAR(500) NOT NULL,
|
|
92
|
+
holder_id VARCHAR(255) NOT NULL,
|
|
93
|
+
lock_mode VARCHAR(20) NOT NULL CHECK (lock_mode IN ('SHARED', 'EXCLUSIVE')),
|
|
94
|
+
acquired_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
|
95
|
+
expires_at TIMESTAMP WITH TIME ZONE,
|
|
96
|
+
state_id VARCHAR(255) NOT NULL,
|
|
97
|
+
FOREIGN KEY (state_id) REFERENCES {schema}.{prefix}states(state_id) ON DELETE CASCADE,
|
|
98
|
+
UNIQUE (resource_id, holder_id)
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
-- Indexes for performance
|
|
102
|
+
CREATE INDEX IF NOT EXISTS idx_{prefix}states_updated_at ON {schema}.{prefix}states(updated_at);
|
|
103
|
+
CREATE INDEX IF NOT EXISTS idx_{prefix}locks_expires_at ON {schema}.{prefix}locks(expires_at);
|
|
104
|
+
CREATE INDEX IF NOT EXISTS idx_{prefix}resource_locks_state_id ON {schema}.{prefix}resource_locks(state_id);
|
|
105
|
+
CREATE INDEX IF NOT EXISTS idx_{prefix}resource_locks_expires_at ON {schema}.{prefix}resource_locks(expires_at);
|
|
106
|
+
CREATE INDEX IF NOT EXISTS idx_{prefix}resource_locks_resource_id ON {schema}.{prefix}resource_locks(resource_id);
|
|
107
|
+
|
|
108
|
+
-- Function to automatically update updated_at timestamp
|
|
109
|
+
CREATE OR REPLACE FUNCTION {schema}.update_{prefix}states_updated_at()
|
|
110
|
+
RETURNS TRIGGER AS $$
|
|
111
|
+
BEGIN
|
|
112
|
+
NEW.updated_at = NOW();
|
|
113
|
+
RETURN NEW;
|
|
114
|
+
END;
|
|
115
|
+
$$ LANGUAGE plpgsql;
|
|
116
|
+
|
|
117
|
+
-- Trigger to automatically update updated_at
|
|
118
|
+
DROP TRIGGER IF EXISTS trigger_update_{prefix}states_updated_at ON {schema}.{prefix}states;
|
|
119
|
+
CREATE TRIGGER trigger_update_{prefix}states_updated_at
|
|
120
|
+
BEFORE UPDATE ON {schema}.{prefix}states
|
|
121
|
+
FOR EACH ROW
|
|
122
|
+
EXECUTE FUNCTION {schema}.update_{prefix}states_updated_at();
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
nf_scope: Stack | None = None,
|
|
128
|
+
nf_id: str | None = None,
|
|
129
|
+
# Connection parameters
|
|
130
|
+
host: str | None = None,
|
|
131
|
+
port: int | None = 5432,
|
|
132
|
+
database: str | None = None,
|
|
133
|
+
username: str | None = None,
|
|
134
|
+
password: str | None = None,
|
|
135
|
+
# Database configuration
|
|
136
|
+
schema: str = "public",
|
|
137
|
+
table_prefix: str = "nf_",
|
|
138
|
+
state_id: str = "default",
|
|
139
|
+
# SSL configuration
|
|
140
|
+
ssl_mode: str | None = "prefer",
|
|
141
|
+
ssl_cert: str | None = None,
|
|
142
|
+
ssl_key: str | None = None,
|
|
143
|
+
ssl_ca: str | None = None,
|
|
144
|
+
# Connection pooling
|
|
145
|
+
pool_size: int = 10,
|
|
146
|
+
max_overflow: int = 20,
|
|
147
|
+
pool_timeout: int = 30,
|
|
148
|
+
# Locking configuration
|
|
149
|
+
lock_timeout: int = 300, # 5 minutes
|
|
150
|
+
deadlock_timeout: int = 30, # 30 seconds
|
|
151
|
+
heartbeat_interval: int = 60, # 1 minute heartbeat
|
|
152
|
+
# Mode detection
|
|
153
|
+
hybrid_mode: bool | None = None,
|
|
154
|
+
# Bootstrap configuration
|
|
155
|
+
nf_backend_settings: BackendSettings | None = None,
|
|
156
|
+
create_schema: bool = True,
|
|
157
|
+
**kwargs: Any,
|
|
158
|
+
) -> None:
|
|
159
|
+
"""Initialize PostgreSQL backend.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
nf_scope: Parent stack (required for synthesis mode)
|
|
163
|
+
nf_id: Backend ID (required for synthesis mode)
|
|
164
|
+
host: PostgreSQL host
|
|
165
|
+
port: PostgreSQL port
|
|
166
|
+
database: Database name
|
|
167
|
+
username: Database username
|
|
168
|
+
password: Database password
|
|
169
|
+
schema: Database schema name
|
|
170
|
+
table_prefix: Prefix for table names
|
|
171
|
+
state_id: State identifier
|
|
172
|
+
ssl_mode: SSL mode (disable, allow, prefer, require, verify-ca, verify-full)
|
|
173
|
+
ssl_cert: Path to SSL certificate file
|
|
174
|
+
ssl_key: Path to SSL private key file
|
|
175
|
+
ssl_ca: Path to SSL CA certificate file
|
|
176
|
+
pool_size: Connection pool size
|
|
177
|
+
max_overflow: Maximum pool overflow
|
|
178
|
+
pool_timeout: Pool connection timeout
|
|
179
|
+
lock_timeout: Lock acquisition timeout in seconds
|
|
180
|
+
deadlock_timeout: Deadlock detection timeout in seconds
|
|
181
|
+
heartbeat_interval: Heartbeat interval for lock renewal in seconds
|
|
182
|
+
hybrid_mode: Whether to initialize for hybrid execution mode (auto-detected if None)
|
|
183
|
+
nf_backend_settings: Framework-owned backend settings
|
|
184
|
+
create_schema: Whether to create database schema if it doesn't exist
|
|
185
|
+
**kwargs: Additional configuration
|
|
186
|
+
|
|
187
|
+
"""
|
|
188
|
+
# Auto-detect mode if not specified
|
|
189
|
+
if hybrid_mode is None:
|
|
190
|
+
# If nf_scope is provided, we're in synthesis mode
|
|
191
|
+
# If database params are strings and no scope, we're in hybrid mode
|
|
192
|
+
hybrid_mode = nf_scope is None and isinstance(host, str) and isinstance(database, str)
|
|
193
|
+
|
|
194
|
+
self._hybrid_mode = hybrid_mode
|
|
195
|
+
self._additional_config: dict[str, Any] = {}
|
|
196
|
+
backend_settings = nf_backend_settings or BackendSettings()
|
|
197
|
+
|
|
198
|
+
# Connection settings: flags (nf --postgresql-host ...), else [tool.nf.config], else the
|
|
199
|
+
# arguments; the password is the argument, else a file (--postgresql-password-file)
|
|
200
|
+
self.host = str(connection.setting("host", host, "localhost"))
|
|
201
|
+
self.port = int(connection.setting("port", port, 5432, parser=lambda value: int(str(value))))
|
|
202
|
+
self.database = connection.setting("database", database)
|
|
203
|
+
self.username = connection.setting("username", username)
|
|
204
|
+
secret_file = connection.password_file(None)
|
|
205
|
+
self.password = password or (connection.read_password_file(secret_file) if secret_file is not None else None)
|
|
206
|
+
|
|
207
|
+
if not self.database:
|
|
208
|
+
raise ValueError("database name is required")
|
|
209
|
+
if not self.username:
|
|
210
|
+
raise ValueError("username is required")
|
|
211
|
+
if not self.password:
|
|
212
|
+
raise ValueError("password is required")
|
|
213
|
+
|
|
214
|
+
# Database configuration
|
|
215
|
+
self.schema = schema
|
|
216
|
+
self.table_prefix = table_prefix
|
|
217
|
+
self.state_id = state_id
|
|
218
|
+
self.create_schema = create_schema
|
|
219
|
+
|
|
220
|
+
# SSL configuration
|
|
221
|
+
self.ssl_mode = str(connection.setting("ssl_mode", ssl_mode, "prefer"))
|
|
222
|
+
self.ssl_cert = ssl_cert
|
|
223
|
+
self.ssl_key = ssl_key
|
|
224
|
+
self.ssl_ca = ssl_ca
|
|
225
|
+
|
|
226
|
+
# Connection pooling
|
|
227
|
+
self.pool_size = pool_size
|
|
228
|
+
self.max_overflow = max_overflow
|
|
229
|
+
self.pool_timeout = pool_timeout
|
|
230
|
+
|
|
231
|
+
# Locking configuration
|
|
232
|
+
self.lock_timeout = lock_timeout
|
|
233
|
+
self.deadlock_timeout = deadlock_timeout
|
|
234
|
+
self.heartbeat_interval = heartbeat_interval
|
|
235
|
+
self._portal: Any | None = None
|
|
236
|
+
self._portal_stack: ExitStack | None = None
|
|
237
|
+
self._portal_lock = threading.Lock()
|
|
238
|
+
self._state_row_initialized: bool = False
|
|
239
|
+
|
|
240
|
+
# Runtime state
|
|
241
|
+
self._pools: dict[Any, asyncpg.Pool] = {}
|
|
242
|
+
self._pool: asyncpg.Pool | None = None # Backwards compatibility for tests
|
|
243
|
+
self._lock = threading.Lock()
|
|
244
|
+
self._lock_id: str | None = None
|
|
245
|
+
self._holder_id = f"{os.getpid()}_{threading.get_ident()}_{uuid.uuid4().hex[:8]}"
|
|
246
|
+
self._heartbeat_thread: threading.Thread | None = None
|
|
247
|
+
self._heartbeat_stop = threading.Event()
|
|
248
|
+
self._resource_locks: set[str] = set() # Track acquired resource locks
|
|
249
|
+
|
|
250
|
+
# Initialize based on mode
|
|
251
|
+
if hybrid_mode:
|
|
252
|
+
# Hybrid mode - initialize for direct state management
|
|
253
|
+
self._init_hybrid_mode(create_schema=create_schema)
|
|
254
|
+
else:
|
|
255
|
+
# Synthesis mode - initialize for Terraform backend config
|
|
256
|
+
if nf_scope is None:
|
|
257
|
+
raise ValueError("nf_scope is required for synthesis mode")
|
|
258
|
+
if nf_id is None:
|
|
259
|
+
raise ValueError("nf_id is required for synthesis mode")
|
|
260
|
+
|
|
261
|
+
super().__init__(
|
|
262
|
+
nf_scope=nf_scope,
|
|
263
|
+
nf_id=nf_id,
|
|
264
|
+
nf_backend_settings=backend_settings,
|
|
265
|
+
)
|
|
266
|
+
self._init_synthesis_mode(bootstrap=backend_settings.bootstrap, kwargs=kwargs)
|
|
267
|
+
|
|
268
|
+
def _ensure_portal(self) -> Any:
|
|
269
|
+
"""Ensure a blocking portal exists for backend operations."""
|
|
270
|
+
with self._portal_lock:
|
|
271
|
+
if self._portal is None:
|
|
272
|
+
self._portal_stack = ExitStack()
|
|
273
|
+
from_thread = cast("Any", anyio.from_thread)
|
|
274
|
+
start_blocking_portal = from_thread.start_blocking_portal
|
|
275
|
+
self._portal = self._portal_stack.enter_context(
|
|
276
|
+
start_blocking_portal(),
|
|
277
|
+
)
|
|
278
|
+
return self._portal
|
|
279
|
+
|
|
280
|
+
def _run_sync(
|
|
281
|
+
self,
|
|
282
|
+
async_fn: Callable[..., Any],
|
|
283
|
+
*args: Any,
|
|
284
|
+
**kwargs: Any,
|
|
285
|
+
) -> Any:
|
|
286
|
+
"""Run an async callable on the backend portal and return its result."""
|
|
287
|
+
portal = self._ensure_portal()
|
|
288
|
+
return portal.call(async_fn, *args, **kwargs)
|
|
289
|
+
|
|
290
|
+
@staticmethod
|
|
291
|
+
def _advisory_key(resource_id: str) -> tuple[int, int]:
|
|
292
|
+
"""Generate a deterministic pair of int32 keys for advisory locks."""
|
|
293
|
+
digest = hashlib.sha256(resource_id.encode("utf-8")).digest()
|
|
294
|
+
return (
|
|
295
|
+
int.from_bytes(digest[:4], "big", signed=True),
|
|
296
|
+
int.from_bytes(digest[4:8], "big", signed=True),
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
def _init_synthesis_mode(
|
|
300
|
+
self,
|
|
301
|
+
bootstrap: bool,
|
|
302
|
+
kwargs: dict[str, Any],
|
|
303
|
+
) -> None:
|
|
304
|
+
"""Initialize for Terraform synthesis mode."""
|
|
305
|
+
# Store configuration for Terraform backend
|
|
306
|
+
self._bootstrap = bootstrap
|
|
307
|
+
self._additional_config = kwargs
|
|
308
|
+
|
|
309
|
+
logger.info(
|
|
310
|
+
f"PostgreSQL backend initialized in synthesis mode for state_id: {self.state_id}",
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
def _init_hybrid_mode(self, create_schema: bool) -> None:
|
|
314
|
+
"""Initialize for hybrid execution mode."""
|
|
315
|
+
# Initialize connection pool lazily
|
|
316
|
+
self._create_schema = create_schema
|
|
317
|
+
|
|
318
|
+
logger.info(
|
|
319
|
+
f"PostgreSQL backend initialized in hybrid mode: host={self.host}, database={self.database}, schema={self.schema}, state_id={self.state_id}",
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
def get_bootstrapper(self) -> BackendBootstrapper | None:
|
|
323
|
+
"""Return a PostgreSQL backend bootstrapper if possible."""
|
|
324
|
+
from netherframe.backends.postgresql.postgresql_backend_bootstrap import (
|
|
325
|
+
PostgreSQLBackendBootstrapper,
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
if self.database is None or self.username is None or self.password is None:
|
|
329
|
+
return None
|
|
330
|
+
|
|
331
|
+
return PostgreSQLBackendBootstrapper(
|
|
332
|
+
host=self.host,
|
|
333
|
+
port=self.port,
|
|
334
|
+
database=self.database,
|
|
335
|
+
username=self.username,
|
|
336
|
+
password=self.password,
|
|
337
|
+
schema=self.schema,
|
|
338
|
+
table_prefix=self.table_prefix,
|
|
339
|
+
state_id=self.state_id,
|
|
340
|
+
ssl_mode=self.ssl_mode,
|
|
341
|
+
ssl_cert=self.ssl_cert,
|
|
342
|
+
ssl_key=self.ssl_key,
|
|
343
|
+
ssl_ca=self.ssl_ca,
|
|
344
|
+
create_schema=self.create_schema,
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
@property
|
|
348
|
+
def backend_type(self) -> str:
|
|
349
|
+
"""Get the backend type name."""
|
|
350
|
+
return "postgresql"
|
|
351
|
+
|
|
352
|
+
def get_backend_type(self) -> str:
|
|
353
|
+
"""Get the backend type identifier."""
|
|
354
|
+
return "postgresql"
|
|
355
|
+
|
|
356
|
+
def to_hcl(self) -> dict[str, Any]:
|
|
357
|
+
"""Convert backend configuration to HCL format (password is never emitted)."""
|
|
358
|
+
return self._build_config(include_type=False, include_additional=True)
|
|
359
|
+
|
|
360
|
+
def _build_config(self, *, include_type: bool, include_additional: bool) -> dict[str, Any]:
|
|
361
|
+
"""Build backend configuration for hybrid or synthesis mode."""
|
|
362
|
+
config: dict[str, Any] = {
|
|
363
|
+
"host": self.host,
|
|
364
|
+
"port": self.port,
|
|
365
|
+
"database": self.database,
|
|
366
|
+
"username": self.username,
|
|
367
|
+
"schema": self.schema,
|
|
368
|
+
"table_prefix": self.table_prefix,
|
|
369
|
+
"state_id": self.state_id,
|
|
370
|
+
"ssl_mode": self.ssl_mode,
|
|
371
|
+
}
|
|
372
|
+
if include_type:
|
|
373
|
+
config["type"] = "postgresql"
|
|
374
|
+
if include_additional:
|
|
375
|
+
config.update(self._additional_config)
|
|
376
|
+
return config
|
|
377
|
+
|
|
378
|
+
@staticmethod
|
|
379
|
+
def _empty_state_payload() -> dict[str, Any]:
|
|
380
|
+
"""Return the default state payload stored for new rows."""
|
|
381
|
+
return State().to_dict()
|
|
382
|
+
|
|
383
|
+
@staticmethod
|
|
384
|
+
def _decode_state_data(state_data: dict[str, Any] | str) -> dict[str, Any]:
|
|
385
|
+
"""Normalize state data returned by asyncpg into a Python dict."""
|
|
386
|
+
return json.loads(state_data) if isinstance(state_data, str) else state_data
|
|
387
|
+
|
|
388
|
+
def _normalize_lock_info(self, info: dict[str, Any] | LockInfo) -> dict[str, Any]:
|
|
389
|
+
"""Normalize lock info into the canonical JSON payload."""
|
|
390
|
+
if isinstance(info, LockInfo):
|
|
391
|
+
return info.to_dict()
|
|
392
|
+
|
|
393
|
+
if "user" in info and "host" in info:
|
|
394
|
+
return {
|
|
395
|
+
"ID": str(info.get("ID") or uuid.uuid4()),
|
|
396
|
+
"Operation": info.get("operation", "unknown"),
|
|
397
|
+
"Who": f"{info.get('user', 'unknown')}@{info.get('host', 'unknown')}",
|
|
398
|
+
"Version": "1.0",
|
|
399
|
+
"Created": info.get("timestamp", time.time()),
|
|
400
|
+
"Path": self.state_id,
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
return info
|
|
404
|
+
|
|
405
|
+
def _build_ssl_config(self) -> bool | ssl.SSLContext:
|
|
406
|
+
"""Build asyncpg SSL configuration."""
|
|
407
|
+
if self.ssl_mode in {"disable", "allow", "prefer"}:
|
|
408
|
+
return False
|
|
409
|
+
|
|
410
|
+
if self.ssl_mode == "require" and not any((self.ssl_cert, self.ssl_key, self.ssl_ca)):
|
|
411
|
+
return True
|
|
412
|
+
|
|
413
|
+
context = ssl.create_default_context()
|
|
414
|
+
if self.ssl_ca:
|
|
415
|
+
context.load_verify_locations(self.ssl_ca)
|
|
416
|
+
if self.ssl_cert and self.ssl_key:
|
|
417
|
+
context.load_cert_chain(self.ssl_cert, self.ssl_key)
|
|
418
|
+
|
|
419
|
+
if self.ssl_mode == "require" and not self.ssl_ca:
|
|
420
|
+
context.check_hostname = False
|
|
421
|
+
context.verify_mode = ssl.CERT_NONE
|
|
422
|
+
elif self.ssl_mode != "verify-full":
|
|
423
|
+
context.check_hostname = False
|
|
424
|
+
|
|
425
|
+
return context
|
|
426
|
+
|
|
427
|
+
async def _ensure_state_row(self, conn: asyncpg.Connection) -> None:
|
|
428
|
+
"""Ensure a state row exists for this backend's state_id."""
|
|
429
|
+
if self._state_row_initialized:
|
|
430
|
+
return
|
|
431
|
+
|
|
432
|
+
await conn.execute(
|
|
433
|
+
f"""
|
|
434
|
+
INSERT INTO {self.schema}.{self.table_prefix}states (state_id, state_data)
|
|
435
|
+
VALUES ($1, $2)
|
|
436
|
+
ON CONFLICT (state_id) DO NOTHING
|
|
437
|
+
""",
|
|
438
|
+
self.state_id,
|
|
439
|
+
json.dumps(self._empty_state_payload()),
|
|
440
|
+
)
|
|
441
|
+
self._state_row_initialized = True
|
|
442
|
+
|
|
443
|
+
def get_config(self) -> dict[str, Any]:
|
|
444
|
+
"""Get the backend configuration."""
|
|
445
|
+
if self._hybrid_mode:
|
|
446
|
+
return self._build_config(include_type=True, include_additional=False)
|
|
447
|
+
return self._build_config(include_type=False, include_additional=True)
|
|
448
|
+
|
|
449
|
+
def state_identity(self) -> dict[str, Any]:
|
|
450
|
+
return {"backend": "postgresql", "host": self.host, "port": self.port, "database": self.database, "schema": self.schema, "table_prefix": self.table_prefix, "state_id": self.state_id}
|
|
451
|
+
|
|
452
|
+
async def _get_pool(self) -> asyncpg.Pool:
|
|
453
|
+
"""Get or create connection pool."""
|
|
454
|
+
loop = _loop_key()
|
|
455
|
+
# If a pool was manually injected (e.g., in tests), honor it without re-init.
|
|
456
|
+
if self._pool is not None and self._pool not in self._pools.values():
|
|
457
|
+
return self._pool
|
|
458
|
+
# Reuse pool for this loop if available
|
|
459
|
+
existing = self._pools.get(loop)
|
|
460
|
+
if existing and not existing._closed:
|
|
461
|
+
return existing
|
|
462
|
+
|
|
463
|
+
with self._lock:
|
|
464
|
+
existing = self._pools.get(loop)
|
|
465
|
+
if existing and not existing._closed:
|
|
466
|
+
return existing
|
|
467
|
+
|
|
468
|
+
# Create connection pool for this loop
|
|
469
|
+
pool = await asyncpg.create_pool(
|
|
470
|
+
host=self.host,
|
|
471
|
+
port=self.port,
|
|
472
|
+
database=self.database,
|
|
473
|
+
user=self.username,
|
|
474
|
+
password=self.password,
|
|
475
|
+
min_size=1,
|
|
476
|
+
max_size=self.pool_size,
|
|
477
|
+
command_timeout=self.pool_timeout,
|
|
478
|
+
ssl=self._build_ssl_config(),
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
# Initialize schema if requested
|
|
482
|
+
if self._create_schema:
|
|
483
|
+
await self._init_schema(pool)
|
|
484
|
+
|
|
485
|
+
self._pools[loop] = pool
|
|
486
|
+
self._pool = pool
|
|
487
|
+
return pool
|
|
488
|
+
|
|
489
|
+
async def _init_schema(self, pool: asyncpg.Pool) -> None:
|
|
490
|
+
"""Initialize database schema."""
|
|
491
|
+
if not pool:
|
|
492
|
+
return
|
|
493
|
+
|
|
494
|
+
# Serialize initialization per unique schema/table_prefix to avoid Postgres type race
|
|
495
|
+
with self._schema_init_lock:
|
|
496
|
+
try:
|
|
497
|
+
async with pool.acquire() as conn:
|
|
498
|
+
# Create schema if it doesn't exist
|
|
499
|
+
if self.schema != "public":
|
|
500
|
+
await conn.execute(f"CREATE SCHEMA IF NOT EXISTS {self.schema}")
|
|
501
|
+
|
|
502
|
+
# Create tables and indexes
|
|
503
|
+
schema_sql = self.SCHEMA_SQL.format(
|
|
504
|
+
schema=self.schema,
|
|
505
|
+
prefix=self.table_prefix,
|
|
506
|
+
)
|
|
507
|
+
await conn.execute(schema_sql)
|
|
508
|
+
|
|
509
|
+
# Ensure state record exists
|
|
510
|
+
await conn.execute(
|
|
511
|
+
f"""
|
|
512
|
+
INSERT INTO {self.schema}.{self.table_prefix}states (state_id, state_data)
|
|
513
|
+
VALUES ($1, $2)
|
|
514
|
+
ON CONFLICT (state_id) DO NOTHING
|
|
515
|
+
""",
|
|
516
|
+
self.state_id,
|
|
517
|
+
json.dumps(self._empty_state_payload()),
|
|
518
|
+
)
|
|
519
|
+
self._state_row_initialized = True
|
|
520
|
+
|
|
521
|
+
logger.info(
|
|
522
|
+
f"PostgreSQL schema initialized successfully in {self.schema}",
|
|
523
|
+
)
|
|
524
|
+
except Exception as e:
|
|
525
|
+
logger.error("Failed to initialize PostgreSQL schema: %s", e)
|
|
526
|
+
raise
|
|
527
|
+
|
|
528
|
+
# StateBackend interface implementation
|
|
529
|
+
|
|
530
|
+
def load(self) -> State:
|
|
531
|
+
"""Load state from PostgreSQL."""
|
|
532
|
+
if not self._hybrid_mode:
|
|
533
|
+
raise RuntimeError("load() is only available in hybrid mode")
|
|
534
|
+
|
|
535
|
+
return self._run_sync(self._load_async)
|
|
536
|
+
|
|
537
|
+
async def _load_async(self) -> State:
|
|
538
|
+
"""Async implementation of state loading."""
|
|
539
|
+
pool = await self._get_pool()
|
|
540
|
+
|
|
541
|
+
try:
|
|
542
|
+
async with pool.acquire() as conn:
|
|
543
|
+
# Load state data
|
|
544
|
+
row = await conn.fetchrow(
|
|
545
|
+
f"SELECT state_data FROM {self.schema}.{self.table_prefix}states WHERE state_id = $1",
|
|
546
|
+
self.state_id,
|
|
547
|
+
)
|
|
548
|
+
|
|
549
|
+
if not row:
|
|
550
|
+
# Return empty state if not found
|
|
551
|
+
logger.info(
|
|
552
|
+
f"No state found for state_id: {self.state_id}, returning empty state",
|
|
553
|
+
)
|
|
554
|
+
return State()
|
|
555
|
+
|
|
556
|
+
state = State.from_dict(self._decode_state_data(row["state_data"]))
|
|
557
|
+
logger.info(f"Loaded state with {len(state.resources)} resources")
|
|
558
|
+
return state
|
|
559
|
+
|
|
560
|
+
except Exception as e:
|
|
561
|
+
logger.error("Failed to load state: %s", e)
|
|
562
|
+
raise
|
|
563
|
+
|
|
564
|
+
def save(self, state: State) -> None:
|
|
565
|
+
"""Save state to PostgreSQL."""
|
|
566
|
+
if not self._hybrid_mode:
|
|
567
|
+
raise RuntimeError("save() is only available in hybrid mode")
|
|
568
|
+
|
|
569
|
+
self._run_sync(self._save_async, state)
|
|
570
|
+
|
|
571
|
+
async def _stored_version(self, conn: asyncpg.Connection) -> StateVersion:
|
|
572
|
+
row = await conn.fetchrow(
|
|
573
|
+
f"SELECT state_data->>'serial' AS serial, state_data->>'lineage' AS lineage FROM {self.schema}.{self.table_prefix}states WHERE state_id = $1",
|
|
574
|
+
self.state_id,
|
|
575
|
+
)
|
|
576
|
+
return StateVersion(int(row["serial"] or 0), row["lineage"] or None) if row else StateVersion()
|
|
577
|
+
|
|
578
|
+
def save_if_unchanged(self, state: State, expected: StateVersion) -> None:
|
|
579
|
+
"""Save state only while the stored state is still ``expected``: its row is locked while it is compared and written."""
|
|
580
|
+
if not self._hybrid_mode:
|
|
581
|
+
raise RuntimeError("save() is only available in hybrid mode")
|
|
582
|
+
|
|
583
|
+
self._run_sync(self._save_async, state, expected)
|
|
584
|
+
|
|
585
|
+
async def _save_async(self, state: State, expected: StateVersion | None = None) -> None:
|
|
586
|
+
"""Async implementation of state saving."""
|
|
587
|
+
pool = await self._get_pool()
|
|
588
|
+
|
|
589
|
+
try:
|
|
590
|
+
async with pool.acquire() as conn:
|
|
591
|
+
async with conn.transaction():
|
|
592
|
+
if expected is not None:
|
|
593
|
+
# FOR UPDATE: no other writer changes the row until this transaction ends
|
|
594
|
+
row = await conn.fetchrow(
|
|
595
|
+
f"SELECT state_data->>'serial' AS serial, state_data->>'lineage' AS lineage FROM {self.schema}.{self.table_prefix}states WHERE state_id = $1 FOR UPDATE",
|
|
596
|
+
self.state_id,
|
|
597
|
+
)
|
|
598
|
+
stored = StateVersion(int(row["serial"] or 0), row["lineage"] or None) if row else StateVersion()
|
|
599
|
+
if stored != expected:
|
|
600
|
+
raise state_conflict(f"{self.schema}.{self.table_prefix}states/{self.state_id}", stored, expected)
|
|
601
|
+
if row is None:
|
|
602
|
+
# FOR UPDATE locked no row: only one of two writers may create it
|
|
603
|
+
created = await conn.execute(
|
|
604
|
+
f"INSERT INTO {self.schema}.{self.table_prefix}states (state_id, state_data, version) VALUES ($1, $2, $3) ON CONFLICT (state_id) DO NOTHING",
|
|
605
|
+
self.state_id,
|
|
606
|
+
json.dumps(state.to_dict()),
|
|
607
|
+
state.version,
|
|
608
|
+
)
|
|
609
|
+
if created != "INSERT 0 1":
|
|
610
|
+
raise state_conflict(f"{self.schema}.{self.table_prefix}states/{self.state_id}", await self._stored_version(conn), expected)
|
|
611
|
+
logger.info(f"Saved state with {len(state.resources)} resources")
|
|
612
|
+
return
|
|
613
|
+
# Prepare state data
|
|
614
|
+
state_data = state.to_dict()
|
|
615
|
+
|
|
616
|
+
# Upsert state
|
|
617
|
+
await conn.execute(
|
|
618
|
+
f"""
|
|
619
|
+
INSERT INTO {self.schema}.{self.table_prefix}states (state_id, state_data, version)
|
|
620
|
+
VALUES ($1, $2, $3)
|
|
621
|
+
ON CONFLICT (state_id)
|
|
622
|
+
DO UPDATE SET
|
|
623
|
+
state_data = EXCLUDED.state_data,
|
|
624
|
+
version = EXCLUDED.version,
|
|
625
|
+
updated_at = NOW()
|
|
626
|
+
""",
|
|
627
|
+
self.state_id,
|
|
628
|
+
json.dumps(state_data),
|
|
629
|
+
state.version,
|
|
630
|
+
)
|
|
631
|
+
|
|
632
|
+
logger.info(f"Saved state with {len(state.resources)} resources")
|
|
633
|
+
|
|
634
|
+
except Exception as e:
|
|
635
|
+
logger.error("Failed to save state: %s", e)
|
|
636
|
+
raise
|
|
637
|
+
|
|
638
|
+
def lock(self, info: dict[str, Any] | LockInfo) -> bool:
|
|
639
|
+
"""Acquire state lock using PostgreSQL."""
|
|
640
|
+
if not self._hybrid_mode:
|
|
641
|
+
raise RuntimeError("lock() is only available in hybrid mode")
|
|
642
|
+
|
|
643
|
+
return self._run_sync(self._lock_async, info)
|
|
644
|
+
|
|
645
|
+
async def _lock_async(self, info: dict[str, Any] | LockInfo) -> bool:
|
|
646
|
+
"""Async implementation of state locking."""
|
|
647
|
+
pool = await self._get_pool()
|
|
648
|
+
|
|
649
|
+
lock_info = self._normalize_lock_info(info)
|
|
650
|
+
|
|
651
|
+
try:
|
|
652
|
+
async with pool.acquire() as conn:
|
|
653
|
+
# Ensure a state row exists for this state_id to satisfy FK on locks
|
|
654
|
+
await self._ensure_state_row(conn)
|
|
655
|
+
|
|
656
|
+
# Try to acquire lock using state_id as primary key
|
|
657
|
+
result = await conn.execute(
|
|
658
|
+
f"""
|
|
659
|
+
INSERT INTO {self.schema}.{self.table_prefix}locks
|
|
660
|
+
(state_id, lock_info, holder_id, operation, expires_at)
|
|
661
|
+
VALUES ($1, $2, $3, $4, NOW() + INTERVAL '{self.lock_timeout} seconds')
|
|
662
|
+
ON CONFLICT (state_id) DO NOTHING
|
|
663
|
+
""",
|
|
664
|
+
self.state_id,
|
|
665
|
+
json.dumps(lock_info),
|
|
666
|
+
self._holder_id,
|
|
667
|
+
lock_info.get("Operation", lock_info.get("operation", "unknown")),
|
|
668
|
+
)
|
|
669
|
+
|
|
670
|
+
# Check if we got the lock
|
|
671
|
+
if result == "INSERT 0 1":
|
|
672
|
+
self._lock_id = self.state_id
|
|
673
|
+
await self._start_heartbeat()
|
|
674
|
+
logger.info(f"Acquired state lock: {self.state_id}")
|
|
675
|
+
return True
|
|
676
|
+
# Lock already exists, check if it's expired
|
|
677
|
+
await self._cleanup_expired_locks(conn)
|
|
678
|
+
|
|
679
|
+
# Try again after cleanup
|
|
680
|
+
result = await conn.execute(
|
|
681
|
+
f"""
|
|
682
|
+
INSERT INTO {self.schema}.{self.table_prefix}locks
|
|
683
|
+
(state_id, lock_info, holder_id, operation, expires_at)
|
|
684
|
+
VALUES ($1, $2, $3, $4, NOW() + INTERVAL '{self.lock_timeout} seconds')
|
|
685
|
+
ON CONFLICT (state_id) DO NOTHING
|
|
686
|
+
""",
|
|
687
|
+
self.state_id,
|
|
688
|
+
json.dumps(lock_info),
|
|
689
|
+
self._holder_id,
|
|
690
|
+
lock_info.get("Operation", lock_info.get("operation", "unknown")),
|
|
691
|
+
)
|
|
692
|
+
|
|
693
|
+
if result == "INSERT 0 1":
|
|
694
|
+
self._lock_id = self.state_id
|
|
695
|
+
await self._start_heartbeat()
|
|
696
|
+
logger.info(
|
|
697
|
+
f"Acquired state lock after cleanup: {self.state_id}",
|
|
698
|
+
)
|
|
699
|
+
return True
|
|
700
|
+
logger.warning(f"Failed to acquire state lock: {self.state_id}")
|
|
701
|
+
return False
|
|
702
|
+
|
|
703
|
+
except Exception as e:
|
|
704
|
+
logger.error("Failed to acquire lock: %s", e)
|
|
705
|
+
return False
|
|
706
|
+
|
|
707
|
+
def unlock(self) -> None:
|
|
708
|
+
"""Release state lock."""
|
|
709
|
+
if not self._hybrid_mode:
|
|
710
|
+
raise RuntimeError("unlock() is only available in hybrid mode")
|
|
711
|
+
|
|
712
|
+
self._run_sync(self._unlock_async)
|
|
713
|
+
|
|
714
|
+
async def _unlock_async(self) -> None:
|
|
715
|
+
"""Async implementation of lock release."""
|
|
716
|
+
if not self._lock_id:
|
|
717
|
+
return
|
|
718
|
+
|
|
719
|
+
pool = await self._get_pool()
|
|
720
|
+
|
|
721
|
+
try:
|
|
722
|
+
async with pool.acquire() as conn:
|
|
723
|
+
# Release lock
|
|
724
|
+
result = await conn.execute(
|
|
725
|
+
f"DELETE FROM {self.schema}.{self.table_prefix}locks WHERE state_id = $1 AND holder_id = $2",
|
|
726
|
+
self._lock_id,
|
|
727
|
+
self._holder_id,
|
|
728
|
+
)
|
|
729
|
+
|
|
730
|
+
if result == "DELETE 1":
|
|
731
|
+
logger.info(f"Released state lock: {self._lock_id}")
|
|
732
|
+
else:
|
|
733
|
+
logger.warning(
|
|
734
|
+
f"Lock not found or not owned by this holder: {self._lock_id}",
|
|
735
|
+
)
|
|
736
|
+
|
|
737
|
+
self._lock_id = None
|
|
738
|
+
try:
|
|
739
|
+
await self._stop_heartbeat()
|
|
740
|
+
except Exception:
|
|
741
|
+
# Ignore cleanup issues from background tasks tied to previous loops
|
|
742
|
+
pass
|
|
743
|
+
|
|
744
|
+
except Exception as e:
|
|
745
|
+
logger.error("Failed to release lock: %s", e)
|
|
746
|
+
|
|
747
|
+
def _checkpoint_state_id(self, name: str) -> str:
|
|
748
|
+
return f"{self.state_id}.checkpoints/{name}"
|
|
749
|
+
|
|
750
|
+
def _checkpoint_location(self, name: str) -> str:
|
|
751
|
+
return f"postgresql://{self.schema}.{self.table_prefix}states/{self._checkpoint_state_id(name)}"
|
|
752
|
+
|
|
753
|
+
def save_checkpoint(self, name: str, *, keep: int) -> str | None:
|
|
754
|
+
"""Copy the stored state to a row of its own (``<state_id>.checkpoints/<name>``), keeping the newest ``keep``."""
|
|
755
|
+
if not self._hybrid_mode:
|
|
756
|
+
return None
|
|
757
|
+
self._run_sync(self._save_checkpoint_async, name, keep)
|
|
758
|
+
return self._checkpoint_location(name)
|
|
759
|
+
|
|
760
|
+
async def _save_checkpoint_async(self, name: str, keep: int) -> None:
|
|
761
|
+
pool = await self._get_pool()
|
|
762
|
+
states = f"{self.schema}.{self.table_prefix}states"
|
|
763
|
+
prefix = self._checkpoint_state_id("")
|
|
764
|
+
async with pool.acquire() as conn, conn.transaction():
|
|
765
|
+
row = await conn.fetchrow(f"SELECT state_data FROM {states} WHERE state_id = $1", self.state_id)
|
|
766
|
+
data = self._decode_state_data(row["state_data"]) if row else self._empty_state_payload()
|
|
767
|
+
await conn.execute(
|
|
768
|
+
f"""
|
|
769
|
+
INSERT INTO {states} (state_id, state_data, version) VALUES ($1, $2, $3)
|
|
770
|
+
ON CONFLICT (state_id) DO UPDATE SET state_data = EXCLUDED.state_data, updated_at = NOW()
|
|
771
|
+
""",
|
|
772
|
+
self._checkpoint_state_id(name),
|
|
773
|
+
json.dumps(data),
|
|
774
|
+
int(data.get("version", 4)),
|
|
775
|
+
)
|
|
776
|
+
rows = await conn.fetch(f"SELECT state_id FROM {states} WHERE left(state_id, length($1)) = $1", prefix)
|
|
777
|
+
stale = stale_checkpoints((row["state_id"] for row in rows), keep)
|
|
778
|
+
if stale:
|
|
779
|
+
await conn.execute(f"DELETE FROM {states} WHERE state_id = ANY($1::varchar[])", stale)
|
|
780
|
+
|
|
781
|
+
def load_checkpoint(self, location: str) -> State | None:
|
|
782
|
+
prefix = self._checkpoint_location("")
|
|
783
|
+
if not self._hybrid_mode or not location.startswith(prefix):
|
|
784
|
+
return None
|
|
785
|
+
return self._run_sync(self._load_checkpoint_async, location.removeprefix(prefix))
|
|
786
|
+
|
|
787
|
+
async def _load_checkpoint_async(self, name: str) -> State:
|
|
788
|
+
pool = await self._get_pool()
|
|
789
|
+
async with pool.acquire() as conn:
|
|
790
|
+
row = await conn.fetchrow(
|
|
791
|
+
f"SELECT state_data FROM {self.schema}.{self.table_prefix}states WHERE state_id = $1",
|
|
792
|
+
self._checkpoint_state_id(name),
|
|
793
|
+
)
|
|
794
|
+
if row is None:
|
|
795
|
+
raise FileNotFoundError(f"No checkpoint at {self._checkpoint_location(name)}")
|
|
796
|
+
return State.from_dict(self._decode_state_data(row["state_data"]))
|
|
797
|
+
|
|
798
|
+
can_force_unlock = True
|
|
799
|
+
|
|
800
|
+
def current_lock(self) -> dict[str, Any] | None:
|
|
801
|
+
"""The info of the lock held on this state, or None."""
|
|
802
|
+
if not self._hybrid_mode:
|
|
803
|
+
return None
|
|
804
|
+
return self._run_sync(self._current_lock_async)
|
|
805
|
+
|
|
806
|
+
async def _current_lock_async(self) -> dict[str, Any] | None:
|
|
807
|
+
pool = await self._get_pool()
|
|
808
|
+
async with pool.acquire() as conn:
|
|
809
|
+
row = await conn.fetchrow(
|
|
810
|
+
f"SELECT lock_info FROM {self.schema}.{self.table_prefix}locks WHERE state_id = $1 AND (expires_at IS NULL OR expires_at >= NOW())",
|
|
811
|
+
self.state_id,
|
|
812
|
+
)
|
|
813
|
+
return self._decode_state_data(row["lock_info"]) if row else None
|
|
814
|
+
|
|
815
|
+
def force_unlock(self, lock_id: str) -> None:
|
|
816
|
+
"""Delete the lock row, only while it is the lock ``lock_id``."""
|
|
817
|
+
if not self._hybrid_mode:
|
|
818
|
+
raise RuntimeError("force_unlock() is only available in hybrid mode")
|
|
819
|
+
self._run_sync(self._force_unlock_async, lock_id)
|
|
820
|
+
|
|
821
|
+
async def _force_unlock_async(self, lock_id: str) -> None:
|
|
822
|
+
pool = await self._get_pool()
|
|
823
|
+
async with pool.acquire() as conn:
|
|
824
|
+
row = await conn.fetchrow(
|
|
825
|
+
f"SELECT lock_info FROM {self.schema}.{self.table_prefix}locks WHERE state_id = $1",
|
|
826
|
+
self.state_id,
|
|
827
|
+
)
|
|
828
|
+
if row is None:
|
|
829
|
+
raise StateLockError(f"State {self.state_id} is not locked")
|
|
830
|
+
holder = self._decode_state_data(row["lock_info"])
|
|
831
|
+
if str(holder.get("ID")) != lock_id:
|
|
832
|
+
raise StateLockError(f"State {self.state_id} is locked by lock {holder.get('ID')}, not {lock_id}")
|
|
833
|
+
result = await conn.execute(
|
|
834
|
+
f"DELETE FROM {self.schema}.{self.table_prefix}locks WHERE state_id = $1 AND lock_info->>'ID' = $2",
|
|
835
|
+
self.state_id,
|
|
836
|
+
lock_id,
|
|
837
|
+
)
|
|
838
|
+
if result != "DELETE 1":
|
|
839
|
+
raise StateLockError(f"State {self.state_id} is no longer locked by lock {lock_id}")
|
|
840
|
+
logger.warning("Released state lock %s of %s", lock_id, holder)
|
|
841
|
+
|
|
842
|
+
async def _cleanup_expired_locks(self, conn: asyncpg.Connection) -> None:
|
|
843
|
+
"""Clean up expired locks."""
|
|
844
|
+
try:
|
|
845
|
+
result = await conn.execute(
|
|
846
|
+
f"DELETE FROM {self.schema}.{self.table_prefix}locks WHERE expires_at < NOW()",
|
|
847
|
+
)
|
|
848
|
+
if result != "DELETE 0":
|
|
849
|
+
logger.info("Cleaned up expired locks: %s", result)
|
|
850
|
+
except Exception as e:
|
|
851
|
+
logger.warning("Failed to cleanup expired locks: %s", e)
|
|
852
|
+
|
|
853
|
+
# Resource-level locking methods
|
|
854
|
+
|
|
855
|
+
async def acquire_resource_lock(
|
|
856
|
+
self,
|
|
857
|
+
resource_id: str,
|
|
858
|
+
mode: str = "EXCLUSIVE",
|
|
859
|
+
timeout: int | None = None, # noqa: ASYNC109
|
|
860
|
+
) -> bool: # noqa: ASYNC109
|
|
861
|
+
"""Acquire a resource-level lock.
|
|
862
|
+
|
|
863
|
+
Args:
|
|
864
|
+
resource_id: Full resource identifier (e.g., "stack.aws_instance.web")
|
|
865
|
+
mode: Lock mode - "SHARED" or "EXCLUSIVE"
|
|
866
|
+
timeout: Lock timeout in seconds (uses default if None)
|
|
867
|
+
|
|
868
|
+
Returns:
|
|
869
|
+
True if lock acquired, False otherwise
|
|
870
|
+
|
|
871
|
+
"""
|
|
872
|
+
if mode not in ("SHARED", "EXCLUSIVE"):
|
|
873
|
+
raise ValueError("Lock mode must be 'SHARED' or 'EXCLUSIVE'")
|
|
874
|
+
|
|
875
|
+
timeout = timeout or self.lock_timeout
|
|
876
|
+
pool = await self._get_pool()
|
|
877
|
+
|
|
878
|
+
try:
|
|
879
|
+
async with pool.acquire() as conn:
|
|
880
|
+
async with conn.transaction():
|
|
881
|
+
# Use PostgreSQL advisory locks to serialize attempts per resource
|
|
882
|
+
key1, key2 = self._advisory_key(resource_id)
|
|
883
|
+
if mode == "EXCLUSIVE":
|
|
884
|
+
got_lock = await conn.fetchval(
|
|
885
|
+
"SELECT pg_try_advisory_xact_lock($1, $2)",
|
|
886
|
+
key1,
|
|
887
|
+
key2,
|
|
888
|
+
)
|
|
889
|
+
else:
|
|
890
|
+
# Shared advisory lock allows concurrent SHARED holders but blocks EXCLUSIVE
|
|
891
|
+
got_lock = await conn.fetchval(
|
|
892
|
+
"SELECT pg_try_advisory_xact_lock_shared($1, $2)",
|
|
893
|
+
key1,
|
|
894
|
+
key2,
|
|
895
|
+
)
|
|
896
|
+
if not got_lock:
|
|
897
|
+
logger.warning(
|
|
898
|
+
"Advisory lock conflict for resource %s",
|
|
899
|
+
resource_id,
|
|
900
|
+
)
|
|
901
|
+
return False
|
|
902
|
+
|
|
903
|
+
# Clean up expired locks first
|
|
904
|
+
await self._cleanup_expired_resource_locks(conn)
|
|
905
|
+
|
|
906
|
+
# Use a stored procedure or CTE for atomic lock acquisition
|
|
907
|
+
if mode == "EXCLUSIVE":
|
|
908
|
+
# For EXCLUSIVE locks, ensure no other locks exist for this resource
|
|
909
|
+
result = await conn.execute(
|
|
910
|
+
f"""
|
|
911
|
+
WITH lock_check AS (
|
|
912
|
+
SELECT COUNT(*) as existing_locks
|
|
913
|
+
FROM {self.schema}.{self.table_prefix}resource_locks
|
|
914
|
+
WHERE resource_id = $1 AND expires_at > NOW()
|
|
915
|
+
)
|
|
916
|
+
INSERT INTO {self.schema}.{self.table_prefix}resource_locks
|
|
917
|
+
(resource_id, holder_id, lock_mode, state_id, expires_at)
|
|
918
|
+
SELECT $1, $2, $3, $4, NOW() + INTERVAL '{timeout} seconds'
|
|
919
|
+
FROM lock_check
|
|
920
|
+
WHERE existing_locks = 0
|
|
921
|
+
ON CONFLICT (resource_id, holder_id)
|
|
922
|
+
DO UPDATE SET
|
|
923
|
+
lock_mode = EXCLUDED.lock_mode,
|
|
924
|
+
expires_at = EXCLUDED.expires_at
|
|
925
|
+
WHERE (SELECT COUNT(*) FROM {self.schema}.{self.table_prefix}resource_locks
|
|
926
|
+
WHERE resource_id = $1 AND expires_at > NOW() AND holder_id != $2) = 0
|
|
927
|
+
""",
|
|
928
|
+
resource_id,
|
|
929
|
+
self._holder_id,
|
|
930
|
+
mode,
|
|
931
|
+
self.state_id,
|
|
932
|
+
)
|
|
933
|
+
else:
|
|
934
|
+
# For SHARED locks, ensure no EXCLUSIVE locks exist for this resource
|
|
935
|
+
result = await conn.execute(
|
|
936
|
+
f"""
|
|
937
|
+
WITH lock_check AS (
|
|
938
|
+
SELECT COUNT(*) as exclusive_locks
|
|
939
|
+
FROM {self.schema}.{self.table_prefix}resource_locks
|
|
940
|
+
WHERE resource_id = $1 AND lock_mode = 'EXCLUSIVE' AND expires_at > NOW()
|
|
941
|
+
)
|
|
942
|
+
INSERT INTO {self.schema}.{self.table_prefix}resource_locks
|
|
943
|
+
(resource_id, holder_id, lock_mode, state_id, expires_at)
|
|
944
|
+
SELECT $1, $2, $3, $4, NOW() + INTERVAL '{timeout} seconds'
|
|
945
|
+
FROM lock_check
|
|
946
|
+
WHERE exclusive_locks = 0
|
|
947
|
+
ON CONFLICT (resource_id, holder_id)
|
|
948
|
+
DO UPDATE SET
|
|
949
|
+
lock_mode = EXCLUDED.lock_mode,
|
|
950
|
+
expires_at = EXCLUDED.expires_at
|
|
951
|
+
WHERE (SELECT COUNT(*) FROM {self.schema}.{self.table_prefix}resource_locks
|
|
952
|
+
WHERE resource_id = $1 AND lock_mode = 'EXCLUSIVE' AND expires_at > NOW()) = 0
|
|
953
|
+
""",
|
|
954
|
+
resource_id,
|
|
955
|
+
self._holder_id,
|
|
956
|
+
mode,
|
|
957
|
+
self.state_id,
|
|
958
|
+
)
|
|
959
|
+
|
|
960
|
+
# Check if lock was acquired
|
|
961
|
+
acquired = result.startswith("INSERT") and "0 1" in result
|
|
962
|
+
if acquired:
|
|
963
|
+
self._resource_locks.add(resource_id)
|
|
964
|
+
logger.info("Acquired %s lock on resource: %s", mode, resource_id)
|
|
965
|
+
return True
|
|
966
|
+
logger.warning(
|
|
967
|
+
"Resource lock conflict for %s (mode: %s)",
|
|
968
|
+
resource_id,
|
|
969
|
+
mode,
|
|
970
|
+
)
|
|
971
|
+
return False
|
|
972
|
+
|
|
973
|
+
except Exception as e:
|
|
974
|
+
logger.error("Failed to acquire resource lock for %s: %s", resource_id, e)
|
|
975
|
+
return False
|
|
976
|
+
|
|
977
|
+
async def release_resource_lock(self, resource_id: str) -> bool:
|
|
978
|
+
"""Release a resource-level lock.
|
|
979
|
+
|
|
980
|
+
Args:
|
|
981
|
+
resource_id: Full resource identifier
|
|
982
|
+
|
|
983
|
+
Returns:
|
|
984
|
+
True if lock released, False if not found
|
|
985
|
+
|
|
986
|
+
"""
|
|
987
|
+
pool = await self._get_pool()
|
|
988
|
+
|
|
989
|
+
try:
|
|
990
|
+
async with pool.acquire() as conn:
|
|
991
|
+
result = await conn.execute(
|
|
992
|
+
f"""
|
|
993
|
+
DELETE FROM {self.schema}.{self.table_prefix}resource_locks
|
|
994
|
+
WHERE resource_id = $1 AND holder_id = $2
|
|
995
|
+
""",
|
|
996
|
+
resource_id,
|
|
997
|
+
self._holder_id,
|
|
998
|
+
)
|
|
999
|
+
|
|
1000
|
+
if result == "DELETE 1":
|
|
1001
|
+
self._resource_locks.discard(resource_id)
|
|
1002
|
+
logger.info("Released resource lock: %s", resource_id)
|
|
1003
|
+
return True
|
|
1004
|
+
logger.warning(
|
|
1005
|
+
"Resource lock not found or not owned: %s",
|
|
1006
|
+
resource_id,
|
|
1007
|
+
)
|
|
1008
|
+
return False
|
|
1009
|
+
|
|
1010
|
+
except Exception as e:
|
|
1011
|
+
logger.error("Failed to release resource lock for %s: %s", resource_id, e)
|
|
1012
|
+
return False
|
|
1013
|
+
|
|
1014
|
+
async def release_all_resource_locks(self) -> int:
|
|
1015
|
+
"""Release all resource locks held by this backend instance.
|
|
1016
|
+
|
|
1017
|
+
Returns:
|
|
1018
|
+
Number of locks released
|
|
1019
|
+
|
|
1020
|
+
"""
|
|
1021
|
+
pool = await self._get_pool()
|
|
1022
|
+
|
|
1023
|
+
try:
|
|
1024
|
+
async with pool.acquire() as conn:
|
|
1025
|
+
result = await conn.execute(
|
|
1026
|
+
f"""
|
|
1027
|
+
DELETE FROM {self.schema}.{self.table_prefix}resource_locks
|
|
1028
|
+
WHERE holder_id = $1
|
|
1029
|
+
""",
|
|
1030
|
+
self._holder_id,
|
|
1031
|
+
)
|
|
1032
|
+
|
|
1033
|
+
count = int(result.split()[-1]) if result.startswith("DELETE") else 0
|
|
1034
|
+
if count > 0:
|
|
1035
|
+
self._resource_locks.clear()
|
|
1036
|
+
logger.info("Released %s resource locks", count)
|
|
1037
|
+
return count
|
|
1038
|
+
|
|
1039
|
+
except Exception as e:
|
|
1040
|
+
logger.error("Failed to release resource locks: %s", e)
|
|
1041
|
+
return 0
|
|
1042
|
+
|
|
1043
|
+
async def _cleanup_expired_resource_locks(self, conn: asyncpg.Connection) -> None:
|
|
1044
|
+
"""Clean up expired resource locks."""
|
|
1045
|
+
try:
|
|
1046
|
+
result = await conn.execute(
|
|
1047
|
+
f"DELETE FROM {self.schema}.{self.table_prefix}resource_locks WHERE expires_at < NOW()",
|
|
1048
|
+
)
|
|
1049
|
+
if result != "DELETE 0":
|
|
1050
|
+
logger.info("Cleaned up expired resource locks: %s", result)
|
|
1051
|
+
except Exception as e:
|
|
1052
|
+
logger.warning("Failed to cleanup expired resource locks: %s", e)
|
|
1053
|
+
|
|
1054
|
+
@asynccontextmanager
|
|
1055
|
+
async def resource_lock_context(
|
|
1056
|
+
self,
|
|
1057
|
+
resource_id: str,
|
|
1058
|
+
mode: str = "EXCLUSIVE",
|
|
1059
|
+
) -> AsyncGenerator[bool]:
|
|
1060
|
+
"""Context manager for resource-level locking.
|
|
1061
|
+
|
|
1062
|
+
Usage:
|
|
1063
|
+
async with backend.resource_lock_context("stack.aws_instance.web") as locked:
|
|
1064
|
+
if locked:
|
|
1065
|
+
# Resource is locked, safe to modify
|
|
1066
|
+
pass
|
|
1067
|
+
"""
|
|
1068
|
+
acquired = await self.acquire_resource_lock(resource_id, mode)
|
|
1069
|
+
try:
|
|
1070
|
+
yield acquired
|
|
1071
|
+
finally:
|
|
1072
|
+
if acquired:
|
|
1073
|
+
await self.release_resource_lock(resource_id)
|
|
1074
|
+
|
|
1075
|
+
# Heartbeat and lock renewal methods
|
|
1076
|
+
|
|
1077
|
+
async def _start_heartbeat(self) -> None:
|
|
1078
|
+
"""Start heartbeat task for lock renewal."""
|
|
1079
|
+
if self.heartbeat_interval <= 0:
|
|
1080
|
+
return
|
|
1081
|
+
if self._heartbeat_thread and self._heartbeat_thread.is_alive():
|
|
1082
|
+
return
|
|
1083
|
+
self._heartbeat_stop.clear()
|
|
1084
|
+
self._heartbeat_thread = threading.Thread(
|
|
1085
|
+
target=self._heartbeat_worker,
|
|
1086
|
+
daemon=True,
|
|
1087
|
+
)
|
|
1088
|
+
self._heartbeat_thread.start()
|
|
1089
|
+
logger.debug("Started heartbeat thread for lock renewal")
|
|
1090
|
+
|
|
1091
|
+
async def _stop_heartbeat(self) -> None:
|
|
1092
|
+
"""Stop heartbeat task."""
|
|
1093
|
+
if not self._heartbeat_thread:
|
|
1094
|
+
return
|
|
1095
|
+
self._heartbeat_stop.set()
|
|
1096
|
+
with suppress(Exception):
|
|
1097
|
+
self._heartbeat_thread.join(timeout=1)
|
|
1098
|
+
self._heartbeat_thread = None
|
|
1099
|
+
logger.debug("Stopped heartbeat thread")
|
|
1100
|
+
|
|
1101
|
+
def _heartbeat_worker(self) -> None:
|
|
1102
|
+
"""Background thread that renews locks periodically."""
|
|
1103
|
+
try:
|
|
1104
|
+
while not self._heartbeat_stop.wait(self.heartbeat_interval):
|
|
1105
|
+
try:
|
|
1106
|
+
self._run_sync(self._renew_locks)
|
|
1107
|
+
except Exception as exc:
|
|
1108
|
+
logger.error("Error in heartbeat thread: %s", exc)
|
|
1109
|
+
except Exception as exc:
|
|
1110
|
+
logger.error("Heartbeat thread stopped with error: %s", exc)
|
|
1111
|
+
|
|
1112
|
+
async def _renew_locks(self) -> None:
|
|
1113
|
+
"""Renew all held locks."""
|
|
1114
|
+
try:
|
|
1115
|
+
pool = await self._get_pool()
|
|
1116
|
+
async with pool.acquire() as conn:
|
|
1117
|
+
# Renew state lock if held
|
|
1118
|
+
if self._lock_id:
|
|
1119
|
+
result = await conn.execute(
|
|
1120
|
+
f"""
|
|
1121
|
+
UPDATE {self.schema}.{self.table_prefix}locks
|
|
1122
|
+
SET expires_at = NOW() + INTERVAL '{self.lock_timeout} seconds'
|
|
1123
|
+
WHERE state_id = $1 AND holder_id = $2
|
|
1124
|
+
""",
|
|
1125
|
+
self._lock_id,
|
|
1126
|
+
self._holder_id,
|
|
1127
|
+
)
|
|
1128
|
+
if result == "UPDATE 1":
|
|
1129
|
+
logger.debug(f"Renewed state lock: {self._lock_id}")
|
|
1130
|
+
else:
|
|
1131
|
+
logger.warning(f"Failed to renew state lock: {self._lock_id}")
|
|
1132
|
+
self._lock_id = None
|
|
1133
|
+
|
|
1134
|
+
# Renew resource locks if any
|
|
1135
|
+
if self._resource_locks:
|
|
1136
|
+
for resource_id in list(self._resource_locks):
|
|
1137
|
+
result = await conn.execute(
|
|
1138
|
+
f"""
|
|
1139
|
+
UPDATE {self.schema}.{self.table_prefix}resource_locks
|
|
1140
|
+
SET expires_at = NOW() + INTERVAL '{self.lock_timeout} seconds'
|
|
1141
|
+
WHERE resource_id = $1 AND holder_id = $2
|
|
1142
|
+
""",
|
|
1143
|
+
resource_id,
|
|
1144
|
+
self._holder_id,
|
|
1145
|
+
)
|
|
1146
|
+
if result == "UPDATE 1":
|
|
1147
|
+
logger.debug("Renewed resource lock: %s", resource_id)
|
|
1148
|
+
else:
|
|
1149
|
+
logger.warning(
|
|
1150
|
+
"Failed to renew resource lock: %s",
|
|
1151
|
+
resource_id,
|
|
1152
|
+
)
|
|
1153
|
+
self._resource_locks.discard(resource_id)
|
|
1154
|
+
|
|
1155
|
+
except Exception as e:
|
|
1156
|
+
logger.error("Failed to renew locks: %s", e)
|
|
1157
|
+
|
|
1158
|
+
# Cleanup methods
|
|
1159
|
+
|
|
1160
|
+
async def close(self) -> None:
|
|
1161
|
+
"""Close the connection pool and release all locks."""
|
|
1162
|
+
try:
|
|
1163
|
+
await self._close_async()
|
|
1164
|
+
except Exception as e:
|
|
1165
|
+
logger.error("Error during cleanup: %s", e)
|
|
1166
|
+
finally:
|
|
1167
|
+
self._shutdown_portal()
|
|
1168
|
+
|
|
1169
|
+
async def _close_async(self) -> None:
|
|
1170
|
+
"""Async cleanup logic."""
|
|
1171
|
+
# Stop heartbeat first
|
|
1172
|
+
await self._stop_heartbeat()
|
|
1173
|
+
|
|
1174
|
+
# Release all locks
|
|
1175
|
+
await self.release_all_resource_locks()
|
|
1176
|
+
await self._unlock_async()
|
|
1177
|
+
|
|
1178
|
+
# Close connection pools (all loops)
|
|
1179
|
+
current_loop = _loop_key()
|
|
1180
|
+
closed_pools: set[int] = set()
|
|
1181
|
+
for loop, pool in list(self._pools.items()):
|
|
1182
|
+
if pool and not pool._closed:
|
|
1183
|
+
closed_pools.add(id(pool))
|
|
1184
|
+
if loop is current_loop:
|
|
1185
|
+
await pool.close()
|
|
1186
|
+
else:
|
|
1187
|
+
terminate = getattr(pool, "terminate", None)
|
|
1188
|
+
if callable(terminate):
|
|
1189
|
+
terminate()
|
|
1190
|
+
else:
|
|
1191
|
+
with suppress(Exception):
|
|
1192
|
+
self._run_sync(pool.close)
|
|
1193
|
+
self._pools.clear()
|
|
1194
|
+
if self._pool and id(self._pool) not in closed_pools and hasattr(self._pool, "close"):
|
|
1195
|
+
try:
|
|
1196
|
+
await self._pool.close()
|
|
1197
|
+
except Exception:
|
|
1198
|
+
pass
|
|
1199
|
+
self._pool = None
|
|
1200
|
+
|
|
1201
|
+
def _shutdown_portal(self) -> None:
|
|
1202
|
+
"""Stop the blocking portal if running."""
|
|
1203
|
+
if self._portal_stack:
|
|
1204
|
+
with suppress(Exception):
|
|
1205
|
+
self._portal_stack.close()
|
|
1206
|
+
self._portal_stack = None
|
|
1207
|
+
self._portal = None
|