1use crate::{TypeRegistry, checking::AdamCheckingEnvironment, checking_environment};
35use cel_parser::{
36 OpLookup,
37 checking::{
38 Capabilities, CheckingDescription, CheckingEnvironment, CheckingType, FunctionDescription,
39 MetadataError, OperationDescription, RecordDescription, TypeDescription,
40 TypeFunctionDescription,
41 },
42};
43use serde::{Deserialize, Serialize};
44
45const SCHEMA_VERSION: u32 = 2;
47const CHECKER_CONTRACT: &str = "cel-adam-checking/2";
49const MAX_BYTES: usize = 8 * 1024 * 1024;
51const MAX_DEPTH: usize = 64;
53
54#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct EnvironmentIdentity {
62 pub application: String,
64 pub revision: String,
66}
67
68pub fn export_checking_metadata(
85 types: &TypeRegistry,
86 lookup: &OpLookup,
87 identity: &EnvironmentIdentity,
88) -> Result<String, MetadataError> {
89 validate_identity(identity)?;
90 let environment = checking_environment(types, lookup).map_err(|error| {
91 MetadataError(format!(
92 "environment registration: {error}; use complete persistent type, operation, \
93 function and record registrations, then regenerate metadata"
94 ))
95 })?;
96 let artifact = Artifact {
97 schema_version: SCHEMA_VERSION,
98 checker_contract: CHECKER_CONTRACT.into(),
99 application: Application {
100 id: identity.application.clone(),
101 revision: identity.revision.clone(),
102 },
103 environment: WireAdamEnvironment {
104 cel: WireEnvironment::from(environment.cel().description()),
105 cell_types: environment.cell_types().to_vec(),
106 },
107 };
108 let text = serde_json::to_string_pretty(&artifact).map_err(|error| json_error(&error))?;
109 validate_bounds(&text)?;
110 Ok(text)
111}
112
113pub fn import_checking_metadata(
131 text: &str,
132 expected: &EnvironmentIdentity,
133) -> Result<AdamCheckingEnvironment, MetadataError> {
134 validate_identity(expected)?;
135 validate_bounds(text)?;
136 let artifact: Artifact = serde_json::from_str(text).map_err(|error| json_error(&error))?;
137 if artifact.schema_version != SCHEMA_VERSION {
138 return Err(MetadataError(format!(
139 "schemaVersion: expected {SCHEMA_VERSION}, received {}; regenerate metadata \
140 or use a compatible server",
141 artifact.schema_version
142 )));
143 }
144 if artifact.checker_contract != CHECKER_CONTRACT {
145 return Err(MetadataError(format!(
146 "checkerContract: expected {CHECKER_CONTRACT:?}, received {:?}; regenerate \
147 metadata or use a compatible server",
148 artifact.checker_contract
149 )));
150 }
151 if artifact.application.id.trim().is_empty() || artifact.application.id != expected.application
152 {
153 return Err(MetadataError(format!(
154 "application.id: expected {:?}, received {:?}; correct the expected application \
155 setting or regenerate metadata",
156 expected.application, artifact.application.id
157 )));
158 }
159 if artifact.application.revision.trim().is_empty()
160 || artifact.application.revision != expected.revision
161 {
162 return Err(MetadataError(format!(
163 "application.revision: expected {:?}, received {:?}; correct the expected revision \
164 setting or regenerate stale metadata",
165 expected.revision, artifact.application.revision
166 )));
167 }
168 let cel = CheckingEnvironment::from_description(artifact.environment.cel.into()).map_err(|error| {
169 MetadataError(format!(
170 "environment description: {error}; correct host registrations and regenerate metadata"
171 ))
172 })?;
173 AdamCheckingEnvironment::from_parts(cel, artifact.environment.cell_types).map_err(|error| {
174 MetadataError(format!(
175 "environment membership: {error}; correct host registrations and regenerate metadata"
176 ))
177 })
178}
179
180fn validate_identity(identity: &EnvironmentIdentity) -> Result<(), MetadataError> {
184 for (field, value) in [
185 ("application", identity.application.as_str()),
186 ("revision", identity.revision.as_str()),
187 ] {
188 if value.trim().is_empty() {
189 return Err(MetadataError(format!(
190 "expected.{field}: must be nonempty; correct the identity setting and regenerate metadata"
191 )));
192 }
193 }
194 Ok(())
195}
196
197fn json_error(error: &serde_json::Error) -> MetadataError {
201 MetadataError(format!(
202 "JSON/schema: {error}; correct the artifact or regenerate metadata with a compatible exporter"
203 ))
204}
205
206fn validate_bounds(text: &str) -> Result<(), MetadataError> {
212 if text.len() > MAX_BYTES {
213 return Err(MetadataError(format!(
214 "JSON size: exceeds {MAX_BYTES} bytes; reduce registrations and regenerate metadata"
215 )));
216 }
217 let mut depth = 0usize;
218 let mut in_string = false;
219 let mut escaped = false;
220 for byte in text.bytes() {
222 if in_string {
223 if escaped {
224 escaped = false;
225 } else if byte == b'\\' {
226 escaped = true;
227 } else if byte == b'"' {
228 in_string = false;
229 }
230 } else {
231 match byte {
232 b'"' => in_string = true,
233 b'{' | b'[' => {
234 depth += 1;
235 if depth > MAX_DEPTH {
236 return Err(MetadataError(format!(
237 "JSON depth: exceeds {MAX_DEPTH} containers; simplify shapes and regenerate metadata"
238 )));
239 }
240 }
241 b'}' | b']' => depth = depth.saturating_sub(1),
242 _ => {}
243 }
244 }
245 }
246 Ok(())
247}
248
249#[derive(Serialize, Deserialize)]
251#[serde(rename_all = "camelCase", deny_unknown_fields)]
252struct Artifact {
253 schema_version: u32,
254 checker_contract: String,
255 application: Application,
256 environment: WireAdamEnvironment,
257}
258
259#[derive(Serialize, Deserialize)]
261#[serde(deny_unknown_fields)]
262struct Application {
263 id: String,
264 revision: String,
265}
266
267#[derive(Serialize, Deserialize)]
269#[serde(deny_unknown_fields)]
270struct WireAdamEnvironment {
271 cel: WireEnvironment,
272 #[serde(rename = "cellTypes")]
273 cell_types: Vec<u32>,
274}
275
276#[derive(Serialize, Deserialize)]
280#[serde(deny_unknown_fields)]
281struct WireEnvironment {
282 builtin_contract: u32,
283 types: Vec<WireLeaf>,
284 operations: Vec<WireOperation>,
285 records: Vec<WireRecord>,
286 functions: Vec<WireFunction>,
287 #[serde(rename = "typeFunctions")]
288 type_functions: Vec<WireTypeFunction>,
289}
290
291#[derive(Serialize, Deserialize)]
293#[serde(deny_unknown_fields)]
294struct WireTypeFunction {
295 name: String,
296 arguments: Vec<WireShape>,
297 result: WireShape,
298}
299
300#[derive(Serialize, Deserialize)]
302#[serde(deny_unknown_fields)]
303struct WireLeaf {
304 id: u32,
305 name: String,
306 aliases: Vec<String>,
307 #[serde(deserialize_with = "required_option")]
308 primitive: Option<String>,
309 capabilities: WireCapabilities,
310 #[serde(deserialize_with = "required_option")]
311 range_element: Option<u32>,
312}
313
314fn required_option<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
318where
319 D: serde::Deserializer<'de>,
320 T: Deserialize<'de>,
321{
322 Option::deserialize(deserializer)
323}
324
325#[derive(Serialize, Deserialize)]
327#[serde(deny_unknown_fields)]
328struct WireCapabilities {
329 default_available: bool,
330 cloneable: bool,
331 comparable: bool,
332 debuggable: bool,
333}
334
335#[derive(Serialize, Deserialize)]
337#[serde(deny_unknown_fields)]
338struct WireOperation {
339 name: String,
340 operands: Vec<WireShape>,
341 result: WireShape,
342}
343
344#[derive(Serialize, Deserialize)]
346#[serde(deny_unknown_fields)]
347struct WireRecord {
348 name: String,
349 ty: u32,
350 fields: Vec<(String, WireShape)>,
351}
352
353#[derive(Serialize, Deserialize)]
355#[serde(deny_unknown_fields)]
356struct WireFunction {
357 name: String,
358 marker: u32,
359}
360
361#[derive(Serialize, Deserialize)]
363#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
364enum WireShape {
365 Leaf {
366 id: u32,
367 },
368 Array {
369 element: Box<WireShape>,
370 },
371 Tuple {
372 elements: Vec<WireShape>,
373 },
374 Callable {
375 parameters: Vec<WireShape>,
376 result: Box<WireShape>,
377 },
378}
379
380impl From<&CheckingType> for WireShape {
381 fn from(shape: &CheckingType) -> Self {
385 match shape {
386 CheckingType::Leaf(id) => Self::Leaf { id: *id },
387 CheckingType::Array(element) => Self::Array {
388 element: Box::new(Self::from(element.as_ref())),
389 },
390 CheckingType::Tuple(elements) => Self::Tuple {
391 elements: elements.iter().map(Self::from).collect(),
392 },
393 CheckingType::Callable(parameters, result) => Self::Callable {
394 parameters: parameters.iter().map(Self::from).collect(),
395 result: Box::new(Self::from(result.as_ref())),
396 },
397 }
398 }
399}
400
401impl From<WireShape> for CheckingType {
402 fn from(shape: WireShape) -> Self {
406 match shape {
407 WireShape::Leaf { id } => Self::Leaf(id),
408 WireShape::Array { element } => Self::Array(Box::new(Self::from(*element))),
409 WireShape::Tuple { elements } => {
410 Self::Tuple(elements.into_iter().map(Self::from).collect())
411 }
412 WireShape::Callable { parameters, result } => Self::Callable(
413 parameters.into_iter().map(Self::from).collect(),
414 Box::new(Self::from(*result)),
415 ),
416 }
417 }
418}
419
420impl From<&CheckingDescription> for WireEnvironment {
421 fn from(description: &CheckingDescription) -> Self {
425 Self {
426 builtin_contract: description.builtin_contract,
427 types: description
428 .types
429 .iter()
430 .map(|leaf| WireLeaf {
431 id: leaf.id,
432 name: leaf.name.clone(),
433 aliases: leaf.aliases.clone(),
434 primitive: leaf.primitive.clone(),
435 capabilities: WireCapabilities {
436 default_available: leaf.capabilities.default_available,
437 cloneable: leaf.capabilities.cloneable,
438 comparable: leaf.capabilities.comparable,
439 debuggable: leaf.capabilities.debuggable,
440 },
441 range_element: leaf.range_element,
442 })
443 .collect(),
444 operations: description
445 .operations
446 .iter()
447 .map(|operation| WireOperation {
448 name: operation.name.clone(),
449 operands: operation.operands.iter().map(WireShape::from).collect(),
450 result: WireShape::from(&operation.result),
451 })
452 .collect(),
453 records: description
454 .records
455 .iter()
456 .map(|record| WireRecord {
457 name: record.name.clone(),
458 ty: record.ty,
459 fields: record
460 .fields
461 .iter()
462 .map(|(name, shape)| (name.clone(), WireShape::from(shape)))
463 .collect(),
464 })
465 .collect(),
466 functions: description
467 .functions
468 .iter()
469 .map(|function| WireFunction {
470 name: function.name.clone(),
471 marker: function.marker,
472 })
473 .collect(),
474 type_functions: description
475 .type_functions
476 .iter()
477 .map(|signature| WireTypeFunction {
478 name: signature.name.clone(),
479 arguments: signature.arguments.iter().map(WireShape::from).collect(),
480 result: WireShape::from(&signature.result),
481 })
482 .collect(),
483 }
484 }
485}
486
487impl From<WireEnvironment> for CheckingDescription {
488 fn from(wire: WireEnvironment) -> Self {
492 Self {
493 builtin_contract: wire.builtin_contract,
494 types: wire
495 .types
496 .into_iter()
497 .map(|leaf| TypeDescription {
498 id: leaf.id,
499 name: leaf.name,
500 aliases: leaf.aliases,
501 primitive: leaf.primitive,
502 capabilities: Capabilities {
503 default_available: leaf.capabilities.default_available,
504 cloneable: leaf.capabilities.cloneable,
505 comparable: leaf.capabilities.comparable,
506 debuggable: leaf.capabilities.debuggable,
507 },
508 range_element: leaf.range_element,
509 })
510 .collect(),
511 operations: wire
512 .operations
513 .into_iter()
514 .map(|operation| OperationDescription {
515 name: operation.name,
516 operands: operation
517 .operands
518 .into_iter()
519 .map(CheckingType::from)
520 .collect(),
521 result: operation.result.into(),
522 })
523 .collect(),
524 records: wire
525 .records
526 .into_iter()
527 .map(|record| RecordDescription {
528 name: record.name,
529 ty: record.ty,
530 fields: record
531 .fields
532 .into_iter()
533 .map(|(name, shape)| (name, shape.into()))
534 .collect(),
535 })
536 .collect(),
537 functions: wire
538 .functions
539 .into_iter()
540 .map(|function| FunctionDescription {
541 name: function.name,
542 marker: function.marker,
543 })
544 .collect(),
545 type_functions: wire
546 .type_functions
547 .into_iter()
548 .map(|signature| TypeFunctionDescription {
549 name: signature.name,
550 arguments: signature
551 .arguments
552 .into_iter()
553 .map(CheckingType::from)
554 .collect(),
555 result: signature.result.into(),
556 })
557 .collect(),
558 }
559 }
560}