oxide-batch-cli 0.5.0

Minimal guarded operator command line for OxideBatch
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! Deterministic fixtures for the operator CLI scenarios.
//!
//! The host is fully injected, so broken output, refused confirmation, file
//! permissions, and per-value precedence are ordinary assertions rather than
//! process-level fixtures. Nothing here reads the real environment, the real
//! filesystem, or the real clock.

#![allow(dead_code, clippy::expect_used, clippy::panic)]

use std::collections::BTreeMap;
use std::io;
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use oxide_batch::{
    BoxFuture, Clock, ComponentRevision, DefinitionIdentity, DefinitionRevision, ExplorerError,
    ExplorerQuery, ExplorerRepository, FlowDecision, IdGenerationError, IdentifierKind,
    InMemoryExplorer, InMemoryJobRepository, JobExecutionId, JobExecutionProjection, JobExplorer,
    JobInstanceId, JobInstanceProjection, JobName, JobOperator, JobRepository, MonotonicClock,
    MonotonicInstant, OperatorRecord, OwnerToken, QueryWindow, RecoveryDecision, RecoveryProposer,
    RepositoryError, RepositoryUnitOfWork, RetentionService, SequentialIdGenerator,
    StepExecutionId, StepExecutionProjection, StepName, StepPartitionProjection,
};
use oxide_batch_cli::{DefinitionCatalog, ExitCategory, Host, NoSchema, Services};

/// A clock that never advances on its own.
#[derive(Debug)]
pub struct FixedClock {
    at: SystemTime,
}

impl FixedClock {
    #[must_use]
    pub fn new() -> Self {
        Self {
            at: UNIX_EPOCH + Duration::from_hours(500_000),
        }
    }
}

impl Default for FixedClock {
    fn default() -> Self {
        Self::new()
    }
}

impl Clock for FixedClock {
    fn now(&self) -> SystemTime {
        self.at
    }
}

#[derive(Debug)]
struct FixedMonotonic;

impl MonotonicClock for FixedMonotonic {
    fn now(&self) -> MonotonicInstant {
        MonotonicInstant::from_duration(Duration::ZERO)
    }
}

/// A deterministic in-memory process boundary.
#[derive(Debug, Default)]
pub struct TestHost {
    env: BTreeMap<String, String>,
    files: BTreeMap<PathBuf, Vec<u8>>,
    modes: BTreeMap<PathBuf, u32>,
    directories: BTreeMap<PathBuf, Vec<String>>,
    stdout: Vec<u8>,
    stderr: Vec<u8>,
    stdin_interactive: bool,
    stdout_terminal: bool,
    confirmation: Option<String>,
    stdout_capacity: Option<usize>,
    operation_ids: u64,
    /// Number of times standard output was written.
    pub writes: usize,
}

impl TestHost {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn with_env(mut self, key: &str, value: &str) -> Self {
        self.env.insert(key.to_owned(), value.to_owned());
        self
    }

    #[must_use]
    pub fn with_file(mut self, path: &str, contents: &str) -> Self {
        self.files
            .insert(PathBuf::from(path), contents.as_bytes().to_vec());
        self.modes.insert(PathBuf::from(path), 0o600);
        self
    }

    #[must_use]
    pub fn with_mode(mut self, path: &str, mode: u32) -> Self {
        self.modes.insert(PathBuf::from(path), mode);
        self
    }

    /// Marks standard input interactive and queues one confirmation response.
    #[must_use]
    pub fn interactive(mut self, response: &str) -> Self {
        self.stdin_interactive = true;
        self.confirmation = Some(response.to_owned());
        self
    }

    /// Marks standard input interactive with no response available.
    #[must_use]
    pub fn interactive_silent(mut self) -> Self {
        self.stdin_interactive = true;
        self
    }

    /// Fails every standard-output write beyond `bytes`.
    #[must_use]
    pub fn with_stdout_capacity(mut self, bytes: usize) -> Self {
        self.stdout_capacity = Some(bytes);
        self
    }

