fisher 1.0.0

Webhooks catcher written in Rust
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
// Copyright (C) 2016-2017 Pietro Albini
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

use std::path::{Path, PathBuf};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use common::prelude::*;
use common::state::{State, UniqueId};
use providers::{Provider, StatusEvent, StatusEventKind};
use requests::Request;
use scripts::collector::Collector;
use scripts::jobs::{Job, JobOutput};
use scripts::script::{Script, ScriptProvider};


pub struct ScriptsIter {
    inner: Arc<RwLock<RepositoryInner>>,
    count: usize,
}

impl ScriptsIter {
    fn new(inner: Arc<RwLock<RepositoryInner>>) -> Self {
        ScriptsIter { inner, count: 0 }
    }
}

impl Iterator for ScriptsIter {
    type Item = Arc<Script>;

    fn next(&mut self) -> Option<Self::Item> {
        self.count += 1;

        match self.inner.read() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }.scripts
            .get(self.count - 1)
            .cloned()
    }
}


pub struct StatusJobsIter {
    inner: Arc<RwLock<RepositoryInner>>,
    event: StatusEvent,
    count: usize,
}

impl StatusJobsIter {
    fn new(inner: Arc<RwLock<RepositoryInner>>, event: StatusEvent) -> Self {
        StatusJobsIter {
            inner,
            event,
            count: 0,
        }
    }
}

impl Iterator for StatusJobsIter {
    type Item = Job;

    fn next(&mut self) -> Option<Self::Item> {
        self.count += 1;

        let inner = match self.inner.read() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };

        if let Some(all) = inner.status_hooks.get(&self.event.kind()) {
            if let Some(hp) = all.get(self.count - 1).cloned() {
                Some(Job::new(
                    hp.script,
                    Some(hp.provider),
                    Request::Status(self.event.clone()),
                ))
            } else {
                None
            }
        } else {
            None
        }
    }
}


#[derive(Debug)]
struct RepositoryInner {
    scripts: Vec<Arc<Script>>,
    by_id: HashMap<UniqueId, Arc<Script>>,
    by_name: HashMap<String, Arc<Script>>,
    status_hooks: HashMap<StatusEventKind, Vec<ScriptProvider>>,
}

impl RepositoryInner {
    pub fn new() -> Self {
        RepositoryInner {
            scripts: Vec::new(),
            by_id: HashMap::new(),
            by_name: HashMap::new(),
            status_hooks: HashMap::new(),
        }
    }

    pub fn insert(&mut self, script: Arc<Script>) {
        self.scripts.push(script.clone());
        self.by_id.insert(script.id(), script.clone());
        self.by_name
            .insert(script.name().to_string(), script.clone());

        for provider in &script.providers {
            if let Provider::Status(ref status) = *provider.as_ref() {
                // Load all the kinds of events
                for event in status.events() {
                    self.status_hooks
                        .entry(*event)
                        .or_insert_with(Vec::new)
                        .push(ScriptProvider {
                            script: script.clone(),
                            provider: provider.clone(),
                        });
                }
            }
        }
    }

    pub fn get_by_name(&self, name: &str) -> Option<Arc<Script>> {
        self.by_name.get(name).cloned()
    }
}


#[derive(Debug)]
pub struct Repository {
    inner: Arc<RwLock<RepositoryInner>>,
}

impl Repository {
    pub fn get_by_name(&self, name: &str) -> Option<Arc<Script>> {
        match self.inner.read() {
            Ok(inner) => inner.get_by_name(name),
            Err(poisoned) => poisoned.get_ref().get_by_name(name),
        }
    }
}

impl ScriptsRepositoryTrait for Repository {
    type Script = Script;
    type Job = Job;
    type ScriptsIter = ScriptsIter;
    type JobsIter = StatusJobsIter;

    fn id_exists(&self, id: &UniqueId) -> bool {
        match self.inner.read() {
            Ok(inner) => inner.by_id.contains_key(id),
            Err(poisoned) => poisoned.get_ref().by_id.contains_key(id),
        }
    }

    fn iter(&self) -> ScriptsIter {
        ScriptsIter::new(self.inner.clone())
    }

    fn jobs_after_output(&self, output: JobOutput) -> Option<StatusJobsIter> {
        if !output.trigger_status_hooks {
            return None;
        }

        let event = if output.success {
            StatusEvent::JobCompleted(output)
        } else {
            StatusEvent::JobFailed(output)
        };

        Some(StatusJobsIter::new(self.inner.clone(), event))
    }
}


#[derive(Debug)]
pub struct Blueprint {
    added: Vec<Arc<Script>>,
    collect_paths: Vec<(PathBuf, bool)>,

    inner: Arc<RwLock<RepositoryInner>>,
    state: Arc<State>,
}

impl Blueprint {
    pub fn new(state: Arc<State>) -> Self {
        Blueprint {
            added: Vec::new(),
            collect_paths: Vec::new(),

            inner: Arc::new(RwLock::new(RepositoryInner::new())),
            state: state,
        }
    }

