felixctl 0.6.2

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
//! `pub`, `sub`, `cache`, `topology`, `group` and `counter`.

use felix_cluster::{CacheSpec, Cluster, ClusterConfig, StreamSpec};
use serial_test::serial;

use crate::Env;

#[tokio::test]
#[serial]
async fn publish_subscribe_cache_and_topology_against_a_cluster() {
    let cluster = Cluster::start(ClusterConfig {
        nodes: 3,
        streams: vec![StreamSpec::new("orders", 1), StreamSpec::new("wide", 3)],
        caches: vec![CacheSpec::new("sessions", 2)],
        ..Default::default()
    })
    .await
    .expect("start cluster");
    let env = Env::new(&cluster);

    // Publish from an argument, from stdin lines, without acks, and once.
    let run = env
        .felixctl(&cluster, &["pub", "orders", "one", "--json"])
        .await
        .ok();
    assert_eq!(run.json()["published"], 1);

    let mut args: Vec<String> = vec!["pub".into(), "orders".into(), "--json".into()];
    args.extend(env.flags(&cluster));
    let run = env.run(&args, &[], Some(b"two\nthree\n")).await.ok();
    assert_eq!(run.json()["published"], 2);

    env.felixctl(&cluster, &["pub", "orders", "four", "--ack", "none"])
        .await
        .ok();
    env.felixctl(&cluster, &["pub", "orders", "five", "--idempotent"])
        .await
        .ok();

    let run = env
        .felixctl(
            &cluster,
            &["pub", "wide", "x", "--key", "k", "--count", "3", "--json"],
        )
        .await
        .ok();
    assert_eq!(run.json()["published"], 3);

    // Read it all back, in order, with offsets.
    let first = env.first_after_probes(&cluster, "orders").await;
    let first_arg = first.to_string();
    let run = env
        .felixctl(
            &cluster,
            &[
                "sub", "orders", "--from", &first_arg, "--count", "5", "--json",
            ],
        )
        .await
        .ok();
    let events = run.json_lines();
    let payloads: Vec<&str> = events
        .iter()
        .map(|e| e["payload"].as_str().unwrap())
        .collect();
    assert_eq!(payloads, ["one", "two", "three", "four", "five"]);
    let offsets: Vec<u64> = events
        .iter()
        .map(|e| e["offset"].as_u64().unwrap())
        .collect();
    assert!(offsets.windows(2).all(|w| w[0] < w[1]), "{offsets:?}");

    let run = env
        .felixctl(
            &cluster,
            &["sub", "orders", "--from", &first_arg, "--count", "1"],
        )
        .await
        .ok();
    assert_eq!(run.stdout, "one\n");

    // `earliest` starts at offset 0, whichever record that is.
    let run = env
        .felixctl(
            &cluster,
            &[
                "sub", "orders", "--from", "earliest", "--count", "1", "--json",
            ],
        )
        .await
        .ok();
    assert_eq!(run.json()["offset"], 0, "{}", run.stdout);

    let run = env
        .felixctl(
            &cluster,
            &[
                "sub", "orders", "--shard", "0", "--from", &first_arg, "--count", "2", "--format",
                "offsets",
            ],
        )
        .await
        .ok();
    let lines: Vec<&str> = run.stdout.lines().collect();
    assert_eq!(lines.len(), 2, "{}", run.stdout);
    assert!(lines[0] == format!("0\t{first}\tone"), "{}", run.stdout);

    // Every shard of a wide stream, merged.
    let run = env
        .felixctl(
            &cluster,
            &[
                "sub", "wide", "--from", "earliest", "--count", "3", "--json",
            ],
        )
        .await
        .ok();
    assert_eq!(run.json_lines().len(), 3);

    // A stream the brokers do not know.
    let run = env
        .felixctl(&cluster, &["sub", "missing", "--count", "1"])
        .await;
    assert_eq!(run.code, 5, "{}", run.stderr);
    let run = env.felixctl(&cluster, &["pub", "missing", "x"]).await;
    assert_eq!(
        run.code, 4,
        "a refused publish is a server error: {}",
        run.stderr
    );

    // Cache keys.
    env.felixctl(
        &cluster,
        &[
            "cache", "put", "sessions", "user-1", "in", "--ttl-ms", "600000",
        ],
    )
    .await
    .ok();
    let run = env
        .felixctl(&cluster, &["cache", "get", "sessions", "user-1"])
        .await
        .ok();
    assert_eq!(run.stdout, "in\n");
    let run = env
        .felixctl(&cluster, &["cache", "get", "sessions", "user-1", "--json"])
        .await
        .ok();
    assert_eq!(run.json()["value"], "in");

    let mut args: Vec<String> = vec![
        "cache".into(),
        "put".into(),
        "sessions".into(),
        "user-2".into(),
    ];
    args.extend(env.flags(&cluster));
    env.run(&args, &[], Some(b"from stdin")).await.ok();

    let run = env
        .felixctl(
            &cluster,
            &[
                "cache",
                "watch",
                "sessions",
                "--key",
                "user-2",
                "--retained",
                "--count",
                "1",
                "--json",
            ],
        )
        .await
        .ok();
    assert_eq!(run.json()["value"], "from stdin");
    let run = env
        .felixctl(
            &cluster,
            &[
                "cache",
                "watch",
                "sessions",
                "--prefix",
                "user-",
                "--retained",
                "--count",
                "2",
                "--json",
            ],
        )
        .await
        .ok();
    let mut keys: Vec<String> = run
        .json_lines()
        .iter()
        .map(|change| change["key"].as_str().unwrap().to_string())
        .collect();
    keys.sort();
    assert_eq!(keys, ["user-1", "user-2"]);

    let run = env
        .felixctl(&cluster, &["cache", "del", "sessions", "user-1", "--json"])
        .await
        .ok();
    assert_eq!(run.json()["deleted"], true);
    let run = env
        .felixctl(&cluster, &["cache", "get", "sessions", "user-1"])
        .await;
    assert_eq!(run.code, 5, "a missing key exits 5: {}", run.stderr);

    // Where things live.
    let run = env
        .felixctl(&cluster, &["topology", "orders", "--json"])
        .await
        .ok();
    let topology = run.json();
    assert_eq!(topology["shards"], 1);
    assert_eq!(topology["owners_known"], true);
    let leader = topology["shard_owners"][0]["leader"]
        .as_str()
        .expect("a leader");
    assert!(
        cluster.node_ids().iter().any(|id| id == leader),
        "{topology}"
    );

    let run = env
        .felixctl(&cluster, &["topology", "sessions", "--cache", "--json"])
        .await
        .ok();
    assert_eq!(run.json()["shards"], 2);
    assert_eq!(run.json()["shard_owners"].as_array().unwrap().len(), 2);

    let run = env.felixctl(&cluster, &["topology", "wide"]).await.ok();
    assert!(run.stdout.contains("3 shard(s)"), "{}", run.stdout);
}

