assay-domain 0.2.4

Shared workflow domain model (types + store traits) for the assay workflow engine, auth layer, and dashboard.
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
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
use utoipa::ToSchema;

// ── Workflow Status ─────────────────────────────────────────

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WorkflowStatus {
    Pending,
    Running,
    Waiting,
    Completed,
    Failed,
    Cancelled,
    TimedOut,
}

impl fmt::Display for WorkflowStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pending => write!(f, "PENDING"),
            Self::Running => write!(f, "RUNNING"),
            Self::Waiting => write!(f, "WAITING"),
            Self::Completed => write!(f, "COMPLETED"),
            Self::Failed => write!(f, "FAILED"),
            Self::Cancelled => write!(f, "CANCELLED"),
            Self::TimedOut => write!(f, "TIMED_OUT"),
        }
    }
}

impl FromStr for WorkflowStatus {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "PENDING" => Ok(Self::Pending),
            "RUNNING" => Ok(Self::Running),
            "WAITING" => Ok(Self::Waiting),
            "COMPLETED" => Ok(Self::Completed),
            "FAILED" => Ok(Self::Failed),
            "CANCELLED" => Ok(Self::Cancelled),
            "TIMED_OUT" => Ok(Self::TimedOut),
            _ => Err(format!("unknown workflow status: {s}")),
        }
    }
}

impl WorkflowStatus {
    pub fn is_terminal(self) -> bool {
        matches!(
            self,
            Self::Completed | Self::Failed | Self::Cancelled | Self::TimedOut
        )
    }
}

// ── Activity Status ─────────────────────────────────────────

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ActivityStatus {
    Pending,
    Running,
    Completed,
    Failed,
    Cancelled,
}

impl fmt::Display for ActivityStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pending => write!(f, "PENDING"),
            Self::Running => write!(f, "RUNNING"),
            Self::Completed => write!(f, "COMPLETED"),
            Self::Failed => write!(f, "FAILED"),
            Self::Cancelled => write!(f, "CANCELLED"),
        }
    }
}

impl FromStr for ActivityStatus {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "PENDING" => Ok(Self::Pending),
            "RUNNING" => Ok(Self::Running),
            "COMPLETED" => Ok(Self::Completed),
            "FAILED" => Ok(Self::Failed),
            "CANCELLED" => Ok(Self::Cancelled),
            _ => Err(format!("unknown activity status: {s}")),
        }
    }
}

// ── Event Types ─────────────────────────────────────────────

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum EventType {
    WorkflowStarted,
    ActivityScheduled,
    ActivityCompleted,
    ActivityFailed,
    TimerStarted,
    TimerFired,
    SignalReceived,
    WorkflowCompleted,
    WorkflowFailed,
    WorkflowCancelled,
    ChildWorkflowStarted,
    ChildWorkflowCompleted,
    SideEffectRecorded,
}

impl fmt::Display for EventType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = serde_json::to_value(self)
            .ok()
            .and_then(|v| v.as_str().map(String::from))
            .unwrap_or_else(|| format!("{self:?}"));
        write!(f, "{s}")
    }
}

impl FromStr for EventType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        serde_json::from_value(serde_json::Value::String(s.to_string()))
            .map_err(|_| format!("unknown event type: {s}"))
    }
}

// ── Overlap Policy ──────────────────────────────────────────

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OverlapPolicy {
    Skip,
    Queue,
    CancelOld,
    AllowAll,
}

impl fmt::Display for OverlapPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Skip => write!(f, "skip"),
            Self::Queue => write!(f, "queue"),
            Self::CancelOld => write!(f, "cancel_old"),
            Self::AllowAll => write!(f, "allow_all"),
        }
    }
}

impl FromStr for OverlapPolicy {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "skip" => Ok(Self::Skip),
            "queue" => Ok(Self::Queue),
            "cancel_old" => Ok(Self::CancelOld),
            "allow_all" => Ok(Self::AllowAll),
            _ => Err(format!("unknown overlap policy: {s}")),
        }
    }
}

