felixctl 0.6.0

Command-line tool for Felix: publish, subscribe, read caches, manage the control plane and run benchmarks
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
//! Control-plane writes: `create`, `set` and `rm` for tenants, namespaces,
//! streams and caches, `node drain|deregister`, `shard move` and `placement`.
//!
//! Request bodies are built as JSON by pure functions, so the tests can check
//! them without a control plane. Each command prints what changed; with
//! `--json`, the control plane's answer.

use std::io::{BufRead, IsTerminal, Write};

use serde_json::{Value, json};

use crate::cli::{
    Bound, CacheCreateArgs, Confirm, ConsistencyArg, DeliveryArg, KindArg, PlacementCommand,
    RoutingArg, ShardMoveArgs, ShardMoveCommand, ShardRef, StreamCreateArgs, StreamSetArgs,
};
use crate::context::Settings;
use crate::controlplane::{Answer, Api, namespace_path, print_one, segment};
use crate::error::{Exit, fail};
use crate::output::{Output, cell};

pub(crate) async fn create_tenant(
    api: &Api,
    tenant: &str,
    display_name: Option<&str>,
    out: &Output,
) -> anyhow::Result<()> {
    let answer = api
        .post(
            "/v1/tenants",
            &[],
            Some(&named_body("tenant_id", tenant, display_name)),
        )
        .await?;
    print_created(out, &format!("tenant {tenant}"), answer)
}

pub(crate) async fn remove_tenant(
    api: &Api,
    tenant: &str,
    confirm: Confirm,
    out: &Output,
) -> anyhow::Result<()> {
    ask(
        &format!("Delete tenant {tenant} and everything in it?"),
        confirm,
    )?;
    api.delete(&format!("/v1/tenants/{}", segment(tenant)), &[])
        .await?;
    print_deleted(out, "tenant", tenant)
}

pub(crate) async fn create_namespace(
    api: &Api,
    settings: &Settings,
    namespace: &str,
    display_name: Option<&str>,
    out: &Output,
) -> anyhow::Result<()> {
    let tenant = settings.tenant()?;
    let answer = api
        .post(
            &format!("/v1/tenants/{}/namespaces", segment(tenant)),
            &[],
            Some(&named_body("namespace", namespace, display_name)),
        )
        .await?;
    print_created(out, &format!("namespace {tenant}/{namespace}"), answer)
}

pub(crate) async fn remove_namespace(
    api: &Api,
    settings: &Settings,
    namespace: &str,
    confirm: Confirm,
    out: &Output,
) -> anyhow::Result<()> {
    let tenant = settings.tenant()?;
    let name = format!("{tenant}/{namespace}");
    ask(
        &format!("Delete namespace {name} with its streams and caches?"),
        confirm,
    )?;
    api.delete(
        &format!(
            "/v1/tenants/{}/namespaces/{}",
            segment(tenant),
            segment(namespace)
        ),
        &[],
    )
    .await?;
    print_deleted(out, "namespace", &name)
}

pub(crate) async fn create_stream(
    api: &Api,
    settings: &Settings,
    args: &StreamCreateArgs,
    out: &Output,
) -> anyhow::Result<()> {
    let base = namespace_path(settings)?;
    let answer = api
        .post(&format!("{base}/streams"), &[], Some(&stream_body(args)))
        .await?;
    print_created(
        out,
        &format!("stream {}", qualified(settings, &args.stream)?),
        answer,
    )
}

pub(crate) async fn set_stream(
    api: &Api,
    settings: &Settings,
    args: &StreamSetArgs,
    out: &Output,
) -> anyhow::Result<()> {
    let path = format!(
        "{}/streams/{}",
        namespace_path(settings)?,
        segment(&args.stream)
    );
    // The patch replaces retention whole, so a bound not given is read first
    // and sent back as it was.
    let before = api.get(&path, &[]).await?;
    let answer = api.patch(&path, &stream_patch(args, &before)).await?;
    print_changed(
        out,
        &format!("stream {}", qualified(settings, &args.stream)?),
        &before,
        answer,
    )
}

pub(crate) async fn remove_stream(
    api: &Api,
    settings: &Settings,
    stream: &str,
    confirm: Confirm,
    out: &Output,
) -> anyhow::Result<()> {
    let name = qualified(settings, stream)?;
    ask(&format!("Delete stream {name} and its records?"), confirm)?;
    api.delete(
        &format!("{}/streams/{}", namespace_path(settings)?, segment(stream)),
        &[],
    )
    .await?;
    print_deleted(out, "stream", &name)
}

