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
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering::Relaxed;
use futures::channel::mpsc;
use futures::future::{BoxFuture, LocalBoxFuture};
use futures::{Future, FutureExt, SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
use crate::cli::CommandCli;
use crate::common::IntoVec;
use crate::env::{DefaultEnv, Env};
use crate::error::Error;
use crate::runtime_api::server::RuntimeEvent;
use crate::{KillProcess, ProcessStatus, RunProcess};
pub type ProcessId = u64;
pub type EmptyResponse<'a> = LocalBoxFuture<'a, Result<(), Error>>;
pub type OutputResponse<'a> = LocalBoxFuture<'a, Result<Option<serde_json::Value>, Error>>;
pub type ProcessIdResponse<'a> = LocalBoxFuture<'a, Result<ProcessId, Error>>;
pub trait Runtime: RuntimeDef + Default {
const MODE: RuntimeMode = RuntimeMode::Server;
fn deploy<'a>(&mut self, ctx: &mut Context<Self>) -> OutputResponse<'a>;
fn start<'a>(&mut self, ctx: &mut Context<Self>) -> OutputResponse<'a>;
fn stop<'a>(&mut self, ctx: &mut Context<Self>) -> EmptyResponse<'a>;
fn run_command<'a>(
&mut self,
command: RunProcess,
mode: RuntimeMode,
ctx: &mut Context<Self>,
) -> ProcessIdResponse<'a>;
fn kill_command<'a>(
&mut self,
_kill: KillProcess,
_ctx: &mut Context<Self>,
) -> EmptyResponse<'a> {
async move { Err(Error::from_string("Not supported")) }.boxed_local()
}
fn offer<'a>(&mut self, _ctx: &mut Context<Self>) -> OutputResponse<'a> {
async move {
Ok(Some(crate::serialize::json::json!({
"constraints": "",
"properties": {}
})))
}
.boxed_local()
}
fn test<'a>(&mut self, _ctx: &mut Context<Self>) -> EmptyResponse<'a> {
async move { Ok(()) }.boxed_local()
}
}
#[derive(Clone, Copy, Debug)]
pub enum RuntimeMode {
Server,
Command,
}
pub trait RuntimeDef {
const NAME: &'static str;
const VERSION: &'static str;
type Cli: CommandCli;
type Conf: Default + Serialize + for<'de> Deserialize<'de>;
}
pub struct Context<R: Runtime + ?Sized> {
pub cli: <R as RuntimeDef>::Cli,
pub conf: <R as RuntimeDef>::Conf,
pub conf_path: PathBuf,
pub emitter: Option<EventEmitter>,
pid_seq: AtomicU64,
}
impl<R: Runtime + ?Sized> Context<R> {
const CONF_EXTENSIONS: [&'static str; 4] = ["toml", "yaml", "yml", "json"];
pub fn try_new() -> anyhow::Result<Self> {
Self::try_with(DefaultEnv::default())
}
pub fn try_with<E: Env>(env: E) -> anyhow::Result<Self> {
let app = <R as RuntimeDef>::Cli::clap()
.name(R::NAME)
.version(R::VERSION);
let cli = <R as RuntimeDef>::Cli::from_clap(&app.get_matches_from(env.args()));
let conf_dir = env.data_directory(R::NAME)?;
let conf_path = Self::config_path(conf_dir)?;
let conf = if conf_path.exists() {
Self::read_config(&conf_path)?
} else {
let conf = Default::default();
Self::write_config(&conf, &conf_path)?;
conf
};
Ok(Self {
cli,
conf,
conf_path,
emitter: None,
pid_seq: Default::default(),
})
}
pub fn read_config<P: AsRef<Path>>(path: P) -> anyhow::Result<<R as RuntimeDef>::Conf> {
use anyhow::Context;
let path = path.as_ref();
let extension = file_extension(path)?;
let err = || format!("Unable to read the configuration file: {}", path.display());
let contents = std::fs::read_to_string(path).with_context(err)?;
let conf: <R as RuntimeDef>::Conf = match extension.as_str() {
"toml" => toml::de::from_str(&contents).with_context(err)?,
"yaml" | "yml" => serde_yaml::from_str(&contents).with_context(err)?,
"json" => serde_json::from_str(&contents).with_context(err)?,
_ => anyhow::bail!("Unsupported extension: {}", extension),
};
Ok(conf)
}
pub fn write_config<P: AsRef<Path>>(
conf: &<R as RuntimeDef>::Conf,
path: P,
) -> anyhow::Result<()> {
use anyhow::Context;
let path = path.as_ref();
let extension = file_extension(path)?;
let err = || format!("Unable to write configuration: {}", path.display());
let parent_dir = path.parent().ok_or_else(|| {
anyhow::anyhow!("Unable to resolve parent directory of {}", path.display())
})?;
if !parent_dir.exists() {
std::fs::create_dir_all(&parent_dir).with_context(err)?;
}
let contents = match extension.as_str() {
"toml" => toml::ser::to_string_pretty(conf).with_context(err)?,
"yaml" | "yml" => serde_yaml::to_string(conf).with_context(err)?,
"json" => serde_json::to_string_pretty(conf).with_context(err)?,
_ => anyhow::bail!("Unsupported extension: {}", extension),
};
std::fs::write(path, contents).with_context(err)?;
Ok(())
}
fn config_path<P: AsRef<Path>>(dir: P) -> anyhow::Result<PathBuf> {
let dir = dir.as_ref();
let candidates = Self::CONF_EXTENSIONS
.iter()
.map(|ext| dir.join(format!("{}.{}", R::NAME, ext)))
.collect::<Vec<_>>();
let conf_path = candidates
.iter()
.filter(|path| path.exists())
.next()
.unwrap_or_else(|| candidates.last().unwrap())
.clone();
Ok(conf_path)
}
pub(crate) fn next_pid(&self) -> ProcessId {
self.pid_seq.fetch_add(1, Relaxed)
}
pub(crate) fn set_emitter(&mut self, emitter: impl RuntimeEvent + Send + Sync + 'static) {
self.emitter.replace(EventEmitter::spawn(emitter));
}
}
impl<R: Runtime + ?Sized> Context<R> {
pub fn command<'a, H, Fh>(&mut self, handler: H) -> ProcessIdResponse<'a>
where
H: (FnOnce(RunCommandContext) -> Fh) + 'static,
Fh: Future<Output = Result<(), Error>> + 'a,
{
let pid = self.next_pid();
let emitter = self.emitter.clone();
run_command(pid, emitter, move |run_ctx| {
async move { Ok(handler(run_ctx).await?) }.boxed_local()
})
}
}
pub trait RunCommandExt<R: Runtime + ?Sized> {
type Item: 'static;
fn as_command<'a, H, Fh>(self, ctx: &mut Context<R>, handler: H) -> ProcessIdResponse<'a>
where
H: (FnOnce(Self::Item, RunCommandContext) -> Fh) + 'static,
Fh: Future<Output = Result<(), Error>> + 'static;
}
impl<R, F, Rt, Re> RunCommandExt<R> for F
where
R: Runtime + ?Sized,
F: Future<Output = Result<Rt, Re>> + 'static,
Rt: 'static,
Re: 'static,
Error: From<Re>,
{
type Item = Rt;
fn as_command<'a, H, Fh>(self, ctx: &mut Context<R>, handler: H) -> ProcessIdResponse<'a>
where
H: (FnOnce(Self::Item, RunCommandContext) -> Fh) + 'static,
Fh: Future<Output = Result<(), Error>> + 'static,
{
let pid = ctx.next_pid();
let emitter = ctx.emitter.clone();
async move {
let value = self.await?;
let fut = run_command(pid, emitter, move |run_ctx| async move {
Ok(handler(value, run_ctx).await?)
});
Ok(fut.await?)
}
.boxed_local()
}
}
fn run_command<'a, H, F>(
pid: ProcessId,
emitter: Option<EventEmitter>,
handler: H,
) -> ProcessIdResponse<'a>
where
H: (FnOnce(RunCommandContext) -> F) + 'static,
F: Future<Output = Result<(), Error>> + 'static,
{
let mut cmd_ctx = RunCommandContext { id: pid, emitter };
async move {
cmd_ctx.started().await;
let fut = handler(cmd_ctx.clone());
tokio::task::spawn_local(async move {
let return_code = fut.await.is_err() as i32;
cmd_ctx.stopped(return_code).await;
});
Ok(pid)
}
.boxed_local()
}
#[derive(Clone)]
pub struct RunCommandContext {
pub(crate) id: ProcessId,
pub(crate) emitter: Option<EventEmitter>,
}
impl RunCommandContext {
pub fn id(&self) -> &ProcessId {
&self.id
}
pub(crate) fn started(&mut self) -> BoxFuture<()> {
let id = self.id;
self.emitter
.as_mut()
.map(|e| e.command_started(id))
.unwrap_or_else(|| futures::future::ready(()).boxed())
}
pub(crate) fn stopped(&mut self, return_code: i32) -> BoxFuture<()> {
let id = self.id;
self.emitter
.as_mut()
.map(|e| e.command_stopped(id, return_code))
.unwrap_or_else(|| futures::future::ready(()).boxed())
}
pub fn stdout(&mut self, output: impl IntoVec<u8>) -> BoxFuture<()> {
let id = self.id;
let output = output.into_vec();
match self.emitter {
Some(ref mut e) => e.command_stdout(id, output),
None => Self::print_output(output),
}
}
pub fn stderr(&mut self, output: impl IntoVec<u8>) -> BoxFuture<()> {
let id = self.id;
let output = output.into_vec();
match self.emitter {
Some(ref mut e) => e.command_stderr(id, output),
None => Self::print_output(output),
}
}
fn print_output<'a>(output: impl IntoVec<u8>) -> BoxFuture<'a, ()> {
let mut stdout = std::io::stdout();
let _ = stdout.write_all(output.into_vec().as_slice());
let _ = stdout.flush();
futures::future::ready(()).boxed()
}
}
#[derive(Clone)]
pub struct EventEmitter {
tx: mpsc::Sender<ProcessStatus>,
}
impl EventEmitter {
pub fn spawn(emitter: impl RuntimeEvent + Send + Sync + 'static) -> Self {
let (tx, rx) = mpsc::channel(1);
tokio::task::spawn(rx.for_each(move |status| emitter.on_process_status(status)));
Self { tx }
}
}
impl EventEmitter {
pub fn command_started(&mut self, process_id: ProcessId) -> BoxFuture<()> {
self.emit(ProcessStatus {
pid: process_id,
running: true,
return_code: 0,
stdout: Default::default(),
stderr: Default::default(),
})
}
pub fn command_stopped(&mut self, process_id: ProcessId, return_code: i32) -> BoxFuture<()> {
self.emit(ProcessStatus {
pid: process_id,
running: false,
return_code,
stdout: Default::default(),
stderr: Default::default(),
})
}
pub fn command_stdout(
&mut self,
process_id: ProcessId,
stdout: impl IntoVec<u8>,
) -> BoxFuture<()> {
self.emit(ProcessStatus {
pid: process_id,
running: true,
return_code: 0,
stdout: stdout.into_vec(),
stderr: Default::default(),
})
}
pub fn command_stderr(
&mut self,
process_id: ProcessId,
stderr: impl IntoVec<u8>,
) -> BoxFuture<()> {
self.emit(ProcessStatus {
pid: process_id,
running: true,
return_code: 0,
stdout: Default::default(),
stderr: stderr.into_vec(),
})
}
pub fn emit(&mut self, status: ProcessStatus) -> BoxFuture<()> {
self.tx.send(status).then(|_| async {}).boxed()
}
}
fn file_extension<P: AsRef<Path>>(path: P) -> anyhow::Result<String> {
Ok(path
.as_ref()
.extension()
.ok_or_else(|| anyhow::anyhow!("Invalid config path"))?
.to_string_lossy()
.to_lowercase())
}