starlane 0.3.18

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
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
use std::env;
use std::fmt::{Display, Formatter};
use crate::executor::{ExeConf, Executor};
use itertools::Itertools;
use nom::AsBytes;
use starlane::space::loc::ToBaseKind;
use starlane::space::util::{IdSelector, MatchSelector, OptSelector, RegexMatcher, ValueMatcher};
use starlane::space::wave::exchange::asynch::{
    DirectedHandler, Router,
};
use starlane_space as starlane;
use std::future::Future;
use std::hash::Hash;
use std::io::Read;
use std::ops::{Deref, DerefMut};
use std::path::{absolute, PathBuf};
use std::str::FromStr;
use strum_macros::EnumString;
use thiserror::Error;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use starlane::space::err::SpaceErr;
use starlane::space::kind::Kind;
use starlane::space::particle::Status;
use starlane::space::point::Point;
use starlane::space::selector::KindSelector;
use crate::env::STARLANE_DATA_DIR;
use crate::executor::cli::HostEnv;
use crate::executor::cli::os::CliOsExecutor;
use crate::executor::dialect::filestore::{FileStore, FileStoreErr, FILE_STORE_ROOT};
use crate::host::{ExeStub, Host, HostCli};
use crate::host::err::HostErr;
use crate::hyperspace::machine::MachineErr;

pub type FileStoreService = Service<FileStore>;

impl FileStoreService {
    pub async fn sub_root( &self, sub_root: PathBuf) -> Result<FileStoreService, ServiceErr> {
        let runner = self.runner.sub_root(sub_root).await?;
        Ok(FileStoreService {
            template: self.template.clone(),
            runner
        })
    }
}


pub struct ServiceCall<I,O> {
    pub input: I,
    pub output: oneshot::Sender<Result<O, ServiceErr>>,
}

#[derive(Clone)]
pub struct ServiceStub<I,O> {
    tx: tokio::sync::mpsc::Sender<ServiceCall<I,O>>,
    status: tokio::sync::watch::Receiver<Status>,
}

pub struct Service<R> {
    pub template: ServiceTemplate,
    runner: R
}

impl Service<ServiceRunner>  {
    pub fn new( template: ServiceTemplate )  -> Service<ServiceRunner>{
        let runner = template.config.clone();
        Self {
            template,
            runner
        }
    }

    pub fn filestore(  self  ) -> Result<FileStoreService, ServiceErr> {
       Ok(FileStoreService{
           template: self.template,
           runner: self.runner.filestore()?
       })
    }
}



impl <R> Deref for Service<R> {
    type Target = R;

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


#[derive(Clone)]
pub enum ServiceRunner {
    Exe(ExeConf)
}



impl ServiceRunner {
    pub fn filestore( & self  ) -> Result<FileStore, ServiceErr> {
        match self {
            ServiceRunner::Exe(exe) => {
                Ok(exe.create()?)
            }
        }
    }
}

#[derive(Hash,Clone,Eq,PartialEq,Debug,EnumString,strum_macros::Display)]
pub enum ServiceKind {
    FileStore
}

impl Into<Service<ServiceRunner>> for ServiceTemplate {
    fn into(self) -> Service<ServiceRunner> {
        let runner = self.config.clone();
        Service {
            template: self,
            runner
        }
    }
}


impl TryInto<Service<FileStore>> for Service<ServiceRunner>{
    type Error = ServiceErr;

    fn try_into(self) -> Result<Service<FileStore>, Self::Error> {
        let filestore = self.runner.filestore()?;
        Ok(Service{
            template: self.template,
            runner: filestore,
        })
    }
}

#[derive(Clone,Debug)]
pub struct ServiceSelector {
    pub name: IdSelector<String>,
    pub kind: ServiceKind,
    pub driver: Option<Kind>
}

impl Display for ServiceSelector {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match &self.driver {
            None => {
                write!(f, "{}<*:{}>",self.name.to_string(),self.kind.to_string())
            }
            Some(kind) => {
                write!(f, "{}<{}:{}>",self.name.to_string(),kind.to_string(),self.kind.to_string())
            }
        }
    }
}


#[derive(Clone,Eq,PartialEq,Debug,Hash)]
pub enum ServiceScopeKind {
    Global,
    Point
}


#[derive(Clone,Eq,PartialEq,Debug,Hash)]
pub enum ServiceScope {
    Global,
    Point(Point)
}

#[derive(Clone)]
pub struct ServiceTemplate {
    pub name: String,
    pub kind: ServiceKind,
    // matches drivers that are allowed to use this Service
    pub driver: OptSelector<KindSelector>,
    pub config: ServiceConf
}