    #[must_use]
    pub fn stdout_text(&self) -> String {
        String::from_utf8_lossy(&self.stdout).into_owned()
    }

    #[must_use]
    pub fn stderr_text(&self) -> String {
        String::from_utf8_lossy(&self.stderr).into_owned()
    }

    /// Returns one generated file as UTF-8 test text.
    #[must_use]
    pub fn file_text(&self, path: &str) -> String {
        self.files
            .get(&PathBuf::from(path))
            .map_or_else(String::new, |bytes| {
                String::from_utf8_lossy(bytes).into_owned()
            })
    }

    /// Returns deterministic file names written below one generated directory.
    #[must_use]
    pub fn directory_files(&self, path: &str) -> Vec<String> {
        self.directories
            .get(&PathBuf::from(path))
            .cloned()
            .unwrap_or_default()
    }

    /// Parses standard output as the versioned JSON envelope.
    #[must_use]
    pub fn envelope(&self) -> serde_json::Value {
        serde_json::from_str(&self.stdout_text()).expect("standard output is one JSON object")
    }
}

impl Host for TestHost {
    fn env(&self, key: &str) -> Option<String> {
        self.env.get(key).cloned().filter(|value| !value.is_empty())
    }

    fn read_file(&self, path: &Path) -> io::Result<Vec<u8>> {
        self.files
            .get(path)
            .cloned()
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such test file"))
    }

    fn file_mode(&self, path: &Path) -> io::Result<Option<u32>> {
        if !self.files.contains_key(path) {
            return Err(io::Error::new(io::ErrorKind::NotFound, "no such test file"));
        }
        Ok(self.modes.get(path).copied())
    }

    fn write_new_directory(&mut self, path: &Path, files: &[(String, Vec<u8>)]) -> io::Result<()> {
        if self.directories.contains_key(path) {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                "target exists",
            ));
        }
        self.directories.insert(
            path.to_path_buf(),
            files.iter().map(|(name, _)| name.clone()).collect(),
        );
        for (name, bytes) in files {
            self.files.insert(path.join(name), bytes.clone());
        }
        Ok(())
    }

    fn write_stdout(&mut self, bytes: &[u8]) -> io::Result<()> {
        self.writes += 1;
        if let Some(capacity) = self.stdout_capacity
            && self.stdout.len() + bytes.len() > capacity
        {
            return Err(io::Error::new(io::ErrorKind::BrokenPipe, "closed pipe"));
        }
        self.stdout.extend_from_slice(bytes);
        Ok(())
    }

    fn flush_stdout(&mut self) -> io::Result<()> {
        Ok(())
    }

    fn write_stderr(&mut self, bytes: &[u8]) {
        self.stderr.extend_from_slice(bytes);
    }

    fn is_stdin_interactive(&self) -> bool {
        self.stdin_interactive
    }

    fn is_stdout_terminal(&self) -> bool {
        self.stdout_terminal
    }

    fn read_confirmation(&mut self) -> io::Result<Option<String>> {
        Ok(self.confirmation.take())
    }

    fn new_operation_id(&mut self) -> String {
        self.operation_ids += 1;
        format!("generated-{}", self.operation_ids)
    }
}

/// The in-memory services one scenario runs against.
pub type TestServices = Services<InMemoryJobRepository, InMemoryExplorer>;

/// Builds in-memory services over a deterministic clock and identifier source.
#[must_use]
pub fn services() -> (TestServices, InMemoryJobRepository) {
    let clock: Arc<dyn Clock> = Arc::new(FixedClock::new());
    let first = NonZeroU64::new(1).expect("one is nonzero");
    let repository = InMemoryJobRepository::new(
        Arc::clone(&clock),
        Arc::new(SequentialIdGenerator::new(first)),
    );
    let explorer_repository = InMemoryExplorer::new(&repository);
    let recovery = RecoveryProposer::new(
        explorer_repository.clone(),
        Arc::clone(&clock),
        Arc::new(FixedMonotonic),
        OwnerToken::from_bytes([0; 16]),
    );
    let explorer = JobExplorer::new(explorer_repository);
    let operator = JobOperator::new(repository.clone(), Arc::clone(&clock));
    let retention = RetentionService::new(repository.clone(), clock);
    (
        Services::new(operator, retention, explorer, Box::new(NoSchema))
            .with_recovery_proposals(Box::new(recovery)),
        repository,
    )
}

