iii-sdk 0.24.2

SDK for III Engine - a platform for building distributed applications
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
use iii_helpers::http::HttpInvocationConfig;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;

/// [`Message::RegistrationRejected`] code: another live worker already holds
/// this `(namespace, worker_name)`. The engine closes the connection; the SDK
/// must stop and not reconnect. Mirrors the engine constant of the same name.
pub const WORKER_NAMESPACE_CONFLICT: &str = "WORKER_NAMESPACE_CONFLICT";

/// [`Message::RegistrationRejected`] code: another live worker in this
/// namespace already exports this function id. Only that one registration is
/// refused; the connection stays open and the worker keeps serving its other
/// functions. Mirrors the engine constant of the same name.
pub const FUNCTION_NAMESPACE_CONFLICT: &str = "FUNCTION_NAMESPACE_CONFLICT";

/// Routing action for [`TriggerRequest`]. Determines how the engine handles
/// the invocation.
///
/// - `Enqueue`: Routes through a named queue for async processing.
/// - `Void`: Fire-and-forget, no response.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum TriggerAction {
    /// Routes the invocation through a named queue.
    Enqueue { queue: String },
    /// Fire-and-forget routing.
    Void,
}

/// Request object for `trigger()`.
///
/// ```rust
/// # use iii_sdk::protocol::{TriggerRequest, TriggerAction};
/// # use serde_json::json;
/// // Simple call
/// TriggerRequest {
///     function_id: "my::function".to_string(),
///     payload: json!({ "key": "value" }),
///     action: None,
///     timeout_ms: None,
/// };
///
/// // With action
/// TriggerRequest {
///     function_id: "my::function".to_string(),
///     payload: json!({}),
///     action: Some(TriggerAction::Enqueue { queue: "payments".to_string() }),
///     timeout_ms: None,
/// };
///
/// // With metadata
/// TriggerRequest {
///     function_id: "my::function".to_string(),
///     payload: json!({}),
///     action: None,
///     timeout_ms: None,
/// }
/// .metadata(json!({ "tenant": "acme" }));
/// ```
#[derive(Debug, Clone)]
pub struct TriggerRequest {
    /// ID of the function to invoke.
    pub function_id: String,
    /// Input data passed to the function.
    pub payload: Value,
    /// Sets how the trigger is routed. `None` for a synchronous request/response.
    /// Set a routing scheme otherwise (e.g. `TriggerAction::Enqueue { .. }`, `TriggerAction::Void`).
    pub action: Option<TriggerAction>,
    /// Override the default invocation timeout, in milliseconds.
    pub timeout_ms: Option<u64>,
}

impl TriggerRequest {
    /// Attach per-invocation metadata without adding a required field to
    /// [`TriggerRequest`] struct literals.
    pub fn metadata(self, metadata: Value) -> TriggerRequestWithMetadata {
        TriggerRequestWithMetadata {
            request: self,
            metadata: Some(metadata),
            namespace: None,
        }
    }

    /// Target a specific namespace for this invocation without adding a
    /// required field to [`TriggerRequest`] struct literals. Serializes into
    /// [`Message::InvokeFunction`]'s `namespace`.
    ///
    /// Leaving it unset does not mean the engine's default: the call inherits
    /// this worker's namespace. Say `default` to reach the engine's from a
    /// namespaced worker.
    pub fn namespace(self, namespace: impl Into<String>) -> TriggerRequestWithMetadata {
        TriggerRequestWithMetadata {
            request: self,
            metadata: None,
            namespace: Some(namespace.into()),
        }
    }
}

/// Trigger request plus optional per-invocation metadata and target namespace.
#[derive(Debug, Clone)]
pub struct TriggerRequestWithMetadata {
    pub(crate) request: TriggerRequest,
    pub(crate) metadata: Option<Value>,
    pub(crate) namespace: Option<String>,
}

