rillflow 0.1.0-alpha.8

Rillflow — a lightweight document + event store for Rust, powered by Postgres.
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
use std::sync::Arc;
use std::time::Duration;

use crate::{
    Error, Result, SessionContext,
    projections::ProjectionHandler,
    store::{TenantStrategy, tenant_schema_name},
};
use serde_json::Value;
use sqlx::{PgPool, types::Json};
use tracing::{info, instrument, warn};

#[derive(Clone)]
pub struct ProjectionWorkerConfig {
    pub batch_size: i64,
    pub max_retries: u32,
    pub base_backoff: Duration,
    pub max_backoff: Duration,
    pub lease_ttl: Duration,
    pub schema: String,
    pub notify_channel: Option<String>,
    pub tenant_strategy: TenantStrategy,
    pub tenant_resolver: Option<Arc<dyn Fn() -> Option<String> + Send + Sync>>,
}

impl Default for ProjectionWorkerConfig {
    fn default() -> Self {
        Self {
            batch_size: 500,
            max_retries: 3,
            base_backoff: Duration::from_secs(1),
            max_backoff: Duration::from_secs(30),
            lease_ttl: Duration::from_secs(30),
            schema: "public".to_string(),
            notify_channel: Some("rillflow_events".to_string()),
            tenant_strategy: TenantStrategy::Single,
            tenant_resolver: None,
        }
    }
}

#[derive(Clone)]
pub struct ProjectionRegistration {
    pub name: String,
    pub handler: Arc<dyn ProjectionHandler>,
}

pub struct ProjectionDaemon {
    pool: PgPool,
    config: ProjectionWorkerConfig,
    registrations: Vec<ProjectionRegistration>,
}

impl ProjectionDaemon {
    pub fn new(pool: PgPool, config: ProjectionWorkerConfig) -> Self {
        Self {
            pool,
            config,
            registrations: Vec::new(),
        }
    }

    pub fn builder(pool: PgPool) -> ProjectionDaemonBuilder {
        ProjectionDaemonBuilder {
            pool,
            config: ProjectionWorkerConfig::default(),
            registrations: Vec::new(),
        }
    }

    pub fn register(&mut self, name: impl Into<String>, handler: Arc<dyn ProjectionHandler>) {
        self.registrations.push(ProjectionRegistration {
            name: name.into(),
            handler,
        });
    }

    fn resolve_schema(&self, context: &SessionContext) -> Result<Option<String>> {
        match self.config.tenant_strategy {
            TenantStrategy::Single => Ok(Some(self.config.schema.clone())),
            TenantStrategy::SchemaPerTenant => {
                if let Some(ref tenant) = context.tenant {
                    Ok(Some(tenant_schema_name(tenant)))
                } else if let Some(resolver) = &self.config.tenant_resolver {
                    match resolver() {
                        Some(tenant) => Ok(Some(tenant_schema_name(&tenant))),
                        None => Err(crate::Error::TenantRequired),
                    }
                } else {
                    Err(crate::Error::TenantRequired)
                }
            }
        }
    }

    /// Long-running loop: ticks all projections, optionally LISTENs for event notifications to wake up.
    /// Stops when the provided stop flag becomes true.
    #[instrument(skip_all, fields(schema = %self.config.schema))]
    pub async fn run_loop(
        &self,
        use_notify: bool,
        stop_flag: Arc<std::sync::atomic::AtomicBool>,
    ) -> Result<()> {
        let mut listener = if use_notify {
            match sqlx::postgres::PgListener::connect_with(&self.pool).await {
                Ok(mut l) => {
                    if let Some(chan) = &self.config.notify_channel {
                        let _ = l.listen(chan).await;
                    }
                    Some(l)
                }
                Err(_) => None,
            }
        } else {
            None
        };

        loop {
            if stop_flag.load(std::sync::atomic::Ordering::Relaxed) {
                return Ok(());
            }
            let mut did_work = false;
            for r in &self.registrations {
                match self.tick_once(&r.name).await? {
                    TickResult::Processed { count } if count > 0 => did_work = true,
                    _ => {}
                }
            }
            if !did_work {
                if let Some(l) = &mut listener {
                    let _ = tokio::time::timeout(Duration::from_secs(5), l.recv()).await;
                } else {
                    tokio::time::sleep(Duration::from_millis(250)).await;
                }
            }
        }
    }

