rustvello-proto 0.1.6

Data transfer objects and wire types for Rustvello
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
mod concurrency;
mod machine;
#[cfg(test)]
mod tests;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
use std::sync::LazyLock;

use crate::identifiers::RunnerId;

pub use concurrency::ConcurrencyControlType;
pub use machine::{
    compute_new_owner, status_record_transition, validate_ownership, validate_transition,
    OwnershipError, StatusMachineError, StatusTransitionError,
};

// ============================================================================
// InvocationStatus enum
// ============================================================================

/// The lifecycle status of an invocation.
///
/// Follows a strict state machine — not all transitions are valid.
/// Mirrors pynenc's `InvocationStatus` enum exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum InvocationStatus {
    /// Invocation created and registered
    Registered,
    /// Paused due to concurrency control (transient — will be rerouted)
    ConcurrencyControlled,
    /// Permanently blocked by concurrency control
    ConcurrencyControlledFinal,
    /// Re-queued in the broker for another execution attempt
    Rerouted,
    /// Queued in the broker, waiting for a runner
    Pending,
    /// Pending recovery after runner failure (timeout exceeded)
    PendingRecovery,
    /// Currently being executed by a runner
    Running,
    /// Being re-executed during recovery (owner runner inactive)
    RunningRecovery,
    /// Task execution is paused
    Paused,
    /// Task execution has been resumed after pause
    Resumed,
    /// Task execution has been killed
    Killed,
    /// Completed successfully
    Success,
    /// Failed with an error
    Failed,
    /// Marked for retry after a failure
    Retry,
}

/// All status variants, for iteration.
pub const ALL_STATUSES: &[InvocationStatus] = &[
    InvocationStatus::Registered,
    InvocationStatus::ConcurrencyControlled,
    InvocationStatus::ConcurrencyControlledFinal,
    InvocationStatus::Rerouted,
    InvocationStatus::Pending,
    InvocationStatus::PendingRecovery,
    InvocationStatus::Running,
    InvocationStatus::RunningRecovery,
    InvocationStatus::Paused,
    InvocationStatus::Resumed,
    InvocationStatus::Killed,
    InvocationStatus::Success,
    InvocationStatus::Failed,
    InvocationStatus::Retry,
];

impl InvocationStatus {
    /// Returns true if this is a terminal (final) status.
    #[inline]
    pub fn is_terminal(&self) -> bool {
        STATUS_CONFIG.definition(*self).is_final
    }

    /// Returns true if this status means the invocation can be picked up by a runner.
    #[inline]
    pub fn is_available_for_run(&self) -> bool {
        STATUS_CONFIG.definition(*self).available_for_run
    }

    /// Returns the set of valid next states from this status.
    #[inline]
    pub fn valid_transitions(&self) -> &[InvocationStatus] {
        &STATUS_CONFIG.definition(*self).allowed_transitions
    }

    /// Check if transitioning to `next` is valid.
    #[inline]
    pub fn can_transition_to(&self, next: InvocationStatus) -> bool {
        self.valid_transitions().contains(&next)
    }

    /// Returns all terminal statuses.
    pub fn final_statuses() -> &'static [InvocationStatus] {
        &STATUS_CONFIG.final_statuses
    }

    /// Returns all statuses where invocations can be picked up by runners.
    pub fn available_for_run_statuses() -> &'static [InvocationStatus] {
        &STATUS_CONFIG.available_for_run_statuses
    }
}

impl fmt::Display for InvocationStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Registered => write!(f, "REGISTERED"),
            Self::ConcurrencyControlled => write!(f, "CONCURRENCY_CONTROLLED"),
            Self::ConcurrencyControlledFinal => write!(f, "CONCURRENCY_CONTROLLED_FINAL"),
            Self::Rerouted => write!(f, "REROUTED"),
            Self::Pending => write!(f, "PENDING"),
            Self::PendingRecovery => write!(f, "PENDING_RECOVERY"),
            Self::Running => write!(f, "RUNNING"),
            Self::RunningRecovery => write!(f, "RUNNING_RECOVERY"),
            Self::Paused => write!(f, "PAUSED"),
            Self::Resumed => write!(f, "RESUMED"),
            Self::Killed => write!(f, "KILLED"),
            Self::Success => write!(f, "SUCCESS"),
            Self::Failed => write!(f, "FAILED"),
            Self::Retry => write!(f, "RETRY"),
        }
    }
}

impl FromStr for InvocationStatus {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_uppercase().as_str() {
            "REGISTERED" => Ok(Self::Registered),
            "CONCURRENCY_CONTROLLED" => Ok(Self::ConcurrencyControlled),
            "CONCURRENCY_CONTROLLED_FINAL" => Ok(Self::ConcurrencyControlledFinal),
            "REROUTED" => Ok(Self::Rerouted),
            "PENDING" => Ok(Self::Pending),
            "PENDING_RECOVERY" => Ok(Self::PendingRecovery),
            "RUNNING" => Ok(Self::Running),
            "RUNNING_RECOVERY" => Ok(Self::RunningRecovery),
            "PAUSED" => Ok(Self::Paused),
            "RESUMED" => Ok(Self::Resumed),
            "KILLED" => Ok(Self::Killed),
            "SUCCESS" => Ok(Self::Success),
            "FAILED" => Ok(Self::Failed),
            "RETRY" => Ok(Self::Retry),
            other => Err(format!("unknown invocation status: {other}")),
        }
    }
}

// ============================================================================
// InvocationStatusRecord
// ============================================================================

/// A status change record with ownership and timestamp.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvocationStatusRecord {
    pub status: InvocationStatus,
    pub runner_id: Option<RunnerId>,
    pub timestamp: DateTime<Utc>,
}

