tmprl-client 0.1.0

Temporal gRPC access layer for tmprl
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
//! The operations that change a cluster.
//!
//! Everything else in this crate reads. These write, and deleting a workflow or a schedule
//! cannot be undone, so nothing here decides *whether* to act, the confirmation in
//! `tmprl-core` does that, and the reducer only reaches this module once the reader has said
//! yes.
//!
//! Every request carries an `identity`. Temporal records it on the resulting history event,
//! so a workflow terminated from tmprl says so in its own history rather than appearing to
//! have stopped on its own.

use temporalio_client::tonic::Request;
use temporalio_common::protos::temporal::api::{
    common::v1::{Payload as ProtoPayload, Payloads, WorkflowExecution, WorkflowType},
    enums::v1::UpdateWorkflowExecutionLifecycleStage,
    schedule::v1::{
        BackfillRequest, Schedule, ScheduleAction, SchedulePatch, ScheduleSpec,
        TriggerImmediatelyRequest, schedule_action::Action as ScheduleActionKind,
    },
    taskqueue::v1::TaskQueue,
    update::v1::{Input as UpdateInput, Meta as UpdateMeta, Request as UpdateRequest, WaitPolicy},
    workflow::v1::NewWorkflowExecutionInfo,
    workflowservice::v1::{
        CreateScheduleRequest, DeleteScheduleRequest, DeleteWorkflowExecutionRequest,
        PatchScheduleRequest, RequestCancelWorkflowExecutionRequest, ResetWorkflowExecutionRequest,
        SignalWorkflowExecutionRequest, TerminateWorkflowExecutionRequest,
        UpdateWorkflowExecutionRequest,
    },
};
use tmprl_core::mutation::Mutation;

use super::OpError;
use crate::Conn;

/// What tmprl calls itself on the events it causes.
fn identity() -> String {
    format!(
        "tmprl@{}",
        std::env::var("USER").unwrap_or_else(|_| "unknown".into())
    )
}

/// A fresh request id.
///
/// `ResetWorkflowExecution` rejects a request without one ("RequestId is not set on request").
/// The others accept one, where it makes a retried call idempotent rather than doubling the
/// effect.
fn request_id() -> String {
    uuid::Uuid::new_v4().to_string()
}

/// Epoch millis as a protobuf timestamp.
fn timestamp(ms: i64) -> prost_wkt_types::Timestamp {
    prost_wkt_types::Timestamp {
        seconds: ms.div_euclid(1_000),
        nanos: (ms.rem_euclid(1_000) * 1_000_000) as i32,
    }
}

fn execution(workflow_id: &str, run_id: &str) -> Option<WorkflowExecution> {
    Some(WorkflowExecution {
        workflow_id: workflow_id.to_string(),
        run_id: run_id.to_string(),
    })
}

