1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
//! Recovery and the operator API.
//!
//! - [`Runtime::recover`] marks attempts whose worker died as unknown, then
//! finishes every unsettled effect that has a registered
//! [handler](crate::handler) from its stored input. Closure effects are
//! not durable, so they wait for a caller to re-run them;
//! - [`Runtime::pending`] lists the effects waiting for a caller or an
//! operator;
//! - [`Runtime::resolve`] records an operator's decision.
use std::time::Duration;
use serde::Serialize;
use serde_json::{Value, json};
use tokio::time::MissedTickBehavior;
use tracing::{info, warn};
use crate::error::RuntimeError;
use crate::id::EffectId;
use crate::runtime::Runtime;
use crate::state::{EffectStatus, Transition};
use crate::store::{
EffectRecord, EffectStore, ErrorRecord, ListQuery, StoreError, TransitionRequest,
};
/// Page size for recovery scans.
const PAGE: usize = 100;
/// What one [`Runtime::recover`] pass did.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RecoveryReport {
/// Effects whose worker's lease expired mid-attempt or mid-verification,
/// now marked unknown.
pub marked_unknown: Vec<EffectId>,
/// Effects that matched the scan but were taken by another caller or
/// worker before this pass reached them.
pub skipped: Vec<EffectId>,
/// Effects with a registered handler that this pass moved forward, and
/// the status each ended in. `Committed`, `Failed` and `Rejected` are
/// settled; `NeedsIntervention` waits for an operator; anything else is
/// still in progress or still unknown.
pub resumed: Vec<(EffectId, EffectStatus)>,
/// Unsettled effects with no registered handler (closure effects). They
/// need a caller to run them again with the same key.
pub unhandled: Vec<EffectId>,
/// Effects whose handler could not be run, with the reason, e.g. a
/// stored input that no longer deserializes.
pub resume_errors: Vec<(EffectId, String)>,
}
/// An operator's decision about an effect the runtime could not resolve.
#[derive(Clone, Debug, PartialEq)]
pub enum Resolution {
/// The effect applied. `output` becomes its result for every later call,
/// so it should deserialize into the type those calls expect.
Applied {
/// The effect's output, as JSON.
output: Option<Value>,
},
/// The effect did not apply. It ends `Failed`, with the operator's note
/// as its error.
NotApplied,
/// Running the effect again is safe. The next call runs it, even if its
/// retry budget is spent, since this is an explicit decision. On a
/// failed compensation: try the compensation again.
Retry,
/// For a failed compensation: the operator undid the effect by hand. It
/// ends `Compensated`.
Compensated,
}
impl Resolution {
/// [`Resolution::Applied`] with `output` serialized.
///
/// # Errors
///
/// If `output` cannot be serialized to JSON.
pub fn applied<T: Serialize + ?Sized>(output: &T) -> Result<Self, serde_json::Error> {
Ok(Self::Applied {
output: Some(serde_json::to_value(output)?),
})
}
}
impl<S: EffectStore> Runtime<S> {
/// One recovery pass, in two steps.
///
/// 1. Every effect whose worker's lease expired mid-attempt or
/// mid-verification becomes `Unknown`, never `Failed`: it may have
/// changed the outside world.
/// 2. Every unsettled effect nobody holds (see [`Self::pending`]) whose
/// name has a registered [handler](crate::handler) is finished from its
/// stored input, exactly as if its caller had called again: verified,
/// re-run if that is safe, or escalated. This includes effects left
/// `Pending` by a crash. Effects waiting for an operator, and retries
/// scheduled for later, are left alone. Unsettled closure effects are
/// reported as `unhandled`: only a caller can re-run them.
///
/// Effects are resumed one at a time, so a pass lasts as long as their
/// retries and verifications take. Safe to run from several workers at
/// once: every change happens under a lease.
///
/// # Errors
///
/// [`RuntimeError::Store`] if the store fails. Progress made before the
/// failure is kept. A handler that cannot run is reported in
/// `resume_errors` instead.
pub async fn recover(&self) -> Result<RecoveryReport, RuntimeError> {
let mut report = RecoveryReport::default();
self.mark_abandoned(&mut report).await?;
self.resume_pending(&mut report).await?;
Ok(report)
}
async fn mark_abandoned(&self, report: &mut RecoveryReport) -> Result<(), RuntimeError> {
let mut after = None;
loop {
let mut query = ListQuery::expired_leases(self.now()).limit(PAGE);
if let Some(id) = after {
query = query.after(id);
}
let page = self.store().list(query).await?;
let full = page.len() == PAGE;
after = page.last().map(|record| record.id);
for record in page {
if self.mark_unknown(record.id).await? {
report.marked_unknown.push(record.id);
} else {
report.skipped.push(record.id);
}
}
if !full {
return Ok(());
}
}
}
async fn resume_pending(&self, report: &mut RecoveryReport) -> Result<(), RuntimeError> {
let mut after = None;
loop {
let page = self.pending(after, PAGE).await?;
let full = page.len() == PAGE;
after = page.last().map(|record| record.id);
for record in page {
let id = record.id;
let not_due = record.next_attempt_at.is_some_and(|at| at > self.now());
let operator = matches!(
record.status,
EffectStatus::NeedsIntervention
| EffectStatus::CompensationFailed
| EffectStatus::AwaitingApproval
);
if operator || not_due {
continue;
}
let Some(resume) = self.resumer(record.key.name.as_str()) else {
report.unhandled.push(id);
continue;
};
match resume(self.clone(), record).await {
Ok(status) => {
info!(effect.id = %id, %status, "recovery resumed effect");
report.resumed.push((id, status));
}
Err(e) => {
warn!(effect.id = %id, error = %e, "recovery could not resume effect");
report.resume_errors.push((id, e.to_string()));
}
}
}
if !full {
return Ok(());
}
}
}
/// Runs [`Self::recover`] every `interval`, forever, followed by
/// [`Self::prune`] when the runtime has a
/// [retention policy](crate::RetentionPolicy). Spawn it:
///
/// ```ignore
/// tokio::spawn({
/// let runtime = runtime.clone();
/// async move { runtime.run_recovery(Duration::from_secs(30)).await }
/// });
/// ```
///
/// A failed pass is logged and retried at the next tick.
pub async fn run_recovery(&self, interval: Duration) {
let mut ticker = tokio::time::interval(interval);
ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
loop {
ticker.tick().await;
match self.recover().await {
Ok(report) if !report.marked_unknown.is_empty() || !report.resumed.is_empty() => {
info!(
marked_unknown = report.marked_unknown.len(),
resumed = report.resumed.len(),
unhandled = report.unhandled.len(),
"recovery pass"
);
}
Ok(_) => {}
Err(e) => warn!(error = %e, "recovery pass failed"),
}
match self.prune().await {
Ok(report) if report.total() > 0 => {
info!(pruned = report.total(), "pruned settled effects");
}
Ok(_) => {}
Err(e) => warn!(error = %e, "pruning failed"),
}
}
}
/// Effects waiting for a caller to re-run them or an operator to decide,
/// ordered by creation, `limit` at a time after `after`.
///
/// These are the effects that are unsettled with nobody working on
/// them: `Pending` (for example a worker died during a backoff wait),
/// `Executing` or `Verifying` with an expired lease (not yet recovered),
/// `Unknown`, `NeedsIntervention`, `AwaitingApproval`, an interrupted
/// `Compensating`, and `CompensationFailed`.
///
/// # Errors
///
/// [`RuntimeError::Store`] if the store fails.
pub async fn pending(
&self,
after: Option<EffectId>,
limit: usize,
) -> Result<Vec<EffectRecord>, RuntimeError> {
let mut query = ListQuery::statuses([
EffectStatus::Pending,
EffectStatus::AwaitingApproval,
EffectStatus::Executing,
EffectStatus::Verifying,
EffectStatus::Unknown,
EffectStatus::NeedsIntervention,
EffectStatus::Compensating,
EffectStatus::CompensationFailed,
])
.limit(limit);
query.lease_expired_at = Some(self.now());
query.after = after;
Ok(self.store().list(query).await?)
}
/// Records an operator's decision about an effect that is `Unknown` or
/// `NeedsIntervention`. `actor` identifies the operator (e.g.
/// `operator:alice`); `note` says why, for the audit trail.
///
/// # Errors
///
/// [`RuntimeError::Store`] wrapping:
///
/// - [`StoreError::NotFound`] for an unknown id;
/// - [`StoreError::InvalidTransition`] if the effect is not unresolved,
/// for example already committed;
/// - [`StoreError::LeaseHeld`] while a caller or worker is working on it;
/// - [`StoreError::VersionConflict`] if it changed during the call.
pub async fn resolve(
&self,
id: EffectId,
resolution: Resolution,
actor: impl Into<String>,
note: impl Into<String>,
) -> Result<EffectRecord, RuntimeError> {
let record = self
.store()
.get(id)
.await?
.ok_or(StoreError::NotFound(id))?;
let note = note.into();
let transition = match resolution {
Resolution::Applied { .. } => Transition::ResolvedApplied,
Resolution::NotApplied => Transition::ResolvedNotApplied,
Resolution::Retry => Transition::ResolvedRetry,
Resolution::Compensated => Transition::ResolvedCompensated,
};
let mut request = TransitionRequest::new(&record, None, transition, self.now());
request.actor = Some(actor.into());
request.payload = Some(json!({ "note": note }));
match resolution {
Resolution::Applied { output } => request.output = output,
Resolution::NotApplied => {
request.error = Some(ErrorRecord {
class: None,
message: note,
});
}
Resolution::Retry | Resolution::Compensated => {}
}
let record = self.commit_transition(&record, request).await?;
info!(effect.id = %id, %transition, "effect resolved by an operator");
Ok(record)
}
/// Approves an effect waiting in `AwaitingApproval`. It becomes
/// `Pending`: a caller's next call runs it, and so does recovery for a
/// registered handler. `actor` is recorded as the approver.
///
/// # Errors
///
/// As for [`Self::resolve`]; `InvalidTransition` if it is not awaiting
/// approval.
pub async fn approve(
&self,
id: EffectId,
actor: impl Into<String>,
note: impl Into<String>,
) -> Result<EffectRecord, RuntimeError> {
self.decide(id, Transition::Approve, actor.into(), note.into())
.await
}
/// Denies an effect waiting in `AwaitingApproval`. It ends `Rejected`,
/// with `reason` as its error.
///
/// # Errors
///
/// As for [`Self::approve`].
pub async fn deny(
&self,
id: EffectId,
actor: impl Into<String>,
reason: impl Into<String>,
) -> Result<EffectRecord, RuntimeError> {
self.decide(id, Transition::Deny, actor.into(), reason.into())
.await
}
async fn decide(
&self,
id: EffectId,
transition: Transition,
actor: String,
note: String,
) -> Result<EffectRecord, RuntimeError> {
let record = self
.store()
.get(id)
.await?
.ok_or(StoreError::NotFound(id))?;
let mut request = TransitionRequest::new(&record, None, transition, self.now());
request.actor = Some(actor);
if transition == Transition::Deny {
request.error = Some(ErrorRecord {
class: None,
message: note.clone(),
});
}
request.payload = Some(json!({ "note": note }));
let record = self.commit_transition(&record, request).await?;
info!(effect.id = %id, %transition, "approval decided by an operator");
Ok(record)
}
/// Moves one effect with an expired lease to `Unknown`. Returns `false`
/// if someone else got to it first.
async fn mark_unknown(&self, id: EffectId) -> Result<bool, RuntimeError> {
let store = self.store();
let lease = match store
.acquire_lease(id, self.worker_id(), self.now(), self.lease_ttl())
.await
{
Ok(lease) => lease,
Err(StoreError::LeaseHeld { .. }) => return Ok(false),
Err(e) => return Err(e.into()),
};
let marked = async {
let record = store.get(id).await?.ok_or(StoreError::NotFound(id))?;
if !matches!(
record.status,
EffectStatus::Executing | EffectStatus::Verifying
) {
return Ok(false);
}
let mut request =
TransitionRequest::new(&record, Some(&lease), Transition::LeaseExpired, self.now());
request.actor = Some(format!("recovery:{}", self.worker_id()));
self.commit_transition(&record, request).await?;
info!(
effect.id = %id,
effect.name = %record.key.name,
"worker lost mid-effect; outcome is now unknown"
);
Ok::<_, RuntimeError>(true)
}
.await;
if let Err(e) = store.release_lease(&lease).await {
warn!(error = %e, "could not release recovery lease; it will expire");
}
marked
}
}