impl InvocationStatusRecord {
    pub fn new(status: InvocationStatus, runner_id: Option<RunnerId>) -> Self {
        Self {
            status,
            runner_id,
            timestamp: Utc::now(),
        }
    }
}

// ============================================================================
// StatusDefinition — declarative rules for each status
// ============================================================================

/// Declarative definition of status behavior and ownership rules.
///
/// Mirrors pynenc's `StatusDefinition` dataclass exactly.
#[derive(Debug, Clone)]
pub struct StatusDefinition {
    /// Valid next statuses from this status.
    pub allowed_transitions: Vec<InvocationStatus>,
    /// Terminates invocation lifecycle.
    pub is_final: bool,
    /// Can be picked up by runners via broker.
    pub available_for_run: bool,
    /// Only the owning runner can modify when in this status.
    pub requires_ownership: bool,
    /// Claims ownership on entry (sets runner_id).
    pub acquires_ownership: bool,
    /// Releases ownership on entry (clears runner_id).
    pub releases_ownership: bool,
    /// Bypasses ownership validation (for recovery scenarios).
    pub overrides_ownership: bool,
}

impl StatusDefinition {
    const fn new() -> Self {
        Self {
            allowed_transitions: Vec::new(),
            is_final: false,
            available_for_run: false,
            requires_ownership: false,
            acquires_ownership: false,
            releases_ownership: false,
            overrides_ownership: false,
        }
    }
}

// ============================================================================
// StatusConfiguration — complete config for all statuses
// ============================================================================

/// Complete configuration for invocation status behavior.
pub(super) struct StatusConfiguration {
    /// Definition for the "no status yet" (None → Registered) transition.
    pub(super) initial: StatusDefinition,
    /// Definitions indexed by status.
    definitions: Vec<(InvocationStatus, StatusDefinition)>,
    /// Cached: all terminal statuses.
    pub(super) final_statuses: Vec<InvocationStatus>,
    /// Cached: all available-for-run statuses.
    pub(super) available_for_run_statuses: Vec<InvocationStatus>,
}

impl StatusConfiguration {
    pub(super) fn definition(&self, status: InvocationStatus) -> &StatusDefinition {
        self.definitions
            .iter()
            .find(|(s, _)| *s == status)
            .map_or_else(
                || panic!("missing StatusDefinition for {status:?}"),
                |(_, d)| d,
            )
    }
}

/// Build the static status configuration. Mirrors pynenc's `_CONFIG` exactly.
fn build_config() -> StatusConfiguration {
    use InvocationStatus::*;

    let initial = StatusDefinition {
        allowed_transitions: vec![Registered],
        ..StatusDefinition::new()
    };

    let definitions = vec![
        (
            Registered,
            StatusDefinition {
                allowed_transitions: vec![
                    Pending,
                    ConcurrencyControlled,
                    ConcurrencyControlledFinal,
                ],
                available_for_run: true,
                releases_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            ConcurrencyControlled,
            StatusDefinition {
                allowed_transitions: vec![Rerouted],
                releases_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            Rerouted,
            StatusDefinition {
                allowed_transitions: vec![Pending, ConcurrencyControlled],
                available_for_run: true,
                releases_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            Pending,
            StatusDefinition {
                // An invocation can FAIL without running by the CYCLE-CONTROL mechanism
                // to avoid deadlocks.
                // PENDING_RECOVERY is for timeout recovery without ownership validation.
                allowed_transitions: vec![Running, Killed, Rerouted, Failed, PendingRecovery],
                requires_ownership: true,
                acquires_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            PendingRecovery,
            StatusDefinition {
                allowed_transitions: vec![Rerouted],
                releases_ownership: true,
                overrides_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            Running,
            StatusDefinition {
                allowed_transitions: vec![Paused, Killed, Retry, Success, Failed, RunningRecovery],
                requires_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            RunningRecovery,
            StatusDefinition {
                allowed_transitions: vec![Rerouted],
                releases_ownership: true,
                overrides_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            Paused,
            StatusDefinition {
                allowed_transitions: vec![Resumed, Killed],
                requires_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            Resumed,
            StatusDefinition {
                allowed_transitions: vec![Paused, Killed, Retry, Success, Failed],
                requires_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            Killed,
            StatusDefinition {
                allowed_transitions: vec![Rerouted],
                releases_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            Retry,
            StatusDefinition {
                allowed_transitions: vec![Pending],
                available_for_run: true,
                releases_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            Success,
            StatusDefinition {
                is_final: true,
                releases_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            Failed,
            StatusDefinition {
                is_final: true,
                releases_ownership: true,
                ..StatusDefinition::new()
            },
        ),
        (
            ConcurrencyControlledFinal,
            StatusDefinition {
                is_final: true,
                releases_ownership: true,
                ..StatusDefinition::new()
            },
        ),
    ];

    let final_statuses: Vec<_> = definitions
        .iter()
        .filter(|(_, d)| d.is_final)
        .map(|(s, _)| *s)
        .collect();
    let available_for_run_statuses: Vec<_> = definitions
        .iter()
        .filter(|(_, d)| d.available_for_run)
        .map(|(s, _)| *s)
        .collect();

    StatusConfiguration {
        initial,
        definitions,
        final_statuses,
        available_for_run_statuses,
    }
}

pub(super) static STATUS_CONFIG: LazyLock<StatusConfiguration> = LazyLock::new(build_config);

/// Get the status definition for a given status.
pub fn get_status_definition(status: InvocationStatus) -> &'static StatusDefinition {
    STATUS_CONFIG.definition(status)
}

/// Get the status definition for the initial (None) state.
pub fn get_initial_definition() -> &'static StatusDefinition {
    &STATUS_CONFIG.initial
}