impl Conn {
    /// Carry out a confirmed mutation.
    ///
    /// One entry point rather than four, so the reducer has exactly one place that writes and
    /// the audit log has exactly one thing to wrap.
    pub async fn mutate(&self, m: &Mutation) -> Result<(), OpError> {
        match m {
            Mutation::Cancel {
                namespace,
                workflow_id,
                run_id,
            } => {
                self.wf()
                    .request_cancel_workflow_execution(Request::new(
                        RequestCancelWorkflowExecutionRequest {
                            namespace: namespace.clone(),
                            workflow_execution: execution(workflow_id, run_id),
                            identity: identity(),
                            request_id: request_id(),
                            ..Default::default()
                        },
                    ))
                    .await
                    .map_err(|s| OpError::rpc("RequestCancelWorkflowExecution", s))?;
            }

            Mutation::Terminate {
                namespace,
                workflow_id,
                run_id,
                reason,
            } => {
                self.wf()
                    .terminate_workflow_execution(Request::new(TerminateWorkflowExecutionRequest {
                        namespace: namespace.clone(),
                        workflow_execution: execution(workflow_id, run_id),
                        reason: reason.clone(),
                        identity: identity(),
                        ..Default::default()
                    }))
                    .await
                    .map_err(|s| OpError::rpc("TerminateWorkflowExecution", s))?;
            }

            Mutation::Signal {
                namespace,
                workflow_id,
                run_id,
                name,
                input,
            } => {
                self.wf()
                    .signal_workflow_execution(Request::new(SignalWorkflowExecutionRequest {
                        namespace: namespace.clone(),
                        workflow_execution: execution(workflow_id, run_id),
                        signal_name: name.clone(),
                        input: input.as_deref().map(json_payload),
                        identity: identity(),
                        request_id: request_id(),
                        ..Default::default()
                    }))
                    .await
                    .map_err(|s| OpError::rpc("SignalWorkflowExecution", s))?;
            }

            Mutation::Delete {
                namespace,
                workflow_id,
                run_id,
            } => {
                self.wf()
                    .delete_workflow_execution(Request::new(DeleteWorkflowExecutionRequest {
                        namespace: namespace.clone(),
                        workflow_execution: execution(workflow_id, run_id),
                    }))
                    .await
                    .map_err(|s| OpError::rpc("DeleteWorkflowExecution", s))?;
            }

            Mutation::Reset {
                namespace,
                workflow_id,
                run_id,
                event_id,
                reason,
            } => {
                self.wf()
                    .reset_workflow_execution(Request::new(ResetWorkflowExecutionRequest {
                        namespace: namespace.clone(),
                        workflow_execution: execution(workflow_id, run_id),
                        reason: reason.clone(),
                        // Already resolved to a completed workflow task; the server rejects
                        // anything else.
                        workflow_task_finish_event_id: *event_id,
                        // Excluding nothing keeps signals sent after the reset point.
                        // Replaces the deprecated `reset_reapply_type`.
                        reset_reapply_exclude_types: Vec::new(),
                        identity: identity(),
                        request_id: request_id(),
                        ..Default::default()
                    }))
                    .await
                    .map_err(|s| OpError::rpc("ResetWorkflowExecution", s))?;
            }

            Mutation::Update {
                namespace,
                workflow_id,
                run_id,
                name,
                input,
            } => {
                let resp = self
                    .wf()
                    .update_workflow_execution(Request::new(UpdateWorkflowExecutionRequest {
                        namespace: namespace.clone(),
                        workflow_execution: execution(workflow_id, run_id),
                        // Wait for the outcome rather than for acceptance, so the reported
                        // result is the workflow's answer and not just "it was allowed in".
                        wait_policy: Some(WaitPolicy {
                            lifecycle_stage: UpdateWorkflowExecutionLifecycleStage::Completed
                                as i32,
                        }),
                        request: Some(UpdateRequest {
                            request_id: request_id(),
                            meta: Some(UpdateMeta {
                                update_id: request_id(),
                                identity: identity(),
                            }),
                            input: Some(UpdateInput {
                                name: name.clone(),
                                args: input.as_deref().map(json_payload),
                                ..Default::default()
                            }),
                            completion_callbacks: Vec::new(),
                            links: Vec::new(),
                        }),
                        ..Default::default()
                    }))
                    .await
                    .map_err(|s| OpError::rpc("UpdateWorkflowExecution", s))?
                    .into_inner();

                // An update can be *accepted* and then rejected by the workflow itself. That
                // is a failure of the thing the user asked for, so it is reported as one
                // rather than as a success that quietly did nothing.
                if let Some(outcome) = resp.outcome
                    && let Some(
                        temporalio_common::protos::temporal::api::update::v1::outcome::Value::Failure(f),
                    ) = outcome.value
                {
                    return Err(OpError::Rpc {
                        operation: "UpdateWorkflowExecution",
                        code: "Rejected".into(),
                        message: f.message,
                    });
                }
            }

            Mutation::PauseSchedule {
                namespace,
                schedule_id,
                paused,
            } => {
                // The reason lands in the schedule's own notes, so a paused schedule says
                // why it is paused rather than merely that it is.
                let note = format!("{} from tmprl", if *paused { "paused" } else { "resumed" });
                self.wf()
                    .patch_schedule(Request::new(PatchScheduleRequest {
                        namespace: namespace.clone(),
                        schedule_id: schedule_id.clone(),
                        patch: Some(SchedulePatch {
                            pause: if *paused { note.clone() } else { String::new() },
                            unpause: if *paused { String::new() } else { note },
                            ..Default::default()
                        }),
                        identity: identity(),
                        request_id: request_id(),
                    }))
                    .await
                    .map_err(|s| OpError::rpc("PatchSchedule", s))?;
            }

            Mutation::TriggerSchedule {
                namespace,
                schedule_id,
            } => {
                self.wf()
                    .patch_schedule(Request::new(PatchScheduleRequest {
                        namespace: namespace.clone(),
                        schedule_id: schedule_id.clone(),
                        patch: Some(SchedulePatch {
                            trigger_immediately: Some(TriggerImmediatelyRequest {
                                // Unspecified leaves the schedule's own overlap policy in
                                // charge, which is what the reader configured.
                                overlap_policy: 0,
                                // None means now, which is what "trigger" asks for.
                                scheduled_time: None,
                            }),
                            ..Default::default()
                        }),
                        identity: identity(),
                        request_id: request_id(),
                    }))
                    .await
                    .map_err(|s| OpError::rpc("PatchSchedule", s))?;
            }

            Mutation::CreateSchedule {
                namespace,
                schedule_id,
                workflow_id,
                workflow_type,
                task_queue,
                spec,
                input,
            } => {
                self.wf()
                    .create_schedule(Request::new(CreateScheduleRequest {
                        namespace: namespace.clone(),
                        schedule_id: schedule_id.clone(),
                        schedule: Some(Schedule {
                            // The cron string is sent as typed. The server parses it, and it
                            // accepts `@every 1h` as well as five-field cron, so validating
                            // here would only reject specs the server would have taken.
                            spec: Some(ScheduleSpec {
                                cron_string: vec![spec.clone()],
                                ..Default::default()
                            }),
                            action: Some(ScheduleAction {
                                action: Some(ScheduleActionKind::StartWorkflow(
                                    NewWorkflowExecutionInfo {
                                        workflow_id: workflow_id.clone(),
                                        workflow_type: Some(WorkflowType {
                                            name: workflow_type.clone(),
                                        }),
                                        task_queue: Some(TaskQueue {
                                            name: task_queue.clone(),
                                            ..Default::default()
                                        }),
                                        input: input.as_deref().map(json_payload),
                                        ..Default::default()
                                    },
                                )),
                            }),
                            ..Default::default()
                        }),
                        identity: identity(),
                        request_id: request_id(),
                        ..Default::default()
                    }))
                    .await
                    .map_err(|s| OpError::rpc("CreateSchedule", s))?;
            }

            Mutation::BackfillSchedule {
                namespace,
                schedule_id,
                range,
                overlap,
            } => {
                self.wf()
                    .patch_schedule(Request::new(PatchScheduleRequest {
                        namespace: namespace.clone(),
                        schedule_id: schedule_id.clone(),
                        patch: Some(SchedulePatch {
                            backfill_request: vec![BackfillRequest {
                                start_time: Some(timestamp(range.start_ms)),
                                end_time: Some(timestamp(range.end_ms)),
                                overlap_policy: overlap.code(),
                            }],
                            ..Default::default()
                        }),
                        identity: identity(),
                        request_id: request_id(),
                    }))
                    .await
                    .map_err(|s| OpError::rpc("PatchSchedule", s))?;
            }

            Mutation::DeleteSchedule {
                namespace,
                schedule_id,
            } => {
                self.wf()
                    .delete_schedule(Request::new(DeleteScheduleRequest {
                        namespace: namespace.clone(),
                        schedule_id: schedule_id.clone(),
                        identity: identity(),
                    }))
                    .await
                    .map_err(|s| OpError::rpc("DeleteSchedule", s))?;
            }
        }
        Ok(())
    }
}

