grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
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
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Conformance runner (SPEC §6): loads `conformance/scenarios/*.json` and runs the scenarios of
//! the registered categories.
//!
//! Each category plugs in through [`CategoryHandler`] (one per category) which opens a
//! [`ScenarioSession`] per scenario. The runner substitutes variables, checks `requires`,
//! evaluates expectations and builds a [`ConformanceReport`].

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{json, Value};

use super::expect::check_expectation;
use crate::core::{Error, Result};

/// One conformance scenario.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct Scenario {
    /// Scenario id, e.g. `secrets.roundtrip`.
    pub id: String,
    /// `core`, `secrets`, `logging` or `tracing`.
    pub category: String,
    /// Human description.
    #[serde(default)]
    pub description: String,
    /// Capabilities the target must declare.
    #[serde(default)]
    pub requires: Vec<String>,
    /// Logging batch options the factory applies.
    #[serde(default, rename = "batchOptions")]
    pub batch_options: Option<Value>,
    /// Steps in order.
    pub steps: Vec<Step>,
}

/// One scenario step.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct Step {
    /// Operation name.
    pub op: String,
    /// Operation arguments (variables substituted before the handler sees them).
    #[serde(default)]
    pub args: Value,
    /// Expectations.
    #[serde(default)]
    pub expect: Option<Value>,
    /// Variable name that receives the result.
    #[serde(default)]
    pub save: Option<String>,
    /// Capabilities this step needs (skipped alone when missing).
    #[serde(default)]
    pub requires: Vec<String>,
}

/// Loads every `*.json` scenario of `dir`, sorted by id.
pub fn load_scenarios(dir: impl AsRef<Path>) -> Result<Vec<Scenario>> {
    let dir = dir.as_ref();
    let entries = std::fs::read_dir(dir).map_err(|e| {
        Error::config(format!(
            "conformance directory {} cannot be read",
            dir.display()
        ))
        .with_source(e)
    })?;
    let mut scenarios = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        let text = std::fs::read_to_string(&path).map_err(|e| {
            Error::config(format!("scenario {} cannot be read", path.display())).with_source(e)
        })?;
        let scenario: Scenario = serde_json::from_str(&text)
            .map_err(|e| Error::config(format!("scenario {} is invalid: {e}", path.display())))?;
        scenarios.push(scenario);
    }
    scenarios.sort_by(|a, b| a.id.cmp(&b.id));
    Ok(scenarios)
}

/// Scenario variables (`${run}`, `${prefix}`, saved results, runner variables).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Vars(BTreeMap<String, String>);

impl Vars {
    /// Empty variables.
    pub fn new() -> Self {
        Vars::default()
    }
    /// Value of a variable.
    pub fn get(&self, name: &str) -> Option<&str> {
        self.0.get(name).map(String::as_str)
    }
    /// Sets a variable.
    pub fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
        self.0.insert(name.into(), value.into());
    }
    /// Replaces every known `${name}` in `text`; unknown references are kept.
    pub fn substitute(&self, text: &str) -> String {
        let mut out = String::with_capacity(text.len());
        let mut rest = text;
        while let Some(start) = rest.find("${") {
            out.push_str(&rest[..start]);
            let after = &rest[start + 2..];
            match after.find('}') {
                Some(end) => {
                    let name = &after[..end];
                    match self.0.get(name) {
                        Some(v) => out.push_str(v),
                        None => out.push_str(&rest[start..start + 3 + end]),
                    }
                    rest = &after[end + 1..];
                }
                None => {
                    out.push_str(&rest[start..]);
                    rest = "";
                }
            }
        }
        out.push_str(rest);
        out
    }
    /// Substitutes variables in every string (keys included) of a JSON value.
    pub fn substitute_value(&self, value: &Value) -> Value {
        match value {
            Value::String(s) => Value::String(self.substitute(s)),
            Value::Array(items) => {
                Value::Array(items.iter().map(|v| self.substitute_value(v)).collect())
            }
            Value::Object(map) => Value::Object(
                map.iter()
                    .map(|(k, v)| (self.substitute(k), self.substitute_value(v)))
                    .collect(),
            ),
            other => other.clone(),
        }
    }
}

/// Result of one operation, in the forms the expectations need.
#[derive(Debug, Clone, PartialEq)]
pub struct StepOutput {
    /// JSON form (used by `equals`, `contains`, `count`, `type`, `sorted`, `tree`, `null`, …).
    pub value: Value,
    /// Text form of the native result (`Debug`/`Display`/JSON), used by `stringForm`.
    pub display: String,
    /// `SecretValue::reveal()` when the result is a secret value.
    pub reveal: Option<String>,
    /// Explicit count (maps, traces); otherwise derived from `value`.
    pub count: Option<usize>,
}

