pylon-storage 0.3.17

Pylon — realtime backend as a single Rust binary. Schema, policies, server functions, live queries, auth — one process.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! [`DataStore`] implementation backed by Postgres.
//!
//! Only available with the `postgres-live` feature. Wraps
//! [`LivePostgresAdapter`] behind a mutex to match the synchronous
//! `DataStore` trait contract.
//!
//! SQL dialect differences from SQLite:
//! - Parameters use `$1, $2, ...` instead of `?1, ?2, ...`
//! - `id` column is `TEXT PRIMARY KEY`
//! - No `PRAGMA` statements
//!
//! For now, the advanced operations (lookup with field validation,
//! query_filtered with operators, query_graph, link, unlink, transact)
//! reuse the SQLite quote_ident strategy but issue Postgres-dialect SQL.

#![cfg(feature = "postgres-live")]

use std::sync::Mutex;

use pylon_http::{DataError, DataStore};
use pylon_kernel::AppManifest;

use crate::pg_tx_store;
use crate::postgres::live::LivePostgresAdapter;

/// Wrapper that implements `DataStore` around `LivePostgresAdapter`.
///
/// Writes go through a mutex to align with the sync trait. This matches
/// SQLite's single-writer model. For true concurrent writes under Postgres,
/// a future enhancement can use a connection pool.
pub struct PostgresDataStore {
    inner: Mutex<LivePostgresAdapter>,
    manifest: AppManifest,
}

impl PostgresDataStore {
    pub fn connect(url: &str, manifest: AppManifest) -> Result<Self, DataError> {
        let adapter = LivePostgresAdapter::connect(url).map_err(Self::map_err)?;
        Ok(Self {
            inner: Mutex::new(adapter),
            manifest,
        })
    }

    fn map_err(e: crate::StorageError) -> DataError {
        DataError {
            code: e.code.to_string(),
            message: e.message,
        }
    }

    /// Run `body` inside a real Postgres transaction. The closure
    /// receives a `&dyn DataStore` that routes every read/write
    /// through the transaction's connection — reads see uncommitted
    /// writes from earlier in the same closure, just like SQLite's
    /// in-handler behavior.
    ///
    /// Commit on `Ok`, rollback on `Err`. Errors from the transaction
    /// infrastructure itself (mutex poisoning, BEGIN failure, COMMIT
    /// failure) propagate as `E::from(DataError)`.
    ///
    /// Used by `pylon-runtime` to wire TS-function `Mutation`
    /// handlers through PG transactions — the SQLite path uses
    /// BEGIN/COMMIT on a held connection; this is the equivalent.
    /// The mutex is held for the entire closure body, so concurrent
    /// PG mutations serialize. Acceptable given mutation handlers
    /// are usually fast and pylon's PG sessions are single-shard.
    /// Borrow the underlying postgres client for the duration of the
    /// closure. Used for one-shot bootstrap work (e.g. creating the
    /// CRDT sidecar table on runtime open) that doesn't need an
    /// explicit transaction. Held connection mutex prevents concurrent
    /// PG ops from racing — same single-writer model as every other
    /// CRUD path here.
    pub fn with_client<F, T, E>(&self, body: F) -> Result<T, E>
    where
        F: FnOnce(&mut postgres::Client) -> Result<T, E>,
        E: From<DataError>,
    {
        let mut guard = self.inner.lock().map_err(|_| {
            E::from(DataError {
                code: "LOCK_POISONED".into(),
                message: "connection mutex poisoned".into(),
            })
        })?;
        body(guard.client_mut())
    }

