forklaunch 1.15.0

Launch faster with forklaunch
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
use anyhow::{Context, Result, bail};
use clap::{Arg, ArgMatches, Command};

use crate::{
    CliCommand,
    constants::get_observability_api_url,
    core::{
        command::command,
        http_client::{delete, get, patch, post},
    },
};

#[derive(Debug)]
pub(super) struct KafkaCommand {
    topics: TopicsCommand,
    create_topic: CreateTopicCommand,
    delete_topic: DeleteTopicCommand,
    update_topic_config: UpdateTopicConfigCommand,
    messages: MessagesCommand,
    topic_metadata: TopicMetadataCommand,
    produce: ProduceCommand,
    consumer_groups: ConsumerGroupsCommand,
    reset_offsets: ResetOffsetsCommand,
}

impl KafkaCommand {
    pub(super) fn new() -> Self {
        Self {
            topics: TopicsCommand::new(),
            create_topic: CreateTopicCommand::new(),
            delete_topic: DeleteTopicCommand::new(),
            update_topic_config: UpdateTopicConfigCommand::new(),
            messages: MessagesCommand::new(),
            topic_metadata: TopicMetadataCommand::new(),
            produce: ProduceCommand::new(),
            consumer_groups: ConsumerGroupsCommand::new(),
            reset_offsets: ResetOffsetsCommand::new(),
        }
    }
}

impl CliCommand for KafkaCommand {
    fn command(&self) -> Command {
        command("kafka", "Explore a provisioned Kafka/Redpanda resource")
            .subcommand_required(true)
            .subcommand(self.topics.command())
            .subcommand(self.create_topic.command())
            .subcommand(self.delete_topic.command())
            .subcommand(self.update_topic_config.command())
            .subcommand(self.messages.command())
            .subcommand(self.topic_metadata.command())
            .subcommand(self.produce.command())
            .subcommand(self.consumer_groups.command())
            .subcommand(self.reset_offsets.command())
    }

    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        match matches.subcommand() {
            Some(("topics", m)) => self.topics.handler(m),
            Some(("create-topic", m)) => self.create_topic.handler(m),
            Some(("delete-topic", m)) => self.delete_topic.handler(m),
            Some(("update-topic-config", m)) => self.update_topic_config.handler(m),
            Some(("messages", m)) => self.messages.handler(m),
            Some(("topic-metadata", m)) => self.topic_metadata.handler(m),
            Some(("produce", m)) => self.produce.handler(m),
            Some(("consumer-groups", m)) => self.consumer_groups.handler(m),
            Some(("reset-offsets", m)) => self.reset_offsets.handler(m),
            _ => unreachable!(),
        }
    }
}

fn resource_arg() -> Arg {
    Arg::new("resource")
        .long("resource")
        .required(true)
        .help("The provisioned Kafka resource id")
}

fn explorer_url(resource_id: &str, path: &str) -> String {
    format!(
        "{}/resources/{}/explorer{}",
        get_observability_api_url(),
        urlencoding::encode(resource_id),
        path
    )
}

fn print_pretty(value: &serde_json::Value) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(value)?);
    Ok(())
}

fn check(response: reqwest::blocking::Response) -> Result<serde_json::Value> {
    if !response.status().is_success() {
        bail!(
            "Request failed ({}): {}",
            response.status(),
            response.text().unwrap_or_default()
        );
    }
    response.json().with_context(|| "Failed to parse response")
}

#[derive(Debug)]
struct TopicsCommand;
impl TopicsCommand {
    fn new() -> Self {
        Self
    }
}
impl CliCommand for TopicsCommand {
    fn command(&self) -> Command {
        command("topics", "List topics").arg(resource_arg())
    }
    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let resource = matches.get_one::<String>("resource").context("--resource is required")?;
        let url = explorer_url(resource, "/topics");
        print_pretty(&check(
            get(&url).with_context(|| "Failed to reach observability API")?,
        )?)
    }
}