impl StepOutput {
    /// No result (`null`).
    pub fn none() -> Self {
        StepOutput::json(Value::Null)
    }
    /// A JSON result whose display form is its JSON text.
    pub fn json(value: Value) -> Self {
        let display = value.to_string();
        StepOutput {
            value,
            display,
            reveal: None,
            count: None,
        }
    }
    /// Sets the display form.
    pub fn with_display(mut self, display: impl Into<String>) -> Self {
        self.display = display.into();
        self
    }
    /// Sets the revealed secret text.
    pub fn with_reveal(mut self, reveal: impl Into<String>) -> Self {
        self.reveal = Some(reveal.into());
        self
    }
    /// Sets the count.
    pub fn with_count(mut self, count: usize) -> Self {
        self.count = Some(count);
        self
    }
}

/// Executes the operations of one category; registered with [`ConformanceRunner::handler`].
#[async_trait]
pub trait CategoryHandler: Send + Sync {
    /// Category served (`core`, `secrets`, `logging`, `tracing`).
    fn category(&self) -> &str;
    /// Opens a session for one scenario (build clients here, e.g. with `batch_options`).
    async fn open(&self, scenario: &Scenario, vars: &Vars) -> Result<Box<dyn ScenarioSession>>;
}

/// Per-scenario state of a category handler.
#[async_trait]
pub trait ScenarioSession: Send {
    /// Runs one operation; `args` already has variables substituted (`#{i}` is left to the
    /// handler). SDK errors are returned as `Err` and matched by `expect.error`.
    async fn run(&mut self, op: &str, args: &Value, vars: &Vars) -> Result<StepOutput>;
    /// Releases resources after the last step (also after a failure).
    async fn close(&mut self) {}
}

/// Outcome of a scenario.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScenarioStatus {
    /// Every step met its expectations.
    Passed,
    /// A step failed (message names the step).
    Failed(String),
    /// Not run (missing capability).
    Skipped(String),
}

/// Result of one scenario.
#[derive(Debug, Clone)]
pub struct ScenarioResult {
    /// Scenario id.
    pub id: String,
    /// Category.
    pub category: String,
    /// Outcome.
    pub status: ScenarioStatus,
    /// Steps skipped for missing capabilities (`"<index>:<op> (missing: …)"`).
    pub skipped_steps: Vec<String>,
    /// Wall time.
    pub duration: Duration,
}

/// Results of a run.
#[derive(Debug, Clone, Default)]
pub struct ConformanceReport {
    /// One entry per scenario of a registered category.
    pub results: Vec<ScenarioResult>,
}

impl ConformanceReport {
    fn count(&self, f: impl Fn(&ScenarioStatus) -> bool) -> usize {
        self.results.iter().filter(|r| f(&r.status)).count()
    }
    /// Number of passed scenarios.
    pub fn passed(&self) -> usize {
        self.count(|s| matches!(s, ScenarioStatus::Passed))
    }
    /// Number of failed scenarios.
    pub fn failed(&self) -> usize {
        self.count(|s| matches!(s, ScenarioStatus::Failed(_)))
    }
    /// Number of skipped scenarios.
    pub fn skipped(&self) -> usize {
        self.count(|s| matches!(s, ScenarioStatus::Skipped(_)))
    }
    /// Whether no scenario failed.
    pub fn is_success(&self) -> bool {
        self.failed() == 0
    }
    /// Result of one scenario.
    pub fn result(&self, id: &str) -> Option<&ScenarioResult> {
        self.results.iter().find(|r| r.id == id)
    }
    /// Machine-readable form.
    pub fn to_json(&self) -> Value {
        let results: Vec<Value> = self
            .results
            .iter()
            .map(|r| {
                let (status, reason) = match &r.status {
                    ScenarioStatus::Passed => ("passed", None),
                    ScenarioStatus::Failed(m) => ("failed", Some(m.clone())),
                    ScenarioStatus::Skipped(m) => ("skipped", Some(m.clone())),
                };
                json!({
                    "id": r.id, "category": r.category, "status": status, "reason": reason,
                    "skippedSteps": r.skipped_steps, "durationMs": r.duration.as_millis() as u64,
                })
            })
            .collect();
        json!({
            "passed": self.passed(), "failed": self.failed(), "skipped": self.skipped(),
            "results": results,
        })
    }
    /// Panics with the summary when a scenario failed.
    pub fn assert_success(&self) {
        assert!(self.is_success(), "conformance failed:\n{self}");
    }
}

impl fmt::Display for ConformanceReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "conformance: {} passed, {} failed, {} skipped",
            self.passed(),
            self.failed(),
            self.skipped()
        )?;
        for r in &self.results {
            match &r.status {
                ScenarioStatus::Passed => writeln!(f, "  PASS {}", r.id)?,
                ScenarioStatus::Failed(m) => writeln!(f, "  FAIL {}: {m}", r.id)?,
                ScenarioStatus::Skipped(m) => writeln!(f, "  SKIP {}: {m}", r.id)?,
            }
            for s in &r.skipped_steps {
                writeln!(f, "       skipped step {s}")?;
            }
        }
        Ok(())
    }
}

/// Default provider prefix (`${run}` is substituted per scenario).
pub const DEFAULT_PREFIX: &str = "grow-conformance/${run}/";

/// Runs conformance scenarios against registered category handlers.
#[derive(Clone)]
pub struct ConformanceRunner {
    dir: PathBuf,
    capabilities: BTreeSet<String>,
    prefix: String,
    vars: Vars,
    handlers: Vec<Arc<dyn CategoryHandler>>,
    only: Option<BTreeSet<String>>,
}