    pub fn clear(&mut self) {
        self.added.clear();
        self.collect_paths.clear();
    }

    #[cfg(test)]
    pub fn insert(&mut self, script: Arc<Script>) -> Result<()> {
        self.added.push(script);

        self.reload()?;
        Ok(())
    }

    pub fn collect_path<P: AsRef<Path>>(
        &mut self,
        path: P,
        recursive: bool,
    ) -> Result<()> {
        self.collect_paths
            .push((path.as_ref().to_path_buf(), recursive));

        self.reload()?;
        Ok(())
    }

    pub fn reload(&mut self) -> Result<()> {
        let mut inner = RepositoryInner::new();

        // Add manually added scripts
        for script in &self.added {
            inner.insert(script.clone());
        }

        // Collect scripts from paths
        let mut collector;
        for &(ref p, recursive) in &self.collect_paths {
            collector = Collector::new(p, self.state.clone(), recursive)?;
            for script in collector {
                inner.insert(script?);
            }
        }

        {
            let mut to_update = self.inner.write()?;
            *to_update = inner;
        }

        Ok(())
    }

    pub fn repository(&self) -> Repository {
        Repository {
            inner: self.inner.clone(),
        }
    }
}


#[cfg(test)]
mod tests {
    use std::fs;
    use std::os::unix::fs as unix_fs;
    use std::sync::Arc;

    use common::prelude::*;
    use providers::StatusEventKind;
    use scripts::test_utils::*;

    use super::{Blueprint, Repository};