#[derive(Debug)]
struct CreateTopicCommand;
impl CreateTopicCommand {
    fn new() -> Self {
        Self
    }
}
impl CliCommand for CreateTopicCommand {
    fn command(&self) -> Command {
        command("create-topic", "Create a topic")
            .arg(resource_arg())
            .arg(Arg::new("name").required(true).help("Topic name"))
            .arg(Arg::new("partitions").long("partitions").help("Partition count"))
            .arg(
                Arg::new("replication_factor")
                    .long("replication-factor")
                    .help("Replication factor"),
            )
    }
    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let resource = matches.get_one::<String>("resource").context("--resource is required")?;
        let name = matches.get_one::<String>("name").context("name is required")?;
        let mut body = serde_json::json!({ "topicName": name });
        if let Some(p) = matches.get_one::<String>("partitions") {
            body["partitions"] = serde_json::Value::from(
                p.parse::<u32>().context("--partitions must be an integer")?,
            );
        }
        if let Some(r) = matches.get_one::<String>("replication_factor") {
            body["replicationFactor"] = serde_json::Value::from(
                r.parse::<u32>().context("--replication-factor must be an integer")?,
            );
        }
        let url = explorer_url(resource, "/topics");
        print_pretty(&check(
            post(&url, body)
                .with_context(|| "Failed to reach observability API")?,
        )?)
    }
}

#[derive(Debug)]
struct DeleteTopicCommand;
impl DeleteTopicCommand {
    fn new() -> Self {
        Self
    }
}
impl CliCommand for DeleteTopicCommand {
    fn command(&self) -> Command {
        command("delete-topic", "Delete a topic")
            .arg(resource_arg())
            .arg(Arg::new("name").required(true).help("Topic name"))
    }
    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let resource = matches.get_one::<String>("resource").context("--resource is required")?;
        let name = matches.get_one::<String>("name").context("name is required")?;
        let url = explorer_url(resource, &format!("/topics/{}", urlencoding::encode(name)));
        print_pretty(&check(
            delete(&url)
                .with_context(|| "Failed to reach observability API")?,
        )?)
    }
}

fn parse_config_entries<'a, I: Iterator<Item = &'a String>>(
    entries: Option<I>,
) -> Result<Vec<serde_json::Value>> {
    let configs: Vec<serde_json::Value> = entries
        .map(|entries| {
            entries
                .map(|e| {
                    let (n, v) = e
                        .split_once('=')
                        .with_context(|| format!("--config '{}' must be in <name>=<value> form", e))?;
                    if n.is_empty() {
                        bail!("--config '{}' has an empty name", e);
                    }
                    Ok(serde_json::json!({ "name": n, "value": v }))
                })
                .collect::<Result<Vec<_>>>()
        })
        .transpose()?
        .unwrap_or_default();
    if configs.is_empty() {
        bail!("At least one --config <name>=<value> is required");
    }
    Ok(configs)
}

fn validate_reset_target(target: &str) -> Result<()> {
    if target != "earliest"
        && target != "latest"
        && !matches!(target.parse::<i64>(), Ok(offset) if offset >= 0)
    {
        bail!(
            "--target must be 'earliest', 'latest', or a specific non-negative integer offset, got '{}'",
            target
        );
    }
    Ok(())
}

#[derive(Debug)]
struct UpdateTopicConfigCommand;
impl UpdateTopicConfigCommand {
    fn new() -> Self {
        Self
    }
}
impl CliCommand for UpdateTopicConfigCommand {
    fn command(&self) -> Command {
        command("update-topic-config", "Update a topic's configuration")
            .arg(resource_arg())
            .arg(Arg::new("name").required(true).help("Topic name"))
            .arg(
                Arg::new("config")
                    .long("config")
                    .action(clap::ArgAction::Append)
                    .help("<name>=<value>, repeatable"),
            )
    }
    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let resource = matches.get_one::<String>("resource").context("--resource is required")?;
        let name = matches.get_one::<String>("name").context("name is required")?;
        let configs =
            parse_config_entries(matches.get_many::<String>("config").map(|v| v.into_iter()))?;
        let body = serde_json::json!({ "configs": configs });
        let url = explorer_url(resource, &format!("/topics/{}/config", urlencoding::encode(name)));
        print_pretty(&check(
            patch(&url, body)
                .with_context(|| "Failed to reach observability API")?,
        )?)
    }
}

