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
/* ***
 *
 * Harmos
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * ***
 */

// Remote observers of one sidecar connection. Each activation submits the
// plugin's observe control and holds that invocation for as long as the
// activation runs; stopping cancels it, and the sidecar stops and cleans the
// observer up through the invocation's ordinary cleanup. The activation keeps
// the connection alive until its invocation settles.

/* === Modules === */

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

/* === Imports === */

// Standard Library Imports
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, OnceLock, Weak};
// Third Party Imports
use tokio::sync::{mpsc, watch};
// Local Imports
use super::{Arrival, SidecarError};
use crate::observers::{ChildSettlement, ObserverActivation, ObserverBackend, ObserverDefinition, ObserverRegistration};
use crate::operations::{Manager, OperationPhase};
use harmos_sidecar::inventory::observers::{Activation, Declaration};

/* === Constants === */

/* === Macros === */

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

/* === Structs === */

struct ControlContext {
    operations: Manager,
    scope: crate::plugin::PluginScope,
    binding: OnceLock<crate::operations::PluginControl>,
}

pub(super) struct Remote {
    pub(super) provider: Option<Arc<crate::supervision::instance::Instance>>,
    arrivals: mpsc::Sender<Arrival>,
    control: OnceLock<ControlContext>,
    fenced: watch::Sender<bool>,
    retirement: OnceLock<Weak<Retirement>>,
    outcome: Arc<Mutex<Option<Arc<crate::Error>>>>,
}

struct Backend {
    definition: ObserverDefinition,
}

struct RetainedControl(Arc<crate::supervision::instance::Instance>);

pub(super) struct Session {
    closing: Option<Closing>,
    outcome: Option<Arc<crate::Error>>,
}

struct Retirement {
    operations: Manager,
    remote: Arc<Remote>,
}

struct Closing {
    remote: Arc<Remote>,
    operations: Manager,
    scope: Option<Arc<Retirement>>,
    end: Option<harmos_sidecar::attach::Ending>,
    ending_failure: Option<String>,
}

/* === Enums === */

/* === Traits === */

/* === Implementations === */

impl Remote {
    pub(super) fn new(arrivals: mpsc::Sender<Arrival>, provider: Option<Arc<crate::supervision::instance::Instance>>) -> Arc<Self> {
        Arc::new(Self {
            provider,
            arrivals,
            control: OnceLock::new(),
            fenced: watch::channel(false).0,
            retirement: OnceLock::new(),
            outcome: Arc::new(Mutex::new(None)),
        })
    }

    pub(super) fn outcome(&self) -> Arc<Mutex<Option<Arc<crate::Error>>>> {
        Arc::clone(&self.outcome)
    }

    pub(super) async fn settle(&self) -> crate::Result<()> {
        let Some(original) = self.retirement.get().and_then(Weak::upgrade) else {
            return Ok(());
        };
        let retired = original.operations.retire_scope_of(&original.remote).await?;
        *self.outcome.lock().expect("observer outcome is healthy") = retired.and_then(|retired| retired.into_outcome().err());
        Ok(())
    }

    pub(super) fn configure(&self, operations: Manager, scope: crate::plugin::PluginScope) -> crate::Result<()> {
        self.control
            .set(ControlContext {
                operations,
                scope,
                binding: OnceLock::new(),
            })
            .map_err(|_| crate::Error::InvalidInput {
                field: "observer control",
                reason: "original transport was already configured",
            })
    }

    pub(super) fn capture_control(&self) -> crate::Result<()> {
        let original = self.control.get().ok_or(crate::Error::NotReady { domain: "observer control" })?;
        let Some(contract) = original.scope.observe_contract() else {
            return Ok(());
        };
        if original.binding.get().is_some() {
            return Ok(());
        }
        let binding = original.operations.capture_host_control(&original.scope, contract)?;
        let _ = original.binding.set(binding);
        Ok(())
    }

    // Submit the observe control for one activation, owned by its children.
    fn observe(
        &self, children: &ChildSettlement, control: &harmos_domain::observers::ControlRequest,
    ) -> crate::Result<crate::operations::EncodedInvocation> {
        let original = self.control.get().ok_or(crate::Error::NotReady { domain: "observer control" })?;
        original.scope.observe_contract().ok_or(crate::Error::NotReady { domain: "observer control" })?;
        self.capture_control()?;
        let binding = original.binding.get().expect("original captured observe control");
        let bytes = control
            .observer
            .len()
            .checked_mul(2)
            .and_then(|bytes| bytes.checked_add(64))
            .and_then(std::num::NonZeroUsize::new)
            .ok_or(crate::Error::ResourceExhausted { resource: "observer control encoding" })?;
        children.submit(false, || binding.submit_with(bytes, |_| Ok(harmos_domain::Message::encode(control))))
    }

