1use std::collections::{BTreeMap, VecDeque};
29use std::marker::PhantomData;
30use std::sync::atomic::{AtomicBool, Ordering};
31use std::sync::{Arc, Mutex};
32use std::time::{Duration, Instant};
33
34use serde::de::DeserializeOwned;
35use serde::{Deserialize, Serialize};
36use tokio::sync::watch;
37use weirdnet_net::Node;
38use weirdnet_sync::{
39 FenceGuard, Hlc, JobEvent, JobRules, JobSpec, JobStatus, JobView, Jobs, LeaseConfig, LeaseError, LeaseHandle, LeaseName, Leases, Stale,
40 SyncState, Term, Voter, Voters, job_lease,
41};
42
43pub type PeerId = String;
45pub const MAX_PAYLOAD: usize = 64 * 1024;
47pub const RETENTION: Duration = Duration::from_secs(30 * 24 * 3600);
50pub const KEEP_CHECKPOINTS: usize = 8;
52pub const PROGRESS_EVERY: Duration = Duration::from_secs(30);
54const NOTE_PROGRESS: &str = "progress";
55const NOTE_HOLDERS: &str = "holders";
56
57type SyncNode = Node<Vec<u8>, Vec<u8>>;
58
59#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)]
61pub struct ContentHash(pub [u8; 32]);
62
63impl ContentHash {
64 pub fn short(&self) -> String {
66 format!("sha256:{}", &hex(&self.0)[..16])
67 }
68}
69
70fn hex(b: &[u8]) -> String {
71 b.iter().map(|x| format!("{x:02x}")).collect()
72}
73
74impl std::fmt::Display for ContentHash {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 write!(f, "sha256:{}", hex(&self.0))
77 }
78}
79
80impl std::fmt::Debug for ContentHash {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 std::fmt::Display::fmt(self, f)
83 }
84}
85
86impl std::str::FromStr for ContentHash {
87 type Err = JobError;
88 fn from_str(s: &str) -> Result<Self, JobError> {
89 let h = s.strip_prefix("sha256:").unwrap_or(s);
90 if h.len() != 64 || !h.bytes().all(|c| c.is_ascii_hexdigit()) {
91 return Err(JobError::Codec(format!("not a sha256 digest: {s:?}")));
92 }
93 let mut out = [0u8; 32];
94 for (i, o) in out.iter_mut().enumerate() {
95 *o = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).map_err(|e| JobError::Codec(e.to_string()))?;
96 }
97 Ok(Self(out))
98 }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
103#[non_exhaustive]
104pub enum JobState {
105 Queued,
106 Running,
107 Paused,
108 Failed,
109 Done,
110 Cancelled,
111}
112
113impl From<JobStatus> for JobState {
114 fn from(s: JobStatus) -> Self {
115 match s {
116 JobStatus::Open => JobState::Queued,
117 JobStatus::Claimed => JobState::Running,
118 JobStatus::Paused => JobState::Paused,
119 JobStatus::Done => JobState::Done,
120 JobStatus::Cancelled => JobState::Cancelled,
121 _ => JobState::Failed,
122 }
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[non_exhaustive]
129pub struct LeaseInfo {
130 pub holder: PeerId,
131 pub term: u64,
133 pub expires_ms: u64,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[non_exhaustive]
141pub struct CheckpointRef {
142 pub seq: u64,
144 pub step: u64,
146 pub root: ContentHash,
148 pub bytes: u64,
149 pub holders: Vec<PeerId>,
151}
152
153impl CheckpointRef {
154 pub fn new(seq: u64, step: u64, root: ContentHash, bytes: u64, holders: Vec<PeerId>) -> Self {
155 Self { seq, step, root, bytes, holders }
156 }
157}
158
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161#[non_exhaustive]
162pub struct JobPolicy {
163 pub claim_ms: u64,
165 pub renew_ms: u64,
167 pub takeover_after_ms: u64,
169 pub max_attempts: u32,
171 pub retry_backoff_ms: u64,
173 pub candidates: Vec<PeerId>,
175 pub role: String,
177}
178
179impl Default for JobPolicy {
180 fn default() -> Self {
182 Self {
183 claim_ms: 60_000,
184 renew_ms: 20_000,
185 takeover_after_ms: 300_000,
186 max_attempts: 3,
187 retry_backoff_ms: 60_000,
188 candidates: Vec::new(),
189 role: String::new(),
190 }
191 }
192}
193
194impl JobPolicy {
195 pub fn for_role(role: impl Into<String>) -> Self {
197 Self { role: role.into(), ..Self::default() }
198 }
199
200 pub fn with_claim(mut self, claim: Duration) -> Self {
202 self.claim_ms = ms(claim);
203 self.renew_ms = self.claim_ms / 3;
204 self
205 }
206
207 pub fn with_renew(mut self, every: Duration) -> Self {
208 self.renew_ms = ms(every);
209 self
210 }
211
212 pub fn with_takeover_after(mut self, wait: Duration) -> Self {
213 self.takeover_after_ms = ms(wait);
214 self
215 }
216
217 pub fn with_max_attempts(mut self, n: u32) -> Self {
218 self.max_attempts = n.max(1);
219 self
220 }
221
222 pub fn with_retry_backoff(mut self, wait: Duration) -> Self {
223 self.retry_backoff_ms = ms(wait);
224 self
225 }
226
227 pub fn with_candidates<S: Into<PeerId>>(mut self, peers: impl IntoIterator<Item = S>) -> Self {
228 self.candidates = peers.into_iter().map(Into::into).collect();
229 self
230 }
231
232 pub fn claim(&self) -> Duration {
233 Duration::from_millis(self.claim_ms)
234 }
235
236 pub fn takeover_after(&self) -> Duration {
237 Duration::from_millis(self.takeover_after_ms)
238 }
239
240 fn voters(&self) -> Voters {
241 if self.role.is_empty() { Voters::Peers(self.candidates.clone()) } else { Voters::Role(self.role.clone()) }
242 }
243
244 pub fn configure_voter(&self, voter: Voter, kind: &str) -> Voter {
247 voter.with_limits(format!("{kind}/"), self.claim(), self.takeover_after())
248 }
249
250 pub fn voter(&self, kind: &str) -> Voter {
254 self.configure_voter(Voter::new(self.voters()), kind)
255 }
256
257 fn rules(&self) -> JobRules {
258 let mut r = JobRules::new()
259 .with_takeover_after(self.takeover_after())
260 .with_retry_backoff(Duration::from_millis(self.retry_backoff_ms))
261 .with_candidates(self.candidates.clone());
262 if !self.role.is_empty() {
263 r = r.with_role(self.role.clone());
264 }
265 r
266 }
267}
268
269fn ms(d: Duration) -> u64 {
270 d.as_millis().min(u64::MAX as u128) as u64
271}
272
273#[derive(Debug, Clone, PartialEq)]
275#[non_exhaustive]
276pub struct JobRecord<P> {
277 pub id: String,
278 pub kind: String,
279 pub owner: PeerId,
282 pub base_revision: String,
283 pub dataset: ContentHash,
284 pub payload: P,
285 pub state: JobState,
286 pub lease: Option<LeaseInfo>,
288 pub checkpoint: Option<CheckpointRef>,
290 pub attempts: u32,
291 pub policy: JobPolicy,
292 pub failure: Option<String>,
293 pub result: Option<Vec<u8>>,
294 pub progress: Option<serde_json::Value>,
296 pub priority: u8,
297 pub created_ms: u64,
298 pub not_before_ms: Option<u64>,
300 pub updated: Hlc,
302}
303
304#[derive(Debug, Clone, PartialEq)]
306#[non_exhaustive]
307pub struct NewJob<P> {
308 pub id: String,
309 pub base_revision: String,
310 pub dataset: ContentHash,
311 pub payload: P,
312 pub policy: JobPolicy,
313 pub priority: u8,
314}
315
316impl<P> NewJob<P> {
317 pub fn new(id: impl Into<String>, base_revision: impl Into<String>, dataset: ContentHash, payload: P) -> Self {
319 Self { id: id.into(), base_revision: base_revision.into(), dataset, payload, policy: JobPolicy::default(), priority: 0 }
320 }
321
322 pub fn with_policy(mut self, policy: JobPolicy) -> Self {
323 self.policy = policy;
324 self
325 }
326
327 pub fn with_priority(mut self, priority: u8) -> Self {
328 self.priority = priority;
329 self
330 }
331}
332
333#[derive(Debug, Clone, Default, PartialEq, Eq)]
335#[non_exhaustive]
336pub struct JobFilter {
337 pub state: Option<JobState>,
338 pub owner: Option<PeerId>,
339 pub include_old: bool,
341}
342
343impl JobFilter {
344 pub fn all() -> Self {
345 Self::default()
346 }
347
348 pub fn state(state: JobState) -> Self {
349 Self { state: Some(state), ..Self::default() }
350 }
351
352 pub fn with_owner(mut self, owner: impl Into<PeerId>) -> Self {
353 self.owner = Some(owner.into());
354 self
355 }
356
357 pub fn with_old(mut self) -> Self {
358 self.include_old = true;
359 self
360 }
361}
362
363#[derive(Debug, Clone, PartialEq)]
365#[non_exhaustive]
366pub struct JobChange<P> {
367 pub id: String,
368 pub record: JobRecord<P>,
369}
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373#[non_exhaustive]
374pub enum Lost {
375 Lease,
377 Superseded,
379 PausedByOwner,
381 Cancelled,
383 Released,
385}
386
387#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
389#[non_exhaustive]
390pub enum JobError {
391 #[error("no job {0}")]
392 NotFound(String),
393 #[error("job is {0:?}")]
394 NotClaimable(JobState),
395 #[error("this device may not claim the job")]
397 Ineligible,
398 #[error("not claimable yet, retry in {retry_in:?}")]
400 NotYet { retry_in: Duration },
401 #[error("held by {holder}, retry in {retry_in:?}")]
403 Held { holder: PeerId, retry_in: Duration },
404 #[error("no quorum: {reached} of {needed} grants")]
405 NoQuorum { reached: usize, needed: usize },
406 #[error("not holding the claim")]
408 NotHolding,
409 #[error("payload is {0} bytes encoded, over the limit")]
410 PayloadTooLarge(usize),
411 #[error("a job needs a role or candidates")]
412 NoVoters,
413 #[error("codec: {0}")]
414 Codec(String),
415 #[error("sync: {0}")]
416 Sync(String),
417}
418
419pub type ClaimError = JobError;
421
422impl From<LeaseError> for JobError {
423 fn from(e: LeaseError) -> Self {
424 match e {
425 LeaseError::Held { holder, retry_in, .. } => JobError::Held { holder, retry_in },
426 LeaseError::NoQuorum { reached, needed } => JobError::NoQuorum { reached, needed },
427 LeaseError::NotEligible => JobError::Ineligible,
428 LeaseError::NotYet { retry_in } => JobError::NotYet { retry_in },
429 LeaseError::Lost => JobError::NotHolding,
430 other => JobError::Sync(other.to_string()),
431 }
432 }
433}
434
435impl From<weirdnet_sync::SyncError> for JobError {
436 fn from(e: weirdnet_sync::SyncError) -> Self {
437 JobError::Sync(e.to_string())
438 }
439}
440
441fn enc<T: Serialize>(v: &T) -> Result<Vec<u8>, JobError> {
442 cbor4ii::serde::to_vec(Vec::new(), v).map_err(|e| JobError::Codec(e.to_string()))
443}
444
445fn dec<T: DeserializeOwned>(b: &[u8]) -> Result<T, JobError> {
446 cbor4ii::serde::from_slice(b).map_err(|e| JobError::Codec(e.to_string()))
447}
448
449fn now_ms() -> u64 {
450 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
451}
452
453#[derive(Serialize, Deserialize)]
455struct Body<P> {
456 base_revision: String,
457 dataset: ContentHash,
458 payload: P,
459 renew_ms: u64,
460 created_ms: u64,
461}
462
463#[derive(Clone)]
465pub struct SyncHandle {
466 leases: Leases,
467}
468
469impl SyncHandle {
470 pub fn new(node: Arc<SyncNode>, state: Arc<Mutex<SyncState>>) -> Self {
471 Self { leases: Leases::new(node, state) }
472 }
473
474 pub fn from_leases(leases: Leases) -> Self {
476 Self { leases }
477 }
478
479 pub fn leases(&self) -> &Leases {
480 &self.leases
481 }
482
483 pub fn state(&self) -> &Arc<Mutex<SyncState>> {
484 self.leases.state()
485 }
486}
487
488fn lock(st: &Mutex<SyncState>) -> Result<std::sync::MutexGuard<'_, SyncState>, JobError> {
489 st.lock().map_err(|_| JobError::Sync("sync state lock poisoned".into()))
490}
491
492pub struct JobBoard<P> {
494 sync: SyncHandle,
495 kind: String,
496 _p: PhantomData<fn() -> P>,
497}
498
499impl<P> Clone for JobBoard<P> {
500 fn clone(&self) -> Self {
501 Self { sync: self.sync.clone(), kind: self.kind.clone(), _p: PhantomData }
502 }
503}
504
505impl<P: Serialize + DeserializeOwned + Clone + Send + Sync + 'static> JobBoard<P> {
506 pub fn open(sync: &SyncHandle, kind: impl Into<String>) -> Result<Self, JobError> {
509 let kind = kind.into();
510 job_lease(&kind, "x")?;
511 Ok(Self { sync: sync.clone(), kind, _p: PhantomData })
512 }
513
514 pub fn kind(&self) -> &str {
515 &self.kind
516 }
517
518 pub fn post(&self, job: NewJob<P>) -> Result<JobRecord<P>, JobError> {
520 job_lease(&self.kind, &job.id)?;
521 if job.policy.role.is_empty() && job.policy.candidates.is_empty() {
522 return Err(JobError::NoVoters);
523 }
524 let size = enc(&job.payload)?.len();
525 if size > MAX_PAYLOAD {
526 return Err(JobError::PayloadTooLarge(size));
527 }
528 let body = Body {
529 base_revision: job.base_revision,
530 dataset: job.dataset,
531 payload: job.payload,
532 renew_ms: job.policy.renew_ms,
533 created_ms: now_ms(),
534 };
535 let spec = JobSpec::new(job.id.clone(), self.kind.clone(), enc(&body)?)
536 .with_priority(job.priority)
537 .with_max_attempts(job.policy.max_attempts)
538 .with_claim(job.policy.claim())
539 .with_rules(job.policy.rules());
540 let mut st = lock(self.sync.state())?;
541 Jobs::new(&mut st, self.kind.clone()).post(now_ms(), spec)?;
542 let view = Jobs::new(&mut st, self.kind.clone()).view(&job.id).ok_or_else(|| JobError::NotFound(job.id.clone()))?;
543 self.record(&st, view)
544 }
545
546 fn record(&self, st: &SyncState, v: JobView) -> Result<JobRecord<P>, JobError> {
547 let body: Body<P> = dec(&v.spec.body)?;
548 let rules = v.spec.rules.clone().unwrap_or_default();
549 let policy = JobPolicy {
550 claim_ms: v.spec.claim_ms,
551 renew_ms: body.renew_ms,
552 takeover_after_ms: rules.takeover_after_ms,
553 max_attempts: v.spec.max_attempts,
554 retry_backoff_ms: rules.retry_backoff_ms,
555 candidates: rules.candidates.clone(),
556 role: rules.role.clone().unwrap_or_default(),
557 };
558 let state = JobState::from(v.status);
559 let lease = v.claim.as_ref().filter(|_| state == JobState::Running).map(|(holder, term)| LeaseInfo {
560 holder: holder.clone(),
561 term: term.0,
562 expires_ms: v.last_seen_ms.unwrap_or(v.changed_ms).saturating_add(v.spec.claim_ms),
563 });
564 let mut checkpoint = latest_checkpoint(&v);
565 if let (Some(cp), Some((_, data))) = (checkpoint.as_mut(), v.notes.get(NOTE_HOLDERS))
566 && let Ok((seq, holders)) = dec::<(u64, Vec<PeerId>)>(data)
567 && seq == cp.seq
568 {
569 cp.holders = holders;
570 }
571 let progress = v.notes.get(NOTE_PROGRESS).and_then(|(_, d)| serde_json::from_slice(d).ok());
572 let updated = st
573 .log
574 .iter()
575 .filter(|e| e.typ == self.kind && e.record_id == v.spec.id)
576 .map(|e| e.hlc.clone())
577 .max_by(|a, b| a.cmp_total(b))
578 .ok_or_else(|| JobError::NotFound(v.spec.id.clone()))?;
579 Ok(JobRecord {
580 id: v.spec.id.clone(),
581 kind: v.spec.kind.clone(),
582 owner: v.owner.clone(),
583 base_revision: body.base_revision,
584 dataset: body.dataset,
585 payload: body.payload,
586 state,
587 lease,
588 checkpoint,
589 attempts: v.attempts,
590 policy,
591 failure: v.failure.clone(),
592 result: v.result.clone(),
593 progress,
594 priority: v.spec.priority,
595 created_ms: body.created_ms,
596 not_before_ms: v.not_before_ms,
597 updated,
598 })
599 }
600
601 fn view(&self, st: &mut SyncState, id: &str) -> Option<JobView> {
602 Jobs::new(st, self.kind.clone()).view(id)
603 }
604
605 pub fn get(&self, id: &str) -> Result<Option<JobRecord<P>>, JobError> {
606 let mut st = lock(self.sync.state())?;
607 match self.view(&mut st, id) {
608 Some(v) => self.record(&st, v).map(Some),
609 None => Ok(None),
610 }
611 }
612
613 pub fn list(&self, filter: &JobFilter) -> Result<Vec<JobRecord<P>>, JobError> {
616 let mut st = lock(self.sync.state())?;
617 let ids = Jobs::new(&mut st, self.kind.clone()).ids();
618 let cutoff = now_ms().saturating_sub(ms(RETENTION));
619 let mut out = Vec::new();
620 for id in ids {
621 let Some(v) = self.view(&mut st, &id) else { continue };
622 let old = matches!(v.status, JobStatus::Done | JobStatus::Cancelled) && v.changed_ms < cutoff;
623 if old && !filter.include_old {
624 continue;
625 }
626 let Ok(r) = self.record(&st, v) else { continue };
627 if filter.state.is_some_and(|s| s != r.state) || filter.owner.as_ref().is_some_and(|o| *o != r.owner) {
628 continue;
629 }
630 out.push(r);
631 }
632 out.sort_by(|a, b| b.priority.cmp(&a.priority).then_with(|| a.id.cmp(&b.id)));
633 Ok(out)
634 }
635
636 pub fn checkpoints(&self, id: &str) -> Result<Vec<CheckpointRef>, JobError> {
638 let mut st = lock(self.sync.state())?;
639 let v = self.view(&mut st, id).ok_or_else(|| JobError::NotFound(id.to_string()))?;
640 let mut cps: Vec<(Term, u64, CheckpointRef)> =
641 v.checkpoints.iter().filter_map(|(t, s, d)| dec::<CheckpointRef>(d).ok().map(|c| (*t, *s, c))).collect();
642 cps.sort_by_key(|c| (c.0, c.1));
643 let skip = cps.len().saturating_sub(KEEP_CHECKPOINTS);
644 Ok(cps.into_iter().skip(skip).map(|c| c.2).collect())
645 }
646
647 pub fn watch(&self) -> impl futures::Stream<Item = JobChange<P>> + Send + 'static {
649 self.watch_every(Duration::from_secs(1))
650 }
651
652 pub fn watch_every(&self, every: Duration) -> impl futures::Stream<Item = JobChange<P>> + Send + 'static {
654 let seen: BTreeMap<String, (JobState, Hlc)> = BTreeMap::new();
655 futures::stream::unfold((self.clone(), seen, VecDeque::new()), move |(board, mut seen, mut queue)| async move {
656 loop {
657 if let Some(c) = queue.pop_front() {
658 return Some((c, (board, seen, queue)));
659 }
660 if let Ok(all) = board.list(&JobFilter::all().with_old()) {
661 for r in all {
662 let key = (r.state, r.updated.clone());
663 if seen.get(&r.id) != Some(&key) {
664 seen.insert(r.id.clone(), key);
665 queue.push_back(JobChange { id: r.id.clone(), record: r });
666 }
667 }
668 }
669 if queue.is_empty() {
670 tokio::time::sleep(every).await;
671 }
672 }
673 })
674 }
675
676 pub async fn claim(&self, id: &str, eligible: impl Fn(&JobRecord<P>) -> bool) -> Result<Claim<P>, JobError> {
681 let record = self.get(id)?.ok_or_else(|| JobError::NotFound(id.to_string()))?;
682 if !matches!(record.state, JobState::Queued | JobState::Running) {
683 return Err(JobError::NotClaimable(record.state));
684 }
685 if !eligible(&record) {
686 return Err(JobError::Ineligible);
687 }
688 let policy = record.policy.clone();
689 let mut cfg = LeaseConfig::new(policy.voters()).with_duration(policy.claim());
690 if policy.renew_ms > 0 {
691 cfg.renew_every = Duration::from_millis(policy.renew_ms);
692 }
693 let (leases, kind, jid, c) = (self.sync.leases.clone(), self.kind.clone(), id.to_string(), cfg.clone());
694 let handle = tokio::task::spawn_blocking(move || leases.claim_job(&kind, &jid, &c)).await.map_err(|e| JobError::Sync(e.to_string()))??;
695 let record = self.get(id)?.ok_or_else(|| JobError::NotFound(id.to_string()))?;
696 let (lost_tx, _) = watch::channel(None);
697 let inner = Arc::new(ClaimInner {
698 leases: self.sync.leases.clone(),
699 cfg,
700 kind: self.kind.clone(),
701 id: id.to_string(),
702 name: handle.name().clone(),
703 term: handle.term(),
704 handle: Mutex::new(handle),
705 stop: AtomicBool::new(false),
706 lost: lost_tx,
707 progress: Mutex::new((None, None)),
708 takeover_after: policy.takeover_after(),
709 thread: Mutex::new(None),
710 });
711 let worker = inner.clone();
712 let t = std::thread::Builder::new()
713 .name(format!("job claim {id}"))
714 .spawn(move || run_claim(worker))
715 .map_err(|e| JobError::Sync(format!("starting the renew thread: {e}")))?;
716 if let Ok(mut slot) = inner.thread.lock() {
717 *slot = Some(t);
718 }
719 Ok(Claim { inner, record })
720 }
721
722 fn owner_op(&self, id: &str, op: impl FnOnce(&mut Jobs<'_>, u64, &str) -> weirdnet_sync::Result<()>) -> Result<(), JobError> {
723 let mut st = lock(self.sync.state())?;
724 let mut jobs = Jobs::new(&mut st, self.kind.clone());
725 if jobs.view(id).is_none() {
726 return Err(JobError::NotFound(id.to_string()));
727 }
728 op(&mut jobs, now_ms(), id).map_err(Into::into)
729 }
730
731 pub fn pause(&self, id: &str) -> Result<(), JobError> {
734 self.owner_op(id, |j, now, id| j.pause(now, id))
735 }
736
737 pub fn resume(&self, id: &str) -> Result<(), JobError> {
739 self.owner_op(id, |j, now, id| j.resume(now, id))
740 }
741
742 pub fn cancel(&self, id: &str) -> Result<(), JobError> {
743 self.owner_op(id, |j, now, id| j.cancel(now, id))
744 }
745}
746
747fn latest_checkpoint(v: &JobView) -> Option<CheckpointRef> {
748 v.checkpoints.iter().filter_map(|(t, s, d)| dec::<CheckpointRef>(d).ok().map(|c| ((*t, *s), c))).max_by(|a, b| a.0.cmp(&b.0)).map(|x| x.1)
749}
750
751struct ClaimInner {
752 leases: Leases,
753 cfg: LeaseConfig,
754 kind: String,
755 id: String,
756 name: LeaseName,
757 term: Term,
758 handle: Mutex<LeaseHandle>,
759 stop: AtomicBool,
760 lost: watch::Sender<Option<Lost>>,
761 progress: Mutex<(Option<Instant>, Option<serde_json::Value>)>,
763 takeover_after: Duration,
764 thread: Mutex<Option<std::thread::JoinHandle<()>>>,
765}
766
767impl ClaimInner {
768 fn handle(&self) -> Option<LeaseHandle> {
769 self.handle.lock().ok().map(|h| h.clone())
770 }
771
772 fn write(&self, ev: JobEvent) -> Result<(), JobError> {
773 let h = self.handle().ok_or(JobError::NotHolding)?;
774 if !h.is_valid() {
775 return Err(JobError::NotHolding);
776 }
777 let mut st = lock(self.leases.state())?;
778 Jobs::new(&mut st, self.kind.clone()).record(now_ms(), &self.id, &h, ev).map_err(|e| match e {
779 weirdnet_sync::SyncError::NotPermitted(_) => JobError::NotHolding,
780 e => e.into(),
781 })
782 }
783
784 fn end(&self, why: Lost) {
785 self.lost.send_if_modified(|v| {
786 if v.is_none() {
787 *v = Some(why);
788 true
789 } else {
790 false
791 }
792 });
793 }
794
795 fn release(&self) {
796 if let Some(h) = self.handle() {
797 self.leases.release(h, &self.cfg);
798 }
799 }
800
801 fn flush_progress(&self, force: bool) {
802 let pending = {
803 let Ok(mut p) = self.progress.lock() else { return };
804 let due = force || p.0.is_none_or(|t| t.elapsed() >= PROGRESS_EVERY);
805 if !due || p.1.is_none() {
806 return;
807 }
808 p.0 = Some(Instant::now());
809 p.1.take()
810 };
811 if let Some(v) = pending
812 && let Ok(data) = serde_json::to_vec(&v)
813 {
814 let _ = self.write(JobEvent::Note { term: self.term, key: NOTE_PROGRESS.into(), data });
815 }
816 }
817
818 fn sleep(&self, d: Duration) -> bool {
819 let end = Instant::now() + d;
820 while Instant::now() < end {
821 if self.stop.load(Ordering::SeqCst) {
822 return false;
823 }
824 std::thread::sleep((end - Instant::now()).min(Duration::from_millis(25)));
825 }
826 !self.stop.load(Ordering::SeqCst)
827 }
828}
829
830fn run_claim(c: Arc<ClaimInner>) {
831 let mut lapsed: Option<Instant> = None;
832 loop {
833 let wait = match (lapsed, c.handle()) {
834 (Some(_), _) => Duration::from_millis(200).min(c.cfg.renew_every),
835 (None, Some(h)) => c.cfg.renew_every.min(h.remaining() / 2).max(Duration::from_millis(20)),
836 (None, None) => return,
837 };
838 if !c.sleep(wait) {
839 return;
840 }
841 let view = c.leases.state().lock().ok().and_then(|mut st| Jobs::new(&mut st, c.kind.clone()).view(&c.id));
843 if let Some(v) = view {
844 if v.claim.as_ref().is_some_and(|(_, t)| *t > c.term) {
845 c.end(Lost::Superseded);
846 return;
847 }
848 match v.status {
849 JobStatus::Paused => {
850 let _ = c.write(JobEvent::Paused { term: Some(c.term) });
853 c.release();
854 c.end(Lost::PausedByOwner);
855 return;
856 }
857 JobStatus::Cancelled => {
858 c.release();
859 c.end(Lost::Cancelled);
860 return;
861 }
862 _ => {}
863 }
864 }
865 c.flush_progress(false);
866 let Some(mut h) = c.handle() else { return };
867 match c.leases.renew(&mut h, &c.cfg) {
868 Ok(()) => {
869 if let Ok(mut slot) = c.handle.lock() {
870 *slot = h;
871 }
872 lapsed = None;
873 }
874 Err(LeaseError::Lost) => {
875 let since = *lapsed.get_or_insert_with(Instant::now);
876 if c.leases.term_seen(&c.name) > c.term {
877 c.end(Lost::Superseded);
878 return;
879 }
880 if since.elapsed() >= c.takeover_after {
881 c.end(Lost::Lease);
882 return;
883 }
884 }
885 Err(LeaseError::NotEligible) => {
886 c.end(Lost::Lease);
887 return;
888 }
889 Err(_) => {}
890 }
891 }
892}
893
894pub struct Claim<P> {
898 inner: Arc<ClaimInner>,
899 record: JobRecord<P>,
900}
901
902#[derive(Debug, Clone, PartialEq, Eq)]
904pub struct Fence {
905 pub name: LeaseName,
906 pub term: Term,
907}
908
909impl Fence {
910 pub fn check(&self, guard: &mut FenceGuard) -> Result<(), Stale> {
912 guard.check(&self.name, self.term)
913 }
914}
915
916impl<P: Clone + Send + 'static> Claim<P> {
917 pub fn id(&self) -> &str {
918 &self.inner.id
919 }
920
921 pub fn term(&self) -> u64 {
923 self.inner.term.0
924 }
925
926 pub fn record(&self) -> &JobRecord<P> {
928 &self.record
929 }
930
931 pub fn resume_from(&self) -> Option<&CheckpointRef> {
933 self.record.checkpoint.as_ref()
934 }
935
936 pub fn is_valid(&self) -> bool {
939 self.inner.handle().is_some_and(|h| h.is_valid()) && self.inner.lost.borrow().is_none()
940 }
941
942 pub async fn lost(&self) -> Lost {
944 let mut rx = self.inner.lost.subscribe();
945 loop {
946 if let Some(l) = *rx.borrow_and_update() {
947 return l;
948 }
949 if rx.changed().await.is_err() {
950 return Lost::Released;
951 }
952 }
953 }
954
955 pub fn checkpoint(&self, cp: CheckpointRef) -> Result<(), JobError> {
957 let data = enc(&cp)?;
958 self.inner.write(JobEvent::Checkpoint { term: self.inner.term, seq: cp.seq, data })
959 }
960
961 pub fn set_holders(&self, seq: u64, holders: Vec<PeerId>) -> Result<(), JobError> {
963 let data = enc(&(seq, holders))?;
964 self.inner.write(JobEvent::Note { term: self.inner.term, key: NOTE_HOLDERS.into(), data })
965 }
966
967 pub fn progress(&self, value: serde_json::Value) -> Result<(), JobError> {
970 if let Ok(mut p) = self.inner.progress.lock() {
971 p.1 = Some(value);
972 }
973 self.inner.flush_progress(false);
974 Ok(())
975 }
976
977 pub fn fence(&self) -> Fence {
979 Fence { name: self.inner.name.clone(), term: self.inner.term }
980 }
981
982 async fn close(&self, ev: Option<JobEvent>) -> Result<(), JobError> {
983 let inner = self.inner.clone();
984 tokio::task::spawn_blocking(move || {
985 inner.stop.store(true, Ordering::SeqCst);
986 if let Some(t) = inner.thread.lock().ok().and_then(|mut t| t.take()) {
987 let _ = t.join();
988 }
989 inner.flush_progress(true);
990 let r = ev.map(|e| inner.write(e)).unwrap_or(Ok(()));
991 inner.release();
992 inner.end(Lost::Released);
993 r
994 })
995 .await
996 .map_err(|e| JobError::Sync(e.to_string()))?
997 }
998
999 pub async fn finish(self, result: Vec<u8>) -> Result<(), JobError> {
1001 self.close(Some(JobEvent::Finished { term: self.inner.term, result })).await
1002 }
1003
1004 pub async fn fail(self, reason: impl Into<String>, retry: bool) -> Result<(), JobError> {
1007 self.close(Some(JobEvent::Failed { term: self.inner.term, reason: reason.into(), retry })).await
1008 }
1009
1010 pub async fn pause(self) -> Result<(), JobError> {
1013 self.close(Some(JobEvent::Paused { term: Some(self.inner.term) })).await
1014 }
1015}
1016
1017impl<P> Drop for Claim<P> {
1018 fn drop(&mut self) {
1019 if self.inner.stop.swap(true, Ordering::SeqCst) {
1020 return;
1021 }
1022 let inner = self.inner.clone();
1023 let _ = std::thread::Builder::new().name("job claim release".into()).spawn(move || {
1025 if let Some(t) = inner.thread.lock().ok().and_then(|mut t| t.take()) {
1026 let _ = t.join();
1027 }
1028 if inner.lost.borrow().is_none() {
1029 inner.release();
1030 inner.end(Lost::Released);
1031 }
1032 });
1033 }
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038 use super::*;
1039
1040 #[test]
1041 fn content_hashes_print_and_parse() {
1042 let h = ContentHash([0xab; 32]);
1043 let s = h.to_string();
1044 assert_eq!(s.len(), 7 + 64);
1045 assert_eq!(s.parse::<ContentHash>().unwrap(), h);
1046 assert_eq!(s[7..].parse::<ContentHash>().unwrap(), h);
1047 assert_eq!(h.short(), "sha256:abababababababab");
1048 assert!("sha256:xyz".parse::<ContentHash>().is_err());
1049 }
1050
1051 #[test]
1052 fn the_default_policy_matches_training_jobs() {
1053 let p = JobPolicy::for_role("ymir.model");
1054 assert_eq!((p.claim_ms, p.renew_ms, p.takeover_after_ms, p.max_attempts, p.retry_backoff_ms), (60_000, 20_000, 300_000, 3, 60_000));
1055 let v = p.voter("ymir.train");
1056 let n = LeaseName::new("ymir.train/j1").unwrap();
1057 assert_eq!(v.limits_for(&n).map(|l| (l.max_duration, l.takeover_after)), Some((Duration::from_secs(60), Duration::from_secs(300))));
1058 let r = p.rules();
1059 assert_eq!((r.role.as_deref(), r.takeover_after_ms, r.retry_backoff_ms), (Some("ymir.model"), 300_000, 60_000));
1060 }
1061}