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
508
509
510
511
512
513
514
515
516
517
518
519
520
#![deny(missing_docs)]

//! `barley-runtime`
//! 
//! This crate contains the runtime for the `barley` workflow engine. It
//! provides the [`Action`] trait, which is the main interface for defining
//! actions that can be executed by the engine. It also provides the
//! [`Context`] struct, which is used to pass information between actions.
//! 
//! [`Action`]: trait.Action.html
//! [`Context`]: struct.Context.html

use anyhow::Result;
use tokio::sync::{RwLock, Barrier};
use std::collections::HashMap;
use uuid::Uuid;
use futures::future::join_all;
use std::sync::Arc;
use async_trait::async_trait;
use async_recursion::async_recursion;

/// The prelude for the `barley-runtime` crate.
/// 
/// This module contains all of the important types
/// and traits for the `barley-runtime` crate. It
/// should be used instead of importing the types
/// directly.
pub mod prelude;

/// A measurable, reversible task.
/// 
/// Any `Action` can test its environment to see if
/// it needs to run at all, and can undo any changes
/// it has made. Any `Action` can also depend on
/// other `Action`s, and the engine will ensure that
/// all dependencies are run before the `Action` itself.
#[async_trait]
pub trait Action: Send + Sync {
  /// Check if the action needs to be run.
  /// 
  /// This method is called before the action is run,
  /// and can be used to check if the action needs to
  /// run at all. If this method returns `false`, the
  /// action has not run yet, and the engine will
  /// proceed to run it. If this method returns `true`,
  /// the action has already run, and the engine will
  /// skip it.
  async fn check(&self, ctx: Arc<RwLock<Context>>) -> Result<bool>;

  /// Run the action.
  async fn perform(&self, ctx: Arc<RwLock<Context>>) -> Result<Option<ActionOutput>>;

  /// Undo the action.
  /// 
  /// This is not currently possible, and will not
  /// do anything. This will be usable in a future
  /// version of Barley.
  async fn rollback(&self, ctx: Arc<RwLock<Context>>) -> Result<()>;

  /// Get the display name of the action.
  fn display_name(&self) -> String;
}

/// A usable action object.
/// 
/// This struct is used by actions to store their
/// dependencies and identification. It should
/// not be constructed directly, unless you are
/// writing a custom Action.
#[derive(Clone)]
pub struct ActionObject {
  action: Arc<dyn Action>,
  deps: Vec<ActionObject>,
  id: Id
}

impl ActionObject {
  /// Create a new action object.
  /// 
  /// This method should not be called directly,
  /// unless you are writing a custom Action.
  pub fn new(action: Arc<dyn Action>) -> Self {
    Self {
      action,
      deps: Vec::new(),
      id: Id::default()
    }
  }

  /// Get the display name of the action.
  pub fn display_name(&self) -> String {
    self.action.display_name()
  }

  pub(crate) fn id(&self) -> Id {
    self.id
  }

  pub(crate) fn deps(&self) -> Vec<ActionObject> {
    self.deps.clone()
  }

  pub(crate) async fn check(&self, ctx: Arc<RwLock<Context>>) -> Result<bool> {
    self.action.check(ctx).await
  }

  #[async_recursion]
  pub(crate) async fn check_deps(&self, ctx: Arc<RwLock<Context>>) -> Result<bool> {
    if self.check(ctx.clone()).await? {
      return Ok(true)
    }

    let deps = self.deps.clone();

    for dep in deps.clone() {
      if !dep.check_deps(ctx.clone()).await? {
        return Ok(false)
      }
    }

    Ok(true)
  }

  pub(crate) async fn perform(&self, ctx: Arc<RwLock<Context>>) -> Result<Option<ActionOutput>> {
    if self.check(ctx.clone()).await? {
      return Ok(None)
    }

    self.action.perform(ctx).await
  }

  pub(crate) async fn rollback(&self, ctx: Arc<RwLock<Context>>) -> Result<()> {
    self.action.rollback(ctx).await
  }

  /// Add a dependency to the action.
  pub fn requires(&mut self, action: ActionObject) {
    self.deps.push(action);
  }
}

/// A context for running actions.
/// 
/// There should only be one of these per workflow
#[derive(Default)]
pub struct Context {
  actions: Vec<ActionObject>,
  variables: HashMap<String, String>,
  callbacks: ContextCallbacks,
  outputs: HashMap<Id, ActionOutput>,
  barriers: HashMap<Id, Arc<Barrier>>
}

/// The abstract interface for a context.
/// 
/// This should always be used in any program using
/// Barley, but it should never be implemented
/// directly. Use the `barley-interface` crate
/// instead.
#[async_trait]
pub trait ContextAbstract {
  /// Add an action to the context.
  /// 
  /// This method adds an action to the context, and
  /// returns a reference to the action. The action
  /// will be run when the context is run.
  /// 
  /// You can use the returned reference as a
  /// dependency for other actions.
  async fn add_action<A: Action + 'static>(self, action: A) -> ActionObject;