/// The identity of one registered test job.
#[must_use]
pub fn test_identity(job: &str) -> DefinitionIdentity {
    let job_name = JobName::new(job).expect("the job name is valid");
    let step = StepName::new("only").expect("the step name is valid");
    let revision = DefinitionRevision::new("r1").expect("the revision is valid");
    let component = ComponentRevision::new("c1").expect("the component revision is valid");
    DefinitionIdentity::tasklet(&job_name, &step, revision, &component)
        .expect("the manifest encodes")
}

/// A catalog registering one test job.
#[must_use]
pub fn test_catalog(job: &str) -> DefinitionCatalog {
    DefinitionCatalog::new()
        .with(test_identity(job))
        .expect("the registration succeeds")
}

/// The durable identifiers a seeded fixture created.
#[derive(Clone, Copy, Debug)]
pub struct Seeded {
    /// The launched logical instance.
    pub instance_id: u64,
    /// The launched execution attempt.
    pub execution_id: u64,
    /// The optimistic version observed right after the launch.
    pub version: u64,
}

/// Builds services that already hold one launched execution.
///
/// The launch goes through the operator service rather than the repository, so
/// the fixture exercises the same guards a CLI invocation would.
#[must_use]
pub fn seeded_services(job: &str) -> (TestServices, Seeded) {
    let (services, _repository) = services();
    let mut host = TestHost::new();
    let catalog = test_catalog(job);
    let category = run_with_catalog(
        &mut host,
        &services,
        &catalog,
        &format!("launch --job {job} --actor fixture --operation-id seed-launch --output json"),
    );
    assert_eq!(
        category,
        ExitCategory::Success,
        "the fixture launch failed: {}",
        host.stdout_text()
    );
    let envelope = host.envelope();
    let execution = &envelope["data"]["execution"];
    let record = &envelope["data"]["record"];
    Seeded {
        instance_id: record["instance_id"]
            .as_u64()
            .expect("the launch recorded an instance"),
        execution_id: execution["execution_id"]
            .as_u64()
            .expect("the launch created an execution"),
        version: execution["version"]
            .as_u64()
            .expect("the launch recorded a version"),
    }
    .pair(services)
}

impl Seeded {
    fn pair(self, services: TestServices) -> (TestServices, Self) {
        (services, self)
    }
}

/// An explorer port that answers every query the same way.
///
/// `Stalled` never completes, which lets a scenario observe the client
/// deadline; the error modes let a scenario observe a category the in-memory
/// adapter cannot produce on its own.
#[derive(Clone, Copy, Debug)]
pub enum FaultyExplorer {
    /// Every query returns [`ExplorerError::Repository`] with `Unavailable`.
    Unavailable,
    /// Every query is pending forever.
    Stalled,
}

impl FaultyExplorer {
    fn answer<'a, T: 'a>(self) -> BoxFuture<'a, Result<T, ExplorerError>> {
        match self {
            Self::Unavailable => {
                Box::pin(async { Err(ExplorerError::Repository(RepositoryError::Unavailable)) })
            }
            Self::Stalled => Box::pin(std::future::pending()),
        }
    }
}

