cf-integration 0.2.0

Integration and conformance harness for ContextForge control-plane and data-plane services
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
//! CLI-to-runtime command resolution.

use std::collections::BTreeSet;
use std::ffi::{OsStr, OsString};
use std::path::{Component, PathBuf};
use std::str::FromStr;

use crate::conformance::DEFAULT_MCP_SPEC_VERSION;
use crate::conformance::profile::{
    DUAL_CLIENT_PROTOCOL_VERSIONS, LEGACY_CLIENT_PROTOCOL_VERSIONS, MODERN_CLIENT_PROTOCOL_VERSIONS,
};
use crate::conformance::results::{ConformanceServerEra, SemanticLane};
use crate::infrastructure::StackMode;
use crate::infrastructure::config::Environment;
use crate::performance::LoadRequest;
use anyhow::{Result, bail};

use crate::cli::{
    CiCommand, Cli, CliLane, CliTopology, Command, ConformanceCommand, DebugCommand, LiveGroup,
    ProtocolVersion, StackCommand, TokenKind, TopologySelection,
};
const STACK_MODE_ENV: &str = "CF_MCP_STACK_MODE";
const PROTOCOL_VERSION_ENV: &str = "MCP_PROTOCOL_VERSION";

/// Fully resolved application operation.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Action {
    Stack(StackAction),
    Probe {
        topology: StackMode,
        protocol_version: ProtocolVersion,
    },
    Load(ResolvedLoadArgs),
    Live {
        lane: SemanticLane,
        group: LiveGroup,
        protocol_version: ProtocolVersion,
    },
    Conformance(ConformanceAction),
    Debug(DebugAction),
    Ci(CiAction),
}

impl Action {
    /// Stable command path used by lifecycle output.
    #[must_use]
    pub(crate) const fn description(&self) -> &'static str {
        match self {
            Self::Stack(StackAction::Up { .. }) => "stack up",
            Self::Stack(StackAction::Down { .. }) => "stack down",
            Self::Stack(StackAction::Status(_)) => "stack status",
            Self::Stack(StackAction::Logs { .. }) => "stack logs",
            Self::Stack(StackAction::Config(_)) => "stack config",
            Self::Probe { .. } => "probe",
            Self::Load(_) => "load test",
            Self::Live { .. } => "live tests",
            Self::Conformance(ConformanceAction::Run { .. }) => "conformance tests",
            Self::Conformance(ConformanceAction::Report { .. }) => "conformance report",
            Self::Debug(DebugAction::Inspect { .. }) => "debug inspect",
            Self::Debug(DebugAction::Token { .. }) => "debug token",
            Self::Ci(CiAction::PrepareImage { .. }) => "prepare prebuilt CI image",
            Self::Ci(CiAction::PrepareRelease) => "prepare release state",
            Self::Ci(CiAction::SelectRelease) => "select release tag",
        }
    }

    /// Resolved execution context printed before the command starts.
    #[must_use]
    pub(crate) fn startup_summary(&self) -> String {
        match self {
            Self::Stack(action) => action.startup_summary(),
            Self::Probe {
                topology,
                protocol_version,
            }
            | Self::Debug(DebugAction::Inspect {
                topology,
                protocol_version,
                ..
            }) => topology_and_protocol(*topology, protocol_version),
            Self::Load(args) => topology_and_protocol(args.topology, &args.protocol_version),
            Self::Live {
                lane,
                protocol_version,
                ..
            } => format!(
                "Topology: {}\nProtocol version: {protocol_version}",
                lane.label()
            ),
            Self::Conformance(ConformanceAction::Run {
                lanes,
                client_eras,
                server_eras,
                ..
            }) => format!(
                "Topology: {}\nClient era: {}\nServer era: {}",
                join_lane_labels(lanes),
                join_client_eras(client_eras),
                join_server_eras(server_eras),
            ),
            Self::Conformance(ConformanceAction::Report { .. }) => String::from(
                "Topology: recorded conformance results\nClient era: recorded conformance results\nServer era: recorded conformance results",
            ),
            Self::Debug(DebugAction::Token { .. }) => {
                String::from("Topology: not applicable (token only)")
            }
            Self::Ci(CiAction::PrepareImage { .. }) => {
                String::from("CI operation: prepare prebuilt image")
            }
            Self::Ci(CiAction::PrepareRelease) => {
                String::from("CI operation: prepare release state")
            }
            Self::Ci(CiAction::SelectRelease) => String::from("CI operation: select release tag"),
        }
    }

    /// Returns whether the dispatcher should own one command-wide activity line.
    #[must_use]
    pub(crate) const fn uses_global_activity(&self) -> bool {
        !matches!(
            self,
            Self::Stack(StackAction::Up { .. })
                | Self::Load(_)
                | Self::Conformance(ConformanceAction::Run { .. })
        )
    }

    /// Returns whether this operation needs Compose overlays or runtime scripts.
    #[must_use]
    pub(crate) const fn requires_runtime_assets(&self) -> bool {
        !matches!(
            self,
            Self::Conformance(ConformanceAction::Report { .. })
                | Self::Debug(DebugAction::Token { .. })
                | Self::Ci(_)
        )
    }
}