    /// Execute one processing tick for the given projection name (if registered).
    #[instrument(skip_all, fields(projection = %name, schema = %self.config.schema))]
    pub async fn tick_once(&self, name: &str) -> Result<TickResult> {
        let reg = self
            .registrations
            .iter()
            .find(|r| r.name == name)
            .ok_or_else(|| Error::UnknownProjection(name.to_string()))?;

        if self.is_paused(name).await? {
            return Ok(TickResult::Paused);
        }

        if let Some(until) = self.backoff_until(name).await? {
            // still in backoff; do nothing
            let now = chrono::Utc::now();
            if until > now {
                return Ok(TickResult::Backoff);
            }
        }

        if !self.acquire_lease(name).await? {
            return Ok(TickResult::LeasedByOther);
        }

        let mut tx = self.pool.begin().await?;
        let context = SessionContext::default();
        if let Some(schema) = self.resolve_schema(&context)? {
            let set_search_path = format!("set local search_path to {}", quote_ident(&schema));
            sqlx::query(&set_search_path).execute(&mut *tx).await?;
        }
        let last_seq: i64 = sqlx::query_scalar("select last_seq from projections where name = $1")
            .bind(name)
            .fetch_optional(&mut *tx)
            .await?
            .unwrap_or(0);

        let rows: Vec<(i64, String, Value)> = sqlx::query_as(
            "select global_seq, event_type, body from events where global_seq > $1 order by global_seq asc limit $2",
        )
        .bind(last_seq)
        .bind(self.config.batch_size)
        .fetch_all(&mut *tx)
        .await?;

        if rows.is_empty() {
            // refresh lease (touch) and exit
            self.refresh_lease(name).await?;
            tx.commit().await?;
            return Ok(TickResult::Idle);
        }

        let mut new_last = last_seq;
        let mut processed: usize = 0;
        for (seq, typ, body) in rows {
            // apply within the same transaction to keep read model + checkpoint atomic
            if let Err(err) = reg.handler.apply(&typ, &body, &mut tx).await {
                // record to DLQ, set backoff, advance checkpoint to skip poison pill for now
                warn!(error = %err, seq = seq, event_type = %typ, "projection handler failed; sending to DLQ and backing off");
                self.insert_dlq(&mut tx, name, seq, &typ, &body, &format!("{}", err))
                    .await?;
                self.increment_attempts_and_set_backoff(name).await?;
                new_last = seq;
                break;
            }

            new_last = seq;
            processed += 1;
            crate::metrics::record_proj_events_processed(context.tenant.as_deref(), 1);
        }

        self.persist_checkpoint(&mut tx, name, new_last).await?;
        tx.commit().await?;
        self.refresh_lease(name).await?;

        info!(
            processed = processed,
            last_seq = new_last,
            "tick processed batch"
        );
        Ok(TickResult::Processed {
            count: processed as u32,
        })
    }

    pub async fn tick_all_once(&self) -> Result<()> {
        for r in &self.registrations {
            let _ = self.tick_once(&r.name).await?;
        }
        Ok(())
    }

    /// Repeatedly tick until no projections have work remaining.
    pub async fn run_until_idle(&self) -> Result<()> {
        loop {
            let before = chrono::Utc::now();
            let mut did_work = false;
            for r in &self.registrations {
                match self.tick_once(&r.name).await? {
                    TickResult::Processed { count } if count > 0 => did_work = true,
                    _ => {}
                }
            }
            if !did_work {
                return Ok(());
            }
            // small guard to avoid hot-looping
            let elapsed = (chrono::Utc::now() - before).num_milliseconds();
            if elapsed < 5 {
                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
            }
        }
    }

    // --- Admin APIs ---

    pub async fn list(&self, tenant: Option<&str>) -> Result<Vec<ProjectionStatus>> {
        // Prefer registered names; if none, fall back to names found in DB.
        let mut names: Vec<String> = if self.registrations.is_empty() {
            self.discover_names().await?
        } else {
            self.registrations.iter().map(|r| r.name.clone()).collect()
        };
        names.sort();
        names.dedup();

        let mut out = Vec::new();
        for name in names {
            out.push(self.status(&name, tenant).await?);
        }
        Ok(out)
    }