#[tokio::test]
#[serial]
async fn groups_and_counters_against_a_cluster() {
    let cluster = Cluster::start(ClusterConfig {
        nodes: 1,
        streams: vec![StreamSpec::new("jobs", 2)],
        caches: vec![CacheSpec::new("stats", 1)],
        ..Default::default()
    })
    .await
    .expect("start cluster");
    let env = Env::new(&cluster);
    let operator = cluster.group_operator_token();
    let op = |args: &[&str]| -> Vec<String> {
        let mut all: Vec<String> = args.iter().map(|a| a.to_string()).collect();
        all.extend(["--token".to_string(), operator.clone()]);
        all
    };

    // Start after the harness's probes, then publish three records. Unkeyed
    // records go to shard 0; idempotent publishes are answered after the
    // write, so a poll right after sees them.
    let args = op(&["group", "create", "jobs", "billing", "--json"]);
    let run = env.felixctl(&cluster, &strs(&args)).await.ok();
    let shards = run.json()["shards"].as_array().unwrap().clone();
    assert_eq!(shards.len(), 2, "{}", run.stdout);
    assert!(
        shards.iter().all(|s| s["created"] == true),
        "{}",
        run.stdout
    );
    for payload in ["a", "b", "c"] {
        env.felixctl(&cluster, &["pub", "jobs", payload, "--idempotent"])
            .await
            .ok();
    }

    let mut polled = Vec::new();
    for _ in 0..20 {
        let run = env
            .felixctl(
                &cluster,
                &[
                    "group",
                    "poll",
                    "jobs",
                    "billing",
                    "--max",
                    "3",
                    "--wait-ms",
                    "500",
                    "--json",
                ],
            )
            .await
            .ok();
        polled.extend(run.json_lines());
        if polled.len() >= 3 {
            break;
        }
    }
    let payloads: Vec<&str> = polled
        .iter()
        .map(|r| r["payload"].as_str().unwrap())
        .collect();
    assert_eq!(payloads, ["a", "b", "c"]);
    let claim = |i: usize| polled[i]["claim"].as_str().unwrap().to_string();
    assert!(
        claim(0).starts_with("0:") && claim(0).ends_with(":1"),
        "{}",
        claim(0)
    );

    // Finish one, hand one back, keep one longer and then give up on it.
    env.felixctl(&cluster, &["group", "ack", "jobs", "billing", &claim(0)])
        .await
        .ok();
    let run = env
        .felixctl(
            &cluster,
            &[
                "group",
                "extend",
                "jobs",
                "billing",
                &claim(2),
                "--for-ms",
                "60000",
                "--json",
            ],
        )
        .await
        .ok();
    assert!(
        run.json()["visible_ms"].as_u64().unwrap() > 0,
        "{}",
        run.stdout
    );
    env.felixctl(&cluster, &["group", "nack", "jobs", "billing", &claim(1)])
        .await
        .ok();
    env.felixctl(
        &cluster,
        &["group", "dead-letters", "add", "jobs", "billing", &claim(2)],
    )
    .await
    .ok();
    let run = env
        .felixctl(
            &cluster,
            &["group", "dead-letters", "ls", "jobs", "billing", "--json"],
        )
        .await
        .ok();
    let dead = run.json()["dead_letters"].as_array().unwrap().clone();
    assert_eq!(dead.len(), 1, "{}", run.stdout);
    let dead_claim = dead[0]["claim"].as_str().unwrap().to_string();
    assert_eq!(dead[0]["offset"], polled[2]["offset"]);

    // The nacked record comes back as a second attempt.
    let run = env
        .felixctl(
            &cluster,
            &[
                "group",
                "poll",
                "jobs",
                "billing",
                "--shard",
                "0",
                "--wait-ms",
                "2000",
                "--json",
            ],
        )
        .await
        .ok();
    let again = run.json_lines();
    assert_eq!(again.len(), 1, "{}", run.stdout);
    assert_eq!(again[0]["payload"], "b");
    assert_eq!(again[0]["attempts"], 2);
    let retry = again[0]["claim"].as_str().unwrap().to_string();
    env.felixctl(&cluster, &["group", "ack", "jobs", "billing", &retry])
        .await
        .ok();

    // Discarding asks first, and nothing can answer here.
    let run = env
        .felixctl(
            &cluster,
            &strs(&op(&[
                "group",
                "dead-letters",
                "discard",
                "jobs",
                "billing",
                &dead_claim,
            ])),
        )
        .await;
    assert_eq!(run.code, 2, "{}", run.stderr);
    let args = op(&[
        "group",
        "dead-letters",
        "discard",
        "jobs",
        "billing",
        &dead_claim,
        "--yes",
    ]);
    env.felixctl(&cluster, &strs(&args)).await.ok();

    let run = env
        .felixctl(
            &cluster,
            &["group", "describe", "jobs", "billing", "--json"],
        )
        .await
        .ok();
    let shard0 = &run.json()["shards"][0];
    assert_eq!(shard0["lag"], 0, "{}", run.stdout);
    assert_eq!(shard0["in_flight"], 0, "{}", run.stdout);
    assert_eq!(shard0["dead_letters"], 0, "{}", run.stdout);
    let run = env
        .felixctl(&cluster, &["group", "describe", "jobs", "billing"])
        .await
        .ok();
    assert!(run.stdout.starts_with("SHARD"), "{}", run.stdout);

    // Back to the start replays finished records, so it needs --yes.
    let args = op(&[
        "group", "seek", "jobs", "billing", "earliest", "--shard", "0",
    ]);
    let run = env.felixctl(&cluster, &strs(&args)).await;
    assert_eq!(run.code, 2, "{}", run.stderr);
    let args = op(&[
        "group", "seek", "jobs", "billing", "earliest", "--shard", "0", "--yes",
    ]);
    env.felixctl(&cluster, &strs(&args)).await.ok();
    // An offset means nothing across two shards.
    let args = op(&["group", "seek", "jobs", "billing", "0", "--yes"]);
    assert_eq!(env.felixctl(&cluster, &strs(&args)).await.code, 2);

    let run = env
        .felixctl(&cluster, &strs(&op(&["group", "rm", "jobs", "billing"])))
        .await;
    assert_eq!(run.code, 2, "{}", run.stderr);
    let args = op(&["group", "rm", "jobs", "billing", "--yes", "--json"]);
    let run = env.felixctl(&cluster, &strs(&args)).await.ok();
    assert_eq!(run.json()["deleted"], true);

    // Counters.
    let run = env
        .felixctl(&cluster, &["counter", "add", "stats", "views", "5"])
        .await
        .ok();
    assert_eq!(run.stdout, "5\n");
    env.felixctl(&cluster, &["counter", "add", "stats", "views", "-2"])
        .await
        .ok();
    let run = env
        .felixctl(&cluster, &["counter", "get", "stats", "views", "--json"])
        .await
        .ok();
    assert_eq!(run.json()["value"], 3);
    let run = env
        .felixctl(&cluster, &["counter", "get", "stats", "never"])
        .await;
    assert_eq!(run.code, 5, "{}", run.stderr);
}

fn strs(args: &[String]) -> Vec<&str> {
    args.iter().map(String::as_str).collect()
}