crucible-codegen-cdk 0.10.1

Jsii-compatible CDK construct emitter for crucible resources
Documentation
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
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;

use crucible_codegen_infra::{Plan, Property};
use crucible_ir::{
    Diagnostics, ShapeId,
    ir::{Constraints, Service, Shape, SimpleKind, TimestampFormat},
};
use serde_json::{Value, json};

pub fn emit(service: &Service, plan: &Plan, diagnostics: &mut Diagnostics) -> String {
    let mut output = String::from(
        "// Generated by crucible. Do not edit.\nimport { CfnResource, IResolvable } from 'aws-cdk-lib';\nimport { Construct } from 'constructs';\nimport { toWire, validate } from './validation';\n\n",
    );
    let mut reachable = BTreeSet::new();
    let mut names = BTreeMap::new();
    if !plan.resources.iter().any(|resource| resource.cdk.is_some()) {
        diagnostics.push(&service.id, "provisioning bindings select no CDK resources");
    }
    for resource in &plan.resources {
        let Some(cdk) = &resource.cdk else {
            continue;
        };
        let class = cdk
            .class_name
            .clone()
            .unwrap_or_else(|| format!("Cfn{}", resource.name));
        register(&class, &resource.id, &mut names, diagnostics);
        if !cdk.resource_type.starts_with("Custom::")
            || cdk.resource_type.len() > 60
            || cdk.resource_type.len() == 8
            || !cdk.resource_type[8.min(cdk.resource_type.len())..]
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || "_@-".contains(c))
        {
            diagnostics.push(
                &resource.id,
                "CDK resource_type must be a Custom:: resource name of at most 60 characters",
            );
        }
        register(
            &format!("{class}Props"),
            &resource.id,
            &mut names,
            diagnostics,
        );
        for property in resource.properties.values().chain(cdk.context.values()) {
            visit(service, &property.target, &mut reachable, diagnostics);
        }
        for (name, attribute) in &resource.attributes {
            if !matches!(service.shape(&attribute.target), Some(Shape::Simple(s)) if matches!(s.kind, SimpleKind::String | SimpleKind::Timestamp))
                && !matches!(service.shape(&attribute.target), Some(Shape::Enum(_)))
                && prelude_kind(&attribute.target) != Some("string")
            {
                diagnostics.push(&resource.id, format!("CDK attribute `{name}` must target a string; other attribute representations are not supported"));
            }
        }
    }
    for id in &reachable {
        if let Some(Shape::Structure(shape)) = service.shape(id) {
            let name = format!("{}Property", service.name_of(id));
            register(&name, id, &mut names, diagnostics);
            docs(&mut output, shape.docs.as_deref(), "", Some("@struct"));
            writeln!(output, "export interface {name} {{").unwrap();
            let mut member_names = BTreeSet::new();
            for member in &shape.members {
                let member_name = &public_name(&member.name);
                check_member(member_name, id, diagnostics);
                if !member_names.insert(member_name.clone()) {
                    diagnostics.push(
                        id,
                        format!("CDK member `{}` collides at `{member_name}`", member.name),
                    );
                }
                docs(&mut output, member.docs.as_deref(), "  ", None);
                writeln!(
                    output,
                    "  readonly {member_name}{}: {};",
                    if member.optional_on_server() { "?" } else { "" },
                    member_type(service, member, &mut BTreeSet::new())
                )
                .unwrap();
            }
            output.push_str("}\n\n");
        }
    }
    let mut schemas = BTreeMap::new();
    for id in &reachable {
        schemas.insert(id.to_string(), shape_schema(service, id));
    }
    writeln!(
        output,
        "const schemas = {};\n",
        crucible_codegen_common::source_json(&serde_json::to_string(&schemas).unwrap())
    )
    .unwrap();
    for resource in &plan.resources {
        let Some(cdk) = &resource.cdk else {
            continue;
        };
        let class = cdk
            .class_name
            .clone()
            .unwrap_or_else(|| format!("Cfn{}", resource.name));
        let properties: BTreeMap<_, _> = resource
            .properties
            .iter()
            .chain(cdk.context.iter())
            .collect();
        let mut property_names = BTreeSet::from(["serviceToken".to_owned()]);
        writeln!(output, "/** @struct */\nexport interface {class}Props {{\n  /** ARN of the provider implementing this resource contract. */\n  readonly serviceToken: string;").unwrap();
        for (name, property) in &properties {
            let public = public_name(name);
            check_member(&public, &resource.id, diagnostics);
            if !property_names.insert(public.clone()) || *name == "ServiceToken" {
                diagnostics.push(
                    &resource.id,
                    format!("CDK property `{name}` collides with another property or ServiceToken"),
                );
            }
            docs(
                &mut output,
                property.docs.as_deref(),
                "  ",
                if property.immutable {
                    Some("Changing this value requires provider-defined replacement.")
                } else {
                    None
                },
            );
            writeln!(
                output,
                "  readonly {public}{}: {};",
                if property.required { "" } else { "?" },
                property
                    .timestamp_format
                    .map(timestamp_type)
                    .map(str::to_owned)
                    .unwrap_or_else(|| type_of(service, &property.target, &mut BTreeSet::new()))
            )
            .unwrap();
        }
        writeln!(output, "}}\n\nexport class {class} extends CfnResource {{").unwrap();
        writeln!(
            output,
            "  public static readonly CFN_RESOURCE_TYPE_NAME: string = {};",
            quote(&cdk.resource_type)
        )
        .unwrap();
        let mut attributes = BTreeSet::new();
        for name in resource.attributes.keys() {
            let attr = format!("attr{}", upper_first(&public_name(name)));
            check_member(&attr, &resource.id, diagnostics);
            if !attributes.insert(attr.clone()) {
                diagnostics.push(&resource.id, format!("CDK attributes collide at `{attr}`"));
            }
            if upper_first(&attr) == class {
                diagnostics.push(
                    &resource.id,
                    format!("CDK attribute `{attr}` collides with its enclosing class in .NET"),
                );
            }
            writeln!(output, "  public readonly {attr}: string;").unwrap();
        }
        writeln!(output, "\n  public constructor(scope: Construct, id: string, props: {class}Props) {{\n    super(scope, id, {{\n      type: {},\n      properties: {{\n        ServiceToken: props.serviceToken,", quote(&cdk.resource_type)).unwrap();
        for (name, property) in &properties {
            // Nested members are spelled for jsii; the provider receives wire names.
            writeln!(
                output,
                "        {}: toWire(props.{}, {}, schemas),",
                quote(name),
                public_name(name),
                quote(&property.target.to_string())
            )
            .unwrap();
        }
        output.push_str("      },\n    });\n    validate(props.serviceToken, { kind: 'string' }, schemas, 'serviceToken', true);\n");
        for (name, property) in &properties {
            writeln!(
                output,
                "    validate(props.{}, {}, schemas, {}, {});",
                public_name(name),
                crucible_codegen_common::source_json(
                    &property_schema(service, property).to_string()
                ),
                quote(&public_name(name)),
                property.required
            )
            .unwrap();
        }
        for name in resource.attributes.keys() {
            writeln!(
                output,
                "    this.attr{} = this.getAttString({});",
                upper_first(&public_name(name)),
                quote(name)
            )
            .unwrap();
        }
        output.push_str("  }\n\n  /** A deployment-time string attribute returned by the provider. */\n  public getAttString(attributeName: string): string {\n    return this.getAtt(attributeName).toString();\n  }\n}\n\n");
    }
    if output.matches("IResolvable").count() == 1 {
        output = output.replace("CfnResource, IResolvable", "CfnResource");
    }
    output.truncate(output.trim_end().len());
    output.push('\n');
    output
}