    /// List DLQ items for a projection (most recent first)
    pub async fn dlq_list(
        &self,
        name: &str,
        limit: i64,
        tenant: Option<&str>,
    ) -> Result<Vec<ProjectionDlqItem>> {
        let mut tx = self.pool.begin().await?;
        if let Some(schema) = tenant.map(tenant_schema_name) {
            let stmt = format!("set local search_path to {}", quote_ident(&schema));
            sqlx::query(&stmt).execute(&mut *tx).await?;
        } else {
            let stmt = format!(
                "set local search_path to {}",
                quote_ident(&self.config.schema)
            );
            sqlx::query(&stmt).execute(&mut *tx).await?;
        }
        let rows: Vec<(i64, i64, String, chrono::DateTime<chrono::Utc>, String)> = sqlx::query_as(
            r#"select id, global_seq, event_type, failed_at, error
                from projection_dlq where name = $1
                order by id desc limit $2"#,
        )
        .bind(name)
        .bind(limit.max(1))
        .fetch_all(&mut *tx)
        .await?;
        tx.commit().await?;

        Ok(rows
            .into_iter()
            .map(|(id, seq, typ, failed_at, error)| ProjectionDlqItem {
                id,
                seq,
                event_type: typ,
                failed_at,
                error,
            })
            .collect())
    }

    /// Delete a single DLQ item
    pub async fn dlq_delete(&self, name: &str, id: i64, tenant: Option<&str>) -> Result<()> {
        let mut tx = self.pool.begin().await?;
        if let Some(schema) = tenant.map(tenant_schema_name) {
            let stmt = format!("set local search_path to {}", quote_ident(&schema));
            sqlx::query(&stmt).execute(&mut *tx).await?;
        } else {
            let stmt = format!(
                "set local search_path to {}",
                quote_ident(&self.config.schema)
            );
            sqlx::query(&stmt).execute(&mut *tx).await?;
        }
        sqlx::query("delete from projection_dlq where name = $1 and id = $2")
            .bind(name)
            .bind(id)
            .execute(&mut *tx)
            .await?;
        tx.commit().await?;
        Ok(())
    }

    /// Requeue a DLQ item by setting checkpoint to seq-1 and deleting the DLQ row
    pub async fn dlq_requeue(&self, name: &str, id: i64, tenant: Option<&str>) -> Result<()> {
        let schema_stmt = if let Some(schema) = tenant.map(tenant_schema_name) {
            format!("set local search_path to {}", quote_ident(&schema))
        } else {
            format!(
                "set local search_path to {}",
                quote_ident(&self.config.schema)
            )
        };
        let mut tx = self.pool.begin().await?;
        sqlx::query(&schema_stmt).execute(&mut *tx).await?;
        let rec: Option<i64> =
            sqlx::query_scalar("select global_seq from projection_dlq where name = $1 and id = $2")
                .bind(name)
                .bind(id)
                .fetch_optional(&mut *tx)
                .await?;
        if let Some(seq) = rec {
            let reset_to = seq.saturating_sub(1);
            self.reset_checkpoint(name, reset_to, tenant).await?;
            sqlx::query("delete from projection_dlq where name = $1 and id = $2")
                .bind(name)
                .bind(id)
                .execute(&mut *tx)
                .await?;
        }
        tx.commit().await?;
        Ok(())
    }