    async fn fence(&self) {
        let _ = self.fenced.subscribe().wait_for(|fenced| *fenced).await;
    }

    async fn failed(&self, error: crate::Error) -> crate::Error {
        let _ = self.arrivals.send(Arrival::ObserverFailed(error.to_string())).await;
        self.fence().await;
        error
    }
}

impl crate::supervision::cleanup::Resource for RetainedControl {
    fn finalize(&mut self) -> crate::supervision::cleanup::Finalize<'_> {
        Box::pin(async move { self.0.settle().await.map_err(|source| Arc::new(crate::Error::OperationSettlement { source })) })
    }
}

impl ObserverBackend for Backend {
    type Resources = Remote;

    fn definition(&self) -> crate::Result<ObserverDefinition> {
        Ok(self.definition.clone())
    }

    async fn run(&self, remote: Arc<Remote>, mut activation: ObserverActivation) -> crate::Result<()> {
        if let Some(provider) = &remote.provider {
            activation.depend_on(provider)?;
        }
        let control = harmos_domain::observers::ControlRequest {
            observer: self.definition.id.clone(),
            generation: activation.id().value(),
        };
        let children = activation.child_settlement();
        let mut invocation = match remote.observe(&children, &control) {
            Ok(invocation) => invocation,
            Err(error) => return Err(remote.failed(error).await),
        };

        // Follow The Remote Observer Until Stopped Or Ended
        let control = Arc::clone(&invocation.control);
        let mut status = control.settlement();
        let ended = loop {
            if status.borrow_and_update().phase() == OperationPhase::Running {
                activation.ready();
            }
            tokio::select! {
                () = activation.stopping() => break None,
                () = remote.fence() => return Err(failure(SidecarError::Unavailable)),
                result = &mut invocation => break Some(result),
                changed = status.changed() => {
                    if changed.is_err() {
                        break Some((&mut invocation).await);
                    }
                }
            }
        };

        // Cancel The Invocation; The Sidecar Stops And Cleans Up The Observer
        activation.begin_stopping();
        let stopped = ended.is_none();
        let result = match ended {
            Some(result) => result,
            None => {
                invocation.cancel();
                tokio::select! {
                    result = &mut invocation => result,
                    () = remote.fence() => return Err(failure(SidecarError::Unavailable)),
                }
            }
        };
        activation.cleaning_up();

        // A Failed Remote Cleanup Stays Retained For A Later Stop To Retry
        if let Some(failure) = control.status().cleanup_failure().cloned() {
            children.forget(&control);
            activation.retain(RetainedControl(control), Arc::clone(&failure));
            return Err(crate::Error::TaskFailed {
                domain: "remote observer cleanup",
                source: failure,
            });
        }
        match result {
            Ok(_) => Ok(()),
            Err(_) if stopped => Ok(()),
            // Cancelled from outside, as runtime admission closes.
            Err(crate::Error::OperationRefused(crate::Refusal::Cancelled)) => Ok(()),
            Err(error) => Err(error),
        }
    }
}

impl Session {
    pub(super) fn new(remote: Arc<Remote>, operations: Manager, end: Option<harmos_sidecar::attach::Ending>) -> Self {
        Self {
            closing: Some(Closing {
                remote,
                operations,
                scope: None,
                end,
                ending_failure: None,
            }),
            outcome: None,
        }
    }

    // Bind retirement of this connection's observers to the session.
    pub(super) fn bind(&mut self) -> Result<(), String> {
        let closing = self.closing.as_mut().ok_or("native session already ended")?;
        if closing.scope.is_some() {
            return Err("native observer scope already bound".to_owned());
        }
        let original = Arc::new(Retirement {
            operations: closing.operations.clone(),
            remote: Arc::clone(&closing.remote),
        });
        closing.remote.retirement.set(Arc::downgrade(&original)).map_err(|_| "native observer retirement already bound".to_owned())?;
        closing.scope = Some(original);
        Ok(())
    }

    pub(super) async fn end(&mut self) -> Result<(), String> {
        if let Some(closing) = self.closing.as_mut() {
            closing.end().await?;
        }
        Ok(())
    }