impl StackAction {
    fn startup_summary(&self) -> String {
        let topology = match self {
            Self::Up { topology, .. }
            | Self::Status(topology)
            | Self::Logs { topology, .. }
            | Self::Config(topology) => topology.topology_label().to_owned(),
            Self::Down { topology, .. } => match topology {
                TopologySelection::Controlplane => {
                    StackMode::Controlplane.topology_label().to_owned()
                }
                TopologySelection::Dataplane => StackMode::Dataplane.topology_label().to_owned(),
                TopologySelection::All => format!(
                    "{}, {}",
                    StackMode::Controlplane.topology_label(),
                    StackMode::Dataplane.topology_label()
                ),
            },
        };
        if matches!(self, Self::Up { .. }) {
            format!("Topology: {topology}\nProtocol version: {DEFAULT_MCP_SPEC_VERSION}")
        } else {
            format!("Topology: {topology}")
        }
    }
}

fn topology_and_protocol(topology: StackMode, protocol_version: &ProtocolVersion) -> String {
    format!(
        "Topology: {}\nProtocol version: {protocol_version}",
        topology.topology_label()
    )
}

fn join_lane_labels(lanes: &[SemanticLane]) -> String {
    lanes
        .iter()
        .map(|lane| lane.label())
        .collect::<Vec<_>>()
        .join(", ")
}

fn join_client_eras(client_eras: &[ConformanceServerEra]) -> String {
    client_eras
        .iter()
        .map(|era| {
            let versions = match era {
                ConformanceServerEra::Dual => DUAL_CLIENT_PROTOCOL_VERSIONS,
                ConformanceServerEra::Legacy => LEGACY_CLIENT_PROTOCOL_VERSIONS,
                ConformanceServerEra::Modern => MODERN_CLIENT_PROTOCOL_VERSIONS,
            };
            format!("{} [{}]", era.label(), versions.join(", "))
        })
        .collect::<Vec<_>>()
        .join("; ")
}

fn join_server_eras(server_eras: &[ConformanceServerEra]) -> String {
    server_eras
        .iter()
        .map(|era| format!("{} [{}]", era.label(), era.protocol_versions_label()))
        .collect::<Vec<_>>()
        .join("; ")
}

/// Fully resolved stack operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StackAction {
    Up {
        topology: StackMode,
        fresh: bool,
    },
    Down {
        topology: TopologySelection,
        volumes: bool,
    },
    Status(StackMode),
    Logs {
        topology: StackMode,
        services: Vec<OsString>,
    },
    Config(StackMode),
}