    pub async fn status(&self, name: &str, tenant: Option<&str>) -> Result<ProjectionStatus> {
        let schema = tenant
            .map(tenant_schema_name)
            .unwrap_or_else(|| self.config.schema.clone());
        let stmt = format!("set local search_path to {}", quote_ident(&schema));
        let mut tx = self.pool.begin().await?;
        sqlx::query(&stmt).execute(&mut *tx).await?;

        let last_seq: i64 = sqlx::query_scalar("select last_seq from projections where name = $1")
            .bind(name)
            .fetch_optional(&mut *tx)
            .await?
            .unwrap_or(0);

        let paused: bool =
            sqlx::query_scalar("select paused from projection_control where name = $1")
                .bind(name)
                .fetch_optional(&mut *tx)
                .await?
                .unwrap_or(false);

        let backoff_until: Option<chrono::DateTime<chrono::Utc>> =
            sqlx::query_scalar("select backoff_until from projection_control where name = $1")
                .bind(name)
                .fetch_optional(&mut *tx)
                .await?;

        let leased_by: Option<String> =
            sqlx::query_scalar("select leased_by from projection_leases where name = $1")
                .bind(name)
                .fetch_optional(&mut *tx)
                .await?;

        let lease_until: Option<chrono::DateTime<chrono::Utc>> =
            sqlx::query_scalar("select lease_until from projection_leases where name = $1")
                .bind(name)
                .fetch_optional(&mut *tx)
                .await?;

        let dlq_count: i64 =
            sqlx::query_scalar("select count(1) from projection_dlq where name = $1")
                .bind(name)
                .fetch_one(&mut *tx)
                .await?;

        tx.commit().await?;

        Ok(ProjectionStatus {
            name: name.to_string(),
            last_seq,
            paused,
            backoff_until,
            leased_by,
            lease_until,
            dlq_count,
        })
    }

    /// Compute simple metrics: last checkpoint, head of events, lag and DLQ size.
    pub async fn metrics(&self, name: &str, tenant: Option<&str>) -> Result<ProjectionMetrics> {
        let schema = tenant
            .map(tenant_schema_name)
            .unwrap_or_else(|| self.config.schema.clone());
        let stmt = format!("set local search_path to {}", quote_ident(&schema));
        let mut tx = self.pool.begin().await?;
        sqlx::query(&stmt).execute(&mut *tx).await?;

        let last_seq: i64 = sqlx::query_scalar("select last_seq from projections where name = $1")
            .bind(name)
            .fetch_optional(&mut *tx)
            .await?
            .unwrap_or(0);

        let head_seq: i64 = sqlx::query_scalar("select coalesce(max(global_seq), 0) from events")
            .fetch_one(&mut *tx)
            .await?;

        let dlq_count: i64 =
            sqlx::query_scalar("select count(1) from projection_dlq where name = $1")
                .bind(name)
                .fetch_one(&mut *tx)
                .await?;

        tx.commit().await?;

        Ok(ProjectionMetrics {
            name: name.to_string(),
            last_seq,
            head_seq,
            lag: (head_seq - last_seq).max(0),
            dlq_count,
        })
    }

    #[instrument(skip_all, fields(projection = %name))]
    pub async fn pause(&self, name: &str, tenant: Option<&str>) -> Result<()> {
        let schema = tenant
            .map(tenant_schema_name)
            .unwrap_or_else(|| self.config.schema.clone());
        let stmt = format!("set local search_path to {}", quote_ident(&schema));
        let mut tx = self.pool.begin().await?;
        sqlx::query(&stmt).execute(&mut *tx).await?;
        sqlx::query(
            r#"insert into projection_control(name, paused) values($1, true)
                on conflict (name) do update set paused = true, updated_at = now()"#,
        )
        .bind(name)
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;
        Ok(())
    }

    #[instrument(skip_all, fields(projection = %name))]
    pub async fn resume(&self, name: &str, tenant: Option<&str>) -> Result<()> {
        let schema = tenant
            .map(tenant_schema_name)
            .unwrap_or_else(|| self.config.schema.clone());
        let stmt = format!("set local search_path to {}", quote_ident(&schema));
        let mut tx = self.pool.begin().await?;
        sqlx::query(&stmt).execute(&mut *tx).await?;
        sqlx::query(
            r#"insert into projection_control(name, paused, backoff_until) values($1, false, null)
                on conflict (name) do update set paused = false, backoff_until = null, updated_at = now()"#,
        )
        .bind(name)
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;
        Ok(())
    }

    #[instrument(skip_all, fields(projection = %name, seq = seq))]
    pub async fn reset_checkpoint(&self, name: &str, seq: i64, tenant: Option<&str>) -> Result<()> {
        let mut tx = self.pool.begin().await?;
        if let Some(schema) = tenant.map(tenant_schema_name) {
            let stmt = format!("set local search_path to {}", quote_ident(&schema));
            sqlx::query(&stmt).execute(&mut *tx).await?;
        } else {
            let stmt = format!(
                "set local search_path to {}",
                quote_ident(&self.config.schema)
            );
            sqlx::query(&stmt).execute(&mut *tx).await?;
        }
        self.persist_checkpoint(&mut tx, name, seq).await?;
        tx.commit().await?;
        Ok(())
    }