/// The jsii-strict (lowerCamelCase) spelling of a wire name. Snake_case wire
/// names are what the Terraform generator requires, so both spellings must
/// derive from one binding.
fn public_name(name: &str) -> String {
    let mut parts = name.split('_').filter(|part| !part.is_empty());
    let mut result = String::new();
    if let Some(first) = parts.next() {
        let mut chars = first.chars();
        if let Some(c) = chars.next() {
            result.extend(c.to_lowercase());
            result.extend(chars);
        }
    }
    for part in parts {
        let part = if part.chars().all(|c| !c.is_lowercase()) {
            part.to_lowercase()
        } else {
            part.to_owned()
        };
        result.push_str(&upper_first(&part));
    }
    result
}
fn upper_first(name: &str) -> String {
    let mut chars = name.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().chain(chars).collect(),
        None => String::new(),
    }
}
fn identifier(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .enumerate()
            .all(|(i, c)| c.is_ascii_alphabetic() || c == '_' || (i > 0 && c.is_ascii_digit()))
}
fn check_member(name: &str, id: &ShapeId, diagnostics: &mut Diagnostics) {
    if !identifier(name) || ["constructor", "prototype", "__proto__"].contains(&name) {
        diagnostics.push(id, format!("`{name}` is not a supported CDK member name"));
    }
}
fn register(
    name: &str,
    id: &ShapeId,
    names: &mut BTreeMap<String, ShapeId>,
    diagnostics: &mut Diagnostics,
) {
    if !identifier(name)
        || !name.starts_with(char::is_uppercase)
        || ["CfnResource", "IResolvable", "Construct"].contains(&name)
    {
        diagnostics.push(id, format!("`{name}` is not a supported CDK type name"));
    }
    if names.insert(name.into(), id.clone()).is_some() {
        diagnostics.push(id, format!("duplicate CDK type name `{name}`"));
    }
}
fn docs(output: &mut String, text: Option<&str>, indent: &str, extra: Option<&str>) {
    if text.is_none() && extra.is_none() {
        return;
    }
    writeln!(output, "{indent}/**").unwrap();
    // Model text as a comment carries it: line breaks normalised, BOM,
    // control and bidirectional characters dropped.
    let text = crucible_codegen_common::docs::comment_text(text.unwrap_or_default());
    for line in text.lines() {
        writeln!(
            output,
            "{indent} * {}",
            line.replace("*/", "* /").replace('@', "&#64;")
        )
        .unwrap();
    }
    if let Some(extra) = extra {
        writeln!(output, "{indent} * {extra}").unwrap();
    }
    writeln!(output, "{indent} */").unwrap();
}
fn quote(value: &str) -> String {
    crucible_codegen_common::quoted(value)
}

