oxide-batch 0.5.0

Embedded Core Production Preview of restartable batch processing for Rust, inspired by Spring Batch
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Guarded, idempotent, audited operator actions.
//!
//! Every mutating action carries a bounded envelope, commits its append-only
//! audit row in the same transaction as its effect, and is replayable by its
//! operation identifier. The service performs no internal retry loop and never
//! guesses an ambiguous commit outcome. The request, audit record, and guard
//! vocabulary it applies live in `oxide-batch-repository`.

use std::error::Error;
use std::fmt;
use std::sync::Arc;
use std::time::SystemTime;

use crate::{
    BatchStatus, Clock, ExecutionVersion, JobExecution, JobExecutionId, JobInstanceId,
    JobRepository, LifecycleTransition, OperationId, OperatorAction, OperatorOutcomeClass,
    OperatorRecord, OperatorRecordDraft, OperatorRejection, OperatorRequest, ReasonCode,
    RecoveryDirective, RecoveryRequestError, RepositoryError, RepositoryUnitOfWork,
    TelemetryEventKind, TelemetryEventSink, TelemetryRecord,
};

/// The result of one guarded operator call.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OperatorOutcome {
    class: OperatorOutcomeClass,
    record: OperatorRecord,
    execution: Option<JobExecution>,
    changed: bool,
}

impl OperatorOutcome {
    const fn new(
        class: OperatorOutcomeClass,
        record: OperatorRecord,
        execution: Option<JobExecution>,
        changed: bool,
    ) -> Self {
        Self {
            class,
            record,
            execution,
            changed,
        }
    }

    /// Returns whether the effect was applied, replayed, or rejected.
    #[must_use]
    pub const fn class(&self) -> OperatorOutcomeClass {
        self.class
    }

    /// Borrows the durable audit record of this operation identifier.
    #[must_use]
    pub const fn record(&self) -> &OperatorRecord {
        &self.record
    }

    /// Borrows the resulting execution snapshot, when the call produced one.
    ///
    /// A replay returns the recorded outcome without re-reading the execution.
    #[must_use]
    pub const fn execution(&self) -> Option<&JobExecution> {
        self.execution.as_ref()
    }

    /// Returns the rejection class, when a guard rejected the action.
    #[must_use]
    pub const fn rejection(&self) -> Option<OperatorRejection> {
        self.record.rejection()
    }

    /// Returns whether this call changed durable state.
    ///
    /// A repeated stop or abandon succeeds and changes nothing.
    #[must_use]
    pub const fn changed_state(&self) -> bool {
        self.changed
    }
}

/// A typed operator-service failure that is not a guard rejection.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum OperatorError {
    /// The operation identifier was reused with a different canonical request.
    OperationIdConflict {
        /// Conflicting action.
        action: OperatorAction,
        /// Conflicting idempotency key.
        operation_id: OperationId,
    },
    /// The commit may or may not have become durable.
    ///
    /// The caller resolves the ambiguity by replaying the same operation
    /// identifier, which either returns the recorded outcome or re-attempts the
    /// effect exactly once.
    OperationOutcomeUnknown,
    /// The recovery arguments could not produce a valid audited request.
    InvalidRecoveryRequest(RecoveryRequestError),
    /// The repository failed for a reason that is not a guard rejection.
    Repository(RepositoryError),
}

impl fmt::Display for OperatorError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OperationIdConflict {
                action,
                operation_id,
            } => write!(
                formatter,
                "operation identifier {operation_id} was already recorded for {action} with a different request"
            ),
            Self::OperationOutcomeUnknown => {
                formatter.write_str("the operator commit outcome is unknown")
            }
            Self::InvalidRecoveryRequest(error) => error.fmt(formatter),
            Self::Repository(error) => error.fmt(formatter),
        }
    }
}

impl Error for OperatorError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::InvalidRecoveryRequest(error) => Some(error),
            Self::Repository(error) => Some(error),
            _ => None,
        }
    }
}

impl From<RepositoryError> for OperatorError {
    fn from(value: RepositoryError) -> Self {
        match value {
            RepositoryError::CommitOutcomeUnknown => Self::OperationOutcomeUnknown,
            other => Self::Repository(other),
        }
    }
}

