harmos-runtime 0.1.8

Harmos runtime: managed state, undo, recovery, background work and typed streams.
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
/* ***
 *
 * Harmos
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * ***
 */

/* === Modules === */

/* === Re-Exports === */

/* === Imports === */

// Standard Library Imports
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};

// Third Party Imports

// Local Imports
use super::{
    Manager, OperationGeneration, OperationInstanceId, OperationStatus, Running, StreamInput, StreamItem, StreamOutput, StreamSettings,
    stream,
};
use crate::operations::OperationDeclaration;
use crate::supervision::instance::{Instance, Phase};
use crate::{Error, Refusal, Result};
use harmos_domain::MemorySize;

/* === Constants === */

/* === Macros === */

/* === Type Aliases === */

pub type Upload<O> = Session<O, SessionInput<<<O as OperationDeclaration>::Input as crate::operations::Direction>::Item>, ()>;
pub type Download<O> = Session<O, (), SessionOutput<<<O as OperationDeclaration>::Output as crate::operations::Direction>::Item>>;
pub type Exchange<O> = Session<
    O,
    SessionInput<<<O as OperationDeclaration>::Input as crate::operations::Direction>::Item>,
    SessionOutput<<<O as OperationDeclaration>::Output as crate::operations::Direction>::Item>,
>;

/* === Structs === */

#[must_use = "dropping a streaming session requests cancellation"]
pub struct Session<O: OperationDeclaration, I = (), R = ()> {
    input: I,
    output: R,
    completion: Completion<O>,
}

pub struct SessionInput<T> {
    sender: Option<StreamOutput<T>>,
    ends: Arc<Ends>,
    control: Arc<Instance>,
}

pub struct SessionOutput<T> {
    receiver: StreamInput<T>,
    ends: Arc<Ends>,
    control: Arc<Instance>,
}

#[must_use = "join completion or explicitly cancel and settle"]
pub struct Completion<O: OperationDeclaration> {
    instance: Running<O>,
    ends: Arc<Ends>,
    delivered: bool,
}

// Channel Progress Only; Execution And Cleanup Remain On Instance.
struct Ends {
    input: AtomicBool,
    output: AtomicBool,
}

/* === Enums === */

/* === Traits === */

/* === Implementations === */

impl<O: OperationDeclaration, I, R> Session<O, I, R> {
    pub fn id(&self) -> OperationInstanceId {
        self.completion.id()
    }

    pub fn generation(&self) -> OperationGeneration {
        self.completion.generation()
    }

    pub fn status(&self) -> OperationStatus {
        self.completion.status()
    }

    pub fn cancel(&self) {
        self.completion.cancel();
    }

    pub fn split(self) -> (I, R, Completion<O>) {
        (self.input, self.output, self.completion)
    }

    pub async fn join(self) -> Result<crate::operations::Response<O::Response>> {
        let (input, output, completion) = self.split();
        drop(input);
        drop(output);
        completion.join().await
    }

    pub async fn cancel_and_settle(self) -> Result<()> {
        self.cancel();
        let (input, output, completion) = self.split();
        drop(input);
        drop(output);
        completion.cancel_and_settle().await
    }
}

impl<O: OperationDeclaration, T, R> Session<O, SessionInput<T>, R> {
    pub fn finish_input(&mut self) {
        self.input.finish_input();
    }
}
impl<O: OperationDeclaration, T: MemorySize, R> Session<O, SessionInput<T>, R> {
    pub async fn send(&self, item: T) -> Result<()> {
        self.input.send(item).await
    }

    pub async fn send_with(&self, bytes: usize, make: impl FnOnce() -> Result<T>) -> Result<()> {
        self.input.send_with(bytes, make).await
    }
}
impl<O: OperationDeclaration, I, T> Session<O, I, SessionOutput<T>> {
    pub async fn next(&mut self) -> Result<Option<StreamItem<T>>> {
        self.output.next().await
    }
}

impl<T> SessionInput<T> {
    pub fn finish_input(&mut self) {
        self.ends.input.store(true, Ordering::Release);
        self.sender.take();
    }
}
impl<T: MemorySize> SessionInput<T> {
    pub async fn send(&self, item: T) -> Result<()> {
        self.send_with(item.memory_size(), || Ok(item)).await
    }