impl PartialEq<ServiceTemplate> for ServiceSelector{
    fn eq(&self, other: &ServiceTemplate) -> bool {
        self.name == other.name &&
            self.kind == other.kind &&
            other.driver == self.driver
    }
}


// at this time, Conf and Runner do not differ
pub type ServiceConf = ServiceRunner;


/*

#[derive(Clone)]
pub struct ServiceStub<C> {
    pub template: ServiceTemplate,
    pub call_tx: tokio::sync::mpsc::Sender<C>,
    pub status_rx: watch::Receiver<Status>,
}

pub struct ServiceRunner<Core,Call> where Core: ServiceCore<Call>
{
    ctx: ServiceCtx,
    call_rx: tokio::sync::mpsc::Receiver<Call>,
    status_tx: tokio::sync::mpsc::Sender<Status>,
    core: Core,
}

impl<Core,Call> ServiceRunner<Core,Call>
where Core: ServiceCore<Call>
{
    fn new(ctx: ServiceCtx, core: Core) -> ServiceStub<Call> {
        let (call_tx, call_rx) = tokio::sync::mpsc::channel(1024);
        let (status_tx, status_rx) = state_relay(Status::Pending);
        let template = ctx.template.clone();
        let rtn = ServiceStub {
            call_tx,
            status_rx,
            template,
        };

        let runner = Self {
            ctx,
            call_rx,
            status_tx,
            core,
        };

        tokio::spawn(async move { runner.launch().await });

        rtn
    }

    async fn launch(mut self) {
        let status_tx = self.status_tx.clone();
        let logger = self.core.ctx.logger.clone();
        match logger.result(self.run().await) {
            Ok(status) => {
                status_tx.send(status);
            }
            Err(_) => {
                status_tx.send(Status::Panic);
            }
        }
    }

    async fn run(mut self) -> Result<Status, StarErr> {
        self.status_tx.send(Status::Ready);

        while let Some(call) = self.call_rx.recv().await {
            self.core.handle(wave).await;
        }

        Ok(Status::Done)
    }
}

pub trait ServiceCore<C>
{
    fn call(&self, ctx: &ServiceCtx, call: C );
}




 */

pub fn service_conf() -> ServiceConf{

    let mut builder = HostEnv::builder();
    builder.pwd(
        absolute(env::current_dir().unwrap())
            .unwrap()
            .to_str()
            .unwrap()
            .to_string(),
    );
    println!("{}", env::current_dir().unwrap().to_str().unwrap());
    builder.env(
        FILE_STORE_ROOT,
        STARLANE_DATA_DIR.to_string(),
    );
    let env = builder.build();
    let path = "../target/debug/starlane-cli-filestore-service".to_string();
    let args: Option<Vec<String>> = Option::None;

    let stub = ExeStub::new(path.into(), env);

    ServiceConf::Exe(ExeConf::Host(Host::Cli(HostCli::Os(stub))))

}

#[cfg(test)]
pub mod tests {
    use crate::host::{ExeStub, Host};

    use crate::executor::cli::HostEnv;
    use crate::executor::dialect::filestore::{FileStore, FileStoreIn, FileStoreOut};
    use crate::host::HostCli;
    use crate::executor::{ExeConf, Executor};
    use std::path::{absolute, PathBuf};
    use std::{env, io};
    use tokio::fs;
    use starlane::space::kind::{BaseKind, Kind};
    use starlane::space::selector::KindSelector;
    use starlane::space::util::OptSelector;
    use crate::service::{service_conf, Service, ServiceConf, ServiceErr, ServiceKind, ServiceTemplate};

    fn filestore() -> FileStore {
        if std::fs::exists("./tmp").unwrap() {
            std::fs::remove_dir_all("./tmp").unwrap();
        }
        let mut builder = HostEnv::builder();
        builder.pwd(
            absolute(env::current_dir().unwrap())
                .unwrap()
                .to_str()
                .unwrap()
                .to_string(),
        );
        println!("{}", env::current_dir().unwrap().to_str().unwrap());
        builder.env(
            "FILE_STORE_ROOT",
            format!("{}/tmp", env::current_dir().unwrap().to_str().unwrap()),
        );
        let env = builder.build();
        let path = "../target/debug/starlane-cli-filestore-service".to_string();
        let args: Option<Vec<String>> = Option::None;
        let stub = ExeStub::new(path.into(), env);
        //        let info = ExeInfo::new(HostDialect::Cli(HostRunner::Os), stub);

        let info = ExeConf::Host(Host::Cli(HostCli::Os(stub.clone())));

         info.create().unwrap()

    }