/// The portable guarded operator application service.
///
/// The service enforces lifecycle, version, definition, checkpoint,
/// idempotency, and bounds. A deployment authenticates the caller and
/// authorizes [`OperatorRequest::authorization_class`] before invoking it.
/// Removing deployment authorization does not weaken a core guard.
#[derive(Clone)]
pub struct JobOperator<R> {
    repository: R,
    clock: Arc<dyn Clock>,
    event_sinks: Vec<Arc<dyn TelemetryEventSink>>,
}

impl<R> fmt::Debug for JobOperator<R> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("JobOperator")
            .finish_non_exhaustive()
    }
}

impl<R: JobRepository> JobOperator<R> {
    /// Binds one repository and one injected facade clock.
    pub const fn new(repository: R, clock: Arc<dyn Clock>) -> Self {
        Self {
            repository,
            clock,
            event_sinks: Vec::new(),
        }
    }

    /// Attaches a non-authoritative, panic-isolated telemetry sink.
    #[must_use]
    pub fn with_event_sink(mut self, sink: Arc<dyn TelemetryEventSink>) -> Self {
        self.event_sinks.push(sink);
        self
    }

    /// Borrows the underlying repository.
    pub const fn repository(&self) -> &R {
        &self.repository
    }

    /// Applies one guarded, audited, idempotent operator action.
    ///
    /// # Errors
    ///
    /// Returns [`OperatorError::OperationIdConflict`] for a reused identifier
    /// with a different canonical request,
    /// [`OperatorError::OperationOutcomeUnknown`] for an ambiguous commit, and
    /// [`OperatorError::Repository`] for an infrastructure failure. A guard
    /// rejection is an audited [`OperatorOutcomeClass::Rejected`] outcome
    /// rather than an error.
    pub async fn execute(
        &self,
        request: &OperatorRequest,
    ) -> Result<OperatorOutcome, OperatorError> {
        if let Some(recorded) = self.replay(request).await? {
            self.emit_outcome(request, &recorded);
            return Ok(recorded);
        }
        let requested_at = self.clock.now();
        let mut unit = self.repository.begin().await?;
        let effect = match self.apply(unit.as_mut(), request).await {
            Ok(effect) => effect,
            Err(EffectFailure::Rejected(rejection)) => {
                // A rejection must still be audited, so the rollback is
                // best-effort: an adapter that cannot roll back discards its
                // connection, and a genuine outage resurfaces when the audit
                // opens its own unit of work.
                let _ = unit.rollback().await;
                let outcome = self
                    .audit_rejection(request, rejection, requested_at)
                    .await?;
                self.emit_outcome(request, &outcome);
                return Ok(outcome);
            }
            Err(EffectFailure::Failed(error)) => {
                // The applied effect is already lost; the failure that caused
                // it is the informative error, not a secondary rollback fault.
                let _ = unit.rollback().await;
                return Err(error);
            }
        };
        let draft = OperatorRecordDraft::applied(
            request,
            effect.job_instance_id,
            effect.job_execution_id,
            effect.prior_status,
            effect.result_status,
            requested_at,
        );
        let record = match unit.append_operator_request(&draft).await {
            Ok(record) => record,
            Err(RepositoryError::ConcurrentModification) => {
                // A concurrent caller may have durably recorded this operation
                // identifier between the replay probe and this append. That
                // transaction owns the effect; this one contributed nothing, so
                // a legitimate duplicate returns the recorded outcome rather
                // than an error that contradicts replay by operation
                // identifier. A conflict that is not this identifier finds no
                // record and keeps the original error.
                let _ = unit.rollback().await;
                return self.replay(request).await?.ok_or(OperatorError::Repository(
                    RepositoryError::ConcurrentModification,
                ));
            }
            Err(error) => return Err(error.into()),
        };
        unit.commit().await?;
        let outcome = OperatorOutcome::new(
            OperatorOutcomeClass::Applied,
            record,
            effect.execution,
            effect.changed,
        );
        self.emit_outcome(request, &outcome);
        Ok(outcome)
    }