    pub async fn send_with(&self, bytes: usize, make: impl FnOnce() -> Result<T>) -> Result<()> {
        let sender = self.sender.as_ref().ok_or(Error::NotReady { domain: "operation input closed" })?;
        tokio::select! {
            biased;
            error = ended(&self.control) => Err(error),
            permit = sender.reserve(bytes) => {
                let permit = permit?;
                let value = make()?;
                Ok(permit.send_with(|| Ok(value))?)
            },
        }
    }
}
impl<T> Drop for SessionInput<T> {
    fn drop(&mut self) {
        if !self.ends.input.load(Ordering::Acquire) {
            cancel_unsettled(&self.control);
        }
    }
}

impl<T> SessionOutput<T> {
    pub async fn next(&mut self) -> Result<Option<StreamItem<T>>> {
        if self.ends.output.load(Ordering::Acquire) {
            return Ok(None);
        }
        let mut status = self.control.settlement();
        loop {
            let current = status.borrow_and_update().clone();
            if current.cancellation_requested() {
                self.receiver.close();
                return Err(Refusal::Cancelled.into());
            }
            if current.outcome().is_some() {
                self.receiver.close();
                let item = self.receiver.try_recv().ok();
                if item.is_none() {
                    self.ends.output.store(true, Ordering::Release);
                }
                return Ok(item);
            }
            tokio::select! {
                biased;
                item = self.receiver.recv() => {
                    if item.is_none() { self.ends.output.store(true, Ordering::Release); }
                    return Ok(item);
                }
                changed = status.changed() => {
                    if changed.is_err() { return Err(Refusal::Unavailable.into()); }
                }
            }
        }
    }
}
impl<T> Drop for SessionOutput<T> {
    fn drop(&mut self) {
        if !self.ends.output.load(Ordering::Acquire) {
            cancel_unsettled(&self.control);
        }
    }
}

impl<O: OperationDeclaration> Completion<O> {
    pub fn id(&self) -> OperationInstanceId {
        self.instance.id()
    }

    pub fn generation(&self) -> OperationGeneration {
        self.instance.generation()
    }

    pub fn status(&self) -> OperationStatus {
        self.instance.status()
    }

    pub fn cancel(&self) {
        self.instance.cancel();
    }

    pub async fn settle(&self) -> Result<()> {
        self.instance.settle().await
    }

    pub async fn join(mut self) -> Result<crate::operations::Response<O::Response>> {
        if !self.ends.input.load(Ordering::Acquire) || !self.ends.output.load(Ordering::Acquire) {
            return Err(Error::InvalidInput {
                field: "operation stream completion",
                reason: "finish input and drain output before joining; use cancel_and_settle to abandon",
            });
        }
        let result = (&mut self.instance).await;
        self.delivered = true;
        result
    }

    pub async fn cancel_and_settle(mut self) -> Result<()> {
        self.instance.cancel();
        let result = self.instance.settle().await;
        self.delivered = true;
        result
    }
}
impl<O: OperationDeclaration> Drop for Completion<O> {
    fn drop(&mut self) {
        if !self.delivered {
            cancel_unsettled(&self.instance.control);
        }
    }
}

impl Manager {
    pub fn upload<O: crate::operations::OperationDeclaration>(&self, request: O::Request, settings: StreamSettings) -> Result<Upload<O>> {
        upload(request, settings, |request, input| self.submit_endpoints::<O, _>(request, input))
    }

    pub fn download<O: crate::operations::OperationDeclaration>(
        &self, request: O::Request, settings: StreamSettings,
    ) -> Result<Download<O>> {
        download(request, settings, |request, output| self.submit_endpoints::<O, _>(request, output))
    }

    pub fn exchange<O: crate::operations::OperationDeclaration>(
        &self, request: O::Request, input: StreamSettings, output: StreamSettings,
    ) -> Result<Exchange<O>> {
        exchange(request, input, output, |request, endpoints| self.submit_endpoints::<O, _>(request, endpoints))
    }
}

impl super::Context<'_> {
    pub fn upload<O: crate::operations::OperationDeclaration>(&self, request: O::Request, settings: StreamSettings) -> Result<Upload<O>> {
        upload(request, settings, |request, input| self.submit_endpoints::<O, _>(request, input))
    }

    pub fn download<O: crate::operations::OperationDeclaration>(
        &self, request: O::Request, settings: StreamSettings,
    ) -> Result<Download<O>> {
        download(request, settings, |request, output| self.submit_endpoints::<O, _>(request, output))
    }

    pub fn exchange<O: crate::operations::OperationDeclaration>(
        &self, request: O::Request, input: StreamSettings, output: StreamSettings,
    ) -> Result<Exchange<O>> {
        exchange(request, input, output, |request, endpoints| self.submit_endpoints::<O, _>(request, endpoints))
    }
}

