Skip to main content

everruns_durable/persistence/postgres/
schedules.rs

1//! Implementation of [`crate::Schedules`].
2
3use super::*;
4
5#[async_trait]
6impl Schedules for PostgresWorkflowEventStore {
7    fn schedule_transaction_pool(&self) -> Option<PgPool> {
8        Some(self.pool.clone())
9    }
10    #[instrument(skip(self, schedule))]
11    async fn create_schedule(&self, schedule: CreateScheduleRow) -> Result<Uuid, StoreError> {
12        let mut connection = crate::schedule_transaction::connection(&self.pool)
13            .await
14            .map_err(|error| StoreError::Database(error.to_string()))?;
15        let id = Uuid::now_v7();
16
17        sqlx::query(
18            r#"
19            INSERT INTO durable_schedules (
20                id, name, description, cron_expression, timezone,
21                target_type, target_name, target_input, enabled,
22                max_concurrent, catch_up_missed, max_catch_up, retry_policy,
23                next_trigger_at
24            )
25            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
26            "#,
27        )
28        .bind(id)
29        .bind(&schedule.name)
30        .bind(&schedule.description)
31        .bind(&schedule.cron_expression)
32        .bind(&schedule.timezone)
33        .bind(schedule.target_type.to_string())
34        .bind(&schedule.target_name)
35        .bind(&schedule.target_input)
36        .bind(schedule.enabled)
37        .bind(schedule.max_concurrent.map(|v| v as i32))
38        .bind(schedule.catch_up_missed)
39        .bind(schedule.max_catch_up.map(|v| v as i32))
40        .bind(&schedule.retry_policy)
41        .bind(schedule.next_trigger_at)
42        .execute(&mut *connection)
43        .await
44        .map_err(|e| {
45            error!(error = %e, "Failed to create schedule");
46            StoreError::Database(e.to_string())
47        })?;
48
49        debug!(%id, name = %schedule.name, "created schedule");
50        Ok(id)
51    }
52
53    #[instrument(skip(self))]
54    async fn get_schedule(&self, id: Uuid) -> Result<ScheduleRow, StoreError> {
55        let mut connection = crate::schedule_transaction::connection(&self.pool)
56            .await
57            .map_err(|error| StoreError::Database(error.to_string()))?;
58        let row = sqlx::query(
59            r#"
60            SELECT id, name, description, cron_expression, timezone,
61                   target_type, target_name, target_input, enabled,
62                   max_concurrent, catch_up_missed, max_catch_up, retry_policy,
63                   last_triggered_at, next_trigger_at, claimed_by, claimed_at,
64                   created_at, updated_at
65            FROM durable_schedules
66            WHERE id = $1
67            "#,
68        )
69        .bind(id)
70        .fetch_optional(&mut *connection)
71        .await
72        .map_err(|e| {
73            error!(error = %e, "Failed to get schedule");
74            StoreError::Database(e.to_string())
75        })?
76        .ok_or(StoreError::ScheduleNotFound(id))?;
77
78        parse_schedule_row(row)
79    }
80
81    #[instrument(skip(self))]
82    async fn list_schedules(
83        &self,
84        filter: ScheduleFilter,
85        pagination: Pagination,
86    ) -> Result<Vec<ScheduleRow>, StoreError> {
87        let mut connection = crate::schedule_transaction::connection(&self.pool)
88            .await
89            .map_err(|error| StoreError::Database(error.to_string()))?;
90        let rows = sqlx::query(
91            r#"
92            SELECT id, name, description, cron_expression, timezone,
93                   target_type, target_name, target_input, enabled,
94                   max_concurrent, catch_up_missed, max_catch_up, retry_policy,
95                   last_triggered_at, next_trigger_at, claimed_by, claimed_at,
96                   created_at, updated_at
97            FROM durable_schedules
98            WHERE ($1::boolean IS NULL OR enabled = $1)
99              AND ($2::text IS NULL OR target_type = $2)
100            ORDER BY created_at DESC
101            OFFSET $3 LIMIT $4
102            "#,
103        )
104        .bind(filter.enabled)
105        .bind(
106            filter
107                .target_type
108                .map(|t: ScheduleTargetType| t.to_string()),
109        )
110        .bind(pagination.offset as i64)
111        .bind(pagination.limit as i64)
112        .fetch_all(&mut *connection)
113        .await
114        .map_err(|e| {
115            error!(error = %e, "Failed to list schedules");
116            StoreError::Database(e.to_string())
117        })?;
118
119        rows.into_iter().map(parse_schedule_row).collect()
120    }
121
122    #[instrument(skip(self))]
123    async fn count_schedules(&self, filter: ScheduleFilter) -> Result<u64, StoreError> {
124        let mut connection = crate::schedule_transaction::connection(&self.pool)
125            .await
126            .map_err(|error| StoreError::Database(error.to_string()))?;
127        let row = sqlx::query(
128            r#"
129            SELECT COUNT(*) as count
130            FROM durable_schedules
131            WHERE ($1::boolean IS NULL OR enabled = $1)
132              AND ($2::text IS NULL OR target_type = $2)
133            "#,
134        )
135        .bind(filter.enabled)
136        .bind(
137            filter
138                .target_type
139                .map(|t: ScheduleTargetType| t.to_string()),
140        )
141        .fetch_one(&mut *connection)
142        .await
143        .map_err(|e| {
144            error!(error = %e, "Failed to count schedules");
145            StoreError::Database(e.to_string())
146        })?;
147
148        let count: i64 = row.get("count");
149        Ok(count as u64)
150    }
151
152    #[instrument(skip(self, update))]
153    async fn update_schedule(&self, id: Uuid, update: UpdateSchedule) -> Result<(), StoreError> {
154        let mut connection = crate::schedule_transaction::connection(&self.pool)
155            .await
156            .map_err(|error| StoreError::Database(error.to_string()))?;
157        // Build dynamic update query
158        let result = sqlx::query(
159            r#"
160            UPDATE durable_schedules
161            SET name = COALESCE($2, name),
162                description = CASE WHEN $3 THEN $4 ELSE description END,
163                cron_expression = COALESCE($5, cron_expression),
164                timezone = COALESCE($6, timezone),
165                target_type = COALESCE($7, target_type),
166                target_name = COALESCE($8, target_name),
167                target_input = COALESCE($9, target_input),
168                enabled = COALESCE($10, enabled),
169                max_concurrent = CASE WHEN $11 THEN $12 ELSE max_concurrent END,
170                catch_up_missed = COALESCE($13, catch_up_missed),
171                max_catch_up = CASE WHEN $14 THEN $15 ELSE max_catch_up END,
172                retry_policy = CASE WHEN $16 THEN $17 ELSE retry_policy END,
173                next_trigger_at = CASE WHEN $18 THEN $19 ELSE next_trigger_at END,
174                updated_at = NOW()
175            WHERE id = $1
176            "#,
177        )
178        .bind(id)
179        .bind(update.name)
180        .bind(update.description.is_changed())
181        .bind(update.description.into_value())
182        .bind(update.cron_expression)
183        .bind(update.timezone)
184        .bind(
185            update
186                .target_type
187                .map(|t: ScheduleTargetType| t.to_string()),
188        )
189        .bind(update.target_name)
190        .bind(update.target_input)
191        .bind(update.enabled)
192        .bind(update.max_concurrent.is_changed())
193        .bind(update.max_concurrent.into_value().map(|v| v as i32))
194        .bind(update.catch_up_missed)
195        .bind(update.max_catch_up.is_changed())
196        .bind(update.max_catch_up.into_value().map(|v| v as i32))
197        .bind(update.retry_policy.is_changed())
198        .bind(update.retry_policy.into_value())
199        .bind(update.next_trigger_at.is_changed())
200        .bind(update.next_trigger_at.into_value())
201        .execute(&mut *connection)
202        .await
203        .map_err(|e| {
204            error!(error = %e, "Failed to update schedule");
205            StoreError::Database(e.to_string())
206        })?;
207
208        if result.rows_affected() == 0 {
209            return Err(StoreError::ScheduleNotFound(id));
210        }
211
212        debug!(%id, "updated schedule");
213        Ok(())
214    }
215
216    #[instrument(skip(self))]
217    async fn delete_schedule(&self, id: Uuid) -> Result<(), StoreError> {
218        let mut connection = crate::schedule_transaction::connection(&self.pool)
219            .await
220            .map_err(|error| StoreError::Database(error.to_string()))?;
221        let result = sqlx::query("DELETE FROM durable_schedules WHERE id = $1")
222            .bind(id)
223            .execute(&mut *connection)
224            .await
225            .map_err(|e| {
226                error!(error = %e, "Failed to delete schedule");
227                StoreError::Database(e.to_string())
228            })?;
229
230        if result.rows_affected() == 0 {
231            return Err(StoreError::ScheduleNotFound(id));
232        }
233
234        debug!(%id, "deleted schedule");
235        Ok(())
236    }
237
238    #[instrument(skip(self))]
239    async fn claim_due_schedules(
240        &self,
241        scheduler_id: &str,
242        limit: u32,
243    ) -> Result<Vec<ScheduleRow>, StoreError> {
244        // Claim due schedules ordered by next_trigger_at
245        let rows = sqlx::query(
246            r#"
247            WITH due_schedules AS (
248                SELECT id
249                FROM durable_schedules
250                WHERE enabled = true
251                  AND next_trigger_at <= NOW()
252                  AND (claimed_by IS NULL OR claimed_at < NOW() - INTERVAL '30 seconds')
253                ORDER BY next_trigger_at
254                FOR UPDATE SKIP LOCKED
255                LIMIT $2
256            )
257            UPDATE durable_schedules s
258            SET claimed_by = $1, claimed_at = NOW()
259            FROM due_schedules d
260            WHERE s.id = d.id
261            RETURNING s.id, s.name, s.description, s.cron_expression, s.timezone,
262                      s.target_type, s.target_name, s.target_input, s.enabled,
263                      s.max_concurrent, s.catch_up_missed, s.max_catch_up, s.retry_policy,
264                      s.last_triggered_at, s.next_trigger_at, s.claimed_by, s.claimed_at,
265                      s.created_at, s.updated_at
266            "#,
267        )
268        .bind(scheduler_id)
269        .bind(limit as i32)
270        .fetch_all(&self.pool)
271        .await
272        .map_err(|e| store_failure("durable.schedules.claim", "claim due schedules failed", e))?;
273
274        let schedules: Result<Vec<_>, _> = rows.into_iter().map(parse_schedule_row).collect();
275        let schedules = schedules?;
276
277        debug!(
278            count = schedules.len(),
279            scheduler_id, "claimed due schedules"
280        );
281        Ok(schedules)
282    }
283
284    #[instrument(skip(self))]
285    async fn update_next_trigger(
286        &self,
287        id: Uuid,
288        next: chrono::DateTime<chrono::Utc>,
289    ) -> Result<(), StoreError> {
290        let result = sqlx::query(
291            r#"
292            UPDATE durable_schedules
293            SET next_trigger_at = $2,
294                last_triggered_at = NOW(),
295                claimed_by = NULL,
296                claimed_at = NULL,
297                updated_at = NOW()
298            WHERE id = $1
299            "#,
300        )
301        .bind(id)
302        .bind(next)
303        .execute(&self.pool)
304        .await
305        .map_err(|e| {
306            error!(error = %e, "Failed to update next trigger");
307            StoreError::Database(e.to_string())
308        })?;
309
310        if result.rows_affected() == 0 {
311            return Err(StoreError::ScheduleNotFound(id));
312        }
313
314        debug!(%id, %next, "updated next trigger");
315        Ok(())
316    }
317
318    #[instrument(skip(self))]
319    async fn skip_schedule_trigger(&self, id: Uuid) -> Result<(), StoreError> {
320        sqlx::query(
321            r#"
322            UPDATE durable_schedules
323            SET claimed_by = NULL, claimed_at = NULL
324            WHERE id = $1
325            "#,
326        )
327        .bind(id)
328        .execute(&self.pool)
329        .await
330        .map_err(|e| {
331            error!(error = %e, "Failed to skip schedule trigger");
332            StoreError::Database(e.to_string())
333        })?;
334
335        debug!(%id, "skipped schedule trigger");
336        Ok(())
337    }
338
339    #[instrument(skip(self))]
340    async fn release_schedule(&self, id: Uuid) -> Result<(), StoreError> {
341        self.skip_schedule_trigger(id).await
342    }
343
344    #[instrument(skip(self))]
345    async fn create_schedule_execution(
346        &self,
347        schedule_id: Uuid,
348        scheduled_at: chrono::DateTime<chrono::Utc>,
349    ) -> Result<Uuid, StoreError> {
350        let id = Uuid::now_v7();
351
352        sqlx::query(
353            r#"
354            INSERT INTO durable_schedule_executions (id, schedule_id, scheduled_at, status)
355            VALUES ($1, $2, $3, 'running')
356            "#,
357        )
358        .bind(id)
359        .bind(schedule_id)
360        .bind(scheduled_at)
361        .execute(&self.pool)
362        .await
363        .map_err(|e| {
364            error!(error = %e, "Failed to create schedule execution");
365            StoreError::Database(e.to_string())
366        })?;
367
368        debug!(%id, %schedule_id, "created schedule execution");
369        Ok(id)
370    }
371
372    #[instrument(skip(self))]
373    async fn get_schedule_execution(&self, id: Uuid) -> Result<ScheduleExecutionRow, StoreError> {
374        let row = sqlx::query(
375            r#"
376            SELECT id, schedule_id, scheduled_at, started_at, completed_at,
377                   status, workflow_id, task_id, error, duration_ms, created_at
378            FROM durable_schedule_executions
379            WHERE id = $1
380            "#,
381        )
382        .bind(id)
383        .fetch_optional(&self.pool)
384        .await
385        .map_err(|e| {
386            error!(error = %e, "Failed to get schedule execution");
387            StoreError::Database(e.to_string())
388        })?
389        .ok_or(StoreError::ScheduleExecutionNotFound(id))?;
390
391        parse_schedule_execution_row(row)
392    }
393
394    #[instrument(skip(self))]
395    async fn complete_schedule_execution(
396        &self,
397        execution_id: Uuid,
398        target_id: Uuid,
399        is_workflow: bool,
400    ) -> Result<(), StoreError> {
401        let result = sqlx::query(
402            r#"
403            UPDATE durable_schedule_executions
404            SET status = 'completed',
405                completed_at = NOW(),
406                duration_ms = EXTRACT(MILLISECONDS FROM (NOW() - started_at))::int,
407                workflow_id = CASE WHEN $2 THEN $3 ELSE workflow_id END,
408                task_id = CASE WHEN NOT $2 THEN $3 ELSE task_id END
409            WHERE id = $1
410            "#,
411        )
412        .bind(execution_id)
413        .bind(is_workflow)
414        .bind(target_id)
415        .execute(&self.pool)
416        .await
417        .map_err(|e| {
418            error!(error = %e, "Failed to complete schedule execution");
419            StoreError::Database(e.to_string())
420        })?;
421
422        if result.rows_affected() == 0 {
423            return Err(StoreError::ScheduleExecutionNotFound(execution_id));
424        }
425
426        debug!(%execution_id, "completed schedule execution");
427        Ok(())
428    }
429
430    #[instrument(skip(self))]
431    async fn fail_schedule_execution(
432        &self,
433        execution_id: Uuid,
434        error: &str,
435    ) -> Result<(), StoreError> {
436        let result = sqlx::query(
437            r#"
438            UPDATE durable_schedule_executions
439            SET status = 'failed',
440                completed_at = NOW(),
441                duration_ms = EXTRACT(MILLISECONDS FROM (NOW() - started_at))::int,
442                error = $2
443            WHERE id = $1
444            "#,
445        )
446        .bind(execution_id)
447        .bind(error)
448        .execute(&self.pool)
449        .await
450        .map_err(|e| {
451            error!(error = %e, "Failed to fail schedule execution");
452            StoreError::Database(e.to_string())
453        })?;
454
455        if result.rows_affected() == 0 {
456            return Err(StoreError::ScheduleExecutionNotFound(execution_id));
457        }
458
459        debug!(%execution_id, "failed schedule execution");
460        Ok(())
461    }
462
463    #[instrument(skip(self))]
464    async fn skip_schedule_execution(
465        &self,
466        execution_id: Uuid,
467        reason: &str,
468    ) -> Result<(), StoreError> {
469        let result = sqlx::query(
470            r#"
471            UPDATE durable_schedule_executions
472            SET status = 'skipped',
473                completed_at = NOW(),
474                duration_ms = EXTRACT(MILLISECONDS FROM (NOW() - started_at))::int,
475                error = $2
476            WHERE id = $1
477            "#,
478        )
479        .bind(execution_id)
480        .bind(reason)
481        .execute(&self.pool)
482        .await
483        .map_err(|e| {
484            error!(error = %e, "Failed to skip schedule execution");
485            StoreError::Database(e.to_string())
486        })?;
487
488        if result.rows_affected() == 0 {
489            return Err(StoreError::ScheduleExecutionNotFound(execution_id));
490        }
491
492        debug!(%execution_id, "skipped schedule execution");
493        Ok(())
494    }
495
496    #[instrument(skip(self))]
497    async fn list_schedule_executions(
498        &self,
499        filter: ScheduleExecutionFilter,
500        pagination: Pagination,
501    ) -> Result<Vec<ScheduleExecutionRow>, StoreError> {
502        let rows = sqlx::query(
503            r#"
504            SELECT id, schedule_id, scheduled_at, started_at, completed_at,
505                   status, workflow_id, task_id, error, duration_ms, created_at
506            FROM durable_schedule_executions
507            WHERE ($1::uuid IS NULL OR schedule_id = $1)
508              AND ($2::text IS NULL OR status = $2)
509            ORDER BY created_at DESC
510            OFFSET $3 LIMIT $4
511            "#,
512        )
513        .bind(filter.schedule_id)
514        .bind(
515            filter
516                .status
517                .map(|s: ScheduleExecutionStatus| s.to_string()),
518        )
519        .bind(pagination.offset as i64)
520        .bind(pagination.limit as i64)
521        .fetch_all(&self.pool)
522        .await
523        .map_err(|e| {
524            error!(error = %e, "Failed to list schedule executions");
525            StoreError::Database(e.to_string())
526        })?;
527
528        rows.into_iter().map(parse_schedule_execution_row).collect()
529    }
530
531    #[instrument(skip(self))]
532    async fn count_running_executions(&self, schedule_id: Uuid) -> Result<u32, StoreError> {
533        let row = sqlx::query(
534            r#"
535            SELECT COUNT(*) as count
536            FROM durable_schedule_executions
537            WHERE schedule_id = $1 AND status = 'running'
538            "#,
539        )
540        .bind(schedule_id)
541        .fetch_one(&self.pool)
542        .await
543        .map_err(|e| {
544            error!(error = %e, "Failed to count running executions");
545            StoreError::Database(e.to_string())
546        })?;
547
548        let count: i64 = row.get("count");
549        Ok(count as u32)
550    }
551
552    #[instrument(skip(self))]
553    async fn last_scheduled_task_pending(&self, schedule_id: Uuid) -> Result<bool, StoreError> {
554        // Reads one execution through idx_durable_schedule_executions_schedule.
555        let pending: Option<bool> = sqlx::query_scalar(
556            r#"
557            SELECT t.status = 'pending'
558            FROM durable_schedule_executions e
559            JOIN durable_task_queue t ON t.id = e.task_id
560            WHERE e.schedule_id = $1 AND e.task_id IS NOT NULL
561            ORDER BY e.created_at DESC
562            LIMIT 1
563            "#,
564        )
565        .bind(schedule_id)
566        .fetch_optional(&self.pool)
567        .await
568        .map_err(|e| {
569            error!(error = %e, "Failed to read the last scheduled task");
570            StoreError::Database(e.to_string())
571        })?;
572        Ok(pending.unwrap_or(false))
573    }
574
575    #[instrument(skip(self))]
576    async fn get_schedule_stats(&self, schedule_id: Uuid) -> Result<ScheduleStats, StoreError> {
577        let row = sqlx::query(
578            r#"
579            SELECT
580                COUNT(*) as total,
581                COUNT(*) FILTER (WHERE status = 'completed') as successful,
582                COUNT(*) FILTER (WHERE status = 'failed') as failed,
583                COUNT(*) FILTER (WHERE status = 'skipped') as skipped,
584                -- AVG over an integer column is NUMERIC; cast so it decodes as f64.
585                (AVG(duration_ms) FILTER (WHERE duration_ms IS NOT NULL))::FLOAT8 as avg_duration
586            FROM durable_schedule_executions
587            WHERE schedule_id = $1
588            "#,
589        )
590        .bind(schedule_id)
591        .fetch_one(&self.pool)
592        .await
593        .map_err(|e| {
594            error!(error = %e, "Failed to get schedule stats");
595            StoreError::Database(e.to_string())
596        })?;
597
598        let total: i64 = row.get("total");
599        let successful: i64 = row.get("successful");
600        let failed: i64 = row.get("failed");
601        let skipped: i64 = row.get("skipped");
602        let avg_duration: Option<f64> = row.get("avg_duration");
603
604        // Get last execution status
605        let last_row = sqlx::query(
606            r#"
607            SELECT status
608            FROM durable_schedule_executions
609            WHERE schedule_id = $1
610            ORDER BY created_at DESC
611            LIMIT 1
612            "#,
613        )
614        .bind(schedule_id)
615        .fetch_optional(&self.pool)
616        .await
617        .map_err(|e| {
618            error!(error = %e, "Failed to get last execution status");
619            StoreError::Database(e.to_string())
620        })?;
621
622        let last_execution_status = last_row
623            .map(|r| {
624                let status: String = r.get("status");
625                parse_schedule_execution_status(&status)
626            })
627            .transpose()?;
628
629        Ok(ScheduleStats {
630            total_executions: total as u64,
631            successful_executions: successful as u64,
632            failed_executions: failed as u64,
633            skipped_executions: skipped as u64,
634            avg_duration_ms: avg_duration.map(|v| v as u64),
635            last_execution_status,
636        })
637    }
638
639    #[instrument(skip(self, instance))]
640    async fn register_scheduler_instance(
641        &self,
642        instance: SchedulerInstanceInfo,
643    ) -> Result<(), StoreError> {
644        sqlx::query(
645            r#"
646            INSERT INTO durable_scheduler_instances (instance_id, started_at, last_heartbeat_at, schedules_processed, hostname, version)
647            VALUES ($1, $2, $3, $4, $5, $6)
648            ON CONFLICT (instance_id) DO UPDATE
649            SET started_at = $2, last_heartbeat_at = $3, schedules_processed = $4, hostname = $5, version = $6
650            "#,
651        )
652        .bind(&instance.instance_id)
653        .bind(instance.started_at)
654        .bind(instance.last_heartbeat_at)
655        .bind(instance.schedules_processed as i64)
656        .bind(&instance.hostname)
657        .bind(&instance.version)
658        .execute(&self.pool)
659        .await
660        .map_err(|e| {
661            error!(error = %e, "Failed to register scheduler instance");
662            StoreError::Database(e.to_string())
663        })?;
664
665        debug!(instance_id = %instance.instance_id, "registered scheduler instance");
666        Ok(())
667    }
668
669    #[instrument(skip(self))]
670    async fn heartbeat_scheduler_instance(
671        &self,
672        instance_id: &str,
673        schedules_processed: u64,
674    ) -> Result<(), StoreError> {
675        sqlx::query(
676            r#"
677            UPDATE durable_scheduler_instances
678            SET last_heartbeat_at = NOW(), schedules_processed = $2
679            WHERE instance_id = $1
680            "#,
681        )
682        .bind(instance_id)
683        .bind(schedules_processed as i64)
684        .execute(&self.pool)
685        .await
686        .map_err(|e| {
687            error!(error = %e, "Failed to heartbeat scheduler instance");
688            StoreError::Database(e.to_string())
689        })?;
690
691        Ok(())
692    }
693
694    #[instrument(skip(self))]
695    async fn list_scheduler_instances(&self) -> Result<Vec<SchedulerInstanceInfo>, StoreError> {
696        let rows = sqlx::query(
697            r#"
698            SELECT instance_id, started_at, last_heartbeat_at, schedules_processed, hostname, version
699            FROM durable_scheduler_instances
700            ORDER BY started_at DESC
701            "#,
702        )
703        .fetch_all(&self.pool)
704        .await
705        .map_err(|e| {
706            error!(error = %e, "Failed to list scheduler instances");
707            StoreError::Database(e.to_string())
708        })?;
709
710        Ok(rows
711            .into_iter()
712            .map(|row| SchedulerInstanceInfo {
713                instance_id: row.get("instance_id"),
714                started_at: row.get("started_at"),
715                last_heartbeat_at: row.get("last_heartbeat_at"),
716                schedules_processed: row.get::<i64, _>("schedules_processed") as u64,
717                hostname: row.get("hostname"),
718                version: row.get("version"),
719            })
720            .collect())
721    }
722
723    #[instrument(skip(self))]
724    async fn deregister_scheduler_instance(&self, instance_id: &str) -> Result<(), StoreError> {
725        sqlx::query(
726            r#"
727            DELETE FROM durable_scheduler_instances WHERE instance_id = $1
728            "#,
729        )
730        .bind(instance_id)
731        .execute(&self.pool)
732        .await
733        .map_err(|e| {
734            error!(error = %e, "Failed to deregister scheduler instance");
735            StoreError::Database(e.to_string())
736        })?;
737
738        debug!(instance_id, "deregistered scheduler instance");
739        Ok(())
740    }
741}