1use std::collections::HashMap;
7
8use crate::cli::InitArgs;
9use crate::error::{CliError, CliResult};
10#[cfg(feature = "cli-interactive")]
11use crate::init_template::discover_tagged_enum_fields;
12use crate::init_template::schema_to_yaml_template_with_choices;
13use crate::registry;
14
15const DEFAULT_SOURCE: &str = "rest";
16const DEFAULT_SINK: &str = "jsonl";
17const DEFAULT_NAME: &str = "my-pipeline";
18const CONFIG_INDENT: usize = 8;
19
20pub async fn run(args: InitArgs) -> CliResult<()> {
22 if args.output.exists() && !args.force {
23 return Err(CliError::ScaffoldExists {
24 path: args.output.clone(),
25 });
26 }
27
28 if args.discover {
29 return run_singer_discover(&args).await;
30 }
31
32 let (source_kind, sink_kind) = resolve_kinds(&args)?;
33 let name = args.name.as_deref().unwrap_or(DEFAULT_NAME);
34 let template = &args.template;
35
36 let source_schema = registry::source_schema(&source_kind)?;
37 let sink_schema = registry::sink_schema(&sink_kind)?;
38 let (source_choices, sink_choices) = if args.interactive {
39 interactive_variant_choices(&source_schema, &sink_schema)?
40 } else {
41 (HashMap::new(), HashMap::new())
42 };
43
44 let body = render_pipeline(
45 name,
46 template,
47 &source_kind,
48 &source_schema,
49 &source_choices,
50 &sink_kind,
51 &sink_schema,
52 &sink_choices,
53 );
54 std::fs::write(&args.output, body)?;
55 println!("wrote {}", args.output.display());
56 Ok(())
57}
58
59#[cfg(feature = "source-singer")]
63async fn run_singer_discover(args: &InitArgs) -> CliResult<()> {
64 let source_kind = args.source.as_deref().unwrap_or("singer");
65 if source_kind != "singer" {
66 return Err(CliError::Config(format!(
67 "`--discover` is only supported for `--source singer` (got `{source_kind}`)"
68 )));
69 }
70 let executable = args.executable.as_deref().ok_or_else(|| {
71 CliError::Config("`--discover` requires `--executable <tap>`".to_string())
72 })?;
73
74 let cfg = faucet_source_singer::SingerSourceConfig::new(executable, "");
75 let catalog = faucet_source_singer::discover(&cfg).await?; let streams = faucet_source_singer::catalog_stream_ids(&catalog);
77
78 let catalog_path = match args.output.parent() {
80 Some(dir) if !dir.as_os_str().is_empty() => dir.join("catalog.json"),
81 _ => std::path::PathBuf::from("catalog.json"),
82 };
83 let catalog_json = serde_json::to_string_pretty(&catalog)
84 .map_err(|e| CliError::Config(format!("failed to serialize catalog: {e}")))?;
85 std::fs::write(&catalog_path, catalog_json)?;
86
87 let catalog_inline = serde_json::to_string(&catalog)
91 .map_err(|e| CliError::Config(format!("failed to serialize catalog: {e}")))?;
92 let name = args.name.as_deref().unwrap_or(DEFAULT_NAME);
93 let body = render_singer_config(name, executable, &catalog_inline, &streams);
94 std::fs::write(&args.output, body)?;
95
96 println!(
97 "discovered {} stream(s): {}",
98 streams.len(),
99 if streams.is_empty() {
100 "(none)".to_string()
101 } else {
102 streams.join(", ")
103 }
104 );
105 println!(
106 "wrote {} and {}",
107 catalog_path.display(),
108 args.output.display()
109 );
110 Ok(())
111}
112
113#[cfg(not(feature = "source-singer"))]
114async fn run_singer_discover(_args: &InitArgs) -> CliResult<()> {
115 Err(CliError::Config(
116 "`--discover` requires the `source-singer` build feature".to_string(),
117 ))
118}
119
120#[cfg(feature = "source-singer")]
125fn render_singer_config(
126 name: &str,
127 executable: &str,
128 catalog_inline: &str,
129 streams: &[String],
130) -> String {
131 let discovered = if streams.is_empty() {
132 "(none discovered)".to_string()
133 } else {
134 streams.join(", ")
135 };
136 format!(
137 "version: 1\n\
138 name: {name}\n\
139 pipeline:\n\
140 \x20 source:\n\
141 \x20 type: singer\n\
142 \x20 config:\n\
143 \x20 executable: {executable}\n\
144 \x20 # Discovered catalog, inlined as compact JSON (also saved to catalog.json).\n\
145 \x20 catalog: {catalog_inline}\n\
146 \x20 # stream is REQUIRED. Discovered streams: {discovered}\n\
147 \x20 # Set it to one of the above; leaving it empty fails `faucet doctor`.\n\
148 \x20 stream: \"\"\n\
149 \x20 # The tap's own config (secret-resolved by faucet). Fill in as the tap needs:\n\
150 \x20 tap_config: {{}}\n\
151 \x20 sink:\n\
152 \x20 type: jsonl\n\
153 \x20 config:\n\
154 \x20 path: ./out/records.jsonl\n"
155 )
156}
157
158fn resolve_kinds(args: &InitArgs) -> CliResult<(String, String)> {
159 let source = args.source.clone();
160 let sink = args.sink.clone();
161
162 let (source, sink) = if args.interactive {
163 interactive_prompt(source, sink)?
164 } else {
165 (
166 source.unwrap_or_else(|| DEFAULT_SOURCE.to_string()),
167 sink.unwrap_or_else(|| DEFAULT_SINK.to_string()),
168 )
169 };
170
171 if !registry::source_exists(&source) {
172 return Err(unknown_kind_err("source", &source));
173 }
174 if !registry::sink_exists(&sink) {
175 return Err(unknown_kind_err("sink", &sink));
176 }
177 Ok((source, sink))
178}
179
180#[cfg(feature = "cli-interactive")]
181fn interactive_prompt(source: Option<String>, sink: Option<String>) -> CliResult<(String, String)> {
182 use std::io::IsTerminal;
183 if !std::io::stdin().is_terminal() {
184 return fallback_kinds(source, sink, "stdin is not a TTY");
185 }
186 let sources = registry::source_kinds();
187 let sinks = registry::sink_kinds();
188 let s = if let Some(s) = source {
189 s
190 } else {
191 prompt_select("source", &sources)?
192 };
193 let k = if let Some(k) = sink {
194 k
195 } else {
196 prompt_select("sink", &sinks)?
197 };
198 Ok((s, k))
199}
200
201#[cfg(not(feature = "cli-interactive"))]
202fn interactive_prompt(source: Option<String>, sink: Option<String>) -> CliResult<(String, String)> {
203 fallback_kinds(
204 source,
205 sink,
206 "the `cli-interactive` build feature is not enabled",
207 )
208}
209
210fn fallback_kinds(
211 source: Option<String>,
212 sink: Option<String>,
213 reason: &str,
214) -> CliResult<(String, String)> {
215 match (source, sink) {
216 (Some(s), Some(k)) => Ok((s, k)),
217 (s, k) => {
218 tracing::warn!(
219 "ignoring --interactive: {reason}; falling back to --source/--sink (or defaults)"
220 );
221 Ok((
222 s.unwrap_or_else(|| DEFAULT_SOURCE.to_string()),
223 k.unwrap_or_else(|| DEFAULT_SINK.to_string()),
224 ))
225 }
226 }
227}
228
229#[cfg(feature = "cli-interactive")]
230fn prompt_select(kind: &str, options: &[&'static str]) -> CliResult<String> {
231 let choice = inquire::Select::new(&format!("Pick a {kind} connector"), options.to_vec())
232 .prompt()
233 .map_err(|e| CliError::Io(std::io::Error::other(e.to_string())))?;
234 Ok(choice.to_string())
235}
236
237#[cfg(feature = "cli-interactive")]
238fn interactive_variant_choices(
239 source_schema: &serde_json::Value,
240 sink_schema: &serde_json::Value,
241) -> CliResult<(HashMap<String, String>, HashMap<String, String>)> {
242 use std::io::IsTerminal;
243 if !std::io::stdin().is_terminal() {
244 return Ok((HashMap::new(), HashMap::new()));
245 }
246 let source = prompt_variants_for("source", source_schema)?;
247 let sink = prompt_variants_for("sink", sink_schema)?;
248 Ok((source, sink))
249}
250
251#[cfg(not(feature = "cli-interactive"))]
252fn interactive_variant_choices(
253 _source_schema: &serde_json::Value,
254 _sink_schema: &serde_json::Value,
255) -> CliResult<(HashMap<String, String>, HashMap<String, String>)> {
256 tracing::warn!("ignoring --interactive: the `cli-interactive` build feature is not enabled");
257 Ok((HashMap::new(), HashMap::new()))
258}
259
260#[cfg(feature = "cli-interactive")]
261fn prompt_variants_for(
262 side: &str,
263 schema: &serde_json::Value,
264) -> CliResult<HashMap<String, String>> {
265 let fields = discover_tagged_enum_fields(schema);
266 let mut choices = HashMap::new();
267 for field in fields {
268 let label = format!("Pick a variant for {side}.{}", field.path);
269 let opts: Vec<String> = field.variants.clone();
270 let chosen = inquire::Select::new(&label, opts)
271 .prompt()
272 .map_err(|e| CliError::Io(std::io::Error::other(e.to_string())))?;
273 choices.insert(field.path, chosen);
274 }
275 Ok(choices)
276}
277
278fn unknown_kind_err(kind: &'static str, name: &str) -> CliError {
279 let available = if kind == "source" {
280 registry::source_kinds()
281 } else {
282 registry::sink_kinds()
283 };
284 CliError::UnknownConnector {
285 kind,
286 name: name.to_owned(),
287 available: if available.is_empty() {
288 "(none — rebuild faucet-cli with the relevant feature enabled)".to_owned()
289 } else {
290 available.join(", ")
291 },
292 }
293}
294
295#[allow(clippy::too_many_arguments)]
296fn render_pipeline(
297 name: &str,
298 template: &str,
299 source_kind: &str,
300 source_schema: &serde_json::Value,
301 source_choices: &HashMap<String, String>,
302 sink_kind: &str,
303 sink_schema: &serde_json::Value,
304 sink_choices: &HashMap<String, String>,
305) -> String {
306 let source_yaml =
307 schema_to_yaml_template_with_choices(source_schema, CONFIG_INDENT, source_choices);
308 let sink_yaml = schema_to_yaml_template_with_choices(sink_schema, CONFIG_INDENT, sink_choices);
309
310 let mut body = String::new();
311 body.push_str("version: 1\n");
312 body.push_str(&format!("name: {name}\n\n"));
313 body.push_str("# Optional shared constants. Reference these anywhere via ${vars.KEY}.\n");
314 body.push_str("# vars:\n");
315 body.push_str("# api_base: https://api.example.com\n\n");
316 body.push_str("# Named source/sink templates. Matrix rows pick from these via ref:.\n");
317 body.push_str("# A matrix row that omits ref: inherits the `default` template,\n");
318 body.push_str("# which keeps backwards-compat with the legacy singular shape.\n");
319 body.push_str("pipeline:\n");
320 body.push_str(" sources:\n");
321 body.push_str(&format!(" {template}:\n"));
322 body.push_str(&format!(" type: {source_kind}\n"));
323 body.push_str(" config:\n");
324 body.push_str(&source_yaml);
325 body.push('\n');
326 body.push_str(" # transforms:\n");
327 body.push_str(" # - { type: keys_case, config: { mode: snake } }\n\n");
328 body.push_str(" sinks:\n");
329 body.push_str(&format!(" {template}:\n"));
330 body.push_str(&format!(" type: {sink_kind}\n"));
331 body.push_str(" config:\n");
332 body.push_str(&sink_yaml);
333 body.push('\n');
334 body.push_str(" # Optional state store (required by CDC sources and resumable runs).\n");
335 body.push_str(" # state:\n");
336 body.push_str(" # type: file\n");
337 body.push_str(" # config: { path: ./.faucet-state }\n\n");
338 body.push_str(" # Optional Dead Letter Queue.\n");
339 body.push_str(" # dlq:\n");
340 body.push_str(" # sink:\n");
341 body.push_str(" # type: jsonl\n");
342 body.push_str(" # config: { path: ./dlq.jsonl }\n");
343 body.push_str(" # on_batch_error: propagate # or dlq_all\n\n");
344 body.push_str("# Optional matrix block. Each row picks a template via ref:\n");
345 body.push_str("# (omit ref: to inherit the `default` template above) and may\n");
346 body.push_str("# override `type:` / `config:` per row.\n");
347 body.push_str("# matrix:\n");
348 body.push_str("# - id: users\n");
349 body.push_str(&format!(
350 "# source: {{ ref: {template}, config: {{ path: /v1/users }} }}\n"
351 ));
352 body
353}