#[derive(Debug)]
struct MessagesCommand;
impl MessagesCommand {
    fn new() -> Self {
        Self
    }
}
impl CliCommand for MessagesCommand {
    fn command(&self) -> Command {
        command("messages", "Read messages from a topic")
            .arg(resource_arg())
            .arg(Arg::new("name").required(true).help("Topic name"))
            .arg(Arg::new("partition").long("partition").help("Partition number"))
            .arg(Arg::new("offset").long("offset").help("Start offset"))
            .arg(Arg::new("count").long("count").help("Max messages to read"))
            .arg(Arg::new("timestamp").long("timestamp").help("Seek to this timestamp"))
    }
    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let resource = matches.get_one::<String>("resource").context("--resource is required")?;
        let name = matches.get_one::<String>("name").context("name is required")?;
        let mut url = explorer_url(resource, &format!("/topics/{}/messages", urlencoding::encode(name)));
        let mut params = Vec::new();
        for (flag, key) in [
            ("partition", "partition"),
            ("offset", "offset"),
            ("count", "count"),
            ("timestamp", "timestamp"),
        ] {
            if let Some(v) = matches.get_one::<String>(flag) {
                params.push(format!("{}={}", key, urlencoding::encode(v)));
            }
        }
        if !params.is_empty() {
            url.push('?');
            url.push_str(&params.join("&"));
        }
        print_pretty(&check(
            get(&url).with_context(|| "Failed to reach observability API")?,
        )?)
    }
}

#[derive(Debug)]
struct TopicMetadataCommand;
impl TopicMetadataCommand {
    fn new() -> Self {
        Self
    }
}
impl CliCommand for TopicMetadataCommand {
    fn command(&self) -> Command {
        command("topic-metadata", "Get a topic's partition/replica metadata")
            .arg(resource_arg())
            .arg(Arg::new("name").required(true).help("Topic name"))
    }
    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let resource = matches.get_one::<String>("resource").context("--resource is required")?;
        let name = matches.get_one::<String>("name").context("name is required")?;
        let url = explorer_url(resource, &format!("/topics/{}/metadata", urlencoding::encode(name)));
        print_pretty(&check(
            get(&url).with_context(|| "Failed to reach observability API")?,
        )?)
    }
}

#[derive(Debug)]
struct ProduceCommand;
impl ProduceCommand {
    fn new() -> Self {
        Self
    }
}
impl CliCommand for ProduceCommand {
    fn command(&self) -> Command {
        command("produce", "Produce a message to a topic")
            .arg(resource_arg())
            .arg(Arg::new("name").required(true).help("Topic name"))
            .arg(Arg::new("value").required(true).help("Message value"))
            .arg(Arg::new("key").long("key").help("Message key"))
            .arg(Arg::new("partition").long("partition").help("Target partition"))
    }
    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let resource = matches.get_one::<String>("resource").context("--resource is required")?;
        let name = matches.get_one::<String>("name").context("name is required")?;
        let value = matches.get_one::<String>("value").context("value is required")?;
        let mut body = serde_json::json!({ "topicName": name, "value": value });
        if let Some(k) = matches.get_one::<String>("key") {
            body["key"] = serde_json::Value::String(k.clone());
        }
        if let Some(p) = matches.get_one::<String>("partition") {
            body["partition"] = serde_json::Value::from(
                p.parse::<u32>().context("--partition must be an integer")?,
            );
        }
        let url = explorer_url(resource, "/produce");
        print_pretty(&check(
            post(&url, body)
                .with_context(|| "Failed to reach observability API")?,
        )?)
    }
}