/// Fully resolved load-test options.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ResolvedLoadArgs {
    pub(crate) topology: StackMode,
    pub(crate) protocol_version: ProtocolVersion,
    pub(crate) request: LoadRequest,
}

/// Fully resolved official conformance operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ConformanceAction {
    Run {
        lanes: Vec<SemanticLane>,
        client_eras: Vec<ConformanceServerEra>,
        client_versions: Vec<String>,
        server_eras: Vec<ConformanceServerEra>,
        results_dir: Option<PathBuf>,
        baseline_dir: Option<PathBuf>,
        bless: bool,
        output_dir: Option<PathBuf>,
    },
    Report {
        results_dir: Option<PathBuf>,
        output_dir: Option<PathBuf>,
    },
}

/// Fully resolved manual debugging operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum DebugAction {
    Inspect {
        topology: StackMode,
        protocol_version: ProtocolVersion,
        method: String,
        server_id: Option<String>,
    },
    Token {
        kind: TokenKind,
        server_id: Option<String>,
    },
}

/// Repository CI operation executed by the published CLI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CiAction {
    PrepareImage {
        artifact: String,
        binary: PathBuf,
        image: String,
        repository: String,
        revision: Option<String>,
        dockerfile: PathBuf,
        target: String,
        download_dir: PathBuf,
    },
    PrepareRelease,
    SelectRelease,
}

/// Resolves a parsed CLI without starting child processes or mutating global state.
///
/// # Errors
///
/// Returns an error when a command needs `CF_MCP_STACK_MODE` and its value is
/// neither `controlplane` nor `dataplane`.
pub(crate) fn resolve_action(cli: Cli, environment: &Environment) -> Result<Action> {
    match cli.command {
        Command::Stack(args) => resolve_stack(args.command, environment).map(Action::Stack),
        Command::Probe(args) => {
            let topology = resolve_topology(args.lane, environment)?;
            Ok(Action::Probe {
                topology,
                protocol_version: resolve_protocol_version(
                    args.protocol_version,
                    environment,
                    ProtocolVersion::default(),
                )?,
            })
        }
        Command::Load(args) => {
            let topology = resolve_topology(args.target.lane, environment)?;
            Ok(Action::Load(ResolvedLoadArgs {
                topology,
                protocol_version: resolve_protocol_version(
                    args.target.protocol_version,
                    environment,
                    ProtocolVersion::default(),
                )?,
                request: LoadRequest {
                    smoke: args.smoke,
                    users: args.users,
                    spawn_rate: args.spawn_rate,
                    run_time: args.run_time,
                },
            }))
        }
        Command::Live(args) => {
            let lane = resolve_live_lane(args.target.lane, environment)?;
            if lane == SemanticLane::FixtureDirect && args.group != LiveGroup::Protocol {
                bail!("--lane fixture-direct requires --group protocol");
            }
            Ok(Action::Live {
                lane,
                group: args.group,
                protocol_version: resolve_protocol_version(
                    args.target.protocol_version,
                    environment,
                    ProtocolVersion::default(),
                )?,
            })
        }
        Command::Conformance(args) => Ok(Action::Conformance(match args.command {
            ConformanceCommand::Run(args) => {
                let (client_eras, client_versions) = resolve_client_eras(args.client_era);
                ConformanceAction::Run {
                    lanes: resolve_lanes(args.lane.into_iter().map(Into::into)),
                    client_eras,
                    client_versions,
                    server_eras: resolve_server_eras(args.server_era),
                    results_dir: args.results_dir,
                    baseline_dir: args.baseline_dir,
                    bless: args.bless,
                    output_dir: args.output_dir,
                }
            }
            ConformanceCommand::Report(args) => ConformanceAction::Report {
                results_dir: args.results_dir,
                output_dir: args.output_dir,
            },
        })),
        Command::Debug(args) => Ok(Action::Debug(match args.command {
            DebugCommand::Inspect(args) => {
                let topology = resolve_topology(args.target.lane, environment)?;
                DebugAction::Inspect {
                    topology,
                    protocol_version: resolve_protocol_version(
                        args.target.protocol_version,
                        environment,
                        ProtocolVersion::default(),
                    )?,
                    method: args.method,
                    server_id: args.server_id,
                }
            }
            DebugCommand::Token(args) => {
                if args.kind == TokenKind::Admin && args.server_id.is_some() {
                    bail!("--server-id is only valid with --kind scoped");
                }
                DebugAction::Token {
                    kind: args.kind,
                    server_id: args.server_id,
                }
            }
        })),
        Command::Ci(args) => Ok(Action::Ci(match args.command {
            CiCommand::PrepareImage(args) => {
                let mut components = args.binary.components();
                if !matches!(components.next(), Some(Component::Normal(_)))
                    || components.next().is_some()
                {
                    bail!("--binary must be one filename at the artifact root");
                }
                let repository = args
                    .repository
                    .or_else(|| environment_utf8(environment, "GITHUB_REPOSITORY"))
                    .filter(|value| !value.is_empty())
                    .ok_or_else(|| anyhow::anyhow!("set --repository or GITHUB_REPOSITORY"))?;
                CiAction::PrepareImage {
                    artifact: args.artifact,
                    binary: args.binary,
                    image: args.image,
                    repository,
                    revision: args.revision,
                    dockerfile: args.dockerfile,
                    target: args.target,
                    download_dir: args.download_dir,
                }
            }
            CiCommand::PrepareRelease => CiAction::PrepareRelease,
            CiCommand::SelectRelease => CiAction::SelectRelease,
        })),
    }
}