pub(crate) async fn create_cache(
    api: &Api,
    settings: &Settings,
    args: &CacheCreateArgs,
    out: &Output,
) -> anyhow::Result<()> {
    let base = namespace_path(settings)?;
    let answer = api
        .post(&format!("{base}/caches"), &[], Some(&cache_body(args)))
        .await?;
    print_created(
        out,
        &format!("cache {}", qualified(settings, &args.cache)?),
        answer,
    )
}

pub(crate) async fn set_cache(
    api: &Api,
    settings: &Settings,
    cache: &str,
    display_name: &str,
    out: &Output,
) -> anyhow::Result<()> {
    let path = format!("{}/caches/{}", namespace_path(settings)?, segment(cache));
    let before = api.get(&path, &[]).await?;
    let answer = api
        .patch(&path, &json!({ "display_name": display_name }))
        .await?;
    print_changed(
        out,
        &format!("cache {}", qualified(settings, cache)?),
        &before,
        answer,
    )
}

pub(crate) async fn remove_cache(
    api: &Api,
    settings: &Settings,
    cache: &str,
    confirm: Confirm,
    out: &Output,
) -> anyhow::Result<()> {
    let name = qualified(settings, cache)?;
    ask(
        &format!("Delete cache {name} and every key in it?"),
        confirm,
    )?;
    api.delete(
        &format!("{}/caches/{}", namespace_path(settings)?, segment(cache)),
        &[],
    )
    .await?;
    print_deleted(out, "cache", &name)
}

/// `node drain` or `node deregister`: `action` is the last path segment.
pub(crate) async fn node_lifecycle(
    api: &Api,
    node: &str,
    action: &str,
    confirm: Confirm,
    out: &Output,
) -> anyhow::Result<()> {
    let question = match action {
        "drain" => format!("Drain node {node}? Placement moves its shards away."),
        _ => format!("Deregister node {node}? Its shards fail over once its lease runs out."),
    };
    ask(&question, confirm)?;
    let answer = api
        .post(&format!("/v1/nodes/{}/{action}", segment(node)), &[], None)
        .await?;
    let body = answer.body.unwrap_or(Value::Null);
    if out.json {
        return out.json_value(&body);
    }
    let lifecycle = body
        .pointer("/status/lifecycle")
        .map(cell)
        .unwrap_or_default();
    out.text(&format!("node {node}: {lifecycle}"))
}

pub(crate) async fn shard_move(
    api: &Api,
    settings: &Settings,
    args: &ShardMoveArgs,
    out: &Output,
) -> anyhow::Result<()> {
    let answer = match &args.cancel {
        Some(ShardMoveCommand::Cancel(shard)) => {
            let (path, query) = shard_path("/v1/shard-moves", settings, shard)?;
            api.delete(&path, &query).await?
        }
        None => {
            let body = move_body(settings.tenant()?, &settings.namespace, args)?;
            api.post("/v1/shard-moves", &[], Some(&body)).await?
        }
    };
    print_move(out, answer)
}

pub(crate) async fn placement(
    command: &PlacementCommand,
    settings: &Settings,
    out: &Output,
) -> anyhow::Result<()> {
    if let PlacementCommand::Abandon { confirm, .. } = command
        && !confirm.yes
    {
        // Never a prompt: a keystroke is too easy a way to lose acknowledged
        // records.
        return Err(fail(
            Exit::Usage,
            "abandoning a shard's log loses its records; pass --yes to do it",
        ));
    }
    let api = Api::new(settings)?;
    let (path, done) = match command {
        PlacementCommand::Pause => ("/v1/placement/pause", "placement's moves are paused"),
        PlacementCommand::Resume => ("/v1/placement/resume", "placement's moves are running"),
        PlacementCommand::Abandon { shard, .. } => {
            let (path, query) = shard_path("/v1/placement/abandon", settings, shard)?;
            let answer = api.post(&path, &query, None).await?;
            return print_move(out, answer);
        }
    };
    let answer = api.post(path, &[], None).await?;
    out.done(done, answer.body.unwrap_or(Value::Null))
}

/// The body that creates a tenant or namespace: its id under `key`, and a
/// display name that defaults to the id.
pub(crate) fn named_body(key: &str, id: &str, display_name: Option<&str>) -> Value {
    json!({ key: id, "display_name": display_name.unwrap_or(id) })
}