    fn emit_outcome(&self, request: &OperatorRequest, outcome: &OperatorOutcome) {
        let primary = match outcome.class() {
            OperatorOutcomeClass::Applied | OperatorOutcomeClass::Replayed => {
                TelemetryEventKind::OperatorRequestAccepted
            }
            // The `Rejected` arm, and any outcome class added later. Telemetry
            // must never report an outcome this build does not recognize as
            // accepted, so it reports the non-accepting kind; the record still
            // carries the exact class.
            _ => TelemetryEventKind::OperatorRequestRejected,
        };
        self.emit_record(&TelemetryRecord::operator(
            primary,
            request,
            Some(outcome.class()),
            outcome.rejection(),
        ));
        if request.action() == OperatorAction::Recover {
            let recovery = if outcome.class() == OperatorOutcomeClass::Rejected {
                TelemetryEventKind::RecoveryRejected
            } else {
                TelemetryEventKind::RecoveryApplied
            };
            self.emit_record(&TelemetryRecord::operator(
                recovery,
                request,
                Some(outcome.class()),
                outcome.rejection(),
            ));
        }
        self.emit_record(&TelemetryRecord::operator(
            TelemetryEventKind::OperatorRequestCompleted,
            request,
            Some(outcome.class()),
            outcome.rejection(),
        ));
    }

    fn emit_record(&self, record: &TelemetryRecord) {
        for sink in &self.event_sinks {
            crate::telemetry::emit_safely(Some(sink), record);
        }
    }

    async fn replay(
        &self,
        request: &OperatorRequest,
    ) -> Result<Option<OperatorOutcome>, OperatorError> {
        let mut unit = self.repository.begin().await?;
        let recorded = unit
            .find_operator_request(request.action(), request.operation_id())
            .await?;
        unit.rollback().await?;
        let Some(record) = recorded else {
            return Ok(None);
        };
        if record.digest() != request.digest() {
            return Err(OperatorError::OperationIdConflict {
                action: request.action(),
                operation_id: request.operation_id().clone(),
            });
        }
        Ok(Some(OperatorOutcome::new(
            OperatorOutcomeClass::Replayed,
            record,
            None,
            false,
        )))
    }

    async fn audit_rejection(
        &self,
        request: &OperatorRequest,
        rejection: OperatorRejection,
        requested_at: SystemTime,
    ) -> Result<OperatorOutcome, OperatorError> {
        let draft = OperatorRecordDraft::rejected(request, rejection, requested_at);
        let mut unit = self.repository.begin().await?;
        let record = match unit.append_operator_request(&draft).await {
            Ok(record) => record,
            Err(RepositoryError::ConcurrentModification) => {
                // As in `execute`, a concurrent caller may have recorded this
                // operation identifier first. The rejection is already audited
                // by that transaction.
                let _ = unit.rollback().await;
                return self.replay(request).await?.ok_or(OperatorError::Repository(
                    RepositoryError::ConcurrentModification,
                ));
            }
            Err(error) => return Err(error.into()),
        };
        unit.commit().await?;
        Ok(OperatorOutcome::new(
            OperatorOutcomeClass::Rejected,
            record,
            None,
            false,
        ))
    }

    async fn apply(
        &self,
        unit: &mut dyn RepositoryUnitOfWork,
        request: &OperatorRequest,
    ) -> Result<AppliedEffect, EffectFailure> {
        match request.action() {
            OperatorAction::Launch => self.launch(unit, request).await,
            OperatorAction::Restart => self.restart(unit, request).await,
            OperatorAction::Stop => self.stop(unit, request).await,
            OperatorAction::Abandon => self.abandon(unit, request).await,
            OperatorAction::Recover => self.recover(unit, request).await,
            // Absorbs any action added later: the build cannot apply it, so it
            // is an audited rejection rather than a silent success.
            _ => Err(EffectFailure::Rejected(
                OperatorRejection::UnsupportedAction,
            )),
        }
    }