    #[instrument(skip_all, fields(projection = %name))]
    pub async fn rebuild(&self, name: &str, tenant: Option<&str>) -> Result<()> {
        let mut tx = self.pool.begin().await?;
        if let Some(schema) = tenant.map(tenant_schema_name) {
            let stmt = format!("set local search_path to {}", quote_ident(&schema));
            sqlx::query(&stmt).execute(&mut *tx).await?;
        } else {
            let stmt = format!(
                "set local search_path to {}",
                quote_ident(&self.config.schema)
            );
            sqlx::query(&stmt).execute(&mut *tx).await?;
        }
        self.persist_checkpoint(&mut tx, name, 0).await?;
        sqlx::query("delete from projection_dlq where name = $1")
            .bind(name)
            .execute(&mut *tx)
            .await?;
        tx.commit().await?;
        Ok(())
    }

    // --- internals ---

    async fn is_paused(&self, name: &str) -> Result<bool> {
        let paused =
            sqlx::query_scalar::<_, bool>("select paused from projection_control where name = $1")
                .bind(name)
                .fetch_optional(&self.pool)
                .await?
                .unwrap_or(false);
        Ok(paused)
    }

    async fn backoff_until(&self, name: &str) -> Result<Option<chrono::DateTime<chrono::Utc>>> {
        let ts = sqlx::query_scalar::<_, Option<chrono::DateTime<chrono::Utc>>>(
            "select backoff_until from projection_control where name = $1",
        )
        .bind(name)
        .fetch_optional(&self.pool)
        .await?;
        Ok(ts.flatten())
    }