fn environment_utf8(environment: &Environment, key: &str) -> Option<String> {
    environment
        .get(std::ffi::OsStr::new(key))
        .and_then(|value| value.to_str())
        .map(str::to_owned)
}

fn resolve_live_lane(lane: Option<CliLane>, environment: &Environment) -> Result<SemanticLane> {
    Ok(match lane {
        Some(CliLane::FixtureDirect) => SemanticLane::FixtureDirect,
        Some(CliLane::BuiltInDataPlane) => SemanticLane::BuiltInDataPlane,
        Some(CliLane::ExternalDataPlane) => SemanticLane::ExternalDataPlane,
        None => match resolve_topology(None, environment)? {
            StackMode::Controlplane => SemanticLane::BuiltInDataPlane,
            StackMode::Dataplane => SemanticLane::ExternalDataPlane,
        },
    })
}

fn resolve_protocol_version(
    explicit: Option<ProtocolVersion>,
    environment: &Environment,
    fallback: ProtocolVersion,
) -> Result<ProtocolVersion> {
    if let Some(version) = explicit {
        return Ok(version);
    }
    let Some(value) = environment.get(OsStr::new(PROTOCOL_VERSION_ENV)) else {
        return Ok(fallback);
    };
    let value = value
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("{PROTOCOL_VERSION_ENV} must be UTF-8"))?;
    if value.is_empty() {
        return Ok(fallback);
    }
    ProtocolVersion::from_str(value)
        .map_err(|error| anyhow::anyhow!("invalid {PROTOCOL_VERSION_ENV}: {error}"))
}

fn resolve_stack(command: StackCommand, environment: &Environment) -> Result<StackAction> {
    match command {
        StackCommand::Up(args) => Ok(StackAction::Up {
            topology: resolve_topology(args.topology, environment)?,
            fresh: args.fresh,
        }),
        StackCommand::Down(args) => Ok(StackAction::Down {
            topology: args.topology.unwrap_or(TopologySelection::All),
            volumes: args.volumes,
        }),
        StackCommand::Status(args) => Ok(StackAction::Status(resolve_topology(
            args.topology,
            environment,
        )?)),
        StackCommand::Logs(args) => Ok(StackAction::Logs {
            topology: resolve_topology(args.topology, environment)?,
            services: args.services,
        }),
        StackCommand::Config(args) => Ok(StackAction::Config(resolve_topology(
            args.topology,
            environment,
        )?)),
    }
}