    async fn launch(
        &self,
        unit: &mut dyn RepositoryUnitOfWork,
        request: &OperatorRequest,
    ) -> Result<AppliedEffect, EffectFailure> {
        let Some(key) = request.job_instance_key() else {
            return Err(EffectFailure::Rejected(OperatorRejection::InstanceNotFound));
        };
        let definition = request
            .definition()
            .ok_or(EffectFailure::Rejected(
                OperatorRejection::IncompatibleDefinition,
            ))?
            .clone();
        let selection = unit
            .select_or_create_job_instance(key)
            .await
            .map_err(EffectFailure::classify)?;
        let instance_id = selection.instance().id();
        let execution = unit
            .create_job_execution_with_definition(instance_id, &definition)
            .await
            .map_err(EffectFailure::classify)?;
        Ok(AppliedEffect::created(instance_id, execution))
    }

    async fn restart(
        &self,
        unit: &mut dyn RepositoryUnitOfWork,
        request: &OperatorRequest,
    ) -> Result<AppliedEffect, EffectFailure> {
        let Some(instance_id) = request.job_instance_id() else {
            return Err(EffectFailure::Rejected(OperatorRejection::InstanceNotFound));
        };
        let definition = request
            .definition()
            .ok_or(EffectFailure::Rejected(
                OperatorRejection::IncompatibleDefinition,
            ))?
            .clone();
        let prior = unit
            .job_executions(instance_id)
            .await
            .map_err(EffectFailure::classify)?;
        let latest = prior.last().ok_or(EffectFailure::Rejected(
            OperatorRejection::RestartWithoutPriorAttempt,
        ))?;
        let prior_status = latest.metadata().status();
        if matches!(prior_status, BatchStatus::Unknown) {
            return Err(EffectFailure::Rejected(OperatorRejection::InvalidState {
                status: prior_status,
            }));
        }
        let execution = unit
            .create_job_execution_with_definition(instance_id, &definition)
            .await
            .map_err(EffectFailure::classify)?;
        Ok(AppliedEffect::created(instance_id, execution).with_prior(prior_status))
    }

    async fn stop(
        &self,
        unit: &mut dyn RepositoryUnitOfWork,
        request: &OperatorRequest,
    ) -> Result<AppliedEffect, EffectFailure> {
        let (id, expected_version) = execution_target(request)?;
        let observed = unit
            .get_job_execution(id)
            .await
            .map_err(EffectFailure::classify)?
            .ok_or(EffectFailure::Rejected(
                OperatorRejection::ExecutionNotFound,
            ))?;
        let status = observed.metadata().status();
        if !matches!(status, BatchStatus::Starting | BatchStatus::Started) {
            if matches!(status, BatchStatus::Stopping) || status.is_finished() {
                // A repeat request on a stopping or terminal execution succeeds
                // and changes nothing.
                return Ok(AppliedEffect::unchanged(&observed));
            }
            return Err(EffectFailure::Rejected(OperatorRejection::InvalidState {
                status,
            }));
        }
        let execution = unit
            .request_execution_stop(id, expected_version, request.actor(), self.clock.now())
            .await
            .map_err(EffectFailure::classify)?;
        Ok(AppliedEffect::updated(&execution, status))
    }

    async fn abandon(
        &self,
        unit: &mut dyn RepositoryUnitOfWork,
        request: &OperatorRequest,
    ) -> Result<AppliedEffect, EffectFailure> {
        let (id, expected_version) = execution_target(request)?;
        let observed = unit
            .get_job_execution(id)
            .await
            .map_err(EffectFailure::classify)?
            .ok_or(EffectFailure::Rejected(
                OperatorRejection::ExecutionNotFound,
            ))?;
        let status = observed.metadata().status();
        match status {
            BatchStatus::Abandoned => return Ok(AppliedEffect::unchanged(&observed)),
            BatchStatus::Stopped | BatchStatus::Failed => {}
            BatchStatus::Unknown => {
                let decision = unit
                    .recovery_decision(id)
                    .await
                    .map_err(EffectFailure::classify)?;
                if decision.is_none() {
                    return Err(EffectFailure::Rejected(
                        OperatorRejection::UnresolvedRecoveryRequired,
                    ));
                }
            }
            other => {
                return Err(EffectFailure::Rejected(OperatorRejection::InvalidState {
                    status: other,
                }));
            }
        }
        let transition = LifecycleTransition::new(BatchStatus::Abandoned, self.clock.now());
        let execution = unit
            .transition_job_execution(id, expected_version, transition)
            .await
            .map_err(EffectFailure::classify)?;
        Ok(AppliedEffect::updated(&execution, status))
    }