// ── Records ─────────────────────────────────────────────────

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct WorkflowRecord {
    pub id: String,
    pub namespace: String,
    pub run_id: String,
    pub workflow_type: String,
    pub task_queue: String,
    pub status: String,
    pub input: Option<String>,
    pub result: Option<String>,
    pub error: Option<String>,
    pub parent_id: Option<String>,
    pub claimed_by: Option<String>,
    /// Application-level indexed metadata, JSON object encoded as a string
    /// (e.g. `{"env":"prod","tenant":"acme","progress":0.5}`). Settable on
    /// workflow start and updatable at runtime via
    /// `ctx:upsert_search_attributes(...)` from workflow code. Filter the
    /// list endpoint with `?search_attrs={"key":"value"}`.
    pub search_attributes: Option<String>,
    /// Set when the archival task has moved this workflow's
    /// events+activities+snapshots off to cold storage. The row itself
    /// stays (with `archive_uri` pointing at the bundle) so that
    /// `GET /workflows/{id}` still resolves.
    pub archived_at: Option<f64>,
    pub archive_uri: Option<String>,
    pub created_at: f64,
    pub updated_at: f64,
    pub completed_at: Option<f64>,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct WorkflowEvent {
    pub id: Option<i64>,
    pub workflow_id: String,
    pub seq: i32,
    pub event_type: String,
    pub payload: Option<String>,
    pub timestamp: f64,
}

/// Options for scheduling an activity. All fields default to sensible values
/// when not provided by the caller; this keeps the per-call API short while
/// still letting workflows tune retry/timeout policy when they need to.
#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
pub struct ScheduleActivityOpts {
    pub max_attempts: Option<i32>,
    pub initial_interval_secs: Option<f64>,
    pub backoff_coefficient: Option<f64>,
    pub start_to_close_secs: Option<f64>,
    pub heartbeat_timeout_secs: Option<f64>,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct WorkflowActivity {
    pub id: Option<i64>,
    pub workflow_id: String,
    pub seq: i32,
    pub name: String,
    pub task_queue: String,
    pub input: Option<String>,
    pub status: String,
    pub result: Option<String>,
    pub error: Option<String>,
    pub attempt: i32,
    pub max_attempts: i32,
    pub initial_interval_secs: f64,
    pub backoff_coefficient: f64,
    pub start_to_close_secs: f64,
    pub heartbeat_timeout_secs: Option<f64>,
    pub claimed_by: Option<String>,
    pub scheduled_at: f64,
    pub started_at: Option<f64>,
    pub completed_at: Option<f64>,
    pub last_heartbeat: Option<f64>,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct RetriedActivity {
    pub activity: WorkflowActivity,
    pub invalidated_activities: u64,
}

#[derive(Clone, Debug)]
pub enum RetryFailedActivityResult {
    Retried(Box<RetriedActivity>),
    NotFound,
    NotFailed { status: String },
    Archived,
    ChildWorkflow,
    NoFailedActivity,
    Unsupported,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct WorkflowTimer {
    pub id: Option<i64>,
    pub workflow_id: String,
    pub seq: i32,
    pub fire_at: f64,
    pub fired: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct WorkflowSignal {
    pub id: Option<i64>,
    pub workflow_id: String,
    pub name: String,
    pub payload: Option<String>,
    pub consumed: bool,
    pub received_at: f64,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct WorkflowSchedule {
    pub name: String,
    pub namespace: String,
    pub workflow_type: String,
    pub cron_expr: String,
    /// IANA time-zone name used to interpret `cron_expr` (e.g. "Europe/Berlin",
    /// "America/New_York"). Defaults to "UTC" when a schedule is created
    /// without an explicit timezone, preserving v0.11.2 behaviour.
    pub timezone: String,
    pub input: Option<String>,
    pub task_queue: String,
    pub overlap_policy: String,
    pub paused: bool,
    pub last_run_at: Option<f64>,
    pub next_run_at: Option<f64>,
    pub last_workflow_id: Option<String>,
    pub created_at: f64,
}

/// Partial update to a `WorkflowSchedule`. Only fields set to `Some` are
/// applied; `None` leaves the existing value untouched. Used by
/// `PATCH /api/v1/schedules/{name}`.
#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
pub struct SchedulePatch {
    pub cron_expr: Option<String>,
    pub timezone: Option<String>,
    pub input: Option<serde_json::Value>,
    pub task_queue: Option<String>,
    pub overlap_policy: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct WorkflowWorker {
    pub id: String,
    pub namespace: String,
    pub identity: String,
    pub task_queue: String,
    pub workflows: Option<String>,
    pub activities: Option<String>,
    pub max_concurrent_workflows: i32,
    pub max_concurrent_activities: i32,
    pub active_tasks: i32,
    pub last_heartbeat: f64,
    pub registered_at: f64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WorkflowSnapshot {
    pub workflow_id: String,
    pub event_seq: i32,
    pub state_json: String,
    pub created_at: f64,
}

// ── Store-level DTOs (moved from assay-workflow::store::mod) ────────

/// Namespace record.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct NamespaceRecord {
    pub name: String,
    pub created_at: f64,
}

/// Namespace-level statistics.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct NamespaceStats {
    pub namespace: String,
    pub total_workflows: i64,
    pub running: i64,
    pub pending: i64,
    pub completed: i64,
    pub failed: i64,
    pub schedules: i64,
    pub workers: i64,
}

/// Task queue statistics.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct QueueStats {
    pub queue: String,
    pub pending_activities: i64,
    pub running_activities: i64,
    pub workers: i64,
}

/// The writes that must land together when an activity reaches a terminal
/// state: the activity row, the history event a replaying workflow reads,
/// and the dispatch arming that wakes the workflow. Passed to
/// [`crate::store::WorkflowStore::settle_activity`], which applies all three
/// in one transaction.
#[derive(Clone, Debug)]
pub struct ActivitySettlement<'a> {
    pub activity_id: i64,
    pub workflow_id: &'a str,
    pub result: Option<&'a str>,
    pub error: Option<&'a str>,
    pub failed: bool,
    /// `ActivityCompleted` or `ActivityFailed`.
    pub event_type: &'a str,
    /// Serialised event payload, built by the caller.
    pub payload: &'a str,
    pub now: f64,
}

/// What [`crate::store::WorkflowStore::settle_activity`] found and did.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SettleOutcome {
    /// The activity was open: status, history event and dispatch arming
    /// all landed in this call.
    Settled,
    /// The activity was already terminal but carried no history event —
    /// the event was appended and the workflow re-armed.
    Repaired,
    /// The activity and its event were already durable. Only the dispatch
    /// arming was re-applied, which recovers a lost workflow task.
    AlreadySettled,
    /// No activity with this id.
    Unknown,
}