    /// Run `body` inside a real Postgres transaction, exposing the
    /// raw `&mut Transaction` so the caller can interleave CRDT
    /// snapshot writes, materialized entity writes, and FTS shadow
    /// maintenance through the SAME transaction. This is the
    /// atomicity primitive the runtime layer needs — without it, the
    /// snapshot persists as one autocommit and the row write as
    /// another, and a failure between them desyncs the CRDT layer
    /// from the materialized columns.
    ///
    /// Commits on `Ok`, rolls back (via Drop) on `Err`. Errors from
    /// the transaction infrastructure itself (lock poisoning, BEGIN,
    /// COMMIT) propagate as `E::from(DataError)`.
    ///
    /// **Do not nest.** This holds the inner connection mutex for
    /// the whole closure. Calling `with_transaction`, `with_client`,
    /// or another `with_transaction_raw` from inside the closure (or
    /// from any code that runs while `body` is on the stack) will
    /// deadlock — `std::sync::Mutex` is not re-entrant. The runtime
    /// path enforces this by structure: the closures only call free
    /// functions in `pg_tx_store` and `pg_search` that take the
    /// `&mut Transaction` directly.
    pub fn with_transaction_raw<F, T, E>(&self, body: F) -> Result<T, E>
    where
        F: FnOnce(&mut postgres::Transaction<'_>) -> Result<T, E>,
        E: From<DataError>,
    {
        let mut guard = self.inner.lock().map_err(|_| {
            E::from(DataError {
                code: "LOCK_POISONED".into(),
                message: "connection mutex poisoned".into(),
            })
        })?;
        let mut tx = guard.client_mut().transaction().map_err(|e| {
            E::from(DataError {
                code: "PG_BEGIN_FAILED".into(),
                message: format!("BEGIN failed: {e}"),
            })
        })?;
        match body(&mut tx) {
            Ok(value) => {
                tx.commit().map_err(|e| {
                    E::from(DataError {
                        code: "PG_COMMIT_FAILED".into(),
                        message: format!("COMMIT failed: {e}"),
                    })
                })?;
                Ok(value)
            }
            Err(e) => {
                // Drop runs implicit ROLLBACK against the postgres
                // connection. Caller's Err propagates as-is.
                drop(tx);
                Err(e)
            }
        }
    }

    /// Run a search query against an entity's PG-side FTS shadow
    /// (`_fts_<entity>`). Held connection is locked for the duration
    /// of the three round-trips (hits / total / facet counts) — same
    /// serialization model as every other read here.
    pub fn run_search(
        &self,
        entity: &str,
        config: &crate::search::SearchConfig,
        query: &crate::search::SearchQuery,
    ) -> Result<crate::search::SearchResult, crate::StorageError> {
        let mut guard = self.inner.lock().map_err(|_| crate::StorageError {
            code: "LOCK_POISONED".into(),
            message: "connection mutex poisoned".into(),
        })?;
        crate::pg_search::run_search(guard.client_mut(), entity, config, query)
    }

    pub fn with_transaction<F, T, E>(&self, body: F) -> Result<T, E>
    where
        F: FnOnce(&dyn DataStore) -> Result<T, E>,
        E: From<DataError>,
    {
        self.with_transaction_inner(None, body)
    }

    /// Variant of `with_transaction` that installs a runtime-supplied
    /// CRDT hook on the underlying `PgTxStore`. Used by FnOpsImpl's
    /// PG mutation path so a TS handler's `ctx.db.X` calls on
    /// `crdt: true` entities maintain the CRDT sidecar in the same
    /// transaction. Without the hook, those writes commit the
    /// materialized row but skip the LoroDoc snapshot — codex
    /// flagged this as a desync vector.
    pub fn with_transaction_crdt<F, T, E>(
        &self,
        crdt_hook: std::sync::Arc<dyn pg_tx_store::PgCrdtHook>,
        body: F,
    ) -> Result<T, E>
    where
        F: FnOnce(&dyn DataStore) -> Result<T, E>,
        E: From<DataError>,
    {
        self.with_transaction_inner(Some(crdt_hook), body)
    }

    fn with_transaction_inner<F, T, E>(
        &self,
        crdt_hook: Option<std::sync::Arc<dyn pg_tx_store::PgCrdtHook>>,
        body: F,
    ) -> Result<T, E>
    where
        F: FnOnce(&dyn DataStore) -> Result<T, E>,
        E: From<DataError>,
    {
        let mut guard = self.inner.lock().map_err(|_| {
            E::from(DataError {
                code: "LOCK_POISONED".into(),
                message: "connection mutex poisoned".into(),
            })
        })?;
        let tx = guard.client_mut().transaction().map_err(|e| {
            E::from(DataError {
                code: "PG_BEGIN_FAILED".into(),
                message: format!("BEGIN failed: {e}"),
            })
        })?;
        let store = match crdt_hook {
            Some(hook) => pg_tx_store::PgTxStore::with_crdt(tx, &self.manifest, hook),
            None => pg_tx_store::PgTxStore::new(tx, &self.manifest),
        };
        match body(&store) {
            Ok(value) => {
                store.commit().map_err(|e| {
                    E::from(DataError {
                        code: "PG_COMMIT_FAILED".into(),
                        message: format!("COMMIT failed: {e}"),
                    })
                })?;
                Ok(value)
            }
            Err(e) => {
                // PgTxStore::Drop runs ROLLBACK + on_rollback hook.
                drop(store);
                Err(e)
            }
        }
    }
}

impl DataStore for PostgresDataStore {
    fn manifest(&self) -> &AppManifest {
        &self.manifest
    }