pub(crate) fn stream_body(args: &StreamCreateArgs) -> Value {
    let mut body = json!({
        "stream": args.stream,
        "kind": kind(args.kind),
        "shards": args.shards,
        "replication_factor": args.replication,
        "retention": {
            "max_age_seconds": args.retention_secs,
            "max_size_bytes": args.retention_bytes,
        },
        "consistency": consistency(args.consistency),
        "delivery": delivery(args.delivery),
        "durable": args.durable,
    });
    if let Some(region) = &args.region {
        body["region"] = json!(region);
    }
    // Left out when it is the default, so a control plane that predates
    // routing choices still accepts the request.
    if args.routing != RoutingArg::Modulo {
        body["routing"] = json!(routing(args.routing));
    }
    body
}

/// The patch `stream set` sends, given the stream as it is now.
pub(crate) fn stream_patch(args: &StreamSetArgs, current: &Value) -> Value {
    let mut patch = json!({});
    if let Some(level) = args.consistency {
        patch["consistency"] = json!(consistency(level));
    }
    if let Some(guarantee) = args.delivery {
        patch["delivery"] = json!(delivery(guarantee));
    }
    if let Some(durable) = args.durable {
        patch["durable"] = json!(durable);
    }
    if args.retention_secs.is_some() || args.retention_bytes.is_some() {
        let mut retention = json!({
            "max_age_seconds": current.pointer("/retention/max_age_seconds").cloned().unwrap_or(Value::Null),
            "max_size_bytes": current.pointer("/retention/max_size_bytes").cloned().unwrap_or(Value::Null),
        });
        for (key, bound) in [
            ("max_age_seconds", args.retention_secs),
            ("max_size_bytes", args.retention_bytes),
        ] {
            match bound {
                Some(Bound::Value(value)) => retention[key] = json!(value),
                Some(Bound::BrokerDefault) => retention[key] = Value::Null,
                None => {}
            }
        }
        patch["retention"] = retention;
    }
    patch
}

pub(crate) fn cache_body(args: &CacheCreateArgs) -> Value {
    json!({
        "cache": args.cache,
        "display_name": args.display_name.as_deref().unwrap_or(&args.cache),
        "shards": args.shards,
        "replication_factor": args.replication,
        "consistency": consistency(args.consistency),
    })
}

/// The body that starts a move. clap requires NAME, SHARD and --to unless
/// `cancel` is given.
pub(crate) fn move_body(
    tenant: &str,
    namespace: &str,
    args: &ShardMoveArgs,
) -> anyhow::Result<Value> {
    let (Some(name), Some(shard), Some(to)) = (&args.name, args.shard, &args.to) else {
        return Err(fail(Exit::Usage, "shard move needs NAME, SHARD and --to"));
    };
    Ok(json!({
        "tenant_id": tenant,
        "namespace": namespace,
        "stream": name,
        "shard": shard,
        "kind": shard_kind(args.cache),
        "destination": to,
        "dry_run": args.dry_run,
    }))
}

/// `prefix/{tenant}/{namespace}/{name}/{shard}`, and the query naming its kind.
pub(crate) fn shard_path(
    prefix: &str,
    settings: &Settings,
    shard: &ShardRef,
) -> anyhow::Result<(String, Vec<(&'static str, &'static str)>)> {
    let path = format!(
        "{prefix}/{}/{}/{}/{}",
        segment(settings.tenant()?),
        segment(&settings.namespace),
        segment(&shard.name),
        shard.shard
    );
    Ok((path, vec![("kind", shard_kind(shard.cache))]))
}

/// `key: before -> after` for each top-level field that differs.
pub(crate) fn changes(before: &Value, after: &Value) -> Vec<String> {
    let Some(after) = after.as_object() else {
        return Vec::new();
    };
    after
        .iter()
        .filter(|(key, value)| before.get(key.as_str()) != Some(*value))
        .map(|(key, value)| {
            let old = before.get(key.as_str()).map(cell).unwrap_or_default();
            format!("{key}: {old} -> {}", cell(value))
        })
        .collect()
}

