1#![forbid(unsafe_code)]
4
5use std::fmt::{self, Write as _};
6use std::path::Path;
7
8use prost_reflect::{
9 DescriptorPool, DynamicMessage, FieldDescriptor, Kind, MessageDescriptor, MethodDescriptor,
10 Value as OptionValue,
11};
12use serde_json::{Map, Value, json};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct CodegenError {
17 at: String,
18 why: String,
19}
20
21impl fmt::Display for CodegenError {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 write!(f, "{}: {}", self.at, self.why)
24 }
25}
26
27impl std::error::Error for CodegenError {}
28
29fn refused(at: &str, why: impl fmt::Display) -> CodegenError {
30 CodegenError {
31 at: at.to_owned(),
32 why: why.to_string(),
33 }
34}
35
36pub fn generate(descriptor_set: &[u8], out_dir: &Path) -> Result<(), CodegenError> {
46 let code = render(&read(descriptor_set)?);
47 let path = out_dir.join("cli.rs");
48 std::fs::write(&path, code).map_err(|e| refused(&path.to_string_lossy(), e))
49}
50
51#[derive(Debug, PartialEq)]
53struct Method {
54 name: String,
56 command: String,
57 rpc: String,
58 summary: String,
59 example: Value,
60 request: String,
61 input: Value,
63 output: Value,
65 asked: String,
67 answer: String,
68 printed: String,
70}
71
72fn read(descriptor_set: &[u8]) -> Result<Vec<Method>, CodegenError> {
73 let pool = DescriptorPool::decode(descriptor_set).map_err(|e| refused("descriptor set", e))?;
74 let messages = pool.all_messages().filter(ours);
75 for field in messages.flat_map(|m| m.fields().collect::<Vec<_>>()) {
76 check_name(&field)?;
77 }
78 let methods = pool
79 .services()
80 .flat_map(|s| s.methods().collect::<Vec<_>>())
81 .map(|m| read_method(&m))
82 .collect::<Result<Vec<_>, _>>()?;
83 for (i, m) in methods.iter().enumerate() {
84 let taken = |other: &&Method| {
86 let (a, b) = (&m.command, &other.command);
87 a == b || a.starts_with(&format!("{b} ")) || b.starts_with(&format!("{a} "))
88 };
89 if let Some(other) = methods[..i].iter().find(taken) {
90 let why = format!("its command clashes with that of {}", other.name);
91 return Err(refused(&m.name, why));
92 }
93 }
94 Ok(methods)
95}
96
97fn ours(message: &MessageDescriptor) -> bool {
98 message.package_name() != "google.protobuf"
99}
100
101fn check_name(field: &FieldDescriptor) -> Result<(), CodegenError> {
103 let name = field.name();
104 let snake = name
105 .bytes()
106 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
107 if snake && field.json_name() == name {
108 return Ok(());
109 }
110 let why = format!("its json_name, {}, is not snake_case", field.json_name());
111 Err(refused(field.full_name(), why))
112}
113
114fn option(pool: &DescriptorPool, options: &DynamicMessage, name: &str) -> Option<OptionValue> {
116 let extension = pool.get_extension_by_name(&format!("ironflowx.v1.{name}"))?;
117 Some(options.get_extension(&extension).into_owned())
118}
119
120fn read_method(method: &MethodDescriptor) -> Result<Method, CodegenError> {
121 let at = method.full_name();
122 let text = |name: &str| {
123 let set = option(method.parent_pool(), &method.options(), name);
124 let text = set.and_then(|v| v.as_str().map(str::to_owned));
125 text.filter(|t| !t.trim().is_empty())
126 .ok_or_else(|| refused(at, format!("has no (ironflowx.v1.{name})")))
127 };
128 let command = text("cli")?;
129 let part = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_lowercase());
130 if !command.split([' ', '-']).all(part) {
131 return Err(refused(
132 at,
133 "its (ironflowx.v1.cli) is not kebab-case words",
134 ));
135 }
136 let summary = text("summary")?;
137 if summary.contains(char::is_control) {
138 return Err(refused(at, "its (ironflowx.v1.summary) is not one line"));
139 }
140 let example = text("example")?;
141 let example: Value = serde_json::from_str(&example)
142 .map_err(|e| refused(at, format!("its (ironflowx.v1.example) is not JSON: {e}")))?;
143 let input = schema(&method.input(), Shape::Input)?;
144 let validator = jsonschema::options()
145 .with_draft(jsonschema::Draft::Draft202012)
146 .should_validate_formats(true)
147 .build(&input)
148 .expect("a schema this generates is one");
149 if let Err(e) = validator.validate(&example) {
150 let why = format!("its (ironflowx.v1.example) fails its schema: {e}");
151 return Err(refused(at, why));
152 }
153 DynamicMessage::deserialize(method.input(), &example)
155 .map_err(|e| refused(at, format!("its (ironflowx.v1.example) is no request: {e}")))?;
156 Ok(Method {
157 name: snake_case(method.name()),
158 command,
159 rpc: format!("{}/{}", method.parent_service().full_name(), method.name()),
160 summary,
161 example,
162 request: method.input().name().to_owned(),
163 input,
164 output: schema(&method.output(), Shape::Output)?,
165 asked: fields(&method.input()),
166 answer: method.output().name().to_owned(),
167 printed: fields(&method.output()),
168 })
169}
170
171fn snake_case(name: &str) -> String {
172 let mut out = String::new();
173 for c in name.chars() {
174 if c.is_ascii_uppercase() && !out.is_empty() {
175 out.push('_');
176 }
177 out.push(c.to_ascii_lowercase());
178 }
179 out
180}
181
182fn json_text(field: &FieldDescriptor) -> bool {
183 let pool = field.parent_message().parent_pool().clone();
184 option(&pool, &field.options(), "json_text") == Some(OptionValue::Bool(true))
185}
186
187#[derive(Clone, Copy, PartialEq, Eq)]
188enum Shape {
189 Input,
190 Output,
191}
192
193fn schema(message: &MessageDescriptor, shape: Shape) -> Result<Value, CodegenError> {
194 let mut root = object(message, shape)?;
195 root["$schema"] = json!("https://json-schema.org/draft/2020-12/schema");
196 Ok(root)
197}
198
199fn decimal_magnitude(bound: u64) -> String {
201 let bound = bound.to_string();
202 let mut pattern = format!("[0-9]{{1,{}}}", bound.len() - 1);
203 for (i, digit) in bound.bytes().enumerate() {
204 if digit > b'0' {
205 let prefix = &bound[..i];
206 let end = char::from(digit - 1);
207 let remaining = bound.len() - i - 1;
208 write!(pattern, "|{prefix}[0-{end}][0-9]{{{remaining}}}")
209 .expect("a string takes any text");
210 }
211 }
212 format!("{pattern}|{bound}")
213}
214
215fn property(field: &FieldDescriptor, shape: Shape) -> Result<Value, CodegenError> {
217 let schema = match field.kind() {
218 Kind::String if json_text(field) => match shape {
219 Shape::Input => json!({"contentMediaType": "application/json", "type": "string"}),
220 Shape::Output => json!(true),
221 },
222 _ if json_text(field) => return Err(refused(field.full_name(), "JSON text is a string")),
223 Kind::String => json!({"type": "string"}),
224 Kind::Bool => json!({"type": "boolean"}),
225 Kind::Int32 | Kind::Sint32 | Kind::Sfixed32 => {
226 json!({"maximum": i32::MAX, "minimum": i32::MIN, "type": "integer"})
227 }
228 Kind::Uint32 | Kind::Fixed32 => {
229 json!({"maximum": u32::MAX, "minimum": 0, "type": "integer"})
230 }
231 Kind::Int64 | Kind::Sint64 | Kind::Sfixed64 => {
233 let max = decimal_magnitude(i64::MAX.unsigned_abs());
234 let min = decimal_magnitude(i64::MIN.unsigned_abs());
235 json!({"pattern": format!("^(?:0*(?:{max})|-0*(?:{min}))$"), "type": "string"})
236 }
237 Kind::Uint64 | Kind::Fixed64 => {
238 let max = decimal_magnitude(u64::MAX);
239 json!({"pattern": format!("^0*(?:{max})$"), "type": "string"})
240 }
241 Kind::Message(m) if m.full_name() == "google.protobuf.Timestamp" => {
242 json!({
244 "format": "date-time",
245 "not": {"pattern": "^0000-"},
246 "pattern": concat!(
247 r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]",
248 r"(?:\.[0-9]{1,3}0{0,6})?(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])$",
249 ),
250 "type": "string",
251 })
252 }
253 Kind::Message(m) if ours(&m) && !m.is_map_entry() => object(&m, shape)?,
254 kind => {
255 let why = format!("the generator does not know the type {kind:?}");
256 return Err(refused(field.full_name(), why));
257 }
258 };
259 let schema = domain_property(field, schema);
260 Ok(if field.is_list() {
261 json!({"items": schema, "type": "array"})
262 } else {
263 schema
264 })
265}
266
267fn domain_property(field: &FieldDescriptor, mut schema: Value) -> Value {
269 match field.full_name() {
270 "ironflowx.v1.ListEventsRequest.limit"
271 | "ironflowx.v1.ListKeysRequest.limit"
272 | "ironflowx.v1.ListFunctionsRequest.limit"
273 | "ironflowx.v1.ListRunsRequest.limit" => {
274 schema["minimum"] = json!(1);
275 }
276 "ironflowx.v1.Next.request" => {
278 schema = json!({"type": "object"});
279 }
280 "ironflowx.v1.CreateKeyRequest.scopes"
281 | "ironflowx.v1.KeyInfo.scopes"
282 | "ironflowx.v1.WhoamiResponse.scopes"
283 | "ironflowx.v1.Next.scope" => {
284 schema["enum"] = json!(["read", "write", "admin", "execute"]);
285 }
286 "ironflowx.v1.RevokeKeyRequest.key_id"
287 | "ironflowx.v1.WhoamiResponse.key_id"
288 | "ironflowx.v1.KeyInfo.key_id"
289 | "ironflowx.v1.GetEventRequest.event_id"
290 | "ironflowx.v1.Event.event_id"
291 | "ironflowx.v1.EmitResponse.event_id"
292 | "ironflowx.v1.Environment.project_id"
293 | "ironflowx.v1.ForkRunRequest.run_id"
294 | "ironflowx.v1.ForkRunResponse.run_id"
295 | "ironflowx.v1.ForkSource.run_id"
296 | "ironflowx.v1.ForkTarget.run_id"
297 | "ironflowx.v1.JournalCarried.origin"
298 | "ironflowx.v1.JournalForked.event_id"
299 | "ironflowx.v1.GetRunRequest.run_id"
300 | "ironflowx.v1.GetRunJournalRequest.run_id"
301 | "ironflowx.v1.StartRunResponse.run_id"
302 | "ironflowx.v1.Run.run_id"
303 | "ironflowx.v1.RunSummary.run_id"
304 | "ironflowx.v1.RunSummary.event_id"
305 | "ironflowx.v1.JournalCreated.event_id"
306 | "ironflowx.v1.RunEnd.run_id"
307 | "ironflowx.v1.Claim.run_id"
308 | "ironflowx.v1.RelabelRunRequest.run_id"
309 | "ironflowx.v1.ExplainRunRequest.run_id"
310 | "ironflowx.v1.Explanation.run_id" => {
311 schema["pattern"] =
312 json!("^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$");
313 }
314 "ironflowx.v1.Run.status"
315 | "ironflowx.v1.Explanation.status"
316 | "ironflowx.v1.RunSummary.status"
317 | "ironflowx.v1.ListRunsRequest.status" => {
318 schema["enum"] = json!(["queued", "running", "completed", "failed"]);
319 }
320 "ironflowx.v1.RunEnd.status" => {
322 schema["enum"] = json!(["completed", "failed"]);
323 }
324 "ironflowx.v1.KeyInfo.created_by" => {
326 schema["pattern"] = json!(
327 "^(?:[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|embedder:.+)$"
328 );
329 }
330 _ => {}
331 }
332 schema
333}
334
335fn object(message: &MessageDescriptor, shape: Shape) -> Result<Value, CodegenError> {
339 let mut properties = Map::new();
340 let mut required = Vec::new();
341 for field in message.fields() {
342 let name = field.json_name();
343 properties.insert(name.to_owned(), property(&field, shape)?);
344 if shape == Shape::Output && always_printed(&field) {
345 required.push(name.to_owned());
346 }
347 }
348 let mut schema =
349 json!({"additionalProperties": false, "properties": properties, "type": "object"});
350 if !required.is_empty() {
351 schema["required"] = json!(required);
352 }
353 if shape == Shape::Input && message.full_name() == "ironflowx.v1.GetEventRequest" {
355 let selectors: Vec<_> = message
356 .fields()
357 .map(|field| json!({"required": [field.json_name()]}))
358 .collect();
359 schema["oneOf"] = json!(selectors);
360 }
361 if shape == Shape::Output {
364 let mut groups: Vec<_> = message
365 .oneofs()
366 .filter(|o| !o.is_synthetic())
367 .map(|oneof| {
368 let shapes: Vec<_> = oneof
369 .fields()
370 .map(|f| json!({"required": [f.json_name()]}))
371 .collect();
372 json!(shapes)
373 })
374 .collect();
375 match groups.len() {
377 0 => {}
378 1 => schema["oneOf"] = groups.remove(0),
379 _ => {
380 let each: Vec<_> = groups.into_iter().map(|g| json!({"oneOf": g})).collect();
381 schema["allOf"] = json!(each);
382 }
383 }
384 }
385 Ok(schema)
386}
387
388fn always_printed(field: &FieldDescriptor) -> bool {
390 !field.supports_presence()
391 || matches!(
392 field.full_name(),
393 "ironflowx.v1.CreateKeyResponse.info"
394 | "ironflowx.v1.Environment.created_at"
395 | "ironflowx.v1.Event.data"
396 | "ironflowx.v1.Event.time"
397 | "ironflowx.v1.KeyInfo.created_at"
398 | "ironflowx.v1.PutFunctionResponse.function"
399 | "ironflowx.v1.Function.put_at"
400 | "ironflowx.v1.Run.created_at"
401 | "ironflowx.v1.RunSummary.created_at"
402 | "ironflowx.v1.Claim.lease_until"
403 | "ironflowx.v1.StepCompleted.output"
404 | "ironflowx.v1.StepFailed.error"
405 | "ironflowx.v1.Ended.run"
406 | "ironflowx.v1.CompleteRunResponse.ended"
407 | "ironflowx.v1.Retry.due_at"
408 | "ironflowx.v1.Sleeping.due_at"
409 | "ironflowx.v1.Renewed.lease_until"
410 | "ironflowx.v1.ReleaseRunResponse.due_at"
411 | "ironflowx.v1.JournalEntry.at"
412 | "ironflowx.v1.JournalClaimed.lease_until"
413 | "ironflowx.v1.JournalReleased.due_at"
414 | "ironflowx.v1.JournalStepCompleted.output"
415 | "ironflowx.v1.JournalStepFailed.error"
416 | "ironflowx.v1.JournalBodyFailed.error"
417 | "ironflowx.v1.JournalBodyFailed.due_at"
418 | "ironflowx.v1.JournalCompleted.output"
419 | "ironflowx.v1.JournalFailed.error"
420 | "ironflowx.v1.JournalFailed.body_failures"
421 | "ironflowx.v1.RelabelRunResponse.run"
422 | "ironflowx.v1.Next.request"
423 | "ironflowx.v1.WhoamiResponse.key_id"
425 )
426}
427
428fn default(field: &FieldDescriptor) -> Option<&'static str> {
430 if field.is_list() {
431 return Some("[]");
432 }
433 if field.supports_presence() {
434 return None;
435 }
436 Some(match field.kind() {
437 Kind::String => r#""""#,
438 Kind::Bool => "false",
439 Kind::Int64 | Kind::Sint64 | Kind::Sfixed64 | Kind::Uint64 | Kind::Fixed64 => r#""0""#,
440 _ => "0",
441 })
442}
443
444fn fields(message: &MessageDescriptor) -> String {
446 let mut code = Vec::new();
447 for field in message.fields() {
448 let default = default(&field);
449 let kind = match field.kind() {
450 Kind::Message(m) if ours(&m) => format!("Message({})", fields(&m)),
451 Kind::Bool => "Bool".to_owned(),
452 _ if json_text(&field) => "JsonText".to_owned(),
453 _ => "Text".to_owned(),
454 };
455 let (name, list) = (field.json_name(), field.is_list());
456 code.push(format!(
457 "Field {{ name: {name:?}, kind: Kind::{kind}, list: {list}, default: {default:?} }}"
458 ));
459 }
460 format!("&[{}]", code.join(", "))
461}
462
463fn render(methods: &[Method]) -> String {
465 let mut commands = String::new();
466 let mut arms = String::new();
467 for m in methods {
468 let Method {
469 name,
470 command,
471 rpc,
472 summary,
473 example,
474 request,
475 input,
476 output,
477 asked,
478 answer,
479 printed,
480 } = m;
481 let (input, output, example) = (input.to_string(), output.to_string(), example.to_string());
482 writeln!(
483 commands,
484 " Command {{ path: {command:?}, summary: {summary:?}, rpc: {rpc:?}, \
485 input: {input:?}, output: {output:?}, example: {example:?}, request: {asked}, \
486 answer: {printed}, \
487 refusal: |v| serde_json::from_value::<wire::{request}>(v).err() }},"
488 )
489 .expect("a string takes any text");
490 writeln!(
491 arms,
492 " {command:?} => {{\n \
493 let request: wire::{request} = \
494 serde_json::from_str(request).map_err(|e| undecoded(&e))?;\n \
495 let request = request.try_into()?;\n \
496 let answer = wire::{answer}::from(client.{name}(cx, request).await?);\n \
497 serde_json::to_value(answer)\n }}"
498 )
499 .expect("a string takes any text");
500 }
501 format!(
502 "// @generated by ironflowx-codegen from the proto.\n\n\
503 /// Every method of the proto.\n\
504 pub(crate) const COMMANDS: &[Command] = &[\n{commands}];\n\n\
505 /// Calls the operation of `command` with `request`, in wire JSON: its answer, likewise.\n\
506 pub(crate) async fn call(command: &str, client: &Client, cx: &Call, request: &str) \
507 -> Result<serde_json::Value, OpError> {{\n Ok(match command {{\n{arms} \
508 other => unreachable!(\"{{other}} is not in COMMANDS\"),\n }}\n \
509 .expect(\"a wire message is JSON\"))\n}}\n"
510 )
511}