#[cfg(any(feature = "plugin", feature = "plugin-guest", feature = "plugin-sidecar"))]
impl super::Caller {
    pub fn upload<O: crate::operations::OperationDeclaration>(&self, request: O::Request, settings: StreamSettings) -> Result<Upload<O>> {
        upload(request, settings, |request, input| self.submit_endpoints::<O, _>(request, input))
    }

    pub fn download<O: crate::operations::OperationDeclaration>(
        &self, request: O::Request, settings: StreamSettings,
    ) -> Result<Download<O>> {
        download(request, settings, |request, output| self.submit_endpoints::<O, _>(request, output))
    }

    pub fn exchange<O: crate::operations::OperationDeclaration>(
        &self, request: O::Request, input: StreamSettings, output: StreamSettings,
    ) -> Result<Exchange<O>> {
        exchange(request, input, output, |request, endpoints| self.submit_endpoints::<O, _>(request, endpoints))
    }
}

/* === Public Functions === */

/* === Private Functions === */

fn upload<O: crate::operations::OperationDeclaration>(
    request: O::Request, settings: StreamSettings,
    submit: impl FnOnce(
        O::Request,
        StreamInput<<<O as OperationDeclaration>::Input as crate::operations::Direction>::Item>,
    ) -> Result<Running<O>>,
) -> Result<Upload<O>> {
    let (sender, input) = stream(settings)?;
    let instance = submit(request, input)?;
    let ends = Arc::new(Ends {
        input: AtomicBool::new(false),
        output: AtomicBool::new(true),
    });
    Ok(Session {
        input: SessionInput {
            sender: Some(sender),
            ends: ends.clone(),
            control: instance.control.clone(),
        },
        output: (),
        completion: Completion { instance, ends, delivered: false },
    })
}
fn download<O: crate::operations::OperationDeclaration>(
    request: O::Request, settings: StreamSettings,
    submit: impl FnOnce(
        O::Request,
        StreamOutput<<<O as OperationDeclaration>::Output as crate::operations::Direction>::Item>,
    ) -> Result<Running<O>>,
) -> Result<Download<O>> {
    let (output, receiver) = stream(settings)?;
    let instance = submit(request, output)?;
    let ends = Arc::new(Ends {
        input: AtomicBool::new(true),
        output: AtomicBool::new(false),
    });
    Ok(Session {
        input: (),
        output: SessionOutput {
            receiver,
            ends: ends.clone(),
            control: instance.control.clone(),
        },
        completion: Completion { instance, ends, delivered: false },
    })
}
fn exchange<O: crate::operations::OperationDeclaration>(
    request: O::Request, input: StreamSettings, output: StreamSettings,
    submit: impl FnOnce(
        O::Request,
        (
            StreamInput<<<O as OperationDeclaration>::Input as crate::operations::Direction>::Item>,
            StreamOutput<<<O as OperationDeclaration>::Output as crate::operations::Direction>::Item>,
        ),
    ) -> Result<Running<O>>,
) -> Result<Exchange<O>> {
    let (sender, input) = stream(input)?;
    let (output, receiver) = stream(output)?;
    let instance = submit(request, (input, output))?;
    let ends = Arc::new(Ends {
        input: AtomicBool::new(false),
        output: AtomicBool::new(false),
    });
    Ok(Session {
        input: SessionInput {
            sender: Some(sender),
            ends: ends.clone(),
            control: instance.control.clone(),
        },
        output: SessionOutput {
            receiver,
            ends: ends.clone(),
            control: instance.control.clone(),
        },
        completion: Completion { instance, ends, delivered: false },
    })
}
fn cancel_unsettled(control: &Instance) {
    if control.status().phase() != Phase::Settled {
        control.cancel();
    }
}
async fn ended(control: &Instance) -> Error {
    let mut status = control.settlement();
    loop {
        let current = status.borrow_and_update().clone();
        if current.cancellation_requested() {
            return Refusal::Cancelled.into();
        }
        if current.outcome().is_some() {
            return Error::NotReady { domain: "operation completed" };
        }
        if status.changed().await.is_err() {
            return Refusal::Unavailable.into();
        }
    }
}

/* === Tests === */