1pub mod admission;
17pub mod app_events;
18pub mod cap_alert;
19pub mod caps;
20pub mod cloud_events;
21pub mod cloud_hub;
22pub mod definition;
23pub mod expect;
24pub mod file_watch;
25pub mod follower;
26pub mod from_template;
27pub mod incidents;
28pub mod paused;
29pub mod policy;
30pub mod poll;
31pub mod remote;
32pub mod reporters;
33pub mod reservation;
34pub mod verdict;
35pub mod webhook_local;
36pub mod watchdog;
37
38use std::sync::Arc;
39
40use agentmux_common::time::now_ms;
41use serde_json::{json, Value};
42
43use crate::backend::cron::{FireOutcome, MissReason};
44use crate::backend::mps::Broker;
45use crate::backend::storage::job_runs::{infra, reason, state, JobFlag, JobRun, RunCost};
46use crate::backend::storage::store::Store;
47use crate::backend::storage::drone_store::DroneStore;
48
49pub const SOURCE_CRON: &str = "cron";
51pub const SOURCE_DRONE: &str = "drone";
52pub const SOURCE_CLOUD: &str = "cloud";
53
54pub const TRIGGER_SCHEDULE: &str = "schedule";
56pub const TRIGGER_CATCH_UP: &str = "catch_up";
57pub const TRIGGER_MANUAL: &str = "manual";
58pub const TRIGGER_RETRY: &str = "retry";
59pub const TRIGGER_EVENT: &str = "event";
60
61pub const BY_SCHEDULER: &str = "scheduler";
63pub const BY_OPERATOR: &str = "operator";
64pub const BY_EVENT: &str = "event";
66
67pub const CATCH_UP_SKIP: &str = "skip";
69pub const CATCH_UP_LATEST: &str = "latest";
70
71pub const FLAG_PAUSED_ALL: &str = "jobs:paused_all";
75
76pub const OVERLAP_REFUSAL: &str = "this job's previous run is still running (policy overlap: skip)";
79
80pub const PAUSED_ALL_REFUSAL: &str =
82 "the operator has paused every job (Pause all); Run now is off until they resume them";
83
84pub const DRONE_STATUS_INTERRUPTED: &str = "interrupted";
87
88pub fn pending_wake() -> &'static tokio::sync::Notify {
91 static WAKE: std::sync::LazyLock<tokio::sync::Notify> = std::sync::LazyLock::new(tokio::sync::Notify::new);
92 &WAKE
93}
94
95pub fn brief_line(run_id: &str, late_for_ms: Option<i64>, now_ms: i64) -> String {
101 let late = late_for_ms
102 .and_then(|slot| {
103 let slot = chrono::DateTime::from_timestamp_millis(slot)?;
104 let now = chrono::DateTime::from_timestamp_millis(now_ms)?;
105 Some(format!(
106 " It was due {} and started {} (late).",
107 slot.format("%Y-%m-%d %H:%M UTC"),
108 now.format("%Y-%m-%d %H:%M UTC")
109 ))
110 })
111 .unwrap_or_default();
112 format!(
113 "(Scheduled run {run_id}.{late} When it is done, say how it went: Schedule action report with run_id \
114 \"{run_id}\", outcome ok, findings or failed, and a one-line summary.)"
115 )
116}
117
118pub type BlockHook = Arc<dyn Fn(&str) + Send + Sync>;
120
121#[derive(Debug, Default)]
123struct Pane {
124 found: bool,
126 agent_uid: String,
127 account: String,
128 provider: String,
129}
130
131fn registered_here(block_id: &str) -> bool {
133 crate::backend::reactive::get_global_handler().list_agents().iter().any(|r| r.block_id == block_id)
134}
135
136fn registered_uid(block_id: &str) -> Option<String> {
138 if block_id.is_empty() {
139 return None;
140 }
141 crate::backend::reactive::get_global_handler()
142 .list_agents()
143 .into_iter()
144 .find(|r| r.block_id == block_id)
145 .and_then(|r| r.uid)
146 .filter(|u| !u.is_empty())
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
151pub enum Begin {
152 Run(String),
154 SlotTaken,
156 Unrecorded,
158}
159
160pub struct RunLedger {
163 store: Arc<Store>,
164 mstore: Option<Arc<Store>>,
167 channel: String,
169 recorded_by: String,
174 follower: follower::Follower,
175 broker: Arc<Broker>,
177 incidents: std::sync::OnceLock<Arc<incidents::Incidents>>,
179 jobs: std::sync::OnceLock<Arc<Store>>,
181 admission: std::sync::Mutex<()>,
183 pending_claims: std::sync::Mutex<std::collections::HashMap<String, String>>,
187 interrupt: std::sync::OnceLock<BlockHook>,
188 worker_stop: std::sync::OnceLock<BlockHook>,
189 remote_stop: std::sync::OnceLock<remote::RemoteStopHook>,
191 caps: std::sync::OnceLock<reservation::CapSources>,
194 #[cfg(any(test, feature = "test-support"))]
196 day_start: std::sync::Mutex<Option<Arc<dyn Fn(i64) -> i64 + Send + Sync>>>,
197 #[cfg(any(test, feature = "test-support"))]
199 cap_alerts: std::sync::Mutex<Vec<(String, String)>>,
200}
201
202impl RunLedger {
203 pub fn new(store: Arc<Store>, mstore: Option<Arc<Store>>, broker: Arc<Broker>) -> Arc<Self> {
206 Self::new_in(store, mstore, broker, &crate::backend::reactive::registry::local_channel_id())
207 }
208
209 pub fn new_in(store: Arc<Store>, mstore: Option<Arc<Store>>, broker: Arc<Broker>, channel: &str) -> Arc<Self> {
212 if let Err(e) = store.job_runs_ensure_schema() {
213 tracing::warn!(error = %e, "jobs: couldn't create the run ledger table");
214 }
215 Arc::new_cyclic(|weak: &std::sync::Weak<RunLedger>| RunLedger {
216 store: store.clone(),
217 mstore,
218 channel: channel.to_string(),
219 recorded_by: format!("{channel}@{}", env!("CARGO_PKG_VERSION")),
220 follower: follower::Follower::start(weak.clone(), broker.clone()),
221 broker,
222 incidents: std::sync::OnceLock::new(),
223 jobs: std::sync::OnceLock::new(),
224 admission: std::sync::Mutex::new(()),
225 pending_claims: std::sync::Mutex::default(),
226 interrupt: std::sync::OnceLock::new(),
227 worker_stop: std::sync::OnceLock::new(),
228 remote_stop: std::sync::OnceLock::new(),
229 caps: std::sync::OnceLock::new(),
230 #[cfg(any(test, feature = "test-support"))]
231 day_start: std::sync::Mutex::new(None),
232 #[cfg(any(test, feature = "test-support"))]
233 cap_alerts: std::sync::Mutex::new(Vec::new()),
234 })
235 }
236
237 pub fn store(&self) -> &Arc<Store> {
238 &self.store
239 }
240
241 pub fn install_incidents(&self, jobs: Option<Arc<Store>>) {
244 if let Some(jobs) = &jobs {
245 self.install_jobs(jobs.clone());
246 }
247 let keeper = incidents::Incidents::new(self.store.clone(), self.mstore.clone(), jobs, self.broker.clone());
248 if self.incidents.set(keeper.clone()).is_ok() {
249 keeper.start();
250 }
251 }
252
253 pub fn changed(&self, job_id: &str) {
257 let event = crate::backend::mps_events::JobsChangedEvent { job_id: job_id.to_string() };
258 self.broker.publish_event::<crate::backend::mps_events::JobsChanged>(&event, vec![], 0);
259 if !job_id.is_empty() {
260 if let Some(keeper) = self.incidents.get() {
261 keeper.nudge(job_id);
262 }
263 }
264 }
265
266 pub(crate) fn run_changed(&self, run_id: &str) {
268 let job_id = self.store.job_run_get(run_id).ok().flatten().map(|r| r.job_id).unwrap_or_default();
269 self.changed(&job_id);
270 }
271
272 pub fn paused_all(&self) -> Option<JobFlag> {
274 self.store.job_flag_get(FLAG_PAUSED_ALL).unwrap_or_else(|e| {
275 tracing::warn!(error = %e, "jobs: couldn't read Pause all");
276 None
277 })
278 }
279
280 pub fn set_paused_all(&self, on: bool, by: &str) -> Result<(), crate::backend::storage::StoreError> {
283 if on {
284 self.store.job_flag_set(FLAG_PAUSED_ALL, "1", by, now_ms())?;
285 } else {
286 self.store.job_flag_clear(FLAG_PAUSED_ALL)?;
287 }
288 self.changed("");
289 Ok(())
290 }
291
292 pub fn record_skip_slot(&self, job: &crate::backend::storage::cron::CronJob, slot_ms: i64, why: &str) {
297 let now = now_ms();
298 let mut run = self.row(&job.id, SOURCE_CRON, &job.name, TRIGGER_SCHEDULE, now);
299 run.state = state::SKIPPED.to_string();
300 run.reason = why.to_string();
301 run.scheduled_for_ms = Some(slot_ms);
302 run.triggered_by = BY_SCHEDULER.to_string();
303 run.target_agent_uid = job.target_uid.clone();
304 run.skip_count = 1;
305 run.last_skip_at_ms = Some(slot_ms);
306 run.ended_at_ms = Some(now);
307 match self.store.job_run_record_skip_slot(&run) {
308 Ok(()) => self.changed(&job.id),
309 Err(e) => tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record a paused slot"),
310 }
311 }
312
313 pub(crate) fn row(&self, job_id: &str, job_source: &str, job_name: &str, trigger: &str, now: i64) -> JobRun {
314 let mut run =
315 JobRun::new(&uuid::Uuid::new_v4().to_string(), job_id, job_source, job_name, trigger, state::SCHEDULED, now);
316 run.recorded_by = self.recorded_by.clone();
317 run
318 }
319
320 pub fn begin_cron(
324 &self,
325 job: &crate::backend::storage::cron::CronJob,
326 trigger: &str,
327 scheduled_for_ms: Option<i64>,
328 triggered_by: &str,
329 ) -> Begin {
330 let mut run = self.row(&job.id, SOURCE_CRON, &job.name, trigger, now_ms());
331 run.scheduled_for_ms = scheduled_for_ms;
332 run.triggered_by = triggered_by.to_string();
333 run.target_agent_uid = job.target_uid.clone();
334 match self.store.job_run_insert(&run) {
335 Ok(true) => Begin::Run(run.id),
336 Ok(false) => Begin::SlotTaken,
337 Err(e) => {
338 tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record a cron run");
339 Begin::Unrecorded
340 }
341 }
342 }
343
344 pub fn record_delivery(
351 &self,
352 run_id: &str,
353 job: &crate::backend::storage::cron::CronJob,
354 outcome: &FireOutcome,
355 scheduled: bool,
356 delivery_started_ms: i64,
357 ) {
358 let now = now_ms();
359 let latest = job.catch_up == CATCH_UP_LATEST;
360 let result = match outcome {
361 FireOutcome::Delivered { block_id } => {
362 self.mark_running(run_id, &job.target_uid, block_id.as_deref().unwrap_or(""), delivery_started_ms);
363 Ok(())
364 }
365 FireOutcome::Missed { reason: MissReason::TargetStopped } => {
366 let st = if latest && scheduled { state::PENDING } else { state::MISSED };
367 self.store.job_run_set_undelivered(run_id, st, reason::TARGET_STOPPED, now).map(drop)
368 }
369 FireOutcome::Missed { reason: MissReason::TargetMissing } => {
370 self.store.job_run_skip(run_id, reason::TARGET_MISSING, 1, now).map(drop)
371 }
372 FireOutcome::Failed { error } => {
373 let finished = self.store.job_run_finish(run_id, infra::ERROR, None, error, now);
374 self.maybe_retry(run_id);
375 self.reap_worker(run_id);
376 finished.map(drop)
377 }
378 };
379 if let Err(e) = result {
380 tracing::warn!(run_id, error = %e, "jobs: couldn't record a fire's delivery");
381 }
382 self.changed(&job.id);
383 if scheduled {
384 let now_pending = self.store.job_run_get(run_id).ok().flatten().is_some_and(|r| r.state == state::PENDING && r.ended_at_ms.is_none());
385 let why = if now_pending { reason::SUPERSEDED } else { reason::EXPIRED };
386 if let Err(e) = self.store.job_runs_end_pending(&job.id, run_id, why, now) {
387 tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't end an older pending fire");
388 }
389 }
390 }
391
392 pub fn record_pending_delivery(&self, run: &JobRun, outcome: &FireOutcome, delivery_started_ms: i64) {
399 let now = now_ms();
400 let result = match outcome {
401 FireOutcome::Delivered { block_id } => {
402 self.mark_running(&run.id, &run.target_agent_uid, block_id.as_deref().unwrap_or(""), delivery_started_ms);
403 Ok(())
404 }
405 FireOutcome::Missed { .. } => Ok(()),
406 FireOutcome::Failed { error } if retry_later(error) => Ok(()),
407 FireOutcome::Failed { error } => self.store.job_run_finish(&run.id, infra::ERROR, None, error, now).map(drop),
408 };
409 if let Err(e) = result {
410 tracing::warn!(run_id = %run.id, error = %e, "jobs: couldn't record a pending fire's delivery");
411 }
412 self.changed(&run.job_id);
413 }
414
415 pub fn expire_pending(&self, run_id: &str) {
417 if let Err(e) = self.store.job_run_end_one_pending(run_id, reason::EXPIRED, now_ms()) {
418 tracing::warn!(run_id, error = %e, "jobs: couldn't expire a pending fire");
419 }
420 self.run_changed(run_id);
421 }
422
423 pub fn waiting_here(&self) -> Vec<JobRun> {
425 self.store
426 .job_runs_open_recorded_by(&self.channel, SOURCE_CRON, &[state::PENDING])
427 .unwrap_or_default()
428 .into_iter()
429 .filter(|r| r.ended_at_ms.is_none())
430 .collect()
431 }
432
433 pub(crate) fn mark_running(&self, run_id: &str, target_uid: &str, block_id: &str, now: i64) {
443 let pane = self.pane(block_id);
444 let remote = !block_id.is_empty() && self.mstore.is_some() && !pane.found && !registered_here(block_id);
445 if remote && self.followed_elsewhere(run_id) {
446 self.follower.watch(run_id, now);
448 return;
449 }
450 let receiver = [pane.agent_uid.as_str(), registered_uid(block_id).as_deref().unwrap_or(""), target_uid]
451 .into_iter()
452 .find(|u| !u.is_empty())
453 .unwrap_or("")
454 .to_string();
455 let (account, provider) = (pane.account, pane.provider);
456 if let Err(e) = self.store.job_run_mark_running(run_id, &receiver, block_id, &account, &provider, now) {
457 tracing::warn!(run_id, error = %e, "jobs: couldn't mark a run running");
458 return;
459 }
460 if block_id.is_empty() {
461 self.turn_finished(run_id, infra::OK, None, "delivered; AgentMux can't follow this run's turn");
465 return;
466 }
467 if remote {
468 self.follower.watch(run_id, now);
470 return;
471 }
472 let _ = self.store.job_run_add_links(run_id, &json!({ "transcript": { "block_id": block_id } }));
473 self.follower.arm(block_id, run_id, now, self.stop_at_usd(run_id, &provider));
474 }
475
476 fn pane(&self, block_id: &str) -> Pane {
479 let Some(mstore) = &self.mstore else { return Pane::default() };
480 if block_id.is_empty() {
481 return Pane::default();
482 }
483 let Ok(Some(block)) = mstore.get::<crate::backend::obj::Block>(block_id) else {
484 return Pane::default();
485 };
486 let account = crate::backend::obj::meta_get_string(
487 &block.meta,
488 crate::backend::agent_state::RUN_ACCOUNT_META_KEY,
489 "",
490 );
491 let agent_uid = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
492 let provider = match mstore.agent_def_get(&agent_uid) {
493 Ok(Some(def)) if !agent_uid.is_empty() => crate::backend::providers::resolve_provider_alias(&def.provider).to_string(),
494 _ => String::new(),
495 };
496 Pane { found: true, agent_uid, account, provider }
497 }
498
499 pub fn record_missed_while_off(&self, job: &crate::backend::storage::cron::CronJob, first_slot_ms: i64, count: i64) {
502 if count <= 0 {
503 return;
504 }
505 let Begin::Run(id) = self.begin_cron(job, TRIGGER_SCHEDULE, Some(first_slot_ms), BY_SCHEDULER) else {
506 return;
507 };
508 if let Err(e) = self.store.job_run_skip(&id, reason::APP_NOT_RUNNING, count, now_ms()) {
509 tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record missed slots");
510 }
511 self.changed(&job.id);
512 }
513
514 pub fn turn_finished(&self, run_id: &str, infra_status: &str, cost: Option<RunCost>, summary: &str) {
516 match self.store.job_run_finish(run_id, infra_status, cost, summary, now_ms()) {
520 Ok(true) => {
521 self.maybe_retry(run_id);
522 self.reap_worker(run_id);
523 }
524 Ok(false) => {}
525 Err(e) => tracing::warn!(run_id, error = %e, "jobs: couldn't close a run"),
526 }
527 self.run_changed(run_id);
528 pending_wake().notify_one();
529 }
530
531 pub(crate) fn turn_bound(&self, run_id: &str, turn_id: i64, partial: bool) {
532 if let Err(e) = self.store.job_run_bind_turn(run_id, turn_id, partial) {
533 tracing::warn!(run_id, error = %e, "jobs: couldn't record a run's turn");
534 }
535 }
536
537 pub fn drone_started(
539 &self,
540 drone_run_id: &str,
541 drone_id: &str,
542 drone_name: &str,
543 started_at_ms: i64,
544 trigger: &Value,
545 ) -> Option<String> {
546 self.drone_started_by(drone_run_id, drone_id, drone_name, started_at_ms, trigger, BY_OPERATOR)
547 }
548
549 pub fn drone_started_by(
552 &self,
553 drone_run_id: &str,
554 drone_id: &str,
555 drone_name: &str,
556 started_at_ms: i64,
557 trigger: &Value,
558 triggered_by: &str,
559 ) -> Option<String> {
560 let mut run = self.row(drone_id, SOURCE_DRONE, drone_name, TRIGGER_MANUAL, started_at_ms);
561 run.state = state::RUNNING.to_string();
562 run.triggered_by = triggered_by.to_string();
563 run.links = json!({
564 "drone_run_id": drone_run_id,
565 "channel": crate::backend::reactive::registry::local_channel_id(),
566 });
567 add_trigger_digest(&mut run.links, trigger);
568 match self.store.job_run_insert(&run) {
569 Ok(true) => {
570 self.changed(drone_id);
571 Some(run.id)
572 }
573 Ok(false) => None,
574 Err(e) => {
575 tracing::warn!(drone_id, error = %e, "jobs: couldn't record a Drone run");
576 None
577 }
578 }
579 }
580
581 pub fn drone_attached(&self, run_id: &str, drone_run_id: &str, trigger: &Value, now: i64) {
585 if let Err(e) = self.store.job_run_mark_running(run_id, "", "", "", "", now) {
586 tracing::warn!(run_id, error = %e, "jobs: couldn't mark a Drone run running");
587 return;
588 }
589 let mut links = json!({
590 "drone_run_id": drone_run_id,
591 "channel": crate::backend::reactive::registry::local_channel_id(),
592 });
593 add_trigger_digest(&mut links, trigger);
594 if let Err(e) = self.store.job_run_add_links(run_id, &links) {
595 tracing::warn!(run_id, error = %e, "jobs: couldn't link a Drone run");
596 }
597 self.run_changed(run_id);
598 }
599
600 pub fn drone_finished(
603 &self,
604 run_id: &str,
605 ok: bool,
606 block_states: &std::collections::HashMap<String, crate::backend::storage::drone_types::BlockState>,
607 error: &str,
608 ) {
609 let infra_status = if ok { infra::OK } else { infra::ERROR };
610 self.turn_finished(run_id, infra_status, Some(drone_cost(block_states)), error);
611 }
612
613 pub fn drone_stopped(
616 &self,
617 run_id: &str,
618 block_states: &std::collections::HashMap<String, crate::backend::storage::drone_types::BlockState>,
619 reason: &str,
620 ) {
621 self.turn_finished(run_id, infra::INTERRUPTED, Some(drone_cost(block_states)), reason);
622 }
623
624 pub fn recover_after_restart(&self) -> usize {
632 self.recover_after_restart_except(&std::collections::HashSet::new())
633 }
634
635 pub fn open_run_of_drone(&self, drone_run_id: &str) -> Option<String> {
638 let sources: [(&str, &[&str]); 2] = [(SOURCE_CRON, &[state::SCHEDULED, state::RUNNING]), (SOURCE_DRONE, &[state::RUNNING])];
639 sources
640 .into_iter()
641 .flat_map(|(source, states)| self.store.job_runs_open_recorded_by(&self.channel, source, states).unwrap_or_default())
642 .find(|r| r.links["drone_run_id"].as_str() == Some(drone_run_id))
643 .map(|r| r.id)
644 }
645
646 pub fn recover_after_restart_except(&self, resuming: &std::collections::HashSet<String>) -> usize {
651 let now = now_ms();
652 let is_resuming = |r: &JobRun| r.links["drone_run_id"].as_str().is_some_and(|d| resuming.contains(d));
653 let open = |source: &str, states: &[&str]| {
654 self.store.job_runs_open_recorded_by(&self.channel, source, states).unwrap_or_else(|e| {
655 tracing::warn!(error = %e, "jobs: couldn't read open runs");
656 Vec::new()
657 })
658 };
659 let mut closed = 0;
660 let followed_here = self.store.job_runs_open_followed_by(&self.channel).unwrap_or_else(|e| {
661 tracing::warn!(error = %e, "jobs: couldn't read followed runs");
662 Vec::new()
663 });
664 let (ours, followed_elsewhere): (Vec<JobRun>, Vec<JobRun>) = open(SOURCE_CRON, &[state::SCHEDULED, state::RUNNING])
667 .into_iter()
668 .filter(|r| !(r.state == state::SCHEDULED && reason::WAITING.contains(&r.reason.as_str())))
669 .partition(|r| remote::followed_by(r).is_none_or(|f| f.channel == self.channel));
670 for run in &followed_elsewhere {
671 self.follower.watch(&run.id, now);
672 }
673 let stale = ours.into_iter().chain(open(SOURCE_DRONE, &[state::RUNNING])).chain(followed_here).filter(|r| !is_resuming(r));
674 let mut jobs = std::collections::BTreeSet::new();
675 for run in stale {
676 if self.store.job_run_finish(&run.id, infra::INTERRUPTED, None, "AgentMux restarted during this run", now).unwrap_or(false) {
677 closed += 1;
678 jobs.insert(run.job_id);
679 }
680 }
681 if let Some(mstore) = &self.mstore {
682 let except: Vec<String> = resuming.iter().cloned().collect();
683 match mstore.drone_runs_mark_interrupted(DRONE_STATUS_INTERRUPTED, now, &except) {
684 Ok(n) if n > 0 => tracing::info!(count = n, "jobs: Drone runs interrupted by the restart marked"),
685 Ok(_) => {}
686 Err(e) => tracing::warn!(error = %e, "jobs: couldn't mark interrupted Drone runs"),
687 }
688 }
689 if closed > 0 {
690 tracing::info!(count = closed, "jobs: closed runs left open by the restart");
691 self.changed("");
692 for job_id in jobs {
693 self.changed(&job_id);
694 }
695 }
696 closed
697 }
698}
699
700fn retry_later(error: &str) -> bool {
705 crate::backend::reactive::is_transient_delivery_error(error)
706 || crate::backend::reactive::is_spawn_gate_refusal(error)
707 || crate::backend::reactive::is_unavailable_refusal(error)
708 || error.contains("out of quota")
709 || error.contains("usage limit")
710}
711
712fn add_trigger_digest(links: &mut Value, trigger: &Value) {
716 use sha2::{Digest, Sha256};
717 if trigger.is_null() {
718 return;
719 }
720 let body = trigger.to_string();
721 links["trigger"] = json!({ "sha256": hex::encode(Sha256::digest(body.as_bytes())), "bytes": body.len() });
722}
723
724pub fn drone_cost(block_states: &std::collections::HashMap<String, crate::backend::storage::drone_types::BlockState>) -> RunCost {
728 let mut cost = RunCost::default();
729 for b in block_states.values() {
730 let Some(out) = &b.output else { continue };
731 if let Some(c) = out.get("cost_usd").and_then(|v| v.as_f64()) {
732 cost.cost_usd += c;
733 cost.cost_known = true;
734 }
735 if let Some(t) = out.pointer("/tokens/output").and_then(|v| v.as_i64()) {
736 cost.output_tokens += t;
737 }
738 }
739 cost
740}
741
742pub fn missed_slots(
748 schedule: &crate::backend::cron::schedule::JobSchedule,
749 base_ms: i64,
750 now_ms: i64,
751 cap: usize,
752) -> Option<(i64, Option<(i64, i64)>)> {
753 let newest = schedule.prev_before(now_ms)?;
754 if newest <= base_ms {
755 return None;
756 }
757 let mut first = None;
758 let mut count: i64 = 0;
759 for ms in schedule.after(base_ms).take(cap) {
760 if ms >= newest {
761 break;
762 }
763 first.get_or_insert(ms);
764 count += 1;
765 }
766 Some((newest, first.map(|f| (f, count))))
767}
768
769pub fn registered_in_another_channel(shared_dir: &std::path::Path, uid: &str, channel: &str) -> bool {
775 !uid.is_empty()
776 && crate::backend::reactive::registry::list_all_shared(shared_dir)
777 .iter()
778 .any(|e| e.uid == uid && e.channel != channel && e.srv_alive())
779}
780
781pub fn next_slot_after(job: &crate::backend::storage::cron::CronJob, slot_ms: i64) -> Option<i64> {
785 crate::backend::cron::schedule::JobSchedule::of(job).ok()?.next_after(slot_ms)
786}
787
788#[cfg(test)]
789#[path = "tests.rs"]
790mod tests;