impl ExplorerRepository for FaultyExplorer {
    fn identity_ceiling<'a>(
        &'a self,
        _query: &'a ExplorerQuery,
    ) -> BoxFuture<'a, Result<u64, ExplorerError>> {
        self.answer()
    }

    fn job_names<'a>(
        &'a self,
        _window: &'a QueryWindow,
    ) -> BoxFuture<'a, Result<Vec<JobName>, ExplorerError>> {
        self.answer()
    }

    fn instances<'a>(
        &'a self,
        _job_name: &'a JobName,
        _window: &'a QueryWindow,
    ) -> BoxFuture<'a, Result<Vec<JobInstanceProjection>, ExplorerError>> {
        self.answer()
    }

    fn executions<'a>(
        &'a self,
        _job_instance_id: JobInstanceId,
        _window: &'a QueryWindow,
    ) -> BoxFuture<'a, Result<Vec<JobExecutionProjection>, ExplorerError>> {
        self.answer()
    }

    fn execution(
        &self,
        _job_execution_id: JobExecutionId,
    ) -> BoxFuture<'_, Result<Option<JobExecutionProjection>, ExplorerError>> {
        self.answer()
    }

    fn step_executions<'a>(
        &'a self,
        _job_execution_id: JobExecutionId,
        _window: &'a QueryWindow,
    ) -> BoxFuture<'a, Result<Vec<StepExecutionProjection>, ExplorerError>> {
        self.answer()
    }

    fn unresolved_executions<'a>(
        &'a self,
        _minimum_age: Duration,
        _window: &'a QueryWindow,
    ) -> BoxFuture<'a, Result<Vec<JobExecutionProjection>, ExplorerError>> {
        self.answer()
    }

    fn recovery_decisions<'a>(
        &'a self,
        _job_execution_id: JobExecutionId,
        _window: &'a QueryWindow,
    ) -> BoxFuture<'a, Result<Vec<RecoveryDecision>, ExplorerError>> {
        self.answer()
    }

    fn flow_decisions<'a>(
        &'a self,
        _job_execution_id: JobExecutionId,
        _window: &'a QueryWindow,
    ) -> BoxFuture<'a, Result<Vec<FlowDecision>, ExplorerError>> {
        self.answer()
    }

    fn step_partitions<'a>(
        &'a self,
        _step_execution_id: StepExecutionId,
        _window: &'a QueryWindow,
    ) -> BoxFuture<'a, Result<Vec<StepPartitionProjection>, ExplorerError>> {
        self.answer()
    }

    fn operator_requests<'a>(
        &'a self,
        _job_execution_id: JobExecutionId,
        _window: &'a QueryWindow,
    ) -> BoxFuture<'a, Result<Vec<OperatorRecord>, ExplorerError>> {
        self.answer()
    }
}

/// A repository whose unit of work can never be opened.
///
/// A failure to begin is the earliest possible failure, so it reaches the
/// operator and retention services before any effect is attempted.
#[derive(Clone, Copy, Debug)]
pub struct FaultyRepository(pub FaultyBegin);

/// How a [`FaultyRepository`] refuses to begin a unit of work.
#[derive(Clone, Copy, Debug)]
pub enum FaultyBegin {
    /// The repository is unavailable.
    Unavailable,
    /// The commit outcome is undetermined.
    OutcomeUnknown,
    /// An injected identifier source failed.
    Identifier,
}

impl JobRepository for FaultyRepository {
    fn connection_capacity(&self) -> u32 {
        1
    }

    fn begin<'a>(
        &'a self,
    ) -> BoxFuture<'a, Result<Box<dyn RepositoryUnitOfWork + 'a>, RepositoryError>> {
        let error = match self.0 {
            FaultyBegin::Unavailable => RepositoryError::Unavailable,
            FaultyBegin::OutcomeUnknown => RepositoryError::CommitOutcomeUnknown,
            FaultyBegin::Identifier => RepositoryError::Identifier(IdGenerationError::Exhausted {
                kind: IdentifierKind::JobExecution,
            }),
        };
        Box::pin(async move { Err(error) })
    }
}