impl fmt::Debug for ConformanceRunner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ConformanceRunner")
            .field("dir", &self.dir)
            .field("capabilities", &self.capabilities)
            .field(
                "handlers",
                &self
                    .handlers
                    .iter()
                    .map(|h| h.category().to_owned())
                    .collect::<Vec<_>>(),
            )
            .finish_non_exhaustive()
    }
}

impl ConformanceRunner {
    /// A runner over the scenarios in `dir` (usually `<repo>/conformance/scenarios`).
    pub fn new(dir: impl Into<PathBuf>) -> Self {
        ConformanceRunner {
            dir: dir.into(),
            capabilities: BTreeSet::new(),
            prefix: DEFAULT_PREFIX.to_owned(),
            vars: Vars::new(),
            handlers: Vec::new(),
            only: None,
        }
    }

    /// Declares capabilities of the target (`write`, `delete`, `versions`, `query`, …).
    pub fn capabilities<I, S>(mut self, caps: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.capabilities.extend(caps.into_iter().map(Into::into));
        self
    }

    /// Provider prefix (default `grow-conformance/${run}/`).
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = prefix.into();
        self
    }

    /// Extra variable, e.g. `serviceName`.
    pub fn var(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.vars.set(name, value);
        self
    }

    /// Registers a category handler (scenarios of other categories are ignored).
    pub fn handler(mut self, handler: impl CategoryHandler + 'static) -> Self {
        self.handlers.push(Arc::new(handler));
        self
    }

    /// Runs only the scenarios with these ids.
    pub fn only<I, S>(mut self, ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.only = Some(ids.into_iter().map(Into::into).collect());
        self
    }

    /// Loads and runs the scenarios.
    pub async fn run(&self) -> Result<ConformanceReport> {
        let scenarios = load_scenarios(&self.dir)?;
        Ok(self.run_scenarios(&scenarios).await)
    }

    /// Runs already loaded scenarios.
    pub async fn run_scenarios(&self, scenarios: &[Scenario]) -> ConformanceReport {
        let mut report = ConformanceReport::default();
        for scenario in scenarios {
            if self
                .only
                .as_ref()
                .is_some_and(|ids| !ids.contains(&scenario.id))
            {
                continue;
            }
            let Some(handler) = self
                .handlers
                .iter()
                .find(|h| h.category() == scenario.category)
            else {
                continue;
            };
            report
                .results
                .push(self.run_one(handler.as_ref(), scenario).await);
        }
        report
    }

    fn missing(&self, requires: &[String]) -> Vec<String> {
        requires
            .iter()
            .filter(|r| !self.capabilities.contains(*r))
            .cloned()
            .collect()
    }

    async fn run_one(&self, handler: &dyn CategoryHandler, scenario: &Scenario) -> ScenarioResult {
        let started = Instant::now();
        let mut result = ScenarioResult {
            id: scenario.id.clone(),
            category: scenario.category.clone(),
            status: ScenarioStatus::Passed,
            skipped_steps: Vec::new(),
            duration: Duration::ZERO,
        };
        let missing = self.missing(&scenario.requires);
        if !missing.is_empty() {
            result.status =
                ScenarioStatus::Skipped(format!("missing capabilities: {}", missing.join(", ")));
            return result;
        }
        let mut vars = self.vars.clone();
        vars.set("run", run_id());
        let prefix = vars.substitute(&self.prefix);
        vars.set("prefix", prefix);

        let mut session = match handler.open(scenario, &vars).await {
            Ok(s) => s,
            Err(e) => {
                result.status =
                    ScenarioStatus::Failed(format!("setup failed: {} ({})", e, e.code()));
                result.duration = started.elapsed();
                return result;
            }
        };
        for (i, step) in scenario.steps.iter().enumerate() {
            let missing = self.missing(&step.requires);
            if !missing.is_empty() {
                result.skipped_steps.push(format!(
                    "{i}:{} (missing: {})",
                    step.op,
                    missing.join(", ")
                ));
                continue;
            }
            let args = vars.substitute_value(&step.args);
            let outcome = session.run(&step.op, &args, &vars).await;
            let checked = match &step.expect {
                Some(expect) => check_expectation(&vars.substitute_value(expect), &outcome),
                None => match &outcome {
                    Ok(_) => Ok(()),
                    Err(e) => Err(format!("unexpected error {}: {}", e.code(), e)),
                },
            };
            if let Err(msg) = checked {
                result.status = ScenarioStatus::Failed(format!("step {i} ({}): {msg}", step.op));
                break;
            }
            if let (Some(name), Ok(out)) = (&step.save, &outcome) {
                let saved = match &out.value {
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                };
                vars.set(name.clone(), saved);
            }
        }
        session.close().await;
        result.duration = started.elapsed();
        result
    }
}

/// Random 8-character lowercase id.
pub fn run_id() -> String {
    const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
    (0..8)
        .map(|_| ALPHABET[rand::random_range(0..ALPHABET.len())] as char)
        .collect()
}