    pub(super) async fn finish(&mut self) -> Result<(), String> {
        if let Some(closing) = self.closing.as_mut() {
            self.outcome = closing.finish().await?;
            self.closing.take();
        }
        Ok(())
    }

    pub(super) fn outcome(&self) -> Option<&Arc<crate::Error>> {
        self.outcome.as_ref()
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        if let Some(mut closing) = self.closing.take() {
            crate::supervision::executor::task(async move {
                let _ = closing.finish().await;
            });
        }
    }
}

impl Closing {
    async fn end(&mut self) -> Result<(), String> {
        if let Some(failure) = &self.ending_failure {
            return Err(failure.clone());
        }
        if let Some(end) = self.end.as_mut() {
            let mut ending = Box::pin(end.settle());
            let result = std::future::poll_fn(|context| {
                match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ending.as_mut().poll(context))) {
                    Ok(poll) => poll.map(Ok),
                    Err(_) => std::task::Poll::Ready(Err("native ending settlement panicked".to_owned())),
                }
            })
            .await;
            drop(ending);
            match result {
                Ok(Ok(())) => {}
                Ok(Err(error)) => return Err(error.to_string()),
                Err(failure) => {
                    self.ending_failure = Some(failure.clone());
                    return Err(failure);
                }
            }
            self.end.take();
        }
        self.remote.fenced.send_replace(true);
        Ok(())
    }

    async fn finish(&mut self) -> Result<Option<Arc<crate::Error>>, String> {
        self.end().await?;
        if let Some(scope) = &self.scope {
            let retirement = scope.operations.retire_scope_of(&scope.remote).await;
            match retirement {
                Ok(retirement) => {
                    let outcome = retirement.and_then(|retirement| retirement.into_outcome().err());
                    *self.remote.outcome.lock().expect("observer outcome is healthy") = outcome.clone();
                    return Ok(outcome);
                }
                Err(error) => {
                    return Err(error.to_string());
                }
            }
        }
        Ok(None)
    }
}

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

pub(super) fn stage(
    operations: &Manager, remote: &Arc<Remote>, plugin: Option<&crate::plugin::PluginScope>, definitions: &[Declaration],
    publications: &[harmos_sidecar::StreamDeclaration],
) -> crate::Result<ObserverRegistration> {
    let backends = definitions.iter().map(|entry| Backend {
        definition: ObserverDefinition {
            id: entry.id.clone(),
            interval: entry.interval,
            demand_keys: entry.demand_keys.clone(),
            streams: publications.iter().filter(|row| entry.streams.contains(&row.id)).cloned().collect(),
        },
    });
    match plugin {
        Some(plugin) => operations.stage_plugin_observers(remote, plugin, backends),
        None => operations.stage_observers(remote, backends),
    }
}

// Hold one activation lease per observer whose plugin or demand wants it.
pub(super) async fn demand(
    operations: Manager, remote: Arc<Remote>, plugin: Option<crate::plugin::PluginScope>, definitions: Vec<Declaration>,
    mut changes: watch::Receiver<BTreeMap<String, bool>>, arrivals: mpsc::Sender<Arrival>,
) {
    if let Some(plugin) = plugin
        && plugin.ready().await.is_err()
    {
        return;
    }

    let mut leases = BTreeMap::new();
    loop {
        let wanted = changes.borrow_and_update().clone();
        for definition in &definitions {
            let active = definition.activation == Activation::Plugin
                || definition.streams.iter().chain(&definition.demand_keys).any(|key| wanted.get(key).copied().unwrap_or(false));
            if !active {
                leases.remove(&definition.id);
            } else if !leases.contains_key(&definition.id) {
                match operations.submit_with_resources_at(&definition.id, Arc::clone(&remote)).await {
                    Ok(lease) => {
                        leases.insert(definition.id.clone(), lease);
                    }
                    Err(crate::Error::Closing { .. }) => return,
                    Err(error) => {
                        let _ = arrivals.send(Arrival::ObserverFailed(error.to_string())).await;
                        return;
                    }
                }
            }
        }
        if changes.changed().await.is_err() {
            break;
        }
    }
}

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

fn failure(error: impl std::error::Error + Send + Sync + 'static) -> crate::Error {
    crate::Error::TaskFailed {
        domain: "remote observer",
        source: Arc::new(error),
    }
}

/* === Tests === */