impl TriggerRequestWithMetadata {
    /// Attach per-invocation metadata.
    pub fn metadata(mut self, metadata: Value) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Target a specific namespace for this invocation.
    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = Some(namespace.into());
        self
    }
}

impl<T> From<T> for TriggerRequestWithMetadata
where
    T: Into<TriggerRequest>,
{
    fn from(request: T) -> Self {
        Self {
            request: request.into(),
            metadata: None,
            namespace: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Message {
    RegisterTriggerType {
        id: String,
        description: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        trigger_request_format: Option<Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        call_request_format: Option<Value>,
        /// Namespace this provider serves. Absent means the connection's own.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        namespace: Option<String>,
    },
    RegisterTrigger {
        id: String,
        trigger_type: String,
        function_id: String,
        config: Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        metadata: Option<Value>,
        /// Namespace the trigger's target function resolves in.
        ///
        /// The engine reads an absent field as its default namespace. The SDK
        /// does not leave it absent: `register_trigger` fills it from this
        /// worker's namespace, because the function a trigger names is one this
        /// worker registered, and that landed in the worker's namespace. Name
        /// another namespace, `default` included, to bind elsewhere.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        namespace: Option<String>,
        /// Namespace to find the provider in. Absent asks the engine to resolve
        /// it: this connection's namespace first, then the engine's own.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        trigger_namespace: Option<String>,
    },
    TriggerRegistrationResult {
        id: String,
        trigger_type: String,
        function_id: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        error: Option<ErrorBody>,
    },
    UnregisterTrigger {
        id: String,
        trigger_type: String,
    },
    UnregisterTriggerType {
        id: String,
    },
    RegisterFunction {
        id: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        request_format: Option<Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        response_format: Option<Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        metadata: Option<Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        invocation: Option<HttpInvocationConfig>,
    },
    UnregisterFunction {
        id: String,
    },
    InvokeFunction {
        invocation_id: Option<Uuid>,
        function_id: String,
        data: Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        traceparent: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        baggage: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        action: Option<TriggerAction>,
        /// Per-invocation metadata sidecar, surfaced to the handler as a
        /// distinct argument alongside `data`. Optional and additive
        /// for wire compatibility with engines that don't send it.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        metadata: Option<Value>,
        /// Target namespace for routing. Optional and additive, so older peers
        /// that don't send it stay wire-compatible, and the engine reads an
        /// absent field as its default namespace.
        ///
        /// A call made through this SDK does not arrive absent: `trigger` fills
        /// it from this worker's namespace unless the request names one.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        namespace: Option<String>,
    },
    InvocationResult {
        invocation_id: Uuid,
        function_id: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        result: Option<Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        error: Option<ErrorBody>,
        #[serde(skip_serializing_if = "Option::is_none")]
        traceparent: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        baggage: Option<String>,
    },
    Ping,
    Pong,
    /// Sent to the engine as the first message of a reconnect, before the
    /// registration replay: `previous_worker_id` and `reattach_token` are
    /// the values the engine assigned via `WorkerRegistered` on the previous
    /// connection. The engine retires that connection so the replay lands on
    /// a clean slate; the token is required because worker ids alone are
    /// publicly discoverable.
    Reattach {
        previous_worker_id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reattach_token: Option<String>,
    },
    WorkerRegistered {
        worker_id: String,
        /// Secret to present in `Reattach` on reconnect; absent on older
        /// engines.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reattach_token: Option<String>,
    },
    /// Pushed by the engine when a registration collides with a live worker in
    /// the same namespace. The `code` distinguishes the two cases:
    /// [`WORKER_NAMESPACE_CONFLICT`] is fatal (the engine closes the connection;
    /// the SDK stops and does not reconnect), while [`FUNCTION_NAMESPACE_CONFLICT`]
    /// refuses a single function id and keeps the connection open.
    RegistrationRejected {
        code: String,
        namespace: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        worker_name: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        function_id: Option<String>,
        owner_worker_id: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterTriggerTypeMessage {
    /// Unique identifier for the trigger type (e.g. `state`, `durable:subscriber`).
    pub id: String,
    /// Human-readable description of what this trigger type does.
    pub description: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_request_format: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub call_request_format: Option<Value>,
    /// Namespace this provider serves. `None` lets the engine use the
    /// connection's own, which is what a worker providing a trigger type for
    /// its own project wants.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<String>,
}

impl RegisterTriggerTypeMessage {
    pub fn to_message(&self) -> Message {
        Message::RegisterTriggerType {
            id: self.id.clone(),
            description: self.description.clone(),
            trigger_request_format: self.trigger_request_format.clone(),
            call_request_format: self.call_request_format.clone(),
            namespace: self.namespace.clone(),
        }
    }
}

/// Input for [`IIIClient::register_trigger`](crate::IIIClient::register_trigger).
/// The `id` is auto-generated internally.
///
/// Build it with [`RegisterTriggerInput::new`], or with
/// [`IIITrigger`](crate::builtin_triggers::IIITrigger) for a type the engine
/// provides. A struct literal has to name every field, so each field added here
/// breaks it -- `namespace` did that once and `trigger_namespace` did it again,
/// which is why the constructors exist.
///
/// The two are different questions. `namespace` is where the target function
/// resolves; `trigger_namespace` is where the trigger type's provider is found,
/// and `None` there asks the engine to take this worker's namespace first and
/// the engine's own second.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterTriggerInput {
    /// Identifier of the registered trigger type this trigger uses (e.g. `storage::object-created`, `http`).
    pub trigger_type: String,
    /// ID of the function this trigger invokes when it fires.
    pub function_id: String,
    /// Trigger-type-specific configuration, matching the shape the trigger type expects.
    pub config: Value,
    /// Arbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Namespace the trigger's target function resolves in. `None` inherits
    /// this worker's namespace; name another namespace, including `default`,
    /// to bind the trigger elsewhere.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<String>,
    /// Namespace to find the trigger type's provider in. `None` asks the
    /// engine to resolve it: this worker's namespace first, the engine's own
    /// second. Naming one is strict.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_namespace: Option<String>,
}

impl RegisterTriggerInput {
    /// A trigger of `trigger_type`, bound to `function_id`, configured by
    /// `config`.
    ///
    /// Use this for a trigger type nothing built in provides -- one this worker
    /// or a neighbour registered. For the engine's own types, prefer
    /// [`IIITrigger`](crate::builtin_triggers::IIITrigger), which knows the id
    /// and the config shape:
    ///
    /// ```no_run
    /// # use iii_sdk::protocol::RegisterTriggerInput;
    /// # use serde_json::json;
    /// RegisterTriggerInput::new("kick", "orders::sync", json!({ "every": "1m" }))
    ///     .in_namespace("billing")
    ///     .in_trigger_namespace("shop-a");
    /// ```
    ///
    /// Everything else defaults to "not named", which is what the great
    /// majority of registrations want. Reaching for a struct literal instead
    /// means every field added here becomes a breaking change for the caller,
    /// which is what this exists to stop.
    pub fn new(
        trigger_type: impl Into<String>,
        function_id: impl Into<String>,
        config: Value,
    ) -> Self {
        Self {
            trigger_type: trigger_type.into(),
            function_id: function_id.into(),
            config,
            metadata: None,
            namespace: None,
            trigger_namespace: None,
        }
    }

    /// Resolve this trigger's target function in `namespace` instead of this
    /// worker's.
    pub fn in_namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = Some(namespace.into());
        self
    }

    /// Find the trigger type's provider in `namespace`, and only there.
    ///
    /// A different question from [`in_namespace`](Self::in_namespace): that one
    /// locates the target function, this one locates the provider that fires
    /// it. Left unset, the engine resolves it -- this worker's namespace first,
    /// then its own -- which is what carries a worker that has not been
    /// migrated onto the engine's providers without saying anything.
    pub fn in_trigger_namespace(mut self, namespace: impl Into<String>) -> Self {
        self.trigger_namespace = Some(namespace.into());
        self
    }

    /// Deliver `metadata` to the handler alongside every payload this trigger
    /// fires.
    pub fn with_metadata(mut self, metadata: Value) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterTriggerMessage {
    pub id: String,
    pub trigger_type: String,
    pub function_id: String,
    pub config: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_namespace: Option<String>,
}

impl RegisterTriggerMessage {
    pub fn to_message(&self) -> Message {
        Message::RegisterTrigger {
            id: self.id.clone(),
            trigger_type: self.trigger_type.clone(),
            function_id: self.function_id.clone(),
            config: self.config.clone(),
            metadata: self.metadata.clone(),
            namespace: self.namespace.clone(),
            trigger_namespace: self.trigger_namespace.clone(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnregisterTriggerMessage {
    pub id: String,
    pub trigger_type: String,
}

impl UnregisterTriggerMessage {
    pub fn to_message(&self) -> Message {
        Message::UnregisterTrigger {
            id: self.id.clone(),
            trigger_type: self.trigger_type.clone(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnregisterTriggerTypeMessage {
    pub id: String,
}

impl UnregisterTriggerTypeMessage {
    pub fn to_message(&self) -> Message {
        Message::UnregisterTriggerType {
            id: self.id.clone(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterFunctionMessage {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_format: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invocation: Option<HttpInvocationConfig>,
}

impl RegisterFunctionMessage {
    pub fn with_id(name: String) -> Self {
        RegisterFunctionMessage {
            id: name,
            description: None,
            request_format: None,
            response_format: None,
            metadata: None,
            invocation: None,
        }
    }
    pub fn with_description(mut self, description: String) -> Self {
        self.description = Some(description);
        self
    }
    pub fn to_message(&self) -> Message {
        Message::RegisterFunction {
            id: self.id.clone(),
            description: self.description.clone(),
            request_format: self.request_format.clone(),
            response_format: self.response_format.clone(),
            metadata: self.metadata.clone(),
            invocation: self.invocation.clone(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionMessage {
    pub function_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_format: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ErrorBody {
    pub code: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stacktrace: Option<String>,
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;

    #[test]
    fn register_function_to_message_and_serializes_type() {
        let msg = RegisterFunctionMessage {
            id: "functions.echo".to_string(),
            description: Some("Echo function".to_string()),
            request_format: None,
            response_format: None,
            metadata: None,
            invocation: None,
        };

        let message = msg.to_message();
        match &message {
            Message::RegisterFunction {
                id, description, ..
            } => {
                assert_eq!(id, "functions.echo");
                assert_eq!(description.as_deref(), Some("Echo function"));
            }
            _ => panic!("unexpected message variant"),
        }

        let serialized = serde_json::to_value(&message).unwrap();
        assert_eq!(serialized["type"], "registerfunction");
        assert_eq!(serialized["id"], "functions.echo");
        assert_eq!(serialized["description"], "Echo function");
    }

    #[test]
    fn register_http_function_serializes_invocation() {
        use iii_helpers::http::{HttpInvocationConfig, HttpMethod};

        let msg = RegisterFunctionMessage {
            id: "external::my_lambda".to_string(),
            description: None,
            request_format: None,
            response_format: None,
            metadata: None,
            invocation: Some(HttpInvocationConfig {
                url: "https://example.com/invoke".to_string(),
                method: HttpMethod::Post,
                timeout_ms: Some(30000),
                headers: HashMap::new(),
                auth: None,
            }),
        };

        let serialized = serde_json::to_value(msg.to_message()).unwrap();
        assert_eq!(serialized["type"], "registerfunction");
        assert_eq!(serialized["id"], "external::my_lambda");
        assert!(serialized["invocation"].is_object());
        assert_eq!(
            serialized["invocation"]["url"],
            "https://example.com/invoke"
        );
        assert_eq!(serialized["invocation"]["method"], "POST");
    }
}