fn resolve_lanes(lanes: impl IntoIterator<Item = SemanticLane>) -> Vec<SemanticLane> {
    let selected = lanes.into_iter().collect::<BTreeSet<_>>();
    let all = [
        SemanticLane::FixtureDirect,
        SemanticLane::BuiltInDataPlane,
        SemanticLane::ExternalDataPlane,
    ];
    if selected.is_empty() {
        all.into_iter().collect()
    } else {
        all.into_iter()
            .filter(|lane| selected.contains(lane))
            .collect()
    }
}

fn resolve_client_eras(
    eras: Vec<crate::cli::CliConformanceEra>,
) -> (Vec<ConformanceServerEra>, Vec<String>) {
    let eras = if eras.is_empty() {
        vec![crate::cli::CliConformanceEra::Modern]
    } else {
        eras
    };
    let mut seen_eras = BTreeSet::new();
    let eras = eras
        .into_iter()
        .map(Into::into)
        .filter(|era| seen_eras.insert(*era))
        .collect::<Vec<ConformanceServerEra>>();
    let mut seen_versions = BTreeSet::new();
    let versions = eras
        .iter()
        .flat_map(|era| match era {
            ConformanceServerEra::Dual => DUAL_CLIENT_PROTOCOL_VERSIONS,
            ConformanceServerEra::Legacy => LEGACY_CLIENT_PROTOCOL_VERSIONS,
            ConformanceServerEra::Modern => MODERN_CLIENT_PROTOCOL_VERSIONS,
        })
        .map(|version| (*version).to_owned())
        .filter(|version| seen_versions.insert(version.clone()))
        .collect();
    (eras, versions)
}

fn resolve_server_eras(eras: Vec<crate::cli::CliConformanceEra>) -> Vec<ConformanceServerEra> {
    let eras = if eras.is_empty() {
        vec![
            crate::cli::CliConformanceEra::Legacy,
            crate::cli::CliConformanceEra::Modern,
        ]
    } else {
        eras
    };
    let mut seen = BTreeSet::new();
    eras.into_iter()
        .map(Into::into)
        .filter(|era| seen.insert(*era))
        .collect()
}

fn resolve_topology(explicit: Option<CliTopology>, environment: &Environment) -> Result<StackMode> {
    if let Some(topology) = explicit {
        return Ok(topology.into());
    }
    Ok(environment_topology(environment)?.unwrap_or(StackMode::Dataplane))
}

fn environment_topology(environment: &Environment) -> Result<Option<StackMode>> {
    let Some(value) = environment.get(OsStr::new(STACK_MODE_ENV)) else {
        return Ok(None);
    };
    match value.to_str() {
        Some("controlplane") => Ok(Some(StackMode::Controlplane)),
        Some("dataplane") => Ok(Some(StackMode::Dataplane)),
        _ => bail!(
            "invalid {STACK_MODE_ENV}; expected controlplane or dataplane (got {:?})",
            value
        ),
    }
}

/// Converts a CLI topology selection into its ordered stack modes.
pub(crate) fn selected_topologies(selection: TopologySelection) -> Vec<StackMode> {
    match selection {
        TopologySelection::Controlplane => vec![StackMode::Controlplane],
        TopologySelection::Dataplane => vec![StackMode::Dataplane],
        TopologySelection::All => vec![StackMode::Controlplane, StackMode::Dataplane],
    }
}

/// Converts one concrete stack mode into a CLI topology selection.
pub(crate) const fn topology_selection(topology: StackMode) -> TopologySelection {
    match topology {
        StackMode::Controlplane => TopologySelection::Controlplane,
        StackMode::Dataplane => TopologySelection::Dataplane,
    }
}