fn visit(
    service: &Service,
    id: &ShapeId,
    seen: &mut BTreeSet<ShapeId>,
    diagnostics: &mut Diagnostics,
) {
    if !seen.insert(id.clone()) {
        return;
    }
    if collection_cycle(service, id, &mut BTreeSet::new()) {
        diagnostics.push(
            id,
            "recursive collection aliases are not supported by the CDK jsii type system",
        );
    }
    match service.shape(id) {
        None if prelude_kind(id).is_some() => {},
        Some(Shape::Simple(simple)) if matches!(simple.kind, SimpleKind::Document | SimpleKind::Blob) => diagnostics.push(id, "CDK properties do not yet support document or blob targets; use an explicit string representation in the provisioning model"),
        Some(Shape::Simple(_)) | Some(Shape::Enum(_)) => {},
        Some(Shape::Structure(s)) => for member in &s.members { visit(service, &member.target, seen, diagnostics); },
        Some(Shape::List(s)) => { if s.sparse { diagnostics.push(id,"CDK sparse lists are not supported"); } visit(service, &s.member.target, seen, diagnostics); },
        Some(Shape::Map(s)) => { if s.sparse { diagnostics.push(id,"CDK sparse maps are not supported"); } visit(service, &s.key.target, seen, diagnostics); visit(service, &s.value.target, seen, diagnostics); },
        _ => diagnostics.push(id, "unsupported CDK property target (union, unit or missing shape)"),
    }
}