    pub async fn filestore_from_service()  -> Result<Service<FileStore>, ServiceErr> {

        let config = service_conf();

       let template = ServiceTemplate {
           name: "some-filestore".to_string(),
           kind: ServiceKind::FileStore,
           driver: OptSelector::Selector(KindSelector::from_base(BaseKind::Repo)),
           config
       };

       let service = Service::new(template);

       Ok(service.try_into()?)

    }


    /*
    #[tokio::test]
    pub async fn test_dialect_old() {
        let logger = RootLogger::default();
        let host = filestore();
        let filestore = Dialect::FileStore.handler(host).unwrap();
        let mut wave = DirectedProto::kind(&DirectedKind::Ping);
        wave.method(HypMethod::Assign);
        let fae = Point::from_str("fae").unwrap();
        let less = Point::from_str("less").unwrap();
        wave.to(fae.clone().to_surface());
        wave.from(less.clone().to_surface());

        let assign = Assign::new(
            AssignmentKind::Create,
            Details::new(
                Stub {
                    point: fae,
                    kind: Kind::File(FileSubKind::File),
                    status: Status::Unknown,
                },
                Default::default(),
            ),
            StateSrc::Substance(Box::new(Substance::Text("helllo everyone".to_string()))),
        );

        wave.body(Substance::Hyper(HyperSubstance::Assign(assign)));
        let wave = wave.build().unwrap();
        let to = Point::central().to_surface();
        let logger = logger.point(to.point.clone());
        let (tx, rx) = tokio::sync::mpsc::channel(1024);
        let router = Arc::new(TxRouter::new(tx));

        let exchanger = Exchanger::new(to.clone(), Default::default(), logger.clone());
        let mut tx_builder = ProtoTransmitterBuilder::new(router, exchanger);

        let transmitter = tx_builder.build();

        let mut ctx = RootInCtx::new(wave, to, logger.span(), transmitter);

        filestore.handle(ctx).await;
    }

     */

    /*
    #[tokio::test]
    pub async fn test_cli_primitive() {
        if let Host::Cli(CliHost::Os(exe)) = filestore() {
            let args = FileStoreCli::new(FileStoreCommand::Init);
            let mut child = exe.execute(args).await.unwrap();
            //           let mut stdout = child.stdout.take().unwrap();
            drop(child.stdout.take().unwrap());

            let mut output = child.wait().await.unwrap();
/*
            tokio::io::copy(&mut output.stdout.as_bytes(), &mut tokio::io::stdout())
                .await
                .unwrap();
            tokio::io::copy(&mut output.stderr.as_bytes(), &mut tokio::io::stderr())
                .await
                .unwrap();

 */
        } else {
            assert!(false)
        }
    }

     */

    #[tokio::test]
    pub async fn test_filestore() {
        let executor= filestore_from_service().await.unwrap();


        if let io::Result::Ok(true) = fs::try_exists("./tmp").await {
            fs::remove_dir_all("./tmp").await.unwrap();
        }

        // init
        {
            let init = FileStoreIn::Init;
            executor
                .execute(init)
                .await.unwrap();
        }

        let path = PathBuf::from("tmp");
        assert!(path.exists());
        assert!(path.is_dir());

        {
            let args = FileStoreIn::Mkdir { path: "blah".into() };

            let mut child = executor
                .execute(args)
                .await
                .unwrap();
        }

        let path = PathBuf::from("tmp/blah");
        assert!(path.exists());
        assert!(path.is_dir());

        let content = "HEllo from me";

        {
            let args = FileStoreIn::Write { path: "blah/somefile.txt".into(), state: content.clone().into() };
            let mut child = executor
                .execute(args)
                .await
                .unwrap();
        }

        let path = PathBuf::from("tmp/blah/somefile.txt");
        assert!(path.exists());
        assert!(path.is_file());

        {
            let args = FileStoreIn::Read { path: "blah/somefile.txt".into() };
            let mut child = executor
                .execute(args)
                .await
                .unwrap();
            if let FileStoreOut::Read(bin) = child {
                let read = String::from_utf8(bin).unwrap();
                println!("content: {}", read);
                assert_eq!(content, read);
            } else {
                assert!(false);
            }
        }
    }
}


#[derive(Debug,Error,Clone)]
pub enum ServiceErr {
    #[error(transparent)]
    MachineErr(#[from] MachineErr),
    #[error(transparent)]
    FileStoreErr(#[from] FileStoreErr),
    #[error(transparent)]
    SpaceErr(#[from] SpaceErr),
    #[error(transparent)]
    HostErr(#[from] HostErr),
    #[error("no template available that matches ServiceSelector: '{0}' (name<DriverKind:ServiceKind>)")]
    NoTemplate(ServiceSelector),
    #[error("call not processed")]
    CallRecvErr(#[from] tokio::sync::oneshot::error::RecvError),
}