    async fn increment_attempts_and_set_backoff(&self, name: &str) -> Result<()> {
        let attempts: i64 = sqlx::query_scalar(
            r#"insert into projection_control(name, attempts)
                   values ($1, 1)
                 on conflict (name) do update
                   set attempts = projection_control.attempts + 1,
                       updated_at = now()
                 returning attempts"#,
        )
        .bind(name)
        .fetch_one(&self.pool)
        .await?;

        let exp = attempts.saturating_sub(1).clamp(0, 16) as u32;
        let mut delay = self.config.base_backoff * (1u32 << exp);
        if delay > self.config.max_backoff {
            delay = self.config.max_backoff;
        }
        let until = chrono::Utc::now() + chrono::Duration::from_std(delay).unwrap();
        sqlx::query(
            r#"update projection_control set backoff_until = $2, updated_at = now() where name = $1"#,
        )
        .bind(name)
        .bind(until)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn acquire_lease(&self, name: &str) -> Result<bool> {
        let id = format!("pid-{}", std::process::id());
        let ttl = chrono::Utc::now() + chrono::Duration::from_std(self.config.lease_ttl).unwrap();

        // Optional advisory lock per projection name to reduce stampedes
        let _ = sqlx::query("select pg_try_advisory_xact_lock(hashtext($1)::bigint)")
            .bind(name)
            .execute(&self.pool)
            .await?;

        // Try to insert or update if expired
        let rows = sqlx::query(
            r#"
            insert into projection_leases(name, leased_by, lease_until)
            values ($1, $2, $3)
            on conflict (name) do update
              set leased_by = excluded.leased_by,
                  lease_until = excluded.lease_until,
                  updated_at = now()
              where projection_leases.lease_until <= now()
                 or projection_leases.leased_by = excluded.leased_by
            "#,
        )
        .bind(name)
        .bind(&id)
        .bind(ttl)
        .execute(&self.pool)
        .await?;

        if rows.rows_affected() > 0 {
            return Ok(true);
        }

        // If a row exists and not expired, we don't own it
        Ok(false)
    }

    async fn refresh_lease(&self, name: &str) -> Result<()> {
        let ttl = chrono::Utc::now() + chrono::Duration::from_std(self.config.lease_ttl).unwrap();
        sqlx::query(
            r#"update projection_leases set lease_until = $2, updated_at = now() where name = $1"#,
        )
        .bind(name)
        .bind(ttl)
        .execute(&self.pool)
        .await?;
        sqlx::query(
            r#"update projection_control set attempts = 0, backoff_until = null, updated_at = now() where name = $1"#,
        )
        .bind(name)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn insert_dlq(
        &self,
        tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
        name: &str,
        seq: i64,
        typ: &str,
        body: &Value,
        err_msg: &str,
    ) -> Result<()> {
        sqlx::query(
            "insert into projection_dlq(name, global_seq, event_type, body, error) values ($1,$2,$3,$4,$5)",
        )
        .bind(name)
        .bind(seq)
        .bind(typ)
        .bind(Json(body))
        .bind(err_msg)
        .execute(&mut **tx)
        .await?;
        Ok(())
    }

    async fn persist_checkpoint(
        &self,
        tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
        name: &str,
        last_seq: i64,
    ) -> Result<()> {
        sqlx::query(
            r#"
            insert into projections(name, last_seq) values ($1,$2)
            on conflict (name) do update set last_seq = excluded.last_seq, updated_at = now()
            "#,
        )
        .bind(name)
        .bind(last_seq)
        .execute(&mut **tx)
        .await?;
        Ok(())
    }

    async fn discover_names(&self) -> Result<Vec<String>> {
        // union of names present anywhere
        let mut names: Vec<String> = Vec::new();
        for sql in [
            "select name from projections",
            "select name from projection_control",
            "select name from projection_leases",
            "select distinct name from projection_dlq",
        ] {
            let mut rows: Vec<String> = sqlx::query_scalar(sql).fetch_all(&self.pool).await?;
            names.append(&mut rows);
        }
        names.sort();
        names.dedup();
        Ok(names)
    }
}

pub struct ProjectionDaemonBuilder {
    pool: PgPool,
    config: ProjectionWorkerConfig,
    registrations: Vec<ProjectionRegistration>,
}

impl ProjectionDaemonBuilder {
    pub fn schema(mut self, schema: impl Into<String>) -> Self {
        self.config.schema = schema.into();
        self
    }
    pub fn tenant_strategy(mut self, strategy: TenantStrategy) -> Self {
        self.config.tenant_strategy = strategy;
        self
    }
    pub fn tenant_resolver<F>(mut self, resolver: F) -> Self
    where
        F: Fn() -> Option<String> + Send + Sync + 'static,
    {
        self.config.tenant_resolver = Some(Arc::new(resolver));
        self
    }
    pub fn batch_size(mut self, size: i64) -> Self {
        self.config.batch_size = size.max(1);
        self
    }
    pub fn lease_ttl(mut self, ttl: Duration) -> Self {
        self.config.lease_ttl = ttl;
        self
    }
    pub fn backoff(mut self, base: Duration, max: Duration) -> Self {
        self.config.base_backoff = base;
        self.config.max_backoff = max;
        self
    }
    pub fn register(
        mut self,
        name: impl Into<String>,
        handler: Arc<dyn ProjectionHandler>,
    ) -> Self {
        self.registrations.push(ProjectionRegistration {
            name: name.into(),
            handler,
        });
        self
    }
    pub fn build(self) -> ProjectionDaemon {
        let mut daemon = ProjectionDaemon::new(self.pool, self.config);
        for r in self.registrations {
            daemon.registrations.push(r);
        }
        daemon
    }
}

#[derive(Clone, Debug)]
pub struct ProjectionStatus {
    pub name: String,
    pub last_seq: i64,
    pub paused: bool,
    pub backoff_until: Option<chrono::DateTime<chrono::Utc>>,
    pub leased_by: Option<String>,
    pub lease_until: Option<chrono::DateTime<chrono::Utc>>,
    pub dlq_count: i64,
}

#[derive(Clone, Debug)]
pub struct ProjectionMetrics {
    pub name: String,
    pub last_seq: i64,
    pub head_seq: i64,
    pub lag: i64,
    pub dlq_count: i64,
}

#[derive(Clone, Debug)]
pub enum TickResult {
    Idle,
    Paused,
    Backoff,
    LeasedByOther,
    Processed { count: u32 },
}

#[derive(Clone, Debug)]
pub struct ProjectionDlqItem {
    pub id: i64,
    pub seq: i64,
    pub event_type: String,
    pub failed_at: chrono::DateTime<chrono::Utc>,
    pub error: String,
}

fn quote_ident(value: &str) -> String {
    let escaped = value.replace('"', "\"\"");
    format!("\"{}\"", escaped)
}