  /// Update an ActionObject
  /// 
  /// After updating an action returned from
  /// `add_action`, you should call this method
  /// to update the action in the context.
  async fn update_action(self, action: ActionObject);

  /// Run the context.
  /// 
  /// While processing the actions, it will
  /// call the callbacks if they are set.
  async fn run(self) -> Result<()>;

  /// Run an individual action.
  /// 
  /// This is called internally, and should not
  /// be called directly. It is used to run
  /// individual actions, and to check if their
  /// outputs are available and successful.
  async fn run_action(self, action: ActionObject) -> Result<Option<ActionOutput>>;

  /// Sets a variable in the context.
  /// 
  /// This can be used to send information between
  /// actions. For example, you could set a return code
  /// in one action, and check it in another.
  async fn set_variable(self, name: &str, value: &str);

  /// Gets a variable from the context.
  /// 
  /// If the variable doesn't exist, this method
  /// returns `None`.
  async fn get_variable(self, name: &str) -> Option<String>;

  /// Sets a local variable for the action.
  /// 
  /// This variable will be namespaced to the action,
  /// and will not be visible to other actions in any
  /// reasonable way. Actions could fetch the ID of the
  /// current action, and use that to access the variable,
  /// but that's voodoo magic and you shouldn't do it.
  async fn set_local(self, action: ActionObject, name: &str, value: &str);

  /// Gets a local variable for the action.
  /// 
  /// This variable will be namespaced to the action,
  /// and will not be visible to other actions in any
  /// reasonable way. Actions could fetch the ID of the
  /// current action, and use that to access the variable,
  /// but that's voodoo magic and you shouldn't do it.
  async fn get_local(self, action: ActionObject, name: &str) -> Option<String>;

  /// Gets the output of the action.
  /// 
  /// If the action has not been run yet, this will return
  /// `None`, regardless of the action's value after running
  /// it. If you are using this outside of an action, you
  /// should only use it after the context has been run.
  async fn get_output(self, action: ActionObject) -> Option<ActionOutput>;
}

impl Context {
  /// Create a new context with the given callbacks.
  /// 
  /// If you don't want any callbacks, it's recommended
  /// to use the [`Default`] implementation instead.
  /// 
  /// [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html
  pub fn new(callbacks: ContextCallbacks) -> Arc<RwLock<Self>> {
    Arc::new(RwLock::new(Self {
      actions: Vec::new(),
      variables: HashMap::new(),
      callbacks,
      outputs: HashMap::new(),
      barriers: HashMap::new()
    }))
  }
}

#[async_trait]
impl ContextAbstract for Arc<RwLock<Context>> {
  async fn add_action<A: Action + 'static>(self, action: A) -> ActionObject {
    let action = Arc::new(action);
    let action = ActionObject::new(action.clone());

    self.write().await.actions.push(action.clone());

    action
  }

  async fn update_action(self, action: ActionObject) {
    let mut actions = self.write().await.actions.clone();

    for (i, other) in actions.clone().iter().enumerate() {
      if action.id() == other.id() {
        actions[i] = action.clone();
      }
    }

    self.write().await.actions = actions;
  }

  async fn run(self) -> Result<()> {
    let mut actions = self.read().await.actions.clone();
    let mut dependents: HashMap<Id, usize> = HashMap::new();

    for action in actions.clone() {
      dependents.insert(action.id(), 0);

      let deps = action.clone().deps()
        .iter().map(|a| a.id()).collect::<Vec<_>>();

      for dep in deps {
        dependents.insert(dep, dependents.get(&dep).unwrap_or(&0) + 1);
      }
    }

    for (id, revdeps) in dependents.clone() {
      if revdeps == 0 {
        continue
      }

      self.clone().write().await
        .barriers.insert(id, Arc::new(Barrier::new(revdeps + 1)));
    }

    actions.sort_by(|a, b| {
      let a_revdeps = dependents.get(&a.id()).unwrap_or(&0);
      let b_revdeps = dependents.get(&b.id()).unwrap_or(&0);

      a_revdeps.cmp(b_revdeps)
    });

    let mut handles = Vec::new();
    for action in actions {
      let ctx = self.clone();
      let action = action.clone();

      let dep_ids = action.clone().deps()
        .iter().map(|a| a.id()).collect::<Vec<_>>();
      let barriers = ctx.clone().read().await.barriers.clone();
      let dep_barriers = dep_ids.iter()
        .map(|id| barriers.get(id).unwrap().clone())
        .collect::<Vec<_>>();
      let self_barrier = barriers.get(&action.id()).cloned();

      handles.push(tokio::spawn(async move {
        for barrier in dep_barriers {
          barrier.wait().await;
        }

        let res = ctx.run_action(action).await;

        if let Some(barrier) = self_barrier {
          barrier.wait().await;
        }

        res
      }))
    }

    let results = join_all(handles).await;

    for result in results {
      result??;
    }

    Ok(())
  }

  async fn run_action(self, action: ActionObject) -> Result<Option<ActionOutput>> {
    let callbacks = self.clone().read().await.callbacks.clone();

    if !action.check(self.clone()).await? {
      if let Some(callback) = callbacks.on_action_started {
        callback(action.clone());
      }

      let output = action.perform(self.clone()).await;

      if let Err(e) = &output {
        if let Some(callback) = callbacks.on_action_failed {
          callback(action, e);
        }

        return output
      }

      if let Some(callback) = callbacks.on_action_finished {
        callback(action.clone());
      }

      if let Some(output) = output.unwrap() {
        self.clone().write().await.outputs.insert(action.id(), output.clone());
        Ok(Some(output))
      } else {
        Ok(None)
      }
    } else {
      Ok(self.clone().write().await.outputs.get(&action.id()).cloned())
    }
  }

  async fn set_variable(self, name: &str, value: &str) {
    self.write().await.variables.insert(name.to_string(), value.to_string());
  }

  async fn get_variable(self, name: &str) -> Option<String> {
    self.read().await.variables.get(name).cloned()
  }

  async fn set_local(self, action: ActionObject, name: &str, value: &str) {
    self.set_variable(&format!("{}::{}", action.id(), name), value).await;
  }

  async fn get_local(self, action: ActionObject, name: &str) -> Option<String> {
    self.get_variable(&format!("{}::{}", action.id(), name)).await
  }

  async fn get_output(self, action: ActionObject) -> Option<ActionOutput> {
    self.read().await.outputs.get(&action.id()).cloned()
  }
}