#[derive(Debug)]
struct ConsumerGroupsCommand;
impl ConsumerGroupsCommand {
    fn new() -> Self {
        Self
    }
}
impl CliCommand for ConsumerGroupsCommand {
    fn command(&self) -> Command {
        command("consumer-groups", "List consumer groups").arg(resource_arg())
    }
    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let resource = matches.get_one::<String>("resource").context("--resource is required")?;
        let url = explorer_url(resource, "/consumer-groups");
        print_pretty(&check(
            get(&url).with_context(|| "Failed to reach observability API")?,
        )?)
    }
}

#[derive(Debug)]
struct ResetOffsetsCommand;
impl ResetOffsetsCommand {
    fn new() -> Self {
        Self
    }
}
impl CliCommand for ResetOffsetsCommand {
    fn command(&self) -> Command {
        command("reset-offsets", "Reset a consumer group's offsets for a topic")
            .arg(resource_arg())
            .arg(Arg::new("group").required(true).help("Consumer group id"))
            .arg(
                Arg::new("topic")
                    .long("topic")
                    .required(true)
                    .help("Topic name"),
            )
            .arg(
                Arg::new("target")
                    .long("target")
                    .required(true)
                    .help("earliest, latest, or a specific offset"),
            )
    }
    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let resource = matches.get_one::<String>("resource").context("--resource is required")?;
        let group = matches.get_one::<String>("group").context("group is required")?;
        let topic = matches.get_one::<String>("topic").context("--topic is required")?;
        let target = matches.get_one::<String>("target").context("--target is required")?;
        validate_reset_target(target)?;
        let body = serde_json::json!({ "topicName": topic, "target": target });
        let url = explorer_url(resource, &format!("/consumer-groups/{}/offsets", urlencoding::encode(group)));
        print_pretty(&check(
            post(&url, body)
                .with_context(|| "Failed to reach observability API")?,
        )?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn kafka_cmd() -> Command {
        KafkaCommand::new().command().version("0.0.0-test")
    }

    #[test]
    fn command_definition_is_valid() {
        kafka_cmd().debug_assert();
    }

    #[test]
    fn topics_requires_resource() {
        assert!(kafka_cmd().try_get_matches_from(["kafka", "topics"]).is_err());
        assert!(
            kafka_cmd()
                .try_get_matches_from(["kafka", "topics", "--resource", "res-1"])
                .is_ok()
        );
    }

    #[test]
    fn reset_offsets_requires_topic_and_target() {
        assert!(
            kafka_cmd()
                .try_get_matches_from(["kafka", "reset-offsets", "--resource", "res-1", "group-1"])
                .is_err()
        );
        assert!(
            kafka_cmd()
                .try_get_matches_from([
                    "kafka", "reset-offsets", "--resource", "res-1", "group-1", "--topic", "orders",
                    "--target", "earliest"
                ])
                .is_ok()
        );
    }

    #[test]
    fn parse_config_entries_rejects_malformed_or_empty_name() {
        assert!(parse_config_entries::<std::slice::Iter<String>>(None).is_err());
        let missing_eq = vec!["retention.ms".to_string()];
        assert!(parse_config_entries(Some(missing_eq.iter())).is_err());
        let empty_name = vec!["=1000".to_string()];
        assert!(parse_config_entries(Some(empty_name.iter())).is_err());
        let valid = vec!["retention.ms=1000".to_string()];
        assert!(parse_config_entries(Some(valid.iter())).is_ok());
    }

    #[test]
    fn validate_reset_target_accepts_named_or_numeric_only() {
        assert!(validate_reset_target("earliest").is_ok());
        assert!(validate_reset_target("latest").is_ok());
        assert!(validate_reset_target("42").is_ok());
        assert!(validate_reset_target("0").is_ok());
        assert!(validate_reset_target("-1").is_err());
        assert!(validate_reset_target("bogus").is_err());
        assert!(validate_reset_target("").is_err());
    }

    #[test]
    fn produce_requires_value() {
        assert!(
            kafka_cmd()
                .try_get_matches_from(["kafka", "produce", "--resource", "res-1", "orders"])
                .is_err()
        );
        assert!(
            kafka_cmd()
                .try_get_matches_from(["kafka", "produce", "--resource", "res-1", "orders", "hello"])
                .is_ok()
        );
    }
}