/// A signal argument, encoded the way an SDK would send it.
///
/// `json/plain` with the text as typed. The confirmation shows the same string next to
/// `--input`, so what the CLI would send and what tmprl sends are the same bytes.
fn json_payload(input: &str) -> Payloads {
    Payloads {
        payloads: vec![ProtoPayload {
            metadata: [("encoding".to_string(), b"json/plain".to_vec())]
                .into_iter()
                .collect(),
            data: input.as_bytes().to_vec(),
            external_payloads: Vec::new(),
        }],
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_signal_argument_is_sent_as_json_plain() {
        let p = json_payload(r#"{"a":1}"#);
        assert_eq!(p.payloads.len(), 1);
        assert_eq!(p.payloads[0].data, br#"{"a":1}"#);
        assert_eq!(
            p.payloads[0].metadata.get("encoding").map(|v| v.as_slice()),
            Some(&b"json/plain"[..])
        );
    }

    #[test]
    fn tmprl_names_itself_on_what_it_causes() {
        // A workflow terminated from here should say so in its own history rather than
        // appearing to have stopped on its own.
        assert!(identity().starts_with("tmprl@"));
    }

    #[test]
    fn an_execution_carries_both_ids() {
        let e = execution("w", "r").unwrap();
        assert_eq!(e.workflow_id, "w");
        assert_eq!(e.run_id, "r");
    }
}