/// Callbacks for the context.
/// 
/// These callbacks are set by interfaces, and are
/// usually not set by scripts directly.
#[derive(Default, Clone)]
pub struct ContextCallbacks {
  /// Called when an action is started.
  pub on_action_started: Option<fn(ActionObject)>,
  /// Called when an action is completed successfully.
  pub on_action_finished: Option<fn(ActionObject)>,
  /// Called when an action fails.
  pub on_action_failed: Option<fn(ActionObject, &anyhow::Error)>
}

/// A unique identifier for an action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Id(Uuid);

impl Default for Id {
  fn default() -> Self {
    Self(Uuid::new_v4())
  }
}

impl std::fmt::Display for Id {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    self.0.fmt(f)
  }
}

/// The output of an action.
/// 
/// When an [`Action`] is run, it can return a value
/// back to the context. This value can be used by
/// other actions depending on said value.
/// 
/// [`Action`]: trait.Action.html
#[derive(Debug, Clone)]
pub enum ActionOutput {
  /// A string.
  String(String),
  /// An integer (i64).
  Integer(i64),
  /// A floating-point number (f64).
  Float(f64),
  /// A boolean.
  Boolean(bool)
}

/// An input for an action.
/// 
/// Action inputs are not required to use this
/// enum, but it is recommended to do so. It allows
/// users to pass both static values and dependency
/// outputs to actions.
pub enum ActionInput<T> {
  /// A static value.
  Static(T),
  /// A value from an action.
  Action(Arc<dyn Action>)
}

impl<T> ActionInput<T> {
  /// Creates a new input from an action.
  pub fn new_action(value: Arc<dyn Action>) -> Self {
    Self::Action(value)
  }

  /// Creates a new input from a static value.
  pub fn new_static(value: T) -> Self {
    Self::Static(value)
  }

  /// Returns the static value, or `None` if the input
  /// is an action.
  pub fn static_value(&self) -> Option<&T> {
    match self {
      Self::Static(value) => Some(value),
      _ => None
    }
  }

  /// Returns the action, or `None` if the input is
  /// static.
  pub fn action(&self) -> Option<Arc<dyn Action>> {
    match self {
      Self::Action(action) => Some(action.clone()),
      _ => None
    }
  }

  /// Returns `true` if the input is static.
  pub fn is_static(&self) -> bool {
    self.static_value().is_some()
  }

  /// Returns `true` if the input is an action.
  pub fn is_action(&self) -> bool {
    self.action().is_some()
  }

  /// Returns the static value, or panics if the input
  /// is an action.
  pub fn unwrap_static(&self) -> &T {
    self.static_value().unwrap()
  }

  /// Returns the action, or panics if the input is
  /// static.
  pub fn unwrap_action(&self) -> Arc<dyn Action> {
    self.action().unwrap()
  }
}

impl<T> From<T> for ActionInput<T> {
  fn from(value: T) -> Self {
    Self::new_static(value)
  }
}

impl<T: Default> Default for ActionInput<T> {
  fn default() -> Self {
    Self::new_static(T::default())
  }
}