/// Builds services whose explorer always fails the same way.
#[must_use]
pub fn faulty_explorer_services(
    mode: FaultyExplorer,
) -> Services<InMemoryJobRepository, FaultyExplorer> {
    let clock: Arc<dyn Clock> = Arc::new(FixedClock::new());
    let first = NonZeroU64::new(1).expect("one is nonzero");
    let repository = InMemoryJobRepository::new(
        Arc::clone(&clock),
        Arc::new(SequentialIdGenerator::new(first)),
    );
    Services::new(
        JobOperator::new(repository.clone(), Arc::clone(&clock)),
        RetentionService::new(repository, Arc::clone(&clock)),
        JobExplorer::new(mode),
        Box::new(NoSchema),
    )
}

/// Builds services whose repository always refuses to begin.
#[must_use]
pub fn faulty_repository_services(
    mode: FaultyBegin,
) -> Services<FaultyRepository, InMemoryExplorer> {
    let clock: Arc<dyn Clock> = Arc::new(FixedClock::new());
    let first = NonZeroU64::new(1).expect("one is nonzero");
    let backing = InMemoryJobRepository::new(
        Arc::clone(&clock),
        Arc::new(SequentialIdGenerator::new(first)),
    );
    let explorer = JobExplorer::new(InMemoryExplorer::new(&backing));
    let repository = FaultyRepository(mode);
    Services::new(
        JobOperator::new(repository, Arc::clone(&clock)),
        RetentionService::new(repository, clock),
        explorer,
        Box::new(NoSchema),
    )
}

/// Runs one invocation against arbitrary services with no client deadline.
pub fn run_against<R, S>(host: &mut TestHost, services: &Services<R, S>, line: &str) -> ExitCategory
where
    R: JobRepository,
    S: ExplorerRepository,
{
    let arguments = words(line);
    let mut plan = match oxide_batch_cli::prepare(host, &arguments) {
        Ok(plan) => plan,
        Err(category) => return category,
    };
    if let Some(category) = oxide_batch_cli::local(host, &plan) {
        return category;
    }
    let catalog = DefinitionCatalog::new();
    futures_executor::block_on(oxide_batch_cli::dispatch(
        host,
        &mut plan,
        services,
        &catalog,
        std::future::pending::<()>(),
    ))
}

/// Runs one invocation whose client deadline has already elapsed.
pub fn run_expired<R, S>(host: &mut TestHost, services: &Services<R, S>, line: &str) -> ExitCategory
where
    R: JobRepository,
    S: ExplorerRepository,
{
    let arguments = words(line);
    let mut plan = match oxide_batch_cli::prepare(host, &arguments) {
        Ok(plan) => plan,
        Err(category) => return category,
    };
    let catalog = DefinitionCatalog::new();
    futures_executor::block_on(oxide_batch_cli::dispatch(
        host,
        &mut plan,
        services,
        &catalog,
        std::future::ready(()),
    ))
}

/// Splits a command line into process arguments.
#[must_use]
pub fn words(line: &str) -> Vec<String> {
    line.split_whitespace().map(str::to_owned).collect()
}

/// Runs one invocation to completion with no client deadline.
///
/// The deadline future never completes, so a scenario observes only the
/// command's own behavior.
pub fn run(host: &mut TestHost, services: &TestServices, line: &str) -> ExitCategory {
    run_with_catalog(host, services, &DefinitionCatalog::new(), line)
}

/// Runs one invocation against an explicit definition catalog.
pub fn run_with_catalog(
    host: &mut TestHost,
    services: &TestServices,
    catalog: &DefinitionCatalog,
    line: &str,
) -> ExitCategory {
    let arguments = words(line);
    let mut plan = match oxide_batch_cli::prepare(host, &arguments) {
        Ok(plan) => plan,
        Err(category) => return category,
    };
    if let Some(category) = oxide_batch_cli::local(host, &plan) {
        return category;
    }
    futures_executor::block_on(oxide_batch_cli::dispatch(
        host,
        &mut plan,
        services,
        catalog,
        std::future::pending::<()>(),
    ))
}