    #[test]
    fn test_blueprint_allows_adding_scripts() {
        test_wrapper(|env| {
            // Create a script
            env.create_script(
                "first.sh",
                &[r#"#!/bin/bash"#, r#"echo "First script""#],
            )?;

            // Create a directory with two scripts
            let dir = env.tempdir()?;
            env.create_script_into(
                &dir,
                "second.sh",
                &[r#"#!/bin/bash"#, r#"echo "Second script""#],
            )?;
            env.create_script_into(
                &dir,
                "third.sh",
                &[r#"#!/bin/bash"#, r#"echo "Third script""#],
            )?;

            // Create a new empty blueprint
            let mut blueprint = Blueprint::new(env.state());

            // Add the single script to the blueprint
            blueprint.insert(Arc::new(env.load_script("first.sh")?))?;

            // Collect the directory with the blueprint
            blueprint.collect_path(&dir, false)?;

            // Ensure all the scripts are in the repository
            let repository = blueprint.repository();
            for script in &["first.sh", "second.sh", "third.sh"] {
                assert!(repository.get_by_name(script).is_some());
            }

            Ok(())
        });
    }


    #[test]
    fn test_blueprint_changes_are_applies_to_existing_repositories() {
        test_wrapper(|env| {
            // Create two scripts
            env.create_script(
                "first.sh",
                &[r#"#!/bin/bash"#, r#"echo "First script""#],
            )?;
            env.create_script(
                "second.sh",
                &[r#"#!/bin/bash"#, r#"echo "Second script""#],
            )?;

            // Create a new empty blueprint
            let mut blueprint = Blueprint::new(env.state());

            // Add one of the script to the blueprint
            blueprint.insert(Arc::new(env.load_script("first.sh")?))?;

            // Get the repository related to the blueprint
            let repository = blueprint.repository();

            // Ensure only the first script is present in the repository
            assert!(repository.get_by_name("first.sh").is_some());
            assert!(repository.get_by_name("second.sh").is_none());

            // Add another script to the blueprint
            blueprint.insert(Arc::new(env.load_script("second.sh")?))?;

            // Ensure all the scripts are present in the existing repository
            assert!(repository.get_by_name("first.sh").is_some());
            assert!(repository.get_by_name("second.sh").is_some());

            Ok(())
        });
    }


    #[test]
    fn test_blueprint_can_be_reloaded() {
        test_wrapper(|env| {
            // Create two scripts
            env.create_script(
                "first.sh",
                &[r#"#!/bin/bash"#, r#"echo "I'm the first script""#],
            )?;
            env.create_script(
                "second.sh",
                &[r#"#!/bin/bash"#, r#"echo "I'm the second script""#],
            )?;

            // Create a new blueprint and collect the directory
            let mut blueprint = Blueprint::new(env.state());
            blueprint.collect_path(&env.scripts_dir(), false)?;

            // Ensure the two scripts are present
            let repository = blueprint.repository();
            let id_original = repository
                .get_by_name("first.sh")
                .expect("The first.sh script was not collected")
                .id();
            assert!(repository.get_by_name("second.sh").is_some());
            assert!(repository.get_by_name("third.sh").is_none());

            // Create a new script and delete one of the existing ones
            env.create_script(
                "third.sh",
                &[r#"#!/bin/bash"#, r#"echo "I'm the third script""#],
            )?;
            fs::remove_file(env.scripts_dir().join("second.sh"))?;

            // Reload the blueprint
            blueprint.reload()?;

            // Ensure the correct scripts are present
            let id_new = repository
                .get_by_name("first.sh")
                .expect("The first.sh script was not collected")
                .id();
            assert!(repository.get_by_name("second.sh").is_none());
            assert!(repository.get_by_name("third.sh").is_some());

            // Ensure the script IDs are different
            assert_ne!(id_original, id_new);

            Ok(())
        });
    }

    #[test]
    fn test_symlinks_are_resolved() {
        test_wrapper(|env| {
            // Create the directory structure
            let base = env.tempdir()?;
            let real = base.join("real");
            let link = base.join("link");

            fs::create_dir(&real)?;
            unix_fs::symlink(&real, &link)?;

            // Create a script in the real directory
            env.create_script_into(&real, "script.sh", &[])?;

            // Load the scripts from the symlink
            let mut blueprint = Blueprint::new(env.state());
            blueprint.collect_path(&link, false)?;

            // Ensure the script is loaded, and it points to the real path
            let repository = blueprint.repository();
            let script = repository.get_by_name("script.sh")
                .expect("the script wasn't loaded properly");

            assert_eq!(
                script.exec(),
                real.join("script.sh").to_str().unwrap()
            );

            Ok(())
        });
    }

    #[test]
    fn test_no_changes_applied_if_blueprint_reload_fails() {
        test_wrapper(|env| {
            // Create a new script
            env.create_script(
                "first.sh",
                &[r#"#!/bin/bash"#, r#"echo "I'm the first script""#],
            )?;

            // Create a new script in another directory
            let dir = env.tempdir()?;
            env.create_script_into(
                &dir,
                "second.sh",
                &[r#"#!/bin/bash"#, r#"echo "I'm the second script""#],
            )?;

            // Create a new blueprint and collect the directories
            let mut blueprint = Blueprint::new(env.state());
            blueprint.collect_path(env.scripts_dir(), false)?;
            blueprint.collect_path(&dir, false)?;

            // Ensure the scripts are present
            let repository = blueprint.repository();
            assert!(repository.get_by_name("first.sh").is_some());
            assert!(repository.get_by_name("second.sh").is_some());
            assert!(repository.get_by_name("third.sh").is_none());

            // Remove the second directory and create a script in the other
            fs::remove_dir_all(&dir)?;
            env.create_script(
                "third.sh",
                &[r#"#!/bin/bash"#, r#"echo "I'm the third script""#],
            )?;

            // Reload the blueprint, and ensure it fails
            assert!(blueprint.reload().is_err());

            // Ensure no changes were applied
            assert!(repository.get_by_name("first.sh").is_some());
            assert!(repository.get_by_name("second.sh").is_some());
            assert!(repository.get_by_name("third.sh").is_none());

            Ok(())
        });
    }


    #[test]
    fn test_status_hooks_are_correctly_stored() {
        // Check in the internal data structure
        fn assert_status_hooks(
            repo: &Repository,
            kind: StatusEventKind,
            expect: &[&str],
        ) {
            let inner = repo.inner.read().unwrap();

            let mut count = 0;
            for script in inner.status_hooks.get(&kind).unwrap() {
                assert!(expect.contains(&script.script.name()));
                count += 1;
            }

            assert_eq!(expect.len(), count);
        }

        test_wrapper(|env| {
            // Create a script and two status hooks
            env.create_script(
                "normal.sh",
                &[
                    r#"#!/bin/bash"#,
                    r#"## Fisher-Testing: {}"#,
                    r#"echo "I'm just a normal script""#,
                ],
            )?;
            env.create_script(
                "status-both.sh",
                &[
                    r#"#!/bin/bash"#,
                    r#"## Fisher-Status: {"events": ["job-completed", "job-failed"]}"#,
                    r#"echo "I'm a status script!""#,
                ],
            )?;
            env.create_script(
                "status-failed.sh",
                &[
                    r#"#!/bin/bash"#,
                    r#"## Fisher-Status: {"events": ["job-failed"]}"#,
                    r#"echo "I'm a failure!""#,
                ],
            )?;

            // Create a new blueprint
            let mut blueprint = Blueprint::new(env.state());
            blueprint.collect_path(&env.scripts_dir(), false)?;

            // Ensure all the scripts are present
            let repository = blueprint.repository();
            assert!(repository.get_by_name("normal.sh").is_some());
            assert!(repository.get_by_name("status-both.sh").is_some());
            assert!(repository.get_by_name("status-failed.sh").is_some());

            // Ensure the correct status hooks are returned
            assert_status_hooks(
                &repository,
                StatusEventKind::JobCompleted,
                &["status-both.sh"],
            );
            assert_status_hooks(
                &repository,
                StatusEventKind::JobFailed,
                &["status-both.sh", "status-failed.sh"],
            );

            Ok(())
        })
    }
}