duroxide_pg/
provider.rs

1use anyhow::Result;
2use chrono::{TimeZone, Utc};
3use duroxide::providers::{
4    ExecutionInfo, ExecutionMetadata, InstanceInfo, OrchestrationItem, Provider, ProviderAdmin,
5    ProviderError, QueueDepths, SystemMetrics, WorkItem,
6};
7use duroxide::Event;
8use sqlx::{postgres::PgPoolOptions, Error as SqlxError, PgPool};
9use std::sync::Arc;
10use std::time::Duration;
11use std::time::{SystemTime, UNIX_EPOCH};
12use tokio::time::sleep;
13use tracing::{debug, error, instrument, warn};
14
15use crate::migrations::MigrationRunner;
16
17/// PostgreSQL-based provider for Duroxide durable orchestrations.
18///
19/// Implements the [`Provider`] and [`ProviderAdmin`] traits from Duroxide,
20/// storing orchestration state, history, and work queues in PostgreSQL.
21///
22/// # Example
23///
24/// ```rust,no_run
25/// use duroxide_pg::PostgresProvider;
26///
27/// # async fn example() -> anyhow::Result<()> {
28/// // Connect using DATABASE_URL or explicit connection string
29/// let provider = PostgresProvider::new("postgres://localhost/mydb").await?;
30///
31/// // Or use a custom schema for isolation
32/// let provider = PostgresProvider::new_with_schema(
33///     "postgres://localhost/mydb",
34///     Some("my_app"),
35/// ).await?;
36/// # Ok(())
37/// # }
38/// ```
39pub struct PostgresProvider {
40    pool: Arc<PgPool>,
41    schema_name: String,
42}
43
44impl PostgresProvider {
45    pub async fn new(database_url: &str) -> Result<Self> {
46        Self::new_with_schema(database_url, None).await
47    }
48
49    pub async fn new_with_schema(database_url: &str, schema_name: Option<&str>) -> Result<Self> {
50        let max_connections = std::env::var("DUROXIDE_PG_POOL_MAX")
51            .ok()
52            .and_then(|s| s.parse::<u32>().ok())
53            .unwrap_or(10);
54
55        let pool = PgPoolOptions::new()
56            .max_connections(max_connections)
57            .min_connections(1)
58            .acquire_timeout(std::time::Duration::from_secs(30))
59            .connect(database_url)
60            .await?;
61
62        let schema_name = schema_name.unwrap_or("public").to_string();
63
64        let provider = Self {
65            pool: Arc::new(pool),
66            schema_name: schema_name.clone(),
67        };
68
69        // Run migrations to initialize schema
70        let migration_runner = MigrationRunner::new(provider.pool.clone(), schema_name.clone());
71        migration_runner.migrate().await?;
72
73        Ok(provider)
74    }
75
76    #[instrument(skip(self), target = "duroxide::providers::postgres")]
77    pub async fn initialize_schema(&self) -> Result<()> {
78        // Schema initialization is now handled by migrations
79        // This method is kept for backward compatibility but delegates to migrations
80        let migration_runner = MigrationRunner::new(self.pool.clone(), self.schema_name.clone());
81        migration_runner.migrate().await?;
82        Ok(())
83    }
84
85    /// Get current timestamp in milliseconds (Unix epoch)
86    fn now_millis() -> i64 {
87        SystemTime::now()
88            .duration_since(UNIX_EPOCH)
89            .unwrap()
90            .as_millis() as i64
91    }
92
93    /// Get schema-qualified table name
94    fn table_name(&self, table: &str) -> String {
95        format!("{}.{}", self.schema_name, table)
96    }
97
98    /// Get the database pool (for testing)
99    pub fn pool(&self) -> &PgPool {
100        &self.pool
101    }
102
103    /// Get the schema name (for testing)
104    pub fn schema_name(&self) -> &str {
105        &self.schema_name
106    }
107
108    /// Convert sqlx::Error to ProviderError with proper classification
109    fn sqlx_to_provider_error(operation: &str, e: SqlxError) -> ProviderError {
110        match e {
111            SqlxError::Database(ref db_err) => {
112                // PostgreSQL error codes
113                let code_opt = db_err.code();
114                let code = code_opt.as_deref();
115                if code == Some("40P01") {
116                    // Deadlock detected
117                    ProviderError::retryable(operation, format!("Deadlock detected: {e}"))
118                } else if code == Some("40001") {
119                    // Serialization failure - permanent error (transaction conflict, not transient)
120                    ProviderError::permanent(operation, format!("Serialization failure: {e}"))
121                } else if code == Some("23505") {
122                    // Unique constraint violation (duplicate event)
123                    ProviderError::permanent(operation, format!("Duplicate detected: {e}"))
124                } else if code == Some("23503") {
125                    // Foreign key constraint violation
126                    ProviderError::permanent(operation, format!("Foreign key violation: {e}"))
127                } else {
128                    ProviderError::permanent(operation, format!("Database error: {e}"))
129                }
130            }
131            SqlxError::PoolClosed | SqlxError::PoolTimedOut => {
132                ProviderError::retryable(operation, format!("Connection pool error: {e}"))
133            }
134            SqlxError::Io(_) => ProviderError::retryable(operation, format!("I/O error: {e}")),
135            _ => ProviderError::permanent(operation, format!("Unexpected error: {e}")),
136        }
137    }
138
139    /// Clean up schema after tests (drops all tables and optionally the schema)
140    ///
141    /// **SAFETY**: Never drops the "public" schema itself, only tables within it.
142    /// Only drops the schema if it's a custom schema (not "public").
143    pub async fn cleanup_schema(&self) -> Result<()> {
144        // Call the stored procedure to drop all tables
145        sqlx::query(&format!("SELECT {}.cleanup_schema()", self.schema_name))
146            .execute(&*self.pool)
147            .await?;
148
149        // SAFETY: Never drop the "public" schema - it's a PostgreSQL system schema
150        // Only drop custom schemas created for testing
151        if self.schema_name != "public" {
152            sqlx::query(&format!(
153                "DROP SCHEMA IF EXISTS {} CASCADE",
154                self.schema_name
155            ))
156            .execute(&*self.pool)
157            .await?;
158        } else {
159            // Explicit safeguard: we only drop tables from public schema, never the schema itself
160            // This ensures we don't accidentally drop the default PostgreSQL schema
161        }
162
163        Ok(())
164    }
165}
166
167#[async_trait::async_trait]
168impl Provider for PostgresProvider {
169    fn name(&self) -> &str {
170        "duroxide-pg"
171    }
172
173    fn version(&self) -> &str {
174        env!("CARGO_PKG_VERSION")
175    }
176
177    #[instrument(skip(self), target = "duroxide::providers::postgres")]
178    async fn fetch_orchestration_item(
179        &self,
180        lock_timeout: Duration,
181        _poll_timeout: Duration,
182    ) -> Result<Option<(OrchestrationItem, String, u32)>, ProviderError> {
183        let start = std::time::Instant::now();
184
185        const MAX_RETRIES: u32 = 3;
186        const RETRY_DELAY_MS: u64 = 50;
187
188        // Convert Duration to milliseconds
189        let lock_timeout_ms = lock_timeout.as_millis() as i64;
190        let mut _last_error: Option<ProviderError> = None;
191
192        for attempt in 0..=MAX_RETRIES {
193            let now_ms = Self::now_millis();
194
195            let result: Result<
196                Option<(
197                    String,
198                    String,
199                    String,
200                    i64,
201                    serde_json::Value,
202                    serde_json::Value,
203                    String,
204                    i32,
205                )>,
206                SqlxError,
207            > = sqlx::query_as(&format!(
208                "SELECT * FROM {}.fetch_orchestration_item($1, $2)",
209                self.schema_name
210            ))
211            .bind(now_ms)
212            .bind(lock_timeout_ms)
213            .fetch_optional(&*self.pool)
214            .await;
215
216            let row = match result {
217                Ok(r) => r,
218                Err(e) => {
219                    let provider_err = Self::sqlx_to_provider_error("fetch_orchestration_item", e);
220                    if provider_err.is_retryable() && attempt < MAX_RETRIES {
221                        warn!(
222                            target = "duroxide::providers::postgres",
223                            operation = "fetch_orchestration_item",
224                            attempt = attempt + 1,
225                            error = %provider_err,
226                            "Retryable error, will retry"
227                        );
228                        _last_error = Some(provider_err);
229                        sleep(std::time::Duration::from_millis(
230                            RETRY_DELAY_MS * (attempt as u64 + 1),
231                        ))
232                        .await;
233                        continue;
234                    }
235                    return Err(provider_err);
236                }
237            };
238
239            if let Some((
240                instance_id,
241                orchestration_name,
242                orchestration_version,
243                execution_id,
244                history_json,
245                messages_json,
246                lock_token,
247                attempt_count,
248            )) = row
249            {
250                let history: Vec<Event> = serde_json::from_value(history_json).map_err(|e| {
251                    ProviderError::permanent(
252                        "fetch_orchestration_item",
253                        format!("Failed to deserialize history: {e}"),
254                    )
255                })?;
256
257                let messages: Vec<WorkItem> =
258                    serde_json::from_value(messages_json).map_err(|e| {
259                        ProviderError::permanent(
260                            "fetch_orchestration_item",
261                            format!("Failed to deserialize messages: {e}"),
262                        )
263                    })?;
264
265                let duration_ms = start.elapsed().as_millis() as u64;
266                debug!(
267                    target = "duroxide::providers::postgres",
268                    operation = "fetch_orchestration_item",
269                    instance_id = %instance_id,
270                    execution_id = execution_id,
271                    message_count = messages.len(),
272                    history_count = history.len(),
273                    attempt_count = attempt_count,
274                    duration_ms = duration_ms,
275                    attempts = attempt + 1,
276                    "Fetched orchestration item via stored procedure"
277                );
278
279                return Ok(Some((
280                    OrchestrationItem {
281                        instance: instance_id,
282                        orchestration_name,
283                        execution_id: execution_id as u64,
284                        version: orchestration_version,
285                        history,
286                        messages,
287                    },
288                    lock_token,
289                    attempt_count as u32,
290                )));
291            }
292
293            if attempt < MAX_RETRIES {
294                sleep(std::time::Duration::from_millis(RETRY_DELAY_MS)).await;
295            }
296        }
297
298        Ok(None)
299    }
300    #[instrument(skip(self), fields(lock_token = %lock_token, execution_id = execution_id), target = "duroxide::providers::postgres")]
301    async fn ack_orchestration_item(
302        &self,
303        lock_token: &str,
304        execution_id: u64,
305        history_delta: Vec<Event>,
306        worker_items: Vec<WorkItem>,
307        orchestrator_items: Vec<WorkItem>,
308        metadata: ExecutionMetadata,
309    ) -> Result<(), ProviderError> {
310        let start = std::time::Instant::now();
311
312        const MAX_RETRIES: u32 = 3;
313        const RETRY_DELAY_MS: u64 = 50;
314
315        let mut history_delta_payload = Vec::with_capacity(history_delta.len());
316        for event in &history_delta {
317            if event.event_id() == 0 {
318                return Err(ProviderError::permanent(
319                    "ack_orchestration_item",
320                    "event_id must be set by runtime",
321                ));
322            }
323
324            let event_json = serde_json::to_string(event).map_err(|e| {
325                ProviderError::permanent(
326                    "ack_orchestration_item",
327                    format!("Failed to serialize event: {e}"),
328                )
329            })?;
330
331            let event_type = format!("{event:?}")
332                .split('{')
333                .next()
334                .unwrap_or("Unknown")
335                .trim()
336                .to_string();
337
338            history_delta_payload.push(serde_json::json!({
339                "event_id": event.event_id(),
340                "event_type": event_type,
341                "event_data": event_json,
342            }));
343        }
344
345        let history_delta_json = serde_json::Value::Array(history_delta_payload);
346
347        let worker_items_json = serde_json::to_value(&worker_items).map_err(|e| {
348            ProviderError::permanent(
349                "ack_orchestration_item",
350                format!("Failed to serialize worker items: {e}"),
351            )
352        })?;
353
354        let orchestrator_items_json = serde_json::to_value(&orchestrator_items).map_err(|e| {
355            ProviderError::permanent(
356                "ack_orchestration_item",
357                format!("Failed to serialize orchestrator items: {e}"),
358            )
359        })?;
360
361        let metadata_json = serde_json::json!({
362            "orchestration_name": metadata.orchestration_name,
363            "orchestration_version": metadata.orchestration_version,
364            "status": metadata.status,
365            "output": metadata.output,
366        });
367
368        for attempt in 0..=MAX_RETRIES {
369            let result = sqlx::query(&format!(
370                "SELECT {}.ack_orchestration_item($1, $2, $3, $4, $5, $6)",
371                self.schema_name
372            ))
373            .bind(lock_token)
374            .bind(execution_id as i64)
375            .bind(&history_delta_json)
376            .bind(&worker_items_json)
377            .bind(&orchestrator_items_json)
378            .bind(&metadata_json)
379            .execute(&*self.pool)
380            .await;
381
382            match result {
383                Ok(_) => {
384                    let duration_ms = start.elapsed().as_millis() as u64;
385                    debug!(
386                        target = "duroxide::providers::postgres",
387                        operation = "ack_orchestration_item",
388                        execution_id = execution_id,
389                        history_count = history_delta.len(),
390                        worker_items_count = worker_items.len(),
391                        orchestrator_items_count = orchestrator_items.len(),
392                        duration_ms = duration_ms,
393                        attempts = attempt + 1,
394                        "Acknowledged orchestration item via stored procedure"
395                    );
396                    return Ok(());
397                }
398                Err(e) => {
399                    // Check for permanent errors first
400                    if let SqlxError::Database(db_err) = &e {
401                        if db_err.message().contains("Invalid lock token") {
402                            return Err(ProviderError::permanent(
403                                "ack_orchestration_item",
404                                "Invalid lock token",
405                            ));
406                        }
407                    } else if e.to_string().contains("Invalid lock token") {
408                        return Err(ProviderError::permanent(
409                            "ack_orchestration_item",
410                            "Invalid lock token",
411                        ));
412                    }
413
414                    let provider_err = Self::sqlx_to_provider_error("ack_orchestration_item", e);
415                    if provider_err.is_retryable() && attempt < MAX_RETRIES {
416                        warn!(
417                            target = "duroxide::providers::postgres",
418                            operation = "ack_orchestration_item",
419                            attempt = attempt + 1,
420                            error = %provider_err,
421                            "Retryable error, will retry"
422                        );
423                        sleep(std::time::Duration::from_millis(
424                            RETRY_DELAY_MS * (attempt as u64 + 1),
425                        ))
426                        .await;
427                        continue;
428                    }
429                    return Err(provider_err);
430                }
431            }
432        }
433
434        // Should never reach here, but just in case
435        Ok(())
436    }
437    #[instrument(skip(self), fields(lock_token = %lock_token), target = "duroxide::providers::postgres")]
438    async fn abandon_orchestration_item(
439        &self,
440        lock_token: &str,
441        delay: Option<Duration>,
442        ignore_attempt: bool,
443    ) -> Result<(), ProviderError> {
444        let start = std::time::Instant::now();
445        let delay_param: Option<i64> = delay.map(|d| d.as_millis() as i64);
446
447        let instance_id = match sqlx::query_scalar::<_, String>(&format!(
448            "SELECT {}.abandon_orchestration_item($1, $2, $3)",
449            self.schema_name
450        ))
451        .bind(lock_token)
452        .bind(delay_param)
453        .bind(ignore_attempt)
454        .fetch_one(&*self.pool)
455        .await
456        {
457            Ok(instance_id) => instance_id,
458            Err(e) => {
459                if let SqlxError::Database(db_err) = &e {
460                    if db_err.message().contains("Invalid lock token") {
461                        return Err(ProviderError::permanent(
462                            "abandon_orchestration_item",
463                            "Invalid lock token",
464                        ));
465                    }
466                } else if e.to_string().contains("Invalid lock token") {
467                    return Err(ProviderError::permanent(
468                        "abandon_orchestration_item",
469                        "Invalid lock token",
470                    ));
471                }
472
473                return Err(Self::sqlx_to_provider_error(
474                    "abandon_orchestration_item",
475                    e,
476                ));
477            }
478        };
479
480        let duration_ms = start.elapsed().as_millis() as u64;
481        debug!(
482            target = "duroxide::providers::postgres",
483            operation = "abandon_orchestration_item",
484            instance_id = %instance_id,
485            delay_ms = delay.map(|d| d.as_millis() as u64),
486            ignore_attempt = ignore_attempt,
487            duration_ms = duration_ms,
488            "Abandoned orchestration item via stored procedure"
489        );
490
491        Ok(())
492    }
493
494    #[instrument(skip(self), fields(instance = %instance), target = "duroxide::providers::postgres")]
495    async fn read(&self, instance: &str) -> Result<Vec<Event>, ProviderError> {
496        let event_data_rows: Vec<String> = sqlx::query_scalar(&format!(
497            "SELECT out_event_data FROM {}.fetch_history($1)",
498            self.schema_name
499        ))
500        .bind(instance)
501        .fetch_all(&*self.pool)
502        .await
503        .map_err(|e| Self::sqlx_to_provider_error("read", e))?;
504
505        Ok(event_data_rows
506            .into_iter()
507            .filter_map(|event_data| serde_json::from_str::<Event>(&event_data).ok())
508            .collect())
509    }
510
511    #[instrument(skip(self), fields(instance = %instance, execution_id = execution_id), target = "duroxide::providers::postgres")]
512    async fn append_with_execution(
513        &self,
514        instance: &str,
515        execution_id: u64,
516        new_events: Vec<Event>,
517    ) -> Result<(), ProviderError> {
518        if new_events.is_empty() {
519            return Ok(());
520        }
521
522        let mut events_payload = Vec::with_capacity(new_events.len());
523        for event in &new_events {
524            if event.event_id() == 0 {
525                error!(
526                    target = "duroxide::providers::postgres",
527                    operation = "append_with_execution",
528                    error_type = "validation_error",
529                    instance_id = %instance,
530                    execution_id = execution_id,
531                    "event_id must be set by runtime"
532                );
533                return Err(ProviderError::permanent(
534                    "append_with_execution",
535                    "event_id must be set by runtime",
536                ));
537            }
538
539            let event_json = serde_json::to_string(event).map_err(|e| {
540                ProviderError::permanent(
541                    "append_with_execution",
542                    format!("Failed to serialize event: {e}"),
543                )
544            })?;
545
546            let event_type = format!("{event:?}")
547                .split('{')
548                .next()
549                .unwrap_or("Unknown")
550                .trim()
551                .to_string();
552
553            events_payload.push(serde_json::json!({
554                "event_id": event.event_id(),
555                "event_type": event_type,
556                "event_data": event_json,
557            }));
558        }
559
560        let events_json = serde_json::Value::Array(events_payload);
561
562        sqlx::query(&format!(
563            "SELECT {}.append_history($1, $2, $3)",
564            self.schema_name
565        ))
566        .bind(instance)
567        .bind(execution_id as i64)
568        .bind(events_json)
569        .execute(&*self.pool)
570        .await
571        .map_err(|e| Self::sqlx_to_provider_error("append_with_execution", e))?;
572
573        debug!(
574            target = "duroxide::providers::postgres",
575            operation = "append_with_execution",
576            instance_id = %instance,
577            execution_id = execution_id,
578            event_count = new_events.len(),
579            "Appended history events via stored procedure"
580        );
581
582        Ok(())
583    }
584
585    #[instrument(skip(self), target = "duroxide::providers::postgres")]
586    async fn enqueue_for_worker(&self, item: WorkItem) -> Result<(), ProviderError> {
587        let work_item = serde_json::to_string(&item).map_err(|e| {
588            ProviderError::permanent(
589                "enqueue_worker_work",
590                format!("Failed to serialize work item: {e}"),
591            )
592        })?;
593
594        sqlx::query(&format!(
595            "SELECT {}.enqueue_worker_work($1)",
596            self.schema_name
597        ))
598        .bind(work_item)
599        .execute(&*self.pool)
600        .await
601        .map_err(|e| {
602            error!(
603                target = "duroxide::providers::postgres",
604                operation = "enqueue_worker_work",
605                error_type = "database_error",
606                error = %e,
607                "Failed to enqueue worker work"
608            );
609            Self::sqlx_to_provider_error("enqueue_worker_work", e)
610        })?;
611
612        Ok(())
613    }
614
615    #[instrument(skip(self), target = "duroxide::providers::postgres")]
616    async fn fetch_work_item(
617        &self,
618        lock_timeout: Duration,
619        _poll_timeout: Duration,
620    ) -> Result<Option<(WorkItem, String, u32)>, ProviderError> {
621        let start = std::time::Instant::now();
622
623        // Convert Duration to milliseconds
624        let lock_timeout_ms = lock_timeout.as_millis() as i64;
625
626        let row = match sqlx::query_as::<_, (String, String, i32)>(&format!(
627            "SELECT * FROM {}.fetch_work_item($1, $2)",
628            self.schema_name
629        ))
630        .bind(Self::now_millis())
631        .bind(lock_timeout_ms)
632        .fetch_optional(&*self.pool)
633        .await
634        {
635            Ok(row) => row,
636            Err(e) => {
637                return Err(Self::sqlx_to_provider_error("fetch_work_item", e));
638            }
639        };
640
641        let (work_item_json, lock_token, attempt_count) = match row {
642            Some(row) => row,
643            None => return Ok(None),
644        };
645
646        let work_item: WorkItem = serde_json::from_str(&work_item_json).map_err(|e| {
647            ProviderError::permanent(
648                "fetch_work_item",
649                format!("Failed to deserialize worker item: {e}"),
650            )
651        })?;
652
653        let duration_ms = start.elapsed().as_millis() as u64;
654
655        // Extract instance for logging - different work item types have different structures
656        let instance_id = match &work_item {
657            WorkItem::ActivityExecute { instance, .. } => instance.as_str(),
658            WorkItem::ActivityCompleted { instance, .. } => instance.as_str(),
659            WorkItem::ActivityFailed { instance, .. } => instance.as_str(),
660            WorkItem::StartOrchestration { instance, .. } => instance.as_str(),
661            WorkItem::TimerFired { instance, .. } => instance.as_str(),
662            WorkItem::ExternalRaised { instance, .. } => instance.as_str(),
663            WorkItem::CancelInstance { instance, .. } => instance.as_str(),
664            WorkItem::ContinueAsNew { instance, .. } => instance.as_str(),
665            WorkItem::SubOrchCompleted {
666                parent_instance, ..
667            } => parent_instance.as_str(),
668            WorkItem::SubOrchFailed {
669                parent_instance, ..
670            } => parent_instance.as_str(),
671        };
672
673        debug!(
674            target = "duroxide::providers::postgres",
675            operation = "fetch_work_item",
676            instance_id = %instance_id,
677            attempt_count = attempt_count,
678            duration_ms = duration_ms,
679            "Fetched activity work item via stored procedure"
680        );
681
682        Ok(Some((work_item, lock_token, attempt_count as u32)))
683    }
684
685    #[instrument(skip(self), fields(token = %token), target = "duroxide::providers::postgres")]
686    async fn ack_work_item(&self, token: &str, completion: WorkItem) -> Result<(), ProviderError> {
687        let start = std::time::Instant::now();
688
689        // Extract instance ID from completion WorkItem
690        let instance_id = match &completion {
691            WorkItem::ActivityCompleted { instance, .. }
692            | WorkItem::ActivityFailed { instance, .. } => instance,
693            _ => {
694                error!(
695                    target = "duroxide::providers::postgres",
696                    operation = "ack_worker",
697                    error_type = "invalid_completion_type",
698                    "Invalid completion work item type"
699                );
700                return Err(ProviderError::permanent(
701                    "ack_worker",
702                    "Invalid completion work item type",
703                ));
704            }
705        };
706
707        let completion_json = serde_json::to_string(&completion).map_err(|e| {
708            ProviderError::permanent("ack_worker", format!("Failed to serialize completion: {e}"))
709        })?;
710
711        // Call stored procedure to atomically delete worker item and enqueue completion
712        sqlx::query(&format!(
713            "SELECT {}.ack_worker($1, $2, $3)",
714            self.schema_name
715        ))
716        .bind(token)
717        .bind(instance_id)
718        .bind(completion_json)
719        .execute(&*self.pool)
720        .await
721        .map_err(|e| {
722            if e.to_string().contains("Worker queue item not found") {
723                error!(
724                    target = "duroxide::providers::postgres",
725                    operation = "ack_worker",
726                    error_type = "worker_item_not_found",
727                    token = %token,
728                    "Worker queue item not found or already processed"
729                );
730                ProviderError::permanent(
731                    "ack_worker",
732                    "Worker queue item not found or already processed",
733                )
734            } else {
735                Self::sqlx_to_provider_error("ack_worker", e)
736            }
737        })?;
738
739        let duration_ms = start.elapsed().as_millis() as u64;
740        debug!(
741            target = "duroxide::providers::postgres",
742            operation = "ack_worker",
743            instance_id = %instance_id,
744            duration_ms = duration_ms,
745            "Acknowledged worker and enqueued completion"
746        );
747
748        Ok(())
749    }
750
751    #[instrument(skip(self), fields(token = %token), target = "duroxide::providers::postgres")]
752    async fn renew_work_item_lock(
753        &self,
754        token: &str,
755        extend_for: Duration,
756    ) -> Result<(), ProviderError> {
757        let start = std::time::Instant::now();
758
759        // Get current time from application for consistent time reference
760        let now_ms = Self::now_millis();
761
762        // Convert Duration to seconds for the stored procedure
763        let extend_secs = extend_for.as_secs() as i64;
764
765        match sqlx::query(&format!(
766            "SELECT {}.renew_work_item_lock($1, $2, $3)",
767            self.schema_name
768        ))
769        .bind(token)
770        .bind(now_ms)
771        .bind(extend_secs)
772        .execute(&*self.pool)
773        .await
774        {
775            Ok(_) => {
776                let duration_ms = start.elapsed().as_millis() as u64;
777                debug!(
778                    target = "duroxide::providers::postgres",
779                    operation = "renew_work_item_lock",
780                    token = %token,
781                    extend_for_secs = extend_secs,
782                    duration_ms = duration_ms,
783                    "Work item lock renewed successfully"
784                );
785                Ok(())
786            }
787            Err(e) => {
788                if let SqlxError::Database(db_err) = &e {
789                    if db_err.message().contains("Lock token invalid") {
790                        return Err(ProviderError::permanent(
791                            "renew_work_item_lock",
792                            "Lock token invalid, expired, or already acked",
793                        ));
794                    }
795                } else if e.to_string().contains("Lock token invalid") {
796                    return Err(ProviderError::permanent(
797                        "renew_work_item_lock",
798                        "Lock token invalid, expired, or already acked",
799                    ));
800                }
801
802                Err(Self::sqlx_to_provider_error("renew_work_item_lock", e))
803            }
804        }
805    }
806
807    #[instrument(skip(self), fields(token = %token), target = "duroxide::providers::postgres")]
808    async fn abandon_work_item(
809        &self,
810        token: &str,
811        delay: Option<Duration>,
812        ignore_attempt: bool,
813    ) -> Result<(), ProviderError> {
814        let start = std::time::Instant::now();
815        let delay_param: Option<i64> = delay.map(|d| d.as_millis() as i64);
816
817        match sqlx::query(&format!(
818            "SELECT {}.abandon_work_item($1, $2, $3)",
819            self.schema_name
820        ))
821        .bind(token)
822        .bind(delay_param)
823        .bind(ignore_attempt)
824        .execute(&*self.pool)
825        .await
826        {
827            Ok(_) => {
828                let duration_ms = start.elapsed().as_millis() as u64;
829                debug!(
830                    target = "duroxide::providers::postgres",
831                    operation = "abandon_work_item",
832                    token = %token,
833                    delay_ms = delay.map(|d| d.as_millis() as u64),
834                    ignore_attempt = ignore_attempt,
835                    duration_ms = duration_ms,
836                    "Abandoned work item via stored procedure"
837                );
838                Ok(())
839            }
840            Err(e) => {
841                if let SqlxError::Database(db_err) = &e {
842                    if db_err.message().contains("Invalid lock token")
843                        || db_err.message().contains("already acked")
844                    {
845                        return Err(ProviderError::permanent(
846                            "abandon_work_item",
847                            "Invalid lock token or already acked",
848                        ));
849                    }
850                } else if e.to_string().contains("Invalid lock token")
851                    || e.to_string().contains("already acked")
852                {
853                    return Err(ProviderError::permanent(
854                        "abandon_work_item",
855                        "Invalid lock token or already acked",
856                    ));
857                }
858
859                Err(Self::sqlx_to_provider_error("abandon_work_item", e))
860            }
861        }
862    }
863
864    #[instrument(skip(self), fields(token = %token), target = "duroxide::providers::postgres")]
865    async fn renew_orchestration_item_lock(
866        &self,
867        token: &str,
868        extend_for: Duration,
869    ) -> Result<(), ProviderError> {
870        let start = std::time::Instant::now();
871
872        // Get current time from application for consistent time reference
873        let now_ms = Self::now_millis();
874
875        // Convert Duration to seconds for the stored procedure
876        let extend_secs = extend_for.as_secs() as i64;
877
878        match sqlx::query(&format!(
879            "SELECT {}.renew_orchestration_item_lock($1, $2, $3)",
880            self.schema_name
881        ))
882        .bind(token)
883        .bind(now_ms)
884        .bind(extend_secs)
885        .execute(&*self.pool)
886        .await
887        {
888            Ok(_) => {
889                let duration_ms = start.elapsed().as_millis() as u64;
890                debug!(
891                    target = "duroxide::providers::postgres",
892                    operation = "renew_orchestration_item_lock",
893                    token = %token,
894                    extend_for_secs = extend_secs,
895                    duration_ms = duration_ms,
896                    "Orchestration item lock renewed successfully"
897                );
898                Ok(())
899            }
900            Err(e) => {
901                if let SqlxError::Database(db_err) = &e {
902                    if db_err.message().contains("Lock token invalid")
903                        || db_err.message().contains("expired")
904                        || db_err.message().contains("already released")
905                    {
906                        return Err(ProviderError::permanent(
907                            "renew_orchestration_item_lock",
908                            "Lock token invalid, expired, or already released",
909                        ));
910                    }
911                } else if e.to_string().contains("Lock token invalid")
912                    || e.to_string().contains("expired")
913                    || e.to_string().contains("already released")
914                {
915                    return Err(ProviderError::permanent(
916                        "renew_orchestration_item_lock",
917                        "Lock token invalid, expired, or already released",
918                    ));
919                }
920
921                Err(Self::sqlx_to_provider_error(
922                    "renew_orchestration_item_lock",
923                    e,
924                ))
925            }
926        }
927    }
928
929    #[instrument(skip(self), target = "duroxide::providers::postgres")]
930    async fn enqueue_for_orchestrator(
931        &self,
932        item: WorkItem,
933        delay: Option<Duration>,
934    ) -> Result<(), ProviderError> {
935        let work_item = serde_json::to_string(&item).map_err(|e| {
936            ProviderError::permanent(
937                "enqueue_orchestrator_work",
938                format!("Failed to serialize work item: {e}"),
939            )
940        })?;
941
942        // Extract instance ID from WorkItem enum
943        let instance_id = match &item {
944            WorkItem::StartOrchestration { instance, .. }
945            | WorkItem::ActivityCompleted { instance, .. }
946            | WorkItem::ActivityFailed { instance, .. }
947            | WorkItem::TimerFired { instance, .. }
948            | WorkItem::ExternalRaised { instance, .. }
949            | WorkItem::CancelInstance { instance, .. }
950            | WorkItem::ContinueAsNew { instance, .. } => instance,
951            WorkItem::SubOrchCompleted {
952                parent_instance, ..
953            }
954            | WorkItem::SubOrchFailed {
955                parent_instance, ..
956            } => parent_instance,
957            WorkItem::ActivityExecute { .. } => {
958                return Err(ProviderError::permanent(
959                    "enqueue_orchestrator_work",
960                    "ActivityExecute should go to worker queue, not orchestrator queue",
961                ));
962            }
963        };
964
965        // Determine visible_at: use max of fire_at_ms (for TimerFired) and delay
966        let now_ms = Self::now_millis();
967
968        let visible_at_ms = if let WorkItem::TimerFired { fire_at_ms, .. } = &item {
969            if *fire_at_ms > 0 {
970                // Take max of fire_at_ms and delay (if provided)
971                if let Some(delay) = delay {
972                    std::cmp::max(*fire_at_ms, now_ms as u64 + delay.as_millis() as u64)
973                } else {
974                    *fire_at_ms
975                }
976            } else {
977                // fire_at_ms is 0, use delay or NOW()
978                delay
979                    .map(|d| now_ms as u64 + d.as_millis() as u64)
980                    .unwrap_or(now_ms as u64)
981            }
982        } else {
983            // Non-timer item: use delay or NOW()
984            delay
985                .map(|d| now_ms as u64 + d.as_millis() as u64)
986                .unwrap_or(now_ms as u64)
987        };
988
989        let visible_at = Utc
990            .timestamp_millis_opt(visible_at_ms as i64)
991            .single()
992            .ok_or_else(|| {
993                ProviderError::permanent(
994                    "enqueue_orchestrator_work",
995                    "Invalid visible_at timestamp",
996                )
997            })?;
998
999        // ⚠️ CRITICAL: DO NOT extract orchestration metadata - instance creation happens via ack_orchestration_item metadata
1000        // Pass NULL for orchestration_name, orchestration_version, execution_id parameters
1001
1002        // Call stored procedure to enqueue work
1003        sqlx::query(&format!(
1004            "SELECT {}.enqueue_orchestrator_work($1, $2, $3, $4, $5, $6)",
1005            self.schema_name
1006        ))
1007        .bind(instance_id)
1008        .bind(&work_item)
1009        .bind(visible_at)
1010        .bind::<Option<String>>(None) // orchestration_name - NULL
1011        .bind::<Option<String>>(None) // orchestration_version - NULL
1012        .bind::<Option<i64>>(None) // execution_id - NULL
1013        .execute(&*self.pool)
1014        .await
1015        .map_err(|e| {
1016            error!(
1017                target = "duroxide::providers::postgres",
1018                operation = "enqueue_orchestrator_work",
1019                error_type = "database_error",
1020                error = %e,
1021                instance_id = %instance_id,
1022                "Failed to enqueue orchestrator work"
1023            );
1024            Self::sqlx_to_provider_error("enqueue_orchestrator_work", e)
1025        })?;
1026
1027        debug!(
1028            target = "duroxide::providers::postgres",
1029            operation = "enqueue_orchestrator_work",
1030            instance_id = %instance_id,
1031            delay_ms = delay.map(|d| d.as_millis() as u64),
1032            "Enqueued orchestrator work"
1033        );
1034
1035        Ok(())
1036    }
1037
1038    #[instrument(skip(self), fields(instance = %instance), target = "duroxide::providers::postgres")]
1039    async fn read_with_execution(
1040        &self,
1041        instance: &str,
1042        execution_id: u64,
1043    ) -> Result<Vec<Event>, ProviderError> {
1044        let event_data_rows: Vec<String> = sqlx::query_scalar(&format!(
1045            "SELECT event_data FROM {} WHERE instance_id = $1 AND execution_id = $2 ORDER BY event_id",
1046            self.table_name("history")
1047        ))
1048        .bind(instance)
1049        .bind(execution_id as i64)
1050        .fetch_all(&*self.pool)
1051        .await
1052        .ok()
1053        .unwrap_or_default();
1054
1055        Ok(event_data_rows
1056            .into_iter()
1057            .filter_map(|event_data| serde_json::from_str::<Event>(&event_data).ok())
1058            .collect())
1059    }
1060
1061    fn as_management_capability(&self) -> Option<&dyn ProviderAdmin> {
1062        Some(self)
1063    }
1064}
1065
1066#[async_trait::async_trait]
1067impl ProviderAdmin for PostgresProvider {
1068    #[instrument(skip(self), target = "duroxide::providers::postgres")]
1069    async fn list_instances(&self) -> Result<Vec<String>, ProviderError> {
1070        sqlx::query_scalar(&format!(
1071            "SELECT instance_id FROM {}.list_instances()",
1072            self.schema_name
1073        ))
1074        .fetch_all(&*self.pool)
1075        .await
1076        .map_err(|e| Self::sqlx_to_provider_error("list_instances", e))
1077    }
1078
1079    #[instrument(skip(self), fields(status = %status), target = "duroxide::providers::postgres")]
1080    async fn list_instances_by_status(&self, status: &str) -> Result<Vec<String>, ProviderError> {
1081        sqlx::query_scalar(&format!(
1082            "SELECT instance_id FROM {}.list_instances_by_status($1)",
1083            self.schema_name
1084        ))
1085        .bind(status)
1086        .fetch_all(&*self.pool)
1087        .await
1088        .map_err(|e| Self::sqlx_to_provider_error("list_instances_by_status", e))
1089    }
1090
1091    #[instrument(skip(self), fields(instance = %instance), target = "duroxide::providers::postgres")]
1092    async fn list_executions(&self, instance: &str) -> Result<Vec<u64>, ProviderError> {
1093        let execution_ids: Vec<i64> = sqlx::query_scalar(&format!(
1094            "SELECT execution_id FROM {}.list_executions($1)",
1095            self.schema_name
1096        ))
1097        .bind(instance)
1098        .fetch_all(&*self.pool)
1099        .await
1100        .map_err(|e| Self::sqlx_to_provider_error("list_executions", e))?;
1101
1102        Ok(execution_ids.into_iter().map(|id| id as u64).collect())
1103    }
1104
1105    #[instrument(skip(self), fields(instance = %instance, execution_id = execution_id), target = "duroxide::providers::postgres")]
1106    async fn read_history_with_execution_id(
1107        &self,
1108        instance: &str,
1109        execution_id: u64,
1110    ) -> Result<Vec<Event>, ProviderError> {
1111        let event_data_rows: Vec<String> = sqlx::query_scalar(&format!(
1112            "SELECT out_event_data FROM {}.fetch_history_with_execution($1, $2)",
1113            self.schema_name
1114        ))
1115        .bind(instance)
1116        .bind(execution_id as i64)
1117        .fetch_all(&*self.pool)
1118        .await
1119        .map_err(|e| Self::sqlx_to_provider_error("read_execution", e))?;
1120
1121        event_data_rows
1122            .into_iter()
1123            .filter_map(|event_data| serde_json::from_str::<Event>(&event_data).ok())
1124            .collect::<Vec<Event>>()
1125            .into_iter()
1126            .map(Ok)
1127            .collect()
1128    }
1129
1130    #[instrument(skip(self), fields(instance = %instance), target = "duroxide::providers::postgres")]
1131    async fn read_history(&self, instance: &str) -> Result<Vec<Event>, ProviderError> {
1132        let execution_id = self.latest_execution_id(instance).await?;
1133        self.read_history_with_execution_id(instance, execution_id)
1134            .await
1135    }
1136
1137    #[instrument(skip(self), fields(instance = %instance), target = "duroxide::providers::postgres")]
1138    async fn latest_execution_id(&self, instance: &str) -> Result<u64, ProviderError> {
1139        sqlx::query_scalar(&format!(
1140            "SELECT {}.latest_execution_id($1)",
1141            self.schema_name
1142        ))
1143        .bind(instance)
1144        .fetch_optional(&*self.pool)
1145        .await
1146        .map_err(|e| Self::sqlx_to_provider_error("latest_execution_id", e))?
1147        .map(|id: i64| id as u64)
1148        .ok_or_else(|| ProviderError::permanent("latest_execution_id", "Instance not found"))
1149    }
1150
1151    #[instrument(skip(self), fields(instance = %instance), target = "duroxide::providers::postgres")]
1152    async fn get_instance_info(&self, instance: &str) -> Result<InstanceInfo, ProviderError> {
1153        let row: Option<(
1154            String,
1155            String,
1156            String,
1157            i64,
1158            chrono::DateTime<Utc>,
1159            Option<chrono::DateTime<Utc>>,
1160            Option<String>,
1161            Option<String>,
1162        )> = sqlx::query_as(&format!(
1163            "SELECT * FROM {}.get_instance_info($1)",
1164            self.schema_name
1165        ))
1166        .bind(instance)
1167        .fetch_optional(&*self.pool)
1168        .await
1169        .map_err(|e| Self::sqlx_to_provider_error("get_instance_info", e))?;
1170
1171        let (
1172            instance_id,
1173            orchestration_name,
1174            orchestration_version,
1175            current_execution_id,
1176            created_at,
1177            updated_at,
1178            status,
1179            output,
1180        ) =
1181            row.ok_or_else(|| ProviderError::permanent("get_instance_info", "Instance not found"))?;
1182
1183        Ok(InstanceInfo {
1184            instance_id,
1185            orchestration_name,
1186            orchestration_version,
1187            current_execution_id: current_execution_id as u64,
1188            status: status.unwrap_or_else(|| "Running".to_string()),
1189            output,
1190            created_at: created_at.timestamp_millis() as u64,
1191            updated_at: updated_at
1192                .map(|dt| dt.timestamp_millis() as u64)
1193                .unwrap_or(created_at.timestamp_millis() as u64),
1194        })
1195    }
1196
1197    #[instrument(skip(self), fields(instance = %instance, execution_id = execution_id), target = "duroxide::providers::postgres")]
1198    async fn get_execution_info(
1199        &self,
1200        instance: &str,
1201        execution_id: u64,
1202    ) -> Result<ExecutionInfo, ProviderError> {
1203        let row: Option<(
1204            i64,
1205            String,
1206            Option<String>,
1207            chrono::DateTime<Utc>,
1208            Option<chrono::DateTime<Utc>>,
1209            i64,
1210        )> = sqlx::query_as(&format!(
1211            "SELECT * FROM {}.get_execution_info($1, $2)",
1212            self.schema_name
1213        ))
1214        .bind(instance)
1215        .bind(execution_id as i64)
1216        .fetch_optional(&*self.pool)
1217        .await
1218        .map_err(|e| Self::sqlx_to_provider_error("get_execution_info", e))?;
1219
1220        let (exec_id, status, output, started_at, completed_at, event_count) = row
1221            .ok_or_else(|| ProviderError::permanent("get_execution_info", "Execution not found"))?;
1222
1223        Ok(ExecutionInfo {
1224            execution_id: exec_id as u64,
1225            status,
1226            output,
1227            started_at: started_at.timestamp_millis() as u64,
1228            completed_at: completed_at.map(|dt| dt.timestamp_millis() as u64),
1229            event_count: event_count as usize,
1230        })
1231    }
1232
1233    #[instrument(skip(self), target = "duroxide::providers::postgres")]
1234    async fn get_system_metrics(&self) -> Result<SystemMetrics, ProviderError> {
1235        let row: Option<(i64, i64, i64, i64, i64, i64)> = sqlx::query_as(&format!(
1236            "SELECT * FROM {}.get_system_metrics()",
1237            self.schema_name
1238        ))
1239        .fetch_optional(&*self.pool)
1240        .await
1241        .map_err(|e| Self::sqlx_to_provider_error("get_system_metrics", e))?;
1242
1243        let (
1244            total_instances,
1245            total_executions,
1246            running_instances,
1247            completed_instances,
1248            failed_instances,
1249            total_events,
1250        ) = row.ok_or_else(|| {
1251            ProviderError::permanent("get_system_metrics", "Failed to get system metrics")
1252        })?;
1253
1254        Ok(SystemMetrics {
1255            total_instances: total_instances as u64,
1256            total_executions: total_executions as u64,
1257            running_instances: running_instances as u64,
1258            completed_instances: completed_instances as u64,
1259            failed_instances: failed_instances as u64,
1260            total_events: total_events as u64,
1261        })
1262    }
1263
1264    #[instrument(skip(self), target = "duroxide::providers::postgres")]
1265    async fn get_queue_depths(&self) -> Result<QueueDepths, ProviderError> {
1266        let now_ms = Self::now_millis();
1267
1268        let row: Option<(i64, i64)> = sqlx::query_as(&format!(
1269            "SELECT * FROM {}.get_queue_depths($1)",
1270            self.schema_name
1271        ))
1272        .bind(now_ms)
1273        .fetch_optional(&*self.pool)
1274        .await
1275        .map_err(|e| Self::sqlx_to_provider_error("get_queue_depths", e))?;
1276
1277        let (orchestrator_queue, worker_queue) = row.ok_or_else(|| {
1278            ProviderError::permanent("get_queue_depths", "Failed to get queue depths")
1279        })?;
1280
1281        Ok(QueueDepths {
1282            orchestrator_queue: orchestrator_queue as usize,
1283            worker_queue: worker_queue as usize,
1284            timer_queue: 0, // Timers are in orchestrator queue with delayed visibility
1285        })
1286    }
1287}