starlane 0.3.21

Starlane -- An Orchestration and Infrastructure Framework for WebAssembly Components (https://starlane.io) This packaged manages `HyperSpace` which provides infrastructure for `Space` Apis (WebAssembly & external programs meant to provide custom behaviors in Starlane), This package references the `starlane-space` package and reuses of it to run the infrastructure and it also contains mechanisms (Drivers) for extending the Starlane Type system
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
pub mod asynch;
pub mod synch;

use std::borrow::Cow;
use std::ops::Deref;

use crate::space::config::bind::RouteSelector;
use crate::space::loc::{ToPoint, ToSurface, Topic};
use crate::space::log::Logger;
use crate::space::wave::core::Method;
use crate::space::wave::{
    Bounce, DirectedProto, DirectedWave, EchoCore, FromReflectedAggregate, Handling, PongCore,
    Recipients, ReflectedProto, ReflectedWave, Scope, Session, ToRecipients, Wave, WaveVariantDef,
};
use crate::space::{Agent, ReflectedCore, SpaceErr, Substance, Surface, ToSubstance};
use asynch::{DirectedHandler, Router};
use starlane_primitive_macros::{log_span, push_loc};
use tokio::sync::broadcast;

#[derive(Clone)]
pub struct DirectedHandlerShellDef<D, T> {
    logger: Logger,
    handler: D,
    surface: Surface,
    builder: T,
}

impl<D, T> DirectedHandlerShellDef<D, T>
where
    D: Sized,
{
    pub fn new(handler: D, builder: T, surface: Surface, logger: Logger) -> Self {
        Self {
            handler,
            builder,
            logger: push_loc!((logger, &surface)),
            surface,
        }
    }
}

pub struct InternalPipeline<H> {
    pub selector: RouteSelector,
    pub handler: H,
}

impl<H> InternalPipeline<H> {
    pub fn new(selector: RouteSelector, mut handler: H) -> Self {
        Self { selector, handler }
    }
}

pub struct RootInCtxDef<T> {
    pub to: Surface,
    pub wave: DirectedWave,
    pub session: Option<Session>,
    pub logger: Logger,
    pub transmitter: T,
}

impl<T> RootInCtxDef<T> {
    pub fn new(wave: DirectedWave, to: Surface, logger: Logger, transmitter: T) -> Self {
        Self {
            wave,
            to,
            logger,
            session: None,
            transmitter,
        }
    }

    pub fn status(self, status: u16, from: Surface) -> Bounce<ReflectedWave> {
        match self.wave {
            DirectedWave::Ping(ping) => {
                Bounce::Reflected(ReflectedWave::Pong(WaveVariantDef::new(
                    PongCore::new(
                        ReflectedCore::status(status),
                        ping.from.clone(),
                        self.to.clone().to_recipients(),
                        ping.id.clone(),
                    ),
                    from,
                )))
            }
            DirectedWave::Ripple(ripple) => {
                Bounce::Reflected(ReflectedWave::Echo(WaveVariantDef::new(
                    EchoCore::new(
                        ReflectedCore::status(status),
                        ripple.from.clone(),
                        ripple.to.clone(),
                        ripple.id.clone(),
                    ),
                    from,
                )))
            }
            DirectedWave::Signal(_) => Bounce::Absorbed,
        }
    }

    pub fn err(self, status: u16, from: Surface, msg: String) -> Bounce<ReflectedWave> {
        match self.wave {
            DirectedWave::Ping(ping) => {
                Bounce::Reflected(ReflectedWave::Pong(WaveVariantDef::new(
                    PongCore::new(
                        ReflectedCore::fail(status, msg),
                        ping.from.clone(),
                        self.to.clone().to_recipients(),
                        ping.id.clone(),
                    ),
                    from,
                )))
            }
            DirectedWave::Ripple(ripple) => {
                Bounce::Reflected(ReflectedWave::Echo(WaveVariantDef::new(
                    EchoCore::new(
                        ReflectedCore::fail(status, msg),
                        ripple.from.clone(),
                        ripple.to.clone(),
                        ripple.id.clone(),
                    ),
                    from,
                )))
            }
            DirectedWave::Signal(_) => Bounce::Absorbed,
        }
    }

    pub fn not_found(self) -> Bounce<ReflectedWave> {
        let to = self.to.clone();
        let msg = format!(
            "<{}>{}",
            self.wave.core().method.to_string(),
            self.wave.core().uri.path().to_string()
        );
        self.err(404, to, msg)
    }

    pub fn timeout(self) -> Bounce<ReflectedWave> {
        let to = self.to.clone();
        self.status(408, to)
    }

    pub fn bad_request(self) -> Bounce<ReflectedWave> {
        let to = self.to.clone();
        let msg = format!(
            "<{}>{} -[ {} ]->",
            self.wave.core().method.to_string(),
            self.wave.core().uri.path().to_string(),
            self.wave.core().body.kind().to_string()
        );
        self.err(400, to, msg)
    }

    pub fn server_error(self) -> Bounce<ReflectedWave> {
        let to = self.to.clone();
        self.status(500, to)
    }

    pub fn forbidden(self) -> Bounce<ReflectedWave> {
        let to = self.to.clone();
        let msg = format!(
            "<{}>{} -[ {} ]->",
            self.wave.core().method.to_string(),
            self.wave.core().uri.path().to_string(),
            self.wave.core().body.kind().to_string()
        );
        self.err(401, to, msg)
    }

    pub fn unavailable(self) -> Bounce<ReflectedWave> {
        let to = self.to.clone();
        self.status(503, to)
    }

    pub fn unauthorized(self) -> Bounce<ReflectedWave> {
        let to = self.to.clone();
        self.status(403, to)
    }
}

pub struct InCtxDef<'a, I, T>
where
    T: Clone,
{
    root: &'a RootInCtxDef<T>,
    pub transmitter: Cow<'a, T>,
    pub input: &'a I,
    pub logger: Logger,
}

impl<'a, I, T> Deref for InCtxDef<'a, I, T>
where
    T: Clone,
{
    type Target = I;

    fn deref(&self) -> &Self::Target {
        self.input
    }
}

impl<'a, I, T> InCtxDef<'a, I, T>
where
    T: Clone,
{
    pub fn new(root: &'a RootInCtxDef<T>, input: &'a I, tx: Cow<'a, T>, logger: Logger) -> Self {
        Self {
            root,
            input,
            logger,
            transmitter: tx,
        }
    }

    pub fn from(&self) -> &Surface {
        self.root.wave.from()
    }

    pub fn to(&self) -> &Surface {
        &self.root.to
    }

    pub fn push(self) -> InCtxDef<'a, I, T> {
        InCtxDef {
            root: self.root,
            input: self.input,
            logger: log_span!(self.logger),
            transmitter: self.transmitter.clone(),
        }
    }

    pub fn push_input_ref<I2>(self, input: &'a I2) -> InCtxDef<'a, I2, T> {
        InCtxDef {
            root: self.root,
            input,
            logger: self.logger.clone(),
            transmitter: self.transmitter.clone(),
        }
    }

    pub fn wave(&self) -> &DirectedWave {
        &self.root.wave
    }

    /*
    pub async fn ping(&self, req: DirectedProto) -> Result<Wave<Pong>, UniErr> {
        self.transmitter.direct(req).await
    }

     */

    pub fn ok_body(self, substance: Substance) -> ReflectedCore {
        self.root.wave.core().ok_body(substance)
    }

    pub fn not_found(self) -> ReflectedCore {
        self.root.wave.core().not_found()
    }

    pub fn forbidden(self) -> ReflectedCore {
        self.root.wave.core().forbidden()
    }

    pub fn bad_request(self) -> ReflectedCore {
        self.root.wave.core().bad_request()
    }

    pub fn err(self, err: SpaceErr) -> ReflectedCore {
        self.root.wave.core().err(err)
    }
}

#[derive(Clone)]
pub struct BroadTxRouter {
    pub tx: broadcast::Sender<Wave>,
}

impl BroadTxRouter {
    pub fn new(tx: broadcast::Sender<Wave>) -> Self {
        Self { tx }
    }
}

#[derive(Clone)]
pub struct ProtoTransmitterBuilderDef<R, E> {
    pub agent: SetStrategy<Agent>,
    pub scope: SetStrategy<Scope>,
    pub handling: SetStrategy<Handling>,
    pub method: SetStrategy<Method>,
    pub via: SetStrategy<Surface>,
    pub from: SetStrategy<Surface>,
    pub to: SetStrategy<Recipients>,
    pub router: R,
    pub exchanger: E,
}

impl<R, E> ProtoTransmitterBuilderDef<R, E> {
    pub fn build(self) -> ProtoTransmitterDef<R, E> {
        ProtoTransmitterDef {
            agent: self.agent,
            scope: self.scope,
            handling: self.handling,
            method: self.method,
            from: self.from,
            to: self.to,
            via: self.via,
            router: self.router,
            exchanger: self.exchanger,
        }
    }
}

#[derive(Clone)]
pub struct ProtoTransmitterDef<R, E> {
    agent: SetStrategy<Agent>,
    scope: SetStrategy<Scope>,
    handling: SetStrategy<Handling>,
    method: SetStrategy<Method>,
    from: SetStrategy<Surface>,
    to: SetStrategy<Recipients>,
    via: SetStrategy<Surface>,
    router: R,
    exchanger: E,
}

impl<R, E> ProtoTransmitterDef<R, E> {
    pub fn from_topic(&mut self, topic: Topic) -> Result<(), SpaceErr> {
        self.from = match self.from.clone() {
            SetStrategy::None => {
                return Err(SpaceErr::server_error(
                    "cannot set Topic without first setting Surface",
                ));
            }
            SetStrategy::Fill(from) => SetStrategy::Fill(from.with_topic(topic)),
            SetStrategy::Override(from) => SetStrategy::Override(from.with_topic(topic)),
        };
        Ok(())
    }

    fn prep_direct(&self, wave: &mut DirectedProto) {
        match &self.from {
            SetStrategy::None => {}
            SetStrategy::Fill(from) => wave.fill_from(from.clone()),
            SetStrategy::Override(from) => wave.from(from.clone()),
        }

        match &self.to {
            SetStrategy::None => {}
            SetStrategy::Fill(to) => wave.fill_to(to.clone()),
            SetStrategy::Override(to) => wave.to(to),
        }

        match &self.via {
            SetStrategy::None => {}
            SetStrategy::Fill(via) => wave.fill_via(via.clone()),
            SetStrategy::Override(via) => wave.via(via),
        }

        match &self.agent {
            SetStrategy::None => {}
            SetStrategy::Fill(agent) => wave.fill_agent(agent),
            SetStrategy::Override(agent) => wave.agent(agent.clone()),
        }

        match &self.scope {
            SetStrategy::None => {}
            SetStrategy::Fill(scope) => wave.fill_scope(scope),
            SetStrategy::Override(scope) => wave.scope(scope.clone()),
        }

        match &self.handling {
            SetStrategy::None => {}
            SetStrategy::Fill(handling) => wave.fill_handling(handling),
            SetStrategy::Override(handling) => wave.handling(handling.clone()),
        }

        match &self.method {
            SetStrategy::None => {}
            SetStrategy::Fill(method) => wave.fill_method(method),
            SetStrategy::Override(handling) => wave.method(handling.clone()),
        }
    }

    fn prep_reflect(&self, wave: &mut ReflectedProto) {
        match &self.from {
            SetStrategy::None => {}
            SetStrategy::Fill(from) => wave.fill_from(from),
            SetStrategy::Override(from) => wave.from(from.clone()),
        }

        match &self.agent {
            SetStrategy::None => {}
            SetStrategy::Fill(agent) => wave.fill_agent(agent),
            SetStrategy::Override(agent) => wave.agent(agent.clone()),
        }

        match &self.scope {
            SetStrategy::None => {}
            SetStrategy::Fill(scope) => wave.fill_scope(scope),
            SetStrategy::Override(scope) => wave.scope(scope.clone()),
        }

        match &self.handling {
            SetStrategy::None => {}
            SetStrategy::Fill(handling) => wave.fill_handling(handling),
            SetStrategy::Override(handling) => wave.handling(handling.clone()),
        }
    }
}

#[derive(Clone, strum_macros::Display)]
pub enum SetStrategy<T> {
    /// The ProtoTransmitter will NOT set a value
    None,
    /// The ProtoTransmitter will set the DirectedProto value unless
    /// the value was already explicitly set
    Fill(T),
    /// The ProtoTransmitter will override the DirectedProto value
    /// even if it has already been explicitly set
    Override(T),
}

impl<T> SetStrategy<T> {
    pub fn unwrap(self) -> Result<T, SpaceErr> {
        match self {
            SetStrategy::None => Err("cannot unwrap a SetStrategy::None".into()),
            SetStrategy::Fill(t) => Ok(t),
            SetStrategy::Override(t) => Ok(t),
        }
    }
}

impl SetStrategy<Surface> {
    pub fn with_topic(self, topic: Topic) -> Result<Self, SpaceErr> {
        match self {
            SetStrategy::None => Err("cannot set topic if Strategy is None".into()),
            SetStrategy::Fill(surface) => Ok(SetStrategy::Fill(surface.with_topic(topic))),
            SetStrategy::Override(surface) => Ok(SetStrategy::Override(surface.with_topic(topic))),
        }
    }
}