    async fn recover(
        &self,
        unit: &mut dyn RepositoryUnitOfWork,
        request: &OperatorRequest,
    ) -> Result<AppliedEffect, EffectFailure> {
        let (id, expected_version) = execution_target(request)?;
        let execution = unit
            .get_job_execution(id)
            .await
            .map_err(EffectFailure::classify)?
            .ok_or(EffectFailure::Rejected(
                OperatorRejection::ExecutionNotFound,
            ))?;
        if execution.version() != expected_version {
            return Err(EffectFailure::Rejected(
                OperatorRejection::OptimisticConflict {
                    current: execution.version(),
                },
            ));
        }
        let (directive, unknown_commit) = request.recovery_guard().ok_or(
            EffectFailure::Rejected(OperatorRejection::InvalidState {
                status: execution.metadata().status(),
            }),
        )?;
        if unknown_commit
            && matches!(directive, RecoveryDirective::MarkFailed(_))
            && request.reason().map(ReasonCode::as_str) != Some("UNKNOWN_EFFECT")
        {
            return Err(EffectFailure::Rejected(
                OperatorRejection::UnresolvedRecoveryRequired,
            ));
        }
        let recovery = request
            .recovery_request()
            .ok_or(EffectFailure::Rejected(OperatorRejection::InvalidState {
                status: BatchStatus::Unknown,
            }))?
            .map_err(|error| EffectFailure::Failed(OperatorError::InvalidRecoveryRequest(error)))?;
        let result = unit
            .recover_job_execution(id, &recovery)
            .await
            .map_err(EffectFailure::classify)?;
        Ok(AppliedEffect::updated(
            result.execution(),
            result.decision().prior_status(),
        ))
    }
}

fn execution_target(
    request: &OperatorRequest,
) -> Result<(JobExecutionId, ExecutionVersion), EffectFailure> {
    let Some(id) = request.job_execution_id() else {
        return Err(EffectFailure::Rejected(
            OperatorRejection::ExecutionNotFound,
        ));
    };
    let expected_version = request.expected_version().ok_or(EffectFailure::Rejected(
        OperatorRejection::InvalidState {
            status: BatchStatus::Unknown,
        },
    ))?;
    Ok((id, expected_version))
}

struct AppliedEffect {
    job_instance_id: Option<JobInstanceId>,
    job_execution_id: Option<JobExecutionId>,
    prior_status: Option<BatchStatus>,
    result_status: Option<BatchStatus>,
    execution: Option<JobExecution>,
    changed: bool,
}

impl AppliedEffect {
    fn created(instance_id: JobInstanceId, execution: JobExecution) -> Self {
        Self {
            job_instance_id: Some(instance_id),
            job_execution_id: Some(execution.id()),
            prior_status: None,
            result_status: Some(execution.metadata().status()),
            execution: Some(execution),
            changed: true,
        }
    }

    fn updated(execution: &JobExecution, prior_status: BatchStatus) -> Self {
        Self {
            job_instance_id: Some(execution.job_instance_id()),
            job_execution_id: Some(execution.id()),
            prior_status: Some(prior_status),
            result_status: Some(execution.metadata().status()),
            execution: Some(execution.clone()),
            changed: true,
        }
    }

    fn unchanged(execution: &JobExecution) -> Self {
        let status = execution.metadata().status();
        Self {
            job_instance_id: Some(execution.job_instance_id()),
            job_execution_id: Some(execution.id()),
            prior_status: Some(status),
            result_status: Some(status),
            execution: Some(execution.clone()),
            changed: false,
        }
    }

    const fn with_prior(mut self, prior_status: BatchStatus) -> Self {
        self.prior_status = Some(prior_status);
        self
    }
}

enum EffectFailure {
    Rejected(OperatorRejection),
    Failed(OperatorError),
}

impl EffectFailure {
    fn classify(error: RepositoryError) -> Self {
        OperatorRejection::from_repository(&error)
            .map_or_else(|| Self::Failed(OperatorError::from(error)), Self::Rejected)
    }
}