1use std::sync::Arc;
63use std::time::Duration;
64
65use adk_core::governance_state::{
66 GovernanceScope, GovernanceState, GovernanceStateStore, governance_conflict_error,
67};
68use adk_core::lease::{Lease, LeaseStore, lease_stale_epoch_error};
69use adk_core::principal::SubjectRef;
70use adk_core::run_store::{
71 ClaimedRun, DurableRunStore, Enqueued, NewRun, OnConflict, RunCheckpointRef, RunFilter,
72 RunOutcome, RunRecord, run_not_found_error,
73};
74use adk_core::schedule::{
75 Schedule, ScheduleStore, invalid_schedule_error, schedule_not_found_error,
76};
77use adk_core::{AdkError, Clock, Result, SystemClock};
78use async_trait::async_trait;
79use chrono::{DateTime, Utc};
80use firestore::errors::{BackoffError, FirestoreError};
81use firestore::{FirestoreDb, FirestoreQueryDirection, FirestoreWritePrecondition};
82use serde::{Deserialize, Serialize};
83use serde_json::json;
84
85use crate::durable_common::{
86 GOVERNANCE_STORAGE, LEASE_STORAGE, RUN_STORAGE, SCHEDULE_STORAGE, deadline, hex,
87 same_definition, state_name, storage_error, stored_now,
88};
89use crate::durable_transitions::{
90 ClaimStep, apply_cancel, apply_checkpoint, apply_claim, apply_exhaust, apply_finish,
91 apply_heartbeat, apply_wait, apply_wake, check_fence, claim_step, ready_micros,
92};
93use crate::firestore_stores::{
94 TxFuture, TxResult, connect, document_id, from_json, retry_or_fail, to_json, transaction_error,
95 transaction_options,
96};
97
98const LEASES: &str = "adk_leases";
99const RUNS: &str = "adk_runs";
100const RUN_QUEUES: &str = "adk_run_queues";
101const RUN_KEYS: &str = "adk_run_keys";
102const RUN_KEY_HOLDERS: &str = "adk_run_key_holders";
103const SCHEDULES: &str = "adk_schedules";
104const GOVERNANCE: &str = "adk_governance";
105
106const CLAIM_PAGE: u32 = 64;
108const PRUNE_BATCH: u32 = 100;
110const MAX_SCHEDULE_ID_BYTES: usize = 700;
112
113fn tx_fail(code: &'static str) -> impl Fn(FirestoreError) -> BackoffError<AdkError> {
115 move |error| {
116 retry_or_fail(error, |e| storage_error(code, format!("firestore request failed: {e}")))
117 }
118}
119
120fn refuse<T>(error: AdkError) -> TxResult<T> {
122 Err(BackoffError::permanent(error))
123}
124
125fn json_text<T: Serialize>(value: &T, code: &'static str) -> TxResult<String> {
126 to_json(value, |m| storage_error(code, m)).map_err(BackoffError::permanent)
127}
128
129fn parse_json<T: serde::de::DeserializeOwned>(
130 text: &str,
131 what: &str,
132 code: &'static str,
133) -> Result<T> {
134 from_json(text, what, |m| storage_error(code, m))
135}
136
137fn sortable(value: i64) -> String {
139 format!("{:020}", (value as u64) ^ (1 << 63))
140}
141
142#[derive(Debug, Clone, Serialize, Deserialize)]
147struct LeaseDoc {
148 resource: String,
149 lease: String,
151 released: bool,
152}
153
154fn lease_id(resource: &str) -> String {
155 document_id(&json!(["lease", resource]))
156}
157
158async fn read_lease(db: &FirestoreDb, resource: &str) -> TxResult<Option<(Lease, bool)>> {
159 let stored: Option<LeaseDoc> = db
160 .fluent()
161 .select()
162 .by_id_in(LEASES)
163 .obj::<LeaseDoc>()
164 .one(lease_id(resource))
165 .await
166 .map_err(tx_fail(LEASE_STORAGE))?;
167 match stored.filter(|doc| doc.resource == resource) {
168 Some(doc) => {
169 let lease =
170 parse_json(&doc.lease, "lease", LEASE_STORAGE).map_err(BackoffError::permanent)?;
171 Ok(Some((lease, doc.released)))
172 }
173 None => Ok(None),
174 }
175}
176
177fn write_lease(
178 db: &FirestoreDb,
179 transaction: &mut firestore::FirestoreTransaction<'_>,
180 lease: &Lease,
181 released: bool,
182) -> TxResult<()> {
183 let doc = LeaseDoc {
184 resource: lease.resource.clone(),
185 lease: json_text(lease, LEASE_STORAGE)?,
186 released,
187 };
188 db.fluent()
189 .update()
190 .in_col(LEASES)
191 .document_id(lease_id(&lease.resource))
192 .object(&doc)
193 .add_to_transaction(transaction)
194 .map_err(tx_fail(LEASE_STORAGE))?;
195 Ok(())
196}
197
198#[derive(Clone)]
219pub struct FirestoreLeaseStore {
220 db: FirestoreDb,
221 clock: Arc<dyn Clock>,
222}
223
224impl std::fmt::Debug for FirestoreLeaseStore {
225 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226 f.debug_struct("FirestoreLeaseStore").field("clock", &self.clock).finish_non_exhaustive()
227 }
228}
229
230impl FirestoreLeaseStore {
231 pub async fn new(project_id: &str) -> Result<Self> {
238 let db = connect(project_id).await.map_err(|e| storage_error(LEASE_STORAGE, e))?;
239 Ok(Self::from_db(db))
240 }
241
242 pub fn from_db(db: FirestoreDb) -> Self {
244 Self { db, clock: Arc::new(SystemClock) }
245 }
246
247 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
249 self.clock = clock;
250 self
251 }
252
253 pub async fn migrate(&self) -> Result<()> {
263 Ok(())
264 }
265}
266
267#[async_trait]
268impl LeaseStore for FirestoreLeaseStore {
269 async fn acquire(&self, resource: &str, owner: &str, ttl: Duration) -> Result<Option<Lease>> {
270 let now = stored_now(self.clock.now());
271 let expires_at = deadline(now, ttl, "lease.invalid_ttl")?;
272 let request = Arc::new((resource.to_string(), owner.to_string()));
273 self.db
274 .run_transaction_with_options(
275 move |db, transaction| -> TxFuture<'_, Option<Lease>> {
276 let request = request.clone();
277 Box::pin(async move {
278 let (resource, owner) = &*request;
279 let previous = match read_lease(&db, resource).await? {
280 Some((lease, released)) => {
281 let live = !released && lease.expires_at > now;
282 if live && lease.owner != *owner {
283 return Ok(None);
284 }
285 lease.epoch
286 }
287 None => 0,
288 };
289 let lease = Lease {
290 resource: resource.clone(),
291 owner: owner.clone(),
292 epoch: previous + 1,
293 expires_at,
294 };
295 write_lease(&db, transaction, &lease, false)?;
296 Ok(Some(lease))
297 })
298 },
299 transaction_options(),
300 )
301 .await
302 .map_err(|e| transaction_error(e, |m| storage_error(LEASE_STORAGE, m)))
303 }
304
305 async fn renew(&self, lease: &Lease, ttl: Duration) -> Result<Lease> {
306 let expires_at = deadline(stored_now(self.clock.now()), ttl, "lease.invalid_ttl")?;
307 let held = Arc::new(lease.clone());
308 self.db
309 .run_transaction_with_options(
310 move |db, transaction| -> TxFuture<'_, Lease> {
311 let held = held.clone();
312 Box::pin(async move {
313 match read_lease(&db, &held.resource).await? {
314 Some((stored, false))
315 if stored.epoch == held.epoch && stored.owner == held.owner =>
316 {
317 let renewed = Lease { expires_at, ..stored };
318 write_lease(&db, transaction, &renewed, false)?;
319 Ok(renewed)
320 }
321 _ => refuse(lease_stale_epoch_error(&held.resource, held.epoch)),
322 }
323 })
324 },
325 transaction_options(),
326 )
327 .await
328 .map_err(|e| transaction_error(e, |m| storage_error(LEASE_STORAGE, m)))
329 }
330
331 async fn release(&self, lease: &Lease) -> Result<()> {
332 let held = Arc::new(lease.clone());
333 self.db
334 .run_transaction_with_options(
335 move |db, transaction| -> TxFuture<'_, ()> {
336 let held = held.clone();
337 Box::pin(async move {
338 if let Some((stored, false)) = read_lease(&db, &held.resource).await?
339 && stored.epoch == held.epoch
340 && stored.owner == held.owner
341 {
342 write_lease(&db, transaction, &stored, true)?;
343 }
344 Ok(())
345 })
346 },
347 transaction_options(),
348 )
349 .await
350 .map_err(|e| transaction_error(e, |m| storage_error(LEASE_STORAGE, m)))
351 }
352
353 async fn current(&self, resource: &str) -> Result<Option<Lease>> {
354 let now = self.clock.now();
355 let stored = read_lease(&self.db, resource).await.map_err(|e| match e {
356 BackoffError::Permanent(error) | BackoffError::Transient { err: error, .. } => error,
357 })?;
358 Ok(stored
359 .filter(|(lease, released)| !released && lease.expires_at > now)
360 .map(|(lease, _)| lease))
361 }
362}
363
364#[derive(Debug, Clone, Default, Serialize, Deserialize)]
370struct QueueDoc {
371 queue: String,
372 #[serde(default)]
373 seq: i64,
374}
375
376#[derive(Debug, Clone, Serialize, Deserialize)]
377struct RunDoc {
378 run_id: String,
379 queue: String,
380 seq: i64,
381 state: String,
382 record: String,
384 #[serde(default, skip_serializing_if = "Option::is_none")]
385 claim_key: Option<String>,
386 #[serde(default, skip_serializing_if = "Option::is_none")]
387 finished_us: Option<i64>,
388}
389
390#[derive(Debug, Clone, Serialize, Deserialize)]
391struct RunKeyDoc {
392 queue: String,
393 key: String,
394 run_id: String,
395}
396
397fn queue_id(queue: &str) -> String {
398 document_id(&json!(["queue", queue]))
399}
400
401fn run_key_id(queue: &str, key: &str) -> String {
402 document_id(&json!(["idempotency", queue, key]))
403}
404
405fn is_run_id(run_id: &str) -> bool {
407 uuid::Uuid::parse_str(run_id).is_ok_and(|id| id.hyphenated().to_string() == run_id)
408}
409
410fn run_doc(record: &RunRecord, seq: i64) -> TxResult<RunDoc> {
411 let unfinished = !record.state.is_terminal();
412 Ok(RunDoc {
413 run_id: record.run_id.clone(),
414 queue: record.queue.clone(),
415 seq,
416 state: state_name(record.state).to_string(),
417 record: json_text(record, RUN_STORAGE)?,
418 claim_key: unfinished.then(|| {
419 format!(
420 "{}:{}:{}",
421 queue_id(&record.queue),
422 sortable(ready_micros(record)),
423 sortable(seq)
424 )
425 }),
426 finished_us: (!unfinished).then(|| record.updated_at.timestamp_micros()),
427 })
428}
429
430fn decode_run(doc: &RunDoc) -> Result<RunRecord> {
431 let record: RunRecord = parse_json(&doc.record, "run record", RUN_STORAGE)?;
432 if record.run_id != doc.run_id {
433 return Err(storage_error(
434 RUN_STORAGE,
435 format!("run document '{}' holds run '{}'", doc.run_id, record.run_id),
436 ));
437 }
438 Ok(record)
439}
440
441fn write_run(
442 db: &FirestoreDb,
443 transaction: &mut firestore::FirestoreTransaction<'_>,
444 record: &RunRecord,
445 seq: i64,
446 precondition: Option<FirestoreWritePrecondition>,
447) -> TxResult<()> {
448 let doc = run_doc(record, seq)?;
449 let builder = db.fluent().update().in_col(RUNS);
450 let builder = match precondition {
451 Some(precondition) => builder.precondition(precondition),
452 None => builder,
453 };
454 builder
455 .document_id(&record.run_id)
456 .object(&doc)
457 .add_to_transaction(transaction)
458 .map_err(tx_fail(RUN_STORAGE))?;
459 Ok(())
460}
461
462async fn read_run(db: &FirestoreDb, run_id: &str) -> TxResult<Option<(RunRecord, i64)>> {
463 if !is_run_id(run_id) {
464 return Ok(None);
465 }
466 let stored: Option<RunDoc> = db
467 .fluent()
468 .select()
469 .by_id_in(RUNS)
470 .obj::<RunDoc>()
471 .one(run_id)
472 .await
473 .map_err(tx_fail(RUN_STORAGE))?;
474 match stored.filter(|doc| doc.run_id == run_id) {
475 Some(doc) => Ok(Some((decode_run(&doc).map_err(BackoffError::permanent)?, doc.seq))),
476 None => Ok(None),
477 }
478}
479
480async fn read_queue(db: &FirestoreDb, queue: &str) -> TxResult<QueueDoc> {
481 let stored: Option<QueueDoc> = db
482 .fluent()
483 .select()
484 .by_id_in(RUN_QUEUES)
485 .obj::<QueueDoc>()
486 .one(queue_id(queue))
487 .await
488 .map_err(tx_fail(RUN_STORAGE))?;
489 Ok(stored
490 .filter(|doc| doc.queue == queue)
491 .unwrap_or_else(|| QueueDoc { queue: queue.to_string(), ..QueueDoc::default() }))
492}
493
494fn write_queue(
495 db: &FirestoreDb,
496 transaction: &mut firestore::FirestoreTransaction<'_>,
497 queue: &QueueDoc,
498) -> TxResult<()> {
499 db.fluent()
500 .update()
501 .in_col(RUN_QUEUES)
502 .document_id(queue_id(&queue.queue))
503 .object(queue)
504 .add_to_transaction(transaction)
505 .map_err(tx_fail(RUN_STORAGE))?;
506 Ok(())
507}
508
509#[derive(Debug, Clone, Default, Serialize, Deserialize)]
511struct KeyHoldersDoc {
512 queue: String,
513 key: String,
514 #[serde(default)]
515 holders: Vec<String>,
516}
517
518fn key_holders_id(queue: &str, key: &str) -> String {
519 document_id(&json!(["holders", queue, key]))
520}
521
522async fn read_holders(db: &FirestoreDb, queue: &str, key: &str) -> TxResult<KeyHoldersDoc> {
523 let stored: Option<KeyHoldersDoc> = db
524 .fluent()
525 .select()
526 .by_id_in(RUN_KEY_HOLDERS)
527 .obj::<KeyHoldersDoc>()
528 .one(key_holders_id(queue, key))
529 .await
530 .map_err(tx_fail(RUN_STORAGE))?;
531 Ok(stored.filter(|doc| doc.queue == queue && doc.key == key).unwrap_or_else(|| KeyHoldersDoc {
532 queue: queue.to_string(),
533 key: key.to_string(),
534 holders: Vec::new(),
535 }))
536}
537
538fn write_holders(
539 db: &FirestoreDb,
540 transaction: &mut firestore::FirestoreTransaction<'_>,
541 doc: &KeyHoldersDoc,
542) -> TxResult<()> {
543 db.fluent()
544 .update()
545 .in_col(RUN_KEY_HOLDERS)
546 .document_id(key_holders_id(&doc.queue, &doc.key))
547 .object(doc)
548 .add_to_transaction(transaction)
549 .map_err(tx_fail(RUN_STORAGE))?;
550 Ok(())
551}
552
553async fn leave_key(
555 db: &FirestoreDb,
556 transaction: &mut firestore::FirestoreTransaction<'_>,
557 record: &RunRecord,
558) -> TxResult<()> {
559 if let Some(key) = record.concurrency_key.as_deref().filter(|_| record.state.is_terminal()) {
560 let mut doc = read_holders(db, &record.queue, key).await?;
561 doc.holders.retain(|id| *id != record.run_id);
562 write_holders(db, transaction, &doc)?;
563 }
564 Ok(())
565}
566
567type RunOp<T> = dyn Fn(&mut RunRecord, DateTime<Utc>) -> Result<(T, bool)> + Send + Sync;
569
570#[derive(Clone)]
595pub struct FirestoreRunStore {
596 db: FirestoreDb,
597 clock: Arc<dyn Clock>,
598}
599
600impl std::fmt::Debug for FirestoreRunStore {
601 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
602 f.debug_struct("FirestoreRunStore").field("clock", &self.clock).finish_non_exhaustive()
603 }
604}
605
606impl FirestoreRunStore {
607 pub async fn new(project_id: &str) -> Result<Self> {
614 let db = connect(project_id).await.map_err(|e| storage_error(RUN_STORAGE, e))?;
615 Ok(Self::from_db(db))
616 }
617
618 pub fn from_db(db: FirestoreDb) -> Self {
620 Self { db, clock: Arc::new(SystemClock) }
621 }
622
623 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
625 self.clock = clock;
626 self
627 }
628
629 pub async fn migrate(&self) -> Result<()> {
639 Ok(())
640 }
641
642 async fn claim_one(
646 &self,
647 run_id: &str,
648 worker: &str,
649 ttl: Duration,
650 ) -> Result<Option<ClaimedRun>> {
651 let clock = self.clock.clone();
652 let request = Arc::new((run_id.to_string(), worker.to_string()));
653 self.db
654 .run_transaction_with_options(
655 move |db, transaction| -> TxFuture<'_, Option<ClaimedRun>> {
656 let (request, clock) = (request.clone(), clock.clone());
657 Box::pin(async move {
658 let (run_id, worker) = &*request;
659 let now = stored_now(clock.now());
660 let expires_at = deadline(now, ttl, "run_store.invalid_ttl")
661 .map_err(BackoffError::permanent)?;
662 let Some((mut record, seq)) = read_run(&db, run_id).await? else {
663 return Ok(None);
664 };
665 let started = match claim_step(&record, now) {
666 ClaimStep::NotReady => return Ok(None),
667 ClaimStep::Exhaust => {
668 apply_exhaust(&mut record, now);
669 leave_key(&db, transaction, &record).await?;
670 write_run(&db, transaction, &record, seq, None)?;
671 return Ok(None);
672 }
673 ClaimStep::Claim { started } => started,
674 };
675 if record.state == adk_core::run_store::RunState::Queued
676 && let Some(key) = &record.concurrency_key
677 && read_holders(&db, &record.queue, key).await?.holders.first()
678 != Some(&record.run_id)
679 {
680 return Ok(None);
681 }
682 let epoch = apply_claim(&mut record, started, worker, now, expires_at);
683 write_run(&db, transaction, &record, seq, None)?;
684 Ok(Some(ClaimedRun { record, epoch }))
685 })
686 },
687 transaction_options(),
688 )
689 .await
690 .map_err(|e| transaction_error(e, |m| storage_error(RUN_STORAGE, m)))
691 }
692
693 async fn mutate<T: Send + 'static>(&self, run_id: &str, op: Arc<RunOp<T>>) -> Result<T> {
694 let clock = self.clock.clone();
695 let run_id = Arc::new(run_id.to_string());
696 self.db
697 .run_transaction_with_options(
698 move |db, transaction| -> TxFuture<'_, T> {
699 let (op, run_id, clock) = (op.clone(), run_id.clone(), clock.clone());
700 Box::pin(async move {
701 let Some((mut record, seq)) = read_run(&db, &run_id).await? else {
702 return refuse(run_not_found_error(&run_id));
703 };
704 let now = stored_now(clock.now());
705 let (value, changed) = match op(&mut record, now) {
706 Ok(done) => done,
707 Err(error) => return refuse(error),
708 };
709 if changed {
710 leave_key(&db, transaction, &record).await?;
711 write_run(
712 &db,
713 transaction,
714 &record,
715 seq,
716 Some(FirestoreWritePrecondition::Exists(true)),
717 )?;
718 }
719 Ok(value)
720 })
721 },
722 transaction_options(),
723 )
724 .await
725 .map_err(|e| transaction_error(e, |m| storage_error(RUN_STORAGE, m)))
726 }
727}
728
729#[async_trait]
730impl DurableRunStore for FirestoreRunStore {
731 async fn enqueue(&self, run: NewRun) -> Result<Enqueued> {
732 run.validate()?;
733 let clock = self.clock.clone();
734 let request = Arc::new((run, uuid::Uuid::new_v4().to_string()));
735 self.db
736 .run_transaction_with_options(
737 move |db, transaction| -> TxFuture<'_, Enqueued> {
738 let (request, clock) = (request.clone(), clock.clone());
739 Box::pin(async move {
740 let (run, run_id) = &*request;
741 let now = stored_now(clock.now());
742 let mut queue = read_queue(&db, &run.queue).await?;
743 if let Some(key) = &run.idempotency_key {
744 let stored: Option<RunKeyDoc> = db
745 .fluent()
746 .select()
747 .by_id_in(RUN_KEYS)
748 .obj::<RunKeyDoc>()
749 .one(run_key_id(&run.queue, key))
750 .await
751 .map_err(tx_fail(RUN_STORAGE))?;
752 if let Some(stored) =
753 stored.filter(|doc| doc.queue == run.queue && doc.key == *key)
754 && let Some((existing, _)) = read_run(&db, &stored.run_id).await?
755 {
756 return Ok(Enqueued::Existing(existing));
757 }
758 }
759 let mut holders = match &run.concurrency_key {
760 Some(key) => Some(read_holders(&db, &run.queue, key).await?),
761 None => None,
762 };
763 if let Some(doc) = &mut holders {
764 match run.on_conflict {
765 OnConflict::Reject => {
766 if let Some(blocking_run_id) = doc.holders.first() {
767 return Ok(Enqueued::Rejected {
768 blocking_run_id: blocking_run_id.clone(),
769 });
770 }
771 }
772 OnConflict::Interrupt => {
773 for holder_id in doc.holders.clone() {
774 let Some((mut holder, seq)) =
775 read_run(&db, &holder_id).await?
776 else {
777 doc.holders.retain(|id| *id != holder_id);
778 continue;
779 };
780 if apply_cancel(&mut holder, now) {
781 write_run(&db, transaction, &holder, seq, None)?;
782 }
783 if holder.state.is_terminal() {
784 doc.holders.retain(|id| *id != holder_id);
785 }
786 }
787 }
788 _ => {}
789 }
790 doc.holders.push(run_id.clone());
791 write_holders(&db, transaction, doc)?;
792 }
793 queue.seq += 1;
794 write_queue(&db, transaction, &queue)?;
795 let record = RunRecord::queued(run_id.clone(), run.clone(), now);
796 write_run(
797 &db,
798 transaction,
799 &record,
800 queue.seq,
801 Some(FirestoreWritePrecondition::Exists(false)),
802 )?;
803 if let Some(key) = &run.idempotency_key {
804 let doc = RunKeyDoc {
805 queue: run.queue.clone(),
806 key: key.clone(),
807 run_id: run_id.clone(),
808 };
809 db.fluent()
810 .update()
811 .in_col(RUN_KEYS)
812 .document_id(run_key_id(&run.queue, key))
813 .object(&doc)
814 .add_to_transaction(transaction)
815 .map_err(tx_fail(RUN_STORAGE))?;
816 }
817 Ok(Enqueued::Created(record))
818 })
819 },
820 transaction_options(),
821 )
822 .await
823 .map_err(|e| transaction_error(e, |m| storage_error(RUN_STORAGE, m)))
824 }
825
826 async fn claim(&self, queue: &str, worker: &str, ttl: Duration) -> Result<Option<ClaimedRun>> {
827 let now = stored_now(self.clock.now());
828 deadline(now, ttl, "run_store.invalid_ttl")?;
829 let prefix = queue_id(queue);
830 let end = format!("{prefix}:{};", sortable(now.timestamp_micros()));
831 let mut after: Option<String> = None;
832 loop {
833 let lower = after.clone().unwrap_or_else(|| format!("{prefix}:"));
836 let first_page = after.is_none();
837 let docs: Vec<RunDoc> = self
838 .db
839 .fluent()
840 .select()
841 .from(RUNS)
842 .filter(|q| {
843 q.for_all([
844 if first_page {
845 q.field("claim_key").greater_than_or_equal(lower.as_str())
846 } else {
847 q.field("claim_key").greater_than(lower.as_str())
848 },
849 q.field("claim_key").less_than(end.as_str()),
850 ])
851 })
852 .order_by([("claim_key", FirestoreQueryDirection::Ascending)])
853 .limit(CLAIM_PAGE)
854 .obj::<RunDoc>()
855 .query()
856 .await
857 .map_err(|e| storage_error(RUN_STORAGE, format!("run store query failed: {e}")))?;
858 let page_len = docs.len();
859 for doc in docs {
860 after = doc.claim_key.clone();
861 if doc.queue != queue {
862 continue;
863 }
864 if let Some(claimed) = self.claim_one(&doc.run_id, worker, ttl).await? {
865 return Ok(Some(claimed));
866 }
867 }
868 if page_len < CLAIM_PAGE as usize {
869 return Ok(None);
870 }
871 }
872 }
873
874 async fn heartbeat(&self, run_id: &str, epoch: u64, ttl: Duration) -> Result<bool> {
875 deadline(stored_now(self.clock.now()), ttl, "run_store.invalid_ttl")?;
876 self.mutate(
877 run_id,
878 Arc::new(move |record: &mut RunRecord, now| {
879 check_fence(record, epoch)?;
880 let expires_at = deadline(now, ttl, "run_store.invalid_ttl")?;
881 apply_heartbeat(record, now, expires_at);
882 Ok((record.cancel_requested, true))
883 }),
884 )
885 .await
886 }
887
888 async fn set_checkpoint(
889 &self,
890 run_id: &str,
891 epoch: u64,
892 checkpoint: RunCheckpointRef,
893 ) -> Result<()> {
894 self.mutate(
895 run_id,
896 Arc::new(move |record: &mut RunRecord, now| {
897 check_fence(record, epoch)?;
898 apply_checkpoint(record, now, checkpoint.clone());
899 Ok(((), true))
900 }),
901 )
902 .await
903 }
904
905 async fn wait(&self, run_id: &str, epoch: u64, until: Option<DateTime<Utc>>) -> Result<()> {
906 self.mutate(
907 run_id,
908 Arc::new(move |record: &mut RunRecord, now| {
909 check_fence(record, epoch)?;
910 apply_wait(record, now, until);
911 Ok(((), true))
912 }),
913 )
914 .await
915 }
916
917 async fn wake(&self, run_id: &str) -> Result<()> {
918 self.mutate(
919 run_id,
920 Arc::new(|record: &mut RunRecord, now| Ok(((), apply_wake(record, now)))),
921 )
922 .await
923 }
924
925 async fn finish(&self, run_id: &str, epoch: u64, outcome: RunOutcome) -> Result<RunRecord> {
926 self.mutate(
927 run_id,
928 Arc::new(move |record: &mut RunRecord, now| {
929 check_fence(record, epoch)?;
930 apply_finish(record, now, outcome.clone());
931 Ok((record.clone(), true))
932 }),
933 )
934 .await
935 }
936
937 async fn request_cancel(&self, run_id: &str) -> Result<()> {
938 self.mutate(
939 run_id,
940 Arc::new(|record: &mut RunRecord, now| Ok(((), apply_cancel(record, now)))),
941 )
942 .await
943 }
944
945 async fn get(&self, run_id: &str) -> Result<Option<RunRecord>> {
946 let stored = read_run(&self.db, run_id).await.map_err(|e| match e {
947 BackoffError::Permanent(error) | BackoffError::Transient { err: error, .. } => error,
948 })?;
949 Ok(stored.map(|(record, _)| record))
950 }
951
952 async fn list(&self, filter: RunFilter) -> Result<Vec<RunRecord>> {
953 let select = self.db.fluent().select().from(RUNS);
954 let docs: Vec<RunDoc> = match &filter.queue {
955 Some(queue) => {
956 select
957 .filter(|q| q.for_all([q.field("queue").eq(queue.as_str())]))
958 .obj::<RunDoc>()
959 .query()
960 .await
961 }
962 None => select.obj::<RunDoc>().query().await,
963 }
964 .map_err(|e| storage_error(RUN_STORAGE, format!("run store query failed: {e}")))?;
965 let mut matching = Vec::new();
966 for doc in docs {
967 let record = decode_run(&doc)?;
968 if filter.matches(&record) {
969 matching.push((doc.seq, record));
970 }
971 }
972 matching.sort_by(|a, b| {
973 (a.1.created_at, a.0, &a.1.run_id).cmp(&(b.1.created_at, b.0, &b.1.run_id))
974 });
975 let limit = filter.limit.unwrap_or(usize::MAX);
976 Ok(matching.into_iter().take(limit).map(|(_, record)| record).collect())
977 }
978
979 async fn prune(&self, finished_before: DateTime<Utc>) -> Result<u64> {
980 let cutoff = finished_before.timestamp_micros();
981 let mut pruned = 0u64;
982 loop {
983 let docs: Vec<RunDoc> = self
984 .db
985 .fluent()
986 .select()
987 .from(RUNS)
988 .filter(|q| q.for_all([q.field("finished_us").less_than(cutoff)]))
989 .limit(PRUNE_BATCH)
990 .obj::<RunDoc>()
991 .query()
992 .await
993 .map_err(|e| storage_error(RUN_STORAGE, format!("run store query failed: {e}")))?;
994 if docs.is_empty() {
995 return Ok(pruned);
996 }
997 let run_ids = Arc::new(docs.into_iter().map(|doc| doc.run_id).collect::<Vec<_>>());
998 let deleted = self
999 .db
1000 .run_transaction_with_options(
1001 move |db, transaction| -> TxFuture<'_, u64> {
1002 let run_ids = run_ids.clone();
1003 Box::pin(async move {
1004 let mut deleted = 0;
1005 for run_id in run_ids.iter() {
1006 let Some((record, _)) = read_run(&db, run_id).await? else {
1007 continue;
1008 };
1009 if !record.state.is_terminal()
1010 || record.updated_at.timestamp_micros() >= cutoff
1011 {
1012 continue;
1013 }
1014 if let Some(key) = &record.idempotency_key {
1015 let key_id = run_key_id(&record.queue, key);
1016 let stored: Option<RunKeyDoc> = db
1017 .fluent()
1018 .select()
1019 .by_id_in(RUN_KEYS)
1020 .obj::<RunKeyDoc>()
1021 .one(&key_id)
1022 .await
1023 .map_err(tx_fail(RUN_STORAGE))?;
1024 if stored.is_some_and(|doc| doc.run_id == record.run_id) {
1025 db.fluent()
1026 .delete()
1027 .from(RUN_KEYS)
1028 .document_id(&key_id)
1029 .add_to_transaction(transaction)
1030 .map_err(tx_fail(RUN_STORAGE))?;
1031 }
1032 }
1033 db.fluent()
1034 .delete()
1035 .from(RUNS)
1036 .document_id(run_id)
1037 .add_to_transaction(transaction)
1038 .map_err(tx_fail(RUN_STORAGE))?;
1039 deleted += 1;
1040 }
1041 Ok(deleted)
1042 })
1043 },
1044 transaction_options(),
1045 )
1046 .await
1047 .map_err(|e| transaction_error(e, |m| storage_error(RUN_STORAGE, m)))?;
1048 if deleted == 0 {
1049 return Ok(pruned);
1050 }
1051 pruned += deleted;
1052 }
1053 }
1054}
1055
1056#[derive(Debug, Clone, Serialize, Deserialize)]
1061struct ScheduleDoc {
1062 id: String,
1063 schedule: String,
1065 #[serde(default, skip_serializing_if = "Option::is_none")]
1066 due_us: Option<i64>,
1067}
1068
1069fn schedule_doc_id(id: &str) -> Option<String> {
1071 (id.len() <= MAX_SCHEDULE_ID_BYTES).then(|| hex(id))
1072}
1073
1074fn schedule_doc(schedule: &Schedule) -> TxResult<ScheduleDoc> {
1075 Ok(ScheduleDoc {
1076 id: schedule.id.clone(),
1077 schedule: json_text(schedule, SCHEDULE_STORAGE)?,
1078 due_us: schedule.next_fire_at.filter(|_| !schedule.paused).map(|at| at.timestamp_micros()),
1079 })
1080}
1081
1082fn decode_schedule(doc: &ScheduleDoc) -> Result<Schedule> {
1083 parse_json(&doc.schedule, "schedule", SCHEDULE_STORAGE)
1084}
1085
1086async fn read_schedule(db: &FirestoreDb, id: &str) -> TxResult<Option<Schedule>> {
1087 let Some(doc_id) = schedule_doc_id(id) else {
1088 return Ok(None);
1089 };
1090 let stored: Option<ScheduleDoc> = db
1091 .fluent()
1092 .select()
1093 .by_id_in(SCHEDULES)
1094 .obj::<ScheduleDoc>()
1095 .one(doc_id)
1096 .await
1097 .map_err(tx_fail(SCHEDULE_STORAGE))?;
1098 stored
1099 .filter(|doc| doc.id == id)
1100 .map(|doc| decode_schedule(&doc))
1101 .transpose()
1102 .map_err(BackoffError::permanent)
1103}
1104
1105fn write_schedule(
1106 db: &FirestoreDb,
1107 transaction: &mut firestore::FirestoreTransaction<'_>,
1108 schedule: &Schedule,
1109) -> TxResult<()> {
1110 let doc = schedule_doc(schedule)?;
1111 db.fluent()
1112 .update()
1113 .in_col(SCHEDULES)
1114 .document_id(hex(&schedule.id))
1115 .object(&doc)
1116 .add_to_transaction(transaction)
1117 .map_err(tx_fail(SCHEDULE_STORAGE))?;
1118 Ok(())
1119}
1120
1121#[derive(Clone)]
1151pub struct FirestoreScheduleStore {
1152 db: FirestoreDb,
1153}
1154
1155impl std::fmt::Debug for FirestoreScheduleStore {
1156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1157 f.debug_struct("FirestoreScheduleStore").finish_non_exhaustive()
1158 }
1159}
1160
1161impl FirestoreScheduleStore {
1162 pub async fn new(project_id: &str) -> Result<Self> {
1169 let db = connect(project_id).await.map_err(|e| storage_error(SCHEDULE_STORAGE, e))?;
1170 Ok(Self::from_db(db))
1171 }
1172
1173 pub fn from_db(db: FirestoreDb) -> Self {
1175 Self { db }
1176 }
1177
1178 pub async fn migrate(&self) -> Result<()> {
1188 Ok(())
1189 }
1190
1191 async fn change<T: Send + 'static>(
1194 &self,
1195 id: &str,
1196 op: Arc<dyn Fn(Schedule) -> (T, Option<Schedule>) + Send + Sync>,
1197 ) -> Result<T> {
1198 let id = Arc::new(id.to_string());
1199 self.db
1200 .run_transaction_with_options(
1201 move |db, transaction| -> TxFuture<'_, T> {
1202 let (op, id) = (op.clone(), id.clone());
1203 Box::pin(async move {
1204 let Some(stored) = read_schedule(&db, &id).await? else {
1205 return refuse(schedule_not_found_error(&id));
1206 };
1207 let (value, changed) = op(stored);
1208 if let Some(changed) = changed {
1209 write_schedule(&db, transaction, &changed)?;
1210 }
1211 Ok(value)
1212 })
1213 },
1214 transaction_options(),
1215 )
1216 .await
1217 .map_err(|e| transaction_error(e, |m| storage_error(SCHEDULE_STORAGE, m)))
1218 }
1219}
1220
1221#[async_trait]
1222impl ScheduleStore for FirestoreScheduleStore {
1223 async fn upsert(&self, schedule: Schedule) -> Result<Schedule> {
1224 schedule.validate()?;
1225 if schedule_doc_id(&schedule.id).is_none() {
1226 return Err(invalid_schedule_error(&format!(
1227 "a Firestore schedule id is at most {MAX_SCHEDULE_ID_BYTES} bytes"
1228 )));
1229 }
1230 let incoming = Arc::new(schedule);
1231 self.db
1232 .run_transaction_with_options(
1233 move |db, transaction| -> TxFuture<'_, Schedule> {
1234 let incoming = incoming.clone();
1235 Box::pin(async move {
1236 let mut schedule = (*incoming).clone();
1237 match read_schedule(&db, &schedule.id).await? {
1238 Some(stored) if same_definition(&stored, &schedule) => {
1239 return Ok(stored);
1240 }
1241 Some(stored) => schedule.revision = stored.revision + 1,
1242 None => schedule.revision = 1,
1243 }
1244 write_schedule(&db, transaction, &schedule)?;
1245 Ok(schedule)
1246 })
1247 },
1248 transaction_options(),
1249 )
1250 .await
1251 .map_err(|e| transaction_error(e, |m| storage_error(SCHEDULE_STORAGE, m)))
1252 }
1253
1254 async fn get(&self, id: &str) -> Result<Option<Schedule>> {
1255 read_schedule(&self.db, id).await.map_err(|e| match e {
1256 BackoffError::Permanent(error) | BackoffError::Transient { err: error, .. } => error,
1257 })
1258 }
1259
1260 async fn list(&self) -> Result<Vec<Schedule>> {
1261 let docs: Vec<ScheduleDoc> =
1262 self.db.fluent().select().from(SCHEDULES).obj::<ScheduleDoc>().query().await.map_err(
1263 |e| storage_error(SCHEDULE_STORAGE, format!("schedule query failed: {e}")),
1264 )?;
1265 let mut schedules = docs.iter().map(decode_schedule).collect::<Result<Vec<_>>>()?;
1266 schedules.sort_by(|a, b| a.id.cmp(&b.id));
1267 Ok(schedules)
1268 }
1269
1270 async fn delete(&self, id: &str) -> Result<()> {
1271 let id = Arc::new(id.to_string());
1272 self.db
1273 .run_transaction_with_options(
1274 move |db, transaction| -> TxFuture<'_, ()> {
1275 let id = id.clone();
1276 Box::pin(async move {
1277 if read_schedule(&db, &id).await?.is_none() {
1278 return refuse(schedule_not_found_error(&id));
1279 }
1280 db.fluent()
1281 .delete()
1282 .from(SCHEDULES)
1283 .document_id(hex(&id))
1284 .add_to_transaction(transaction)
1285 .map_err(tx_fail(SCHEDULE_STORAGE))?;
1286 Ok(())
1287 })
1288 },
1289 transaction_options(),
1290 )
1291 .await
1292 .map_err(|e| transaction_error(e, |m| storage_error(SCHEDULE_STORAGE, m)))
1293 }
1294
1295 async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule> {
1296 self.change(
1297 id,
1298 Arc::new(move |mut schedule: Schedule| {
1299 if schedule.paused == paused {
1300 return (schedule, None);
1301 }
1302 schedule.paused = paused;
1303 schedule.revision += 1;
1304 (schedule.clone(), Some(schedule))
1305 }),
1306 )
1307 .await
1308 }
1309
1310 async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>> {
1311 if limit == 0 {
1312 return Ok(Vec::new());
1313 }
1314 let now_us = now.timestamp_micros();
1315 let docs: Vec<ScheduleDoc> = self
1316 .db
1317 .fluent()
1318 .select()
1319 .from(SCHEDULES)
1320 .filter(|q| q.for_all([q.field("due_us").less_than_or_equal(now_us)]))
1321 .order_by([("due_us", FirestoreQueryDirection::Ascending)])
1324 .limit(u32::try_from(limit).unwrap_or(u32::MAX))
1325 .obj::<ScheduleDoc>()
1326 .query()
1327 .await
1328 .map_err(|e| storage_error(SCHEDULE_STORAGE, format!("schedule query failed: {e}")))?;
1329 let mut due = docs.iter().map(decode_schedule).collect::<Result<Vec<_>>>()?;
1330 due.retain(|schedule| {
1331 !schedule.paused && schedule.next_fire_at.is_some_and(|at| at <= now)
1332 });
1333 due.sort_by(|a, b| (a.next_fire_at, &a.id).cmp(&(b.next_fire_at, &b.id)));
1334 Ok(due)
1335 }
1336
1337 async fn advance(
1338 &self,
1339 id: &str,
1340 expected_revision: u64,
1341 next_fire_at: Option<DateTime<Utc>>,
1342 ) -> Result<bool> {
1343 self.change(
1344 id,
1345 Arc::new(move |mut schedule: Schedule| {
1346 if schedule.revision != expected_revision {
1347 return (false, None);
1348 }
1349 schedule.next_fire_at = next_fire_at;
1350 schedule.revision += 1;
1351 (true, Some(schedule))
1352 }),
1353 )
1354 .await
1355 }
1356}
1357
1358#[derive(Debug, Clone, Serialize, Deserialize)]
1363struct GovernanceDoc {
1364 key: String,
1365 state: String,
1367}
1368
1369fn governance_id(key: &str) -> String {
1370 document_id(&json!(["governance", key]))
1371}
1372
1373fn decode_governance(doc: &GovernanceDoc) -> Result<GovernanceState> {
1374 parse_json(&doc.state, "governance state", GOVERNANCE_STORAGE)
1375}
1376
1377async fn read_governance(db: &FirestoreDb, key: &str) -> TxResult<Option<GovernanceState>> {
1378 let stored: Option<GovernanceDoc> = db
1379 .fluent()
1380 .select()
1381 .by_id_in(GOVERNANCE)
1382 .obj::<GovernanceDoc>()
1383 .one(governance_id(key))
1384 .await
1385 .map_err(tx_fail(GOVERNANCE_STORAGE))?;
1386 stored
1387 .filter(|doc| doc.key == key)
1388 .map(|doc| decode_governance(&doc))
1389 .transpose()
1390 .map_err(BackoffError::permanent)
1391}
1392
1393#[derive(Clone)]
1415pub struct FirestoreGovernanceStateStore {
1416 db: FirestoreDb,
1417 clock: Arc<dyn Clock>,
1418}
1419
1420impl std::fmt::Debug for FirestoreGovernanceStateStore {
1421 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1422 f.debug_struct("FirestoreGovernanceStateStore")
1423 .field("clock", &self.clock)
1424 .finish_non_exhaustive()
1425 }
1426}
1427
1428impl FirestoreGovernanceStateStore {
1429 pub async fn new(project_id: &str) -> Result<Self> {
1436 let db = connect(project_id).await.map_err(|e| storage_error(GOVERNANCE_STORAGE, e))?;
1437 Ok(Self::from_db(db))
1438 }
1439
1440 pub fn from_db(db: FirestoreDb) -> Self {
1442 Self { db, clock: Arc::new(SystemClock) }
1443 }
1444
1445 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
1447 self.clock = clock;
1448 self
1449 }
1450
1451 pub async fn migrate(&self) -> Result<()> {
1461 Ok(())
1462 }
1463}
1464
1465#[async_trait]
1466impl GovernanceStateStore for FirestoreGovernanceStateStore {
1467 async fn get(&self, scope: &GovernanceScope) -> Result<Option<GovernanceState>> {
1468 read_governance(&self.db, &scope.key()).await.map_err(|e| match e {
1469 BackoffError::Permanent(error) | BackoffError::Transient { err: error, .. } => error,
1470 })
1471 }
1472
1473 async fn set(
1474 &self,
1475 scope: GovernanceScope,
1476 expected_epoch: u64,
1477 frozen: bool,
1478 reason: Option<String>,
1479 issued_by: Option<SubjectRef>,
1480 ) -> Result<GovernanceState> {
1481 let clock = self.clock.clone();
1482 let request = Arc::new((scope, reason, issued_by));
1483 self.db
1484 .run_transaction_with_options(
1485 move |db, transaction| -> TxFuture<'_, GovernanceState> {
1486 let (request, clock) = (request.clone(), clock.clone());
1487 Box::pin(async move {
1488 let (scope, reason, issued_by) = &*request;
1489 let key = scope.key();
1490 let current =
1491 read_governance(&db, &key).await?.map_or(0, |state| state.epoch);
1492 if current != expected_epoch {
1493 return refuse(governance_conflict_error(
1494 scope,
1495 expected_epoch,
1496 current,
1497 ));
1498 }
1499 let state = GovernanceState {
1500 scope: scope.clone(),
1501 frozen,
1502 reason: reason.clone(),
1503 issued_by: issued_by.clone(),
1504 issued_at: stored_now(clock.now()),
1505 epoch: current + 1,
1506 };
1507 let doc = GovernanceDoc {
1508 key: key.clone(),
1509 state: json_text(&state, GOVERNANCE_STORAGE)?,
1510 };
1511 db.fluent()
1512 .update()
1513 .in_col(GOVERNANCE)
1514 .document_id(governance_id(&key))
1515 .object(&doc)
1516 .add_to_transaction(transaction)
1517 .map_err(tx_fail(GOVERNANCE_STORAGE))?;
1518 Ok(state)
1519 })
1520 },
1521 transaction_options(),
1522 )
1523 .await
1524 .map_err(|e| transaction_error(e, |m| storage_error(GOVERNANCE_STORAGE, m)))
1525 }
1526
1527 async fn list(&self) -> Result<Vec<GovernanceState>> {
1528 let docs: Vec<GovernanceDoc> = self
1529 .db
1530 .fluent()
1531 .select()
1532 .from(GOVERNANCE)
1533 .obj::<GovernanceDoc>()
1534 .query()
1535 .await
1536 .map_err(|e| {
1537 storage_error(GOVERNANCE_STORAGE, format!("governance query failed: {e}"))
1538 })?;
1539 let mut states = docs.iter().map(decode_governance).collect::<Result<Vec<_>>>()?;
1540 states.sort_by_key(|state| state.scope.key());
1541 Ok(states)
1542 }
1543}
1544
1545#[cfg(test)]
1546mod tests {
1547 use super::*;
1548
1549 #[test]
1550 fn sortable_text_orders_like_the_integer() {
1551 let values = [i64::MIN, -5_000_000, -1, 0, 1, 1_800_000_000_000_000, i64::MAX];
1552 let keys: Vec<_> = values.iter().map(|value| sortable(*value)).collect();
1553 assert!(keys.windows(2).all(|pair| pair[0] < pair[1]), "{keys:?}");
1554 assert!(keys.iter().all(|key| key.len() == 20));
1555 }
1556
1557 #[test]
1558 fn claim_keys_stay_inside_their_queue_and_ready_range() {
1559 let prefix = queue_id("conformance:q/ü");
1560 let key = format!("{prefix}:{}:{}", sortable(10), sortable(3));
1561 let end = format!("{prefix}:{};", sortable(10));
1562 assert!(key.as_str() >= format!("{prefix}:").as_str() && key < end);
1563 let later = format!("{prefix}:{}:{}", sortable(11), sortable(1));
1564 assert!(later > end, "a run ready later is outside the range");
1565 assert_ne!(queue_id("a"), queue_id("b"));
1566 }
1567
1568 #[test]
1569 fn derived_fields_follow_the_state() {
1570 let run = NewRun::new("q", "a", "u", "t", json!({}))
1571 .with_concurrency_key("k", OnConflict::Enqueue);
1572 let mut record = RunRecord::queued(uuid::Uuid::new_v4().to_string(), run, Utc::now());
1573 let doc = run_doc(&record, 7).unwrap();
1574 assert!(doc.claim_key.is_some() && doc.finished_us.is_none());
1575 assert_eq!(doc.state, "queued");
1576 assert!(apply_cancel(&mut record, Utc::now()));
1577 let doc = run_doc(&record, 7).unwrap();
1578 assert!(doc.claim_key.is_none() && doc.finished_us.is_some());
1579 assert_eq!(decode_run(&doc).unwrap(), record);
1580 }
1581
1582 #[test]
1583 fn only_hyphenated_uuids_name_runs() {
1584 assert!(is_run_id(&uuid::Uuid::new_v4().to_string()));
1585 assert!(!is_run_id("conformance:missing/ü"));
1586 assert!(!is_run_id(&uuid::Uuid::new_v4().simple().to_string()));
1587 }
1588
1589 #[test]
1590 fn schedule_ids_keep_their_order_and_length_limit() {
1591 assert!(schedule_doc_id("a").unwrap() < schedule_doc_id("b").unwrap());
1592 assert!(schedule_doc_id(&"x".repeat(MAX_SCHEDULE_ID_BYTES + 1)).is_none());
1593 }
1594}