/// Go ahead only with `--yes`, or when someone at a terminal says yes.
pub(crate) fn ask(question: &str, confirm: Confirm) -> anyhow::Result<()> {
    let stdin = std::io::stdin();
    let interactive = stdin.is_terminal();
    confirm_with(question, confirm, interactive, || {
        let mut stderr = std::io::stderr().lock();
        write!(stderr, "{question} [y/N] ")?;
        stderr.flush()?;
        let mut answer = String::new();
        stdin.lock().read_line(&mut answer)?;
        Ok(answer)
    })
}

/// [`ask`] with the terminal check and the prompt passed in.
pub(crate) fn confirm_with(
    question: &str,
    confirm: Confirm,
    interactive: bool,
    prompt: impl FnOnce() -> std::io::Result<String>,
) -> anyhow::Result<()> {
    if confirm.yes {
        return Ok(());
    }
    if !interactive {
        return Err(fail(
            Exit::Usage,
            format!("{question} Pass --yes to confirm; stdin is not a terminal to ask on"),
        ));
    }
    let answer =
        prompt().map_err(|err| fail(Exit::Failure, format!("read the confirmation: {err}")))?;
    match answer.trim().to_ascii_lowercase().as_str() {
        "y" | "yes" => Ok(()),
        _ => Err(fail(Exit::Failure, "not confirmed; nothing was changed")),
    }
}

fn print_created(out: &Output, what: &str, answer: Answer) -> anyhow::Result<()> {
    let body = answer.body.unwrap_or(Value::Null);
    if out.json {
        return out.json_value(&body);
    }
    // A stream or cache that already exists with the same settings is
    // answered 200, not refused.
    let verb = if answer.created {
        format!("created {what}")
    } else {
        format!("{what} already exists with these settings")
    };
    out.text(&verb)?;
    print_one(out, &body)
}

fn print_changed(out: &Output, what: &str, before: &Value, answer: Answer) -> anyhow::Result<()> {
    let after = answer.body.unwrap_or(Value::Null);
    if out.json {
        return out.json_value(&after);
    }
    let changed = changes(before, &after);
    if changed.is_empty() {
        return out.text(&format!("{what}: nothing changed"));
    }
    out.text(&format!("updated {what}\n{}", changed.join("\n")))
}

fn print_deleted(out: &Output, kind: &str, name: &str) -> anyhow::Result<()> {
    out.done(
        &format!("deleted {kind} {name}"),
        json!({ "deleted": kind, "name": name }),
    )
}

fn print_move(out: &Output, answer: Answer) -> anyhow::Result<()> {
    let body = answer.body.unwrap_or(Value::Null);
    if out.json {
        return out.json_value(&body);
    }
    let field = |pointer: &str| body.pointer(pointer).map(cell).unwrap_or_default();
    let mut text = format!(
        "{}/{} shard {}: {}\nleader {}, replicas {}, generation {}",
        field("/assignment/kind"),
        field("/assignment/stream"),
        field("/assignment/shard"),
        field("/step"),
        field("/assignment/leader"),
        field("/assignment/replicas"),
        field("/assignment/generation"),
    );
    if let (Some(before), Some(after)) = (body.get("zones_before"), body.get("zones_after")) {
        text.push_str(&format!("\nzones {} -> {}", cell(before), cell(after)));
    }
    if body["dry_run"] == true {
        text.push_str("\n(dry run: nothing was written)");
    }
    out.text(&text)
}

fn qualified(settings: &Settings, name: &str) -> anyhow::Result<String> {
    Ok(format!(
        "{}/{}/{name}",
        settings.tenant()?,
        settings.namespace
    ))
}

fn shard_kind(cache: bool) -> &'static str {
    if cache { "cache" } else { "stream" }
}

fn kind(kind: KindArg) -> &'static str {
    match kind {
        KindArg::Stream => "Stream",
        KindArg::Queue => "Queue",
    }
}

fn consistency(level: ConsistencyArg) -> &'static str {
    match level {
        ConsistencyArg::Leader => "Leader",
        ConsistencyArg::Quorum => "Quorum",
    }
}

fn delivery(guarantee: DeliveryArg) -> &'static str {
    match guarantee {
        DeliveryArg::AtMostOnce => "AtMostOnce",
        DeliveryArg::AtLeastOnce => "AtLeastOnce",
    }
}

fn routing(routing: RoutingArg) -> &'static str {
    match routing {
        RoutingArg::Modulo => "modulo",
        RoutingArg::JumpHash => "jump_hash",
    }
}

#[cfg(test)]
mod tests;