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.CreateKeyRequest.scopes"
277 | "ironflowx.v1.KeyInfo.scopes"
278 | "ironflowx.v1.WhoamiResponse.scopes" => {
279 schema["enum"] = json!(["read", "write", "admin", "execute"]);
280 }
281 "ironflowx.v1.RevokeKeyRequest.key_id"
282 | "ironflowx.v1.WhoamiResponse.key_id"
283 | "ironflowx.v1.KeyInfo.key_id"
284 | "ironflowx.v1.GetEventRequest.event_id"
285 | "ironflowx.v1.Event.event_id"
286 | "ironflowx.v1.EmitResponse.event_id"
287 | "ironflowx.v1.Environment.project_id"
288 | "ironflowx.v1.GetRunRequest.run_id"
289 | "ironflowx.v1.StartRunResponse.run_id"
290 | "ironflowx.v1.Run.run_id"
291 | "ironflowx.v1.RunSummary.run_id"
292 | "ironflowx.v1.RunSummary.event_id"
293 | "ironflowx.v1.RunEnd.run_id"
294 | "ironflowx.v1.Claim.run_id" => {
295 schema["pattern"] =
296 json!("^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$");
297 }
298 "ironflowx.v1.Run.status"
299 | "ironflowx.v1.RunSummary.status"
300 | "ironflowx.v1.ListRunsRequest.status" => {
301 schema["enum"] = json!(["queued", "running", "completed", "failed"]);
302 }
303 "ironflowx.v1.RunEnd.status" => {
305 schema["enum"] = json!(["completed", "failed"]);
306 }
307 "ironflowx.v1.KeyInfo.created_by" => {
309 schema["pattern"] = json!(
310 "^(?:[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|embedder:.+)$"
311 );
312 }
313 _ => {}
314 }
315 schema
316}
317
318fn object(message: &MessageDescriptor, shape: Shape) -> Result<Value, CodegenError> {
322 let mut properties = Map::new();
323 let mut required = Vec::new();
324 for field in message.fields() {
325 let name = field.json_name();
326 properties.insert(name.to_owned(), property(&field, shape)?);
327 if shape == Shape::Output && always_printed(&field) {
328 required.push(name.to_owned());
329 }
330 }
331 let mut schema =
332 json!({"additionalProperties": false, "properties": properties, "type": "object"});
333 if !required.is_empty() {
334 schema["required"] = json!(required);
335 }
336 if shape == Shape::Output {
339 let mut groups: Vec<_> = message
340 .oneofs()
341 .filter(|o| !o.is_synthetic())
342 .map(|oneof| {
343 let shapes: Vec<_> = oneof
344 .fields()
345 .map(|f| json!({"required": [f.json_name()]}))
346 .collect();
347 json!(shapes)
348 })
349 .collect();
350 match groups.len() {
352 0 => {}
353 1 => schema["oneOf"] = groups.remove(0),
354 _ => {
355 let each: Vec<_> = groups.into_iter().map(|g| json!({"oneOf": g})).collect();
356 schema["allOf"] = json!(each);
357 }
358 }
359 }
360 Ok(schema)
361}
362
363fn always_printed(field: &FieldDescriptor) -> bool {
365 !field.supports_presence()
366 || matches!(
367 field.full_name(),
368 "ironflowx.v1.CreateKeyResponse.info"
369 | "ironflowx.v1.Environment.created_at"
370 | "ironflowx.v1.Event.data"
371 | "ironflowx.v1.Event.time"
372 | "ironflowx.v1.KeyInfo.created_at"
373 | "ironflowx.v1.PutFunctionResponse.function"
374 | "ironflowx.v1.Function.put_at"
375 | "ironflowx.v1.Run.created_at"
376 | "ironflowx.v1.RunSummary.created_at"
377 | "ironflowx.v1.Claim.lease_until"
378 | "ironflowx.v1.StepCompleted.output"
379 | "ironflowx.v1.StepFailed.error"
380 | "ironflowx.v1.Ended.run"
381 | "ironflowx.v1.CompleteRunResponse.ended"
382 | "ironflowx.v1.Retry.due_at"
383 | "ironflowx.v1.Renewed.lease_until"
384 | "ironflowx.v1.ReleaseRunResponse.due_at"
385 | "ironflowx.v1.WhoamiResponse.key_id"
387 )
388}
389
390fn default(field: &FieldDescriptor) -> Option<&'static str> {
392 if field.is_list() {
393 return Some("[]");
394 }
395 if field.supports_presence() {
396 return None;
397 }
398 Some(match field.kind() {
399 Kind::String => r#""""#,
400 Kind::Bool => "false",
401 Kind::Int64 | Kind::Sint64 | Kind::Sfixed64 | Kind::Uint64 | Kind::Fixed64 => r#""0""#,
402 _ => "0",
403 })
404}
405
406fn fields(message: &MessageDescriptor) -> String {
408 let mut code = Vec::new();
409 for field in message.fields() {
410 let default = default(&field);
411 let kind = match field.kind() {
412 Kind::Message(m) if ours(&m) => format!("Message({})", fields(&m)),
413 Kind::Bool => "Bool".to_owned(),
414 _ if json_text(&field) => "JsonText".to_owned(),
415 _ => "Text".to_owned(),
416 };
417 let (name, list) = (field.json_name(), field.is_list());
418 code.push(format!(
419 "Field {{ name: {name:?}, kind: Kind::{kind}, list: {list}, default: {default:?} }}"
420 ));
421 }
422 format!("&[{}]", code.join(", "))
423}
424
425fn render(methods: &[Method]) -> String {
427 let mut commands = String::new();
428 let mut arms = String::new();
429 for m in methods {
430 let Method {
431 name,
432 command,
433 rpc,
434 summary,
435 example,
436 request,
437 input,
438 output,
439 asked,
440 answer,
441 printed,
442 } = m;
443 let (input, output, example) = (input.to_string(), output.to_string(), example.to_string());
444 writeln!(
445 commands,
446 " Command {{ path: {command:?}, summary: {summary:?}, rpc: {rpc:?}, \
447 input: {input:?}, output: {output:?}, example: {example:?}, request: {asked}, \
448 answer: {printed}, \
449 refusal: |v| serde_json::from_value::<wire::{request}>(v).err() }},"
450 )
451 .expect("a string takes any text");
452 writeln!(
453 arms,
454 " {command:?} => {{\n \
455 let request: wire::{request} = \
456 serde_json::from_str(request).map_err(|e| undecoded(&e))?;\n \
457 let request = request.try_into()?;\n \
458 let answer = wire::{answer}::from(client.{name}(cx, request).await?);\n \
459 serde_json::to_value(answer)\n }}"
460 )
461 .expect("a string takes any text");
462 }
463 format!(
464 "// @generated by ironflowx-codegen from the proto.\n\n\
465 /// Every method of the proto.\n\
466 pub(crate) const COMMANDS: &[Command] = &[\n{commands}];\n\n\
467 /// Calls the operation of `command` with `request`, in wire JSON: its answer, likewise.\n\
468 pub(crate) async fn call(command: &str, client: &Client, cx: &Call, request: &str) \
469 -> Result<serde_json::Value, OpError> {{\n Ok(match command {{\n{arms} \
470 other => unreachable!(\"{{other}} is not in COMMANDS\"),\n }}\n \
471 .expect(\"a wire message is JSON\"))\n}}\n"
472 )
473}