    fn insert(&self, entity: &str, data: &serde_json::Value) -> Result<String, DataError> {
        // Wrap CRUD + search maintenance in one transaction so a failure
        // on the FTS shadow row rolls the entity insert back too. Without
        // this the entity row would commit on its own and the FTS row
        // would lag — search results would silently miss the new row.
        self.with_transaction(|store| store.insert(entity, data))
    }

    fn get_by_id(&self, entity: &str, id: &str) -> Result<Option<serde_json::Value>, DataError> {
        let mut guard = self.inner.lock().map_err(|_| DataError {
            code: "LOCK_POISONED".into(),
            message: "connection mutex poisoned".into(),
        })?;
        guard.get_by_id(entity, id).map_err(Self::map_err)
    }

    fn list(&self, entity: &str) -> Result<Vec<serde_json::Value>, DataError> {
        let mut guard = self.inner.lock().map_err(|_| DataError {
            code: "LOCK_POISONED".into(),
            message: "connection mutex poisoned".into(),
        })?;
        guard.list(entity).map_err(Self::map_err)
    }

    fn list_after(
        &self,
        entity: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Vec<serde_json::Value>, DataError> {
        let mut guard = self.inner.lock().map_err(|_| DataError {
            code: "LOCK_POISONED".into(),
            message: "connection mutex poisoned".into(),
        })?;
        guard
            .list_after(entity, after, limit)
            .map_err(Self::map_err)
    }

    fn update(&self, entity: &str, id: &str, data: &serde_json::Value) -> Result<bool, DataError> {
        // Same atomicity as `insert` — entity write + FTS rebuild share
        // one BEGIN/COMMIT.
        self.with_transaction(|store| store.update(entity, id, data))
    }

    fn delete(&self, entity: &str, id: &str) -> Result<bool, DataError> {
        // FK CASCADE on `_fts_<entity>.entity_id` would clean up
        // automatically, but PgTxStore::delete also runs the explicit
        // `apply_delete` so the maintenance contract matches SQLite.
        self.with_transaction(|store| store.delete(entity, id))
    }

    fn lookup(
        &self,
        entity: &str,
        field: &str,
        value: &str,
    ) -> Result<Option<serde_json::Value>, DataError> {
        // Validate the field against the manifest BEFORE quoting it into SQL.
        // Otherwise a caller could pass any string and we'd happily query an
        // arbitrary column (or get a Postgres error from a missing one).
        let ent = self
            .manifest
            .entities
            .iter()
            .find(|e| e.name == entity)
            .ok_or_else(|| DataError {
                code: "ENTITY_NOT_FOUND".into(),
                message: format!("Unknown entity: \"{entity}\""),
            })?;
        if field != "id" && !ent.fields.iter().any(|f| f.name == field) {
            return Err(DataError {
                code: "UNKNOWN_COLUMN".into(),
                message: format!("Unknown column \"{field}\" on entity \"{entity}\""),
            });
        }

        let mut guard = self.inner.lock().map_err(|_| DataError {
            code: "LOCK_POISONED".into(),
            message: "connection mutex poisoned".into(),
        })?;
        guard
            .lookup_field(entity, field, value)
            .map_err(Self::map_err)
    }

    fn link(
        &self,
        entity: &str,
        id: &str,
        relation: &str,
        target_id: &str,
    ) -> Result<bool, DataError> {
        let ent = self
            .manifest
            .entities
            .iter()
            .find(|e| e.name == entity)
            .ok_or_else(|| DataError {
                code: "ENTITY_NOT_FOUND".into(),
                message: format!("Unknown entity: \"{entity}\""),
            })?;
        let rel = ent
            .relations
            .iter()
            .find(|r| r.name == relation)
            .ok_or_else(|| DataError {
                code: "RELATION_NOT_FOUND".into(),
                message: format!("Relation \"{relation}\" not found"),
            })?;
        let data = serde_json::json!({ rel.field.clone(): target_id });
        self.update(entity, id, &data)
    }

    fn unlink(&self, entity: &str, id: &str, relation: &str) -> Result<bool, DataError> {
        let ent = self
            .manifest
            .entities
            .iter()
            .find(|e| e.name == entity)
            .ok_or_else(|| DataError {
                code: "ENTITY_NOT_FOUND".into(),
                message: format!("Unknown entity: \"{entity}\""),
            })?;
        let rel = ent
            .relations
            .iter()
            .find(|r| r.name == relation)
            .ok_or_else(|| DataError {
                code: "RELATION_NOT_FOUND".into(),
                message: format!("Relation \"{relation}\" not found"),
            })?;
        let data = serde_json::json!({ rel.field.clone(): serde_json::Value::Null });
        self.update(entity, id, &data)
    }

    fn aggregate(
        &self,
        entity: &str,
        spec: &serde_json::Value,
    ) -> Result<serde_json::Value, DataError> {
        let ent = self
            .manifest
            .entities
            .iter()
            .find(|e| e.name == entity)
            .ok_or_else(|| DataError {
                code: "ENTITY_NOT_FOUND".into(),
                message: format!("Unknown entity: \"{entity}\""),
            })?;
        let columns: Vec<String> = ent.fields.iter().map(|f| f.name.clone()).collect();

        let mut guard = self.inner.lock().map_err(|_| DataError {
            code: "LOCK_POISONED".into(),
            message: "connection mutex poisoned".into(),
        })?;
        guard
            .aggregate(entity, spec, &columns)
            .map_err(Self::map_err)
    }

    fn query_filtered(
        &self,
        entity: &str,
        filter: &serde_json::Value,
    ) -> Result<Vec<serde_json::Value>, DataError> {
        let ent = self
            .manifest
            .entities
            .iter()
            .find(|e| e.name == entity)
            .ok_or_else(|| DataError {
                code: "ENTITY_NOT_FOUND".into(),
                message: format!("Unknown entity: \"{entity}\""),
            })?;
        let columns: Vec<String> = ent.fields.iter().map(|f| f.name.clone()).collect();

        let mut guard = self.inner.lock().map_err(|_| DataError {
            code: "LOCK_POISONED".into(),
            message: "connection mutex poisoned".into(),
        })?;
        guard
            .query_filtered(entity, filter, &columns)
            .map_err(Self::map_err)
    }

    fn query_graph(&self, query: &serde_json::Value) -> Result<serde_json::Value, DataError> {
        let obj = query.as_object().ok_or_else(|| DataError {
            code: "INVALID_QUERY".into(),
            message: "Graph query must be a JSON object".into(),
        })?;
        let mut results = serde_json::Map::new();
        for (entity_name, opts) in obj {
            // Validate entity exists up front so the error matches the
            // SQLite path (`ENTITY_NOT_FOUND` not `PG_QUERY_FAILED`).
            let ent = self
                .manifest
                .entities
                .iter()
                .find(|e| e.name == *entity_name)
                .ok_or_else(|| DataError {
                    code: "ENTITY_NOT_FOUND".into(),
                    message: format!("Unknown entity: \"{entity_name}\""),
                })?;

            let filter = opts.get("where").cloned().unwrap_or(serde_json::json!({}));
            let rows = self.query_filtered(entity_name, &filter)?;

            // Apply `include` (relation expansion). One-to-many uses the
            // child side's FK; one-to-one / many-to-one calls get_by_id
            // on the target. Mirrors `Runtime::query_graph` so callers
            // see the same shape on both adapters.
            let rows = if let Some(include) = opts.get("include").and_then(|v| v.as_object()) {
                rows.into_iter()
                    .map(|mut row| {
                        for (rel_name, _sub_query) in include {
                            if let Some(rel) = ent.relations.iter().find(|r| r.name == *rel_name) {
                                let fk_value = row
                                    .get(&rel.field)
                                    .and_then(|v| v.as_str())
                                    .map(|s| s.to_string());
                                if let Some(fk) = fk_value {
                                    if rel.many {
                                        let sub_filter =
                                            serde_json::json!({ &rel.field: &fk });
                                        if let Ok(related) =
                                            self.query_filtered(&rel.target, &sub_filter)
                                        {
                                            row[rel_name] = serde_json::json!(related);
                                        }
                                    } else if let Ok(Some(related)) =
                                        self.get_by_id(&rel.target, &fk)
                                    {
                                        row[rel_name] = related;
                                    }
                                }
                            }
                        }
                        row
                    })
                    .collect()
            } else {
                rows
            };

            // Apply `limit` after expansion to match SQLite. Docs commit
            // to "the limit applies to the top-level rows," so trimming
            // pre-expansion would change semantics.
            let rows = if let Some(limit) = opts.get("limit").and_then(|v| v.as_u64()) {
                rows.into_iter().take(limit as usize).collect()
            } else {
                rows
            };

            results.insert(entity_name.clone(), serde_json::json!(rows));
        }
        Ok(serde_json::Value::Object(results))
    }

    fn transact(
        &self,
        ops: &[serde_json::Value],
    ) -> Result<(bool, Vec<serde_json::Value>), DataError> {
        use crate::pg_tx_store::{tx_delete, tx_insert, tx_update};

        // Validate every op shape up front so a malformed payload
        // doesn't open a tx and immediately roll back.
        #[derive(Clone)]
        enum Op<'a> {
            Insert {
                entity: &'a str,
                data: &'a serde_json::Value,
            },
            Update {
                entity: &'a str,
                id: &'a str,
                data: &'a serde_json::Value,
            },
            Delete {
                entity: &'a str,
                id: &'a str,
            },
        }

        let mut typed: Vec<Op<'_>> = Vec::with_capacity(ops.len());
        for op in ops {
            let op_type = op.get("op").and_then(|v| v.as_str()).unwrap_or("");
            let entity = op
                .get("entity")
                .and_then(|v| v.as_str())
                .ok_or_else(|| DataError {
                    code: "TX_INVALID_OP".into(),
                    message: "Each transact op must have an \"entity\" field".into(),
                })?;
            match op_type {
                "insert" => {
                    let data = op.get("data").ok_or_else(|| DataError {
                        code: "TX_INVALID_OP".into(),
                        message: "insert op requires \"data\"".into(),
                    })?;
                    typed.push(Op::Insert { entity, data });
                }
                "update" => {
                    let id = op
                        .get("id")
                        .and_then(|v| v.as_str())
                        .ok_or_else(|| DataError {
                            code: "TX_INVALID_OP".into(),
                            message: "update op requires \"id\"".into(),
                        })?;
                    let data = op.get("data").ok_or_else(|| DataError {
                        code: "TX_INVALID_OP".into(),
                        message: "update op requires \"data\"".into(),
                    })?;
                    typed.push(Op::Update { entity, id, data });
                }
                "delete" => {
                    let id = op
                        .get("id")
                        .and_then(|v| v.as_str())
                        .ok_or_else(|| DataError {
                            code: "TX_INVALID_OP".into(),
                            message: "delete op requires \"id\"".into(),
                        })?;
                    typed.push(Op::Delete { entity, id });
                }
                other => {
                    return Err(DataError {
                        code: "TX_INVALID_OP".into(),
                        message: format!("unknown op \"{other}\""),
                    });
                }
            }
        }

        // Run each op through the same `tx_*` helpers PgTxStore uses
        // — so FTS shadow rows + future maintenance hooks stay
        // consistent whether the batch arrived via /api/transact or
        // a TS mutation handler. Codex flagged that the previous path
        // bypassed FTS via `LivePostgresAdapter::transact`.
        let manifest = self.manifest.clone();
        self.with_transaction_raw(|tx| -> Result<(bool, Vec<serde_json::Value>), DataError> {
            let mut json_results: Vec<serde_json::Value> = Vec::with_capacity(typed.len());
            for op in &typed {
                let result = match op {
                    Op::Insert { entity, data } => {
                        let id = tx_insert(tx, &manifest, entity, data)?;
                        serde_json::json!({ "op": "insert", "id": id })
                    }
                    Op::Update { entity, id, data } => {
                        let updated = tx_update(tx, &manifest, entity, id, data)?;
                        serde_json::json!({ "op": "update", "id": id, "updated": updated })
                    }
                    Op::Delete { entity, id } => {
                        let deleted = tx_delete(tx, &manifest, entity, id)?;
                        serde_json::json!({ "op": "delete", "id": id, "deleted": deleted })
                    }
                };
                json_results.push(result);
            }
            Ok((true, json_results))
        })
    }
}