fn collection_cycle(service: &Service, id: &ShapeId, chain: &mut BTreeSet<ShapeId>) -> bool {
    let next = match service.shape(id) {
        Some(Shape::List(list)) => &list.member.target,
        Some(Shape::Map(map)) => &map.value.target,
        _ => return false,
    };
    if !chain.insert(id.clone()) {
        return true;
    }
    collection_cycle(service, next, chain)
}
fn type_of(service: &Service, id: &ShapeId, chain: &mut BTreeSet<ShapeId>) -> String {
    if !chain.insert(id.clone()) {
        return "IResolvable".into();
    }
    let result = match service.shape(id) {
        None if prelude_kind(id).is_some() => match prelude_kind(id).unwrap() {
            "boolean" => "boolean | IResolvable",
            kind => kind,
        }
        .into(),
        Some(Shape::Simple(s)) => match s.kind {
            SimpleKind::String => "string",
            SimpleKind::Boolean => "boolean | IResolvable",
            SimpleKind::Timestamp => {
                timestamp_type(s.timestamp_format.unwrap_or(TimestampFormat::DateTime))
            }
            _ => "number",
        }
        .into(),
        Some(Shape::Enum(_)) => "string".into(),
        Some(Shape::Structure(_)) => format!("{}Property | IResolvable", service.name_of(id)),
        Some(Shape::List(s)) => format!(
            "Array<{}> | IResolvable",
            member_type(service, &s.member, chain)
        ),
        Some(Shape::Map(s)) => format!(
            "{{ [key: string]: {} }} | IResolvable",
            member_type(service, &s.value, chain)
        ),
        _ => "IResolvable".into(),
    };
    chain.remove(id);
    result
}
fn constraints(value: &Constraints) -> Value {
    json!({"minLength":value.length.as_ref().and_then(|b| b.min), "maxLength":value.length.as_ref().and_then(|b| b.max), "min":value.range.as_ref().and_then(|b| b.min.as_ref()), "max":value.range.as_ref().and_then(|b| b.max.as_ref()), "pattern":value.pattern, "unique":value.unique_items})
}
/// Bounds of the fixed-width integer types. Long is bounded by the
/// safe-integer check alone, since a JavaScript number cannot hold its range.
fn integer_range(service: &Service, id: &ShapeId) -> Option<[i64; 2]> {
    let kind = match service.shape(id) {
        Some(Shape::Simple(s)) => s.kind,
        None if id.is_prelude() && id.name() == "Integer" => SimpleKind::Integer,
        _ => return None,
    };
    match kind {
        SimpleKind::Byte => Some([i8::MIN.into(), i8::MAX.into()]),
        SimpleKind::Short => Some([i16::MIN.into(), i16::MAX.into()]),
        SimpleKind::Integer => Some([i32::MIN.into(), i32::MAX.into()]),
        _ => None,
    }
}
fn property_schema(service: &Service, property: &Property) -> Value {
    json!({"target": property.target.to_string(), "constraints":constraints(&property.constraints), "enumValues":property.enum_values, "integer":property.integer, "intRange":integer_range(service, &property.target), "timestamp":property.timestamp_format.map(timestamp_name)})
}
fn shape_schema(service: &Service, id: &ShapeId) -> Value {
    match service.shape(id) {
        None if prelude_kind(id).is_some() => {
            json!({"kind":prelude_kind(id),"integer":matches!(id.name(),"Integer"|"Long"),"intRange":integer_range(service, id)})
        }
        Some(Shape::Simple(s)) => {
            json!({"kind": match s.kind { SimpleKind::String => "string", SimpleKind::Boolean => "boolean", SimpleKind::Timestamp => "timestamp", _ => "number" }, "timestamp":if s.kind == SimpleKind::Timestamp {Some(timestamp_name(s.timestamp_format.unwrap_or(TimestampFormat::DateTime)))} else {None}, "integer":matches!(s.kind,SimpleKind::Byte|SimpleKind::Short|SimpleKind::Integer|SimpleKind::Long), "intRange":integer_range(service, id), "constraints":constraints(&s.constraints)})
        }
        Some(Shape::Enum(s)) => {
            json!({"kind":"string", "enumValues":s.values.iter().map(|v| &v.value).collect::<Vec<_>>()})
        }
        Some(Shape::Structure(s)) => {
            json!({"kind":"object", "members":s.members.iter().map(|m| (public_name(&m.name),member_schema(service,m))).collect::<BTreeMap<_,_>>()})
        }
        Some(Shape::List(s)) => {
            json!({"kind":"array", "element":member_schema(service,&s.member), "constraints":constraints(&s.constraints)})
        }
        Some(Shape::Map(s)) => {
            json!({"kind":"map", "key":member_schema(service,&s.key), "element":member_schema(service,&s.value), "constraints":constraints(&s.constraints)})
        }
        _ => json!({}),
    }
}

fn timestamp_type(format: TimestampFormat) -> &'static str {
    if format == TimestampFormat::EpochSeconds {
        "number"
    } else {
        "string"
    }
}
fn timestamp_name(format: TimestampFormat) -> &'static str {
    match format {
        TimestampFormat::EpochSeconds => "epoch-seconds",
        TimestampFormat::DateTime => "date-time",
        TimestampFormat::HttpDate => "http-date",
    }
}
fn member_type(
    service: &Service,
    member: &crucible_ir::ir::Member,
    chain: &mut BTreeSet<ShapeId>,
) -> String {
    if matches!(service.shape(&member.target),Some(Shape::Simple(s)) if s.kind == SimpleKind::Timestamp)
    {
        timestamp_type(service.timestamp_format(member)).into()
    } else {
        type_of(service, &member.target, chain)
    }
}
fn member_schema(service: &Service, member: &crucible_ir::ir::Member) -> Value {
    json!({"wire":member.name, "target":member.target.to_string(), "required":!member.optional_on_server(), "constraints":constraints(&member.constraints), "timestamp":if matches!(service.shape(&member.target),Some(Shape::Simple(s)) if s.kind == SimpleKind::Timestamp) {Some(timestamp_name(service.timestamp_format(member)))} else {None}})
}

fn prelude_kind(id: &ShapeId) -> Option<&'static str> {
    if !id.is_prelude() {
        return None;
    }
    match id.name() {
        "String" => Some("string"),
        "Boolean" => Some("boolean"),
        "Integer" | "Long" | "Double" => Some("number"),
        _ => None,
    }
}