mod advice;
mod advice_policy;
mod native;
mod render;
pub use advice::{BulkLintReport, BulkWarning};
pub use advice_policy::{BulkAdvisory, BulkPolicy, BulkSite};
use alloc::{
collections::{BTreeMap, BTreeSet},
string::{String, ToString},
vec,
vec::Vec,
};
pub use ic_wire_derive::Wire;
#[doc(hidden)]
pub use native::{PackedField, SerdeBytesField};
pub use native::{SchemaContext, SchemaRegistry, Wire};
use serde_json::{Number, Value};
const MAX_SAFE_INTEGER: u64 = (1_u64 << 53) - 1;
#[doc(hidden)]
pub mod __private {
pub use serde_json::{Value, json};
}
pub const RUNTIME_SCHEMA_FORMAT: &str = "ic-wire-sparse-v1";
pub const RUNTIME: &str = include_str!("runtime.ts");
#[derive(Clone, Copy, Debug)]
pub struct PayloadLimits {
pub bytes: u64,
pub nodes: u64,
pub depth: u64,
}
#[derive(Clone, Copy, Debug)]
pub struct Method<'a> {
pub export: &'a str,
pub id: u64,
pub request: &'a str,
pub response: &'a str,
pub request_limits: PayloadLimits,
pub response_limits: PayloadLimits,
}
#[cfg(feature = "service-client")]
#[derive(Clone, Copy, Debug)]
pub struct ServiceMethod<'a> {
pub binding: &'a str,
pub codec_export: &'a str,
pub endpoint: &'a str,
pub codec_module: &'a str,
pub mode: &'a str,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GenerationError {
Schema,
Complexity,
}
#[derive(Clone, Copy, Debug)]
pub struct SchemaLimits {
pub nodes: usize,
pub depth: usize,
pub names_bytes: usize,
pub output_bytes: usize,
}
impl Default for SchemaLimits {
fn default() -> Self {
Self {
nodes: 65_536,
depth: 64,
names_bytes: 1_048_576,
output_bytes: 1_048_576,
}
}
}
#[derive(Debug)]
struct ScalarBounds {
min: Option<Number>,
max: Option<Number>,
}
#[derive(Debug)]
struct Annotations {
check: Option<String>,
bounds: Option<ScalarBounds>,
fixed: bool,
projected: bool,
}
#[derive(Debug)]
struct ExtensionField {
id: u32,
name: String,
child: usize,
required: bool,
}
#[derive(Debug)]
enum Node {
Unit,
Bool,
Integer {
bits: u8,
signed: bool,
},
Float {
bits: u8,
},
Text {
max: Option<u64>,
},
Bytes {
min: Option<u64>,
max: Option<u64>,
},
Packed {
word: &'static str,
nonzero: bool,
max: Option<u64>,
},
List {
item: usize,
max: Option<u64>,
},
Array {
item: usize,
len: u64,
},
Tuple(Vec<usize>),
Result {
ok: usize,
err: usize,
},
Option(usize),
Recover(usize),
Alias(usize),
Ref(usize),
Record(Vec<(String, usize)>),
Enum(Vec<(String, u32, usize)>),
ExtensionRecord {
fields: Vec<(String, usize)>,
extensions: Vec<ExtensionField>,
},
ExtensionTuple {
items: Vec<usize>,
extensions: Vec<ExtensionField>,
},
OpenVariant {
variants: Vec<(String, u32, usize)>,
required: bool,
},
}
#[derive(Debug)]
pub struct ValidatedRegistry {
names: Vec<String>,
roots: Vec<usize>,
nodes: Vec<Node>,
annotations: BTreeMap<usize, Annotations>,
output_bytes: usize,
}
impl ValidatedRegistry {
pub fn from_metadata(
types: &BTreeMap<String, Value>,
limits: SchemaLimits,
) -> Result<Self, GenerationError> {
if limits.depth > 64 || types.len() > limits.nodes {
return Err(GenerationError::Complexity);
}
let mut importer = Importer {
nodes: Vec::new(),
annotations: BTreeMap::new(),
names: BTreeMap::new(),
remaining: limits.nodes - types.len(),
name_bytes: limits.names_bytes,
depth: limits.depth,
};
let mut names = Vec::new();
for (index, name) in types.keys().enumerate() {
identifier(name)?;
let name = importer.name(name)?;
importer.names.insert(name.clone(), index);
names.push(name);
}
let mut roots = Vec::new();
for value in types.values() {
roots.push(importer.parse(value, 0)?);
}
let graph = Self {
names,
roots,
nodes: importer.nodes,
annotations: importer.annotations,
output_bytes: limits.output_bytes,
};
graph.validate_aliases()?;
Ok(graph)
}
fn message_root_nodes(&self, roots: &[usize]) -> Result<Vec<usize>, GenerationError> {
if roots.is_empty() {
return Ok(Vec::new());
}
let mut checked_roots = vec![false; self.nodes.len()];
let mut terminals = Vec::new();
for &root in roots {
let mut id = self.roots[root];
while !core::mem::replace(&mut checked_roots[id], true) {
match &self.nodes[id] {
Node::Alias(item) if !self.annotations.get(&id).is_some_and(|a| a.fixed) => {
id = *item
}
Node::Ref(root) => id = self.roots[*root],
_ if !self.sparse_node(id) => {
return Err(GenerationError::Schema);
}
_ => {
terminals.push(id);
break;
}
}
}
}
Ok(terminals)
}
fn validate_evolving_roots(&self, roots: &BTreeSet<String>) -> Result<(), GenerationError> {
let indices = roots
.iter()
.map(|root| self.root_index(root))
.collect::<Result<Vec<_>, _>>()?;
self.validate_projection_layouts(self.message_root_nodes(&indices)?)
}
fn sparse_node(&self, id: usize) -> bool {
matches!(
self.nodes[id],
Node::ExtensionRecord { .. } | Node::ExtensionTuple { .. }
)
}
fn validate_message_roots(&self, roots: &[usize]) -> Result<(), GenerationError> {
let roots = self
.message_root_nodes(roots)?
.into_iter()
.filter(|id| {
self.annotations
.get(id)
.is_some_and(|annotation| annotation.projected)
})
.collect();
self.validate_projection_layouts(roots)
}
fn validate_projection_layouts(&self, roots: Vec<usize>) -> Result<(), GenerationError> {
#[derive(Clone, Copy, PartialEq, Eq)]
enum Layout {
Projected,
FixedChild,
}
use Layout::{FixedChild, Projected};
let mut pending = Vec::new();
for id in roots {
match &self.nodes[id] {
Node::ExtensionRecord { fields, extensions } => {
pending.extend(fields.iter().map(|(_, child)| (*child, Projected)));
pending.extend(extensions.iter().map(|entry| (entry.child, Projected)));
}
Node::ExtensionTuple { items, extensions } => {
pending.extend(items.iter().map(|&item| (item, Projected)));
pending.extend(extensions.iter().map(|entry| (entry.child, Projected)));
}
_ => unreachable!("admitted evolving root"),
}
}
if pending.is_empty() {
return Ok(());
}
let mut visited = vec![[false; 2]; self.nodes.len()];
while let Some((id, layout)) = pending.pop() {
if core::mem::replace(&mut visited[id][layout as usize], true) {
continue;
}
let flags = self.annotations.get(&id);
let fixed = layout != Projected || flags.is_some_and(|a| a.fixed);
let projected = layout == Projected && flags.is_some_and(|a| a.projected);
if layout == FixedChild && flags.is_some_and(|a| a.projected) {
return Err(GenerationError::Schema);
}
let child_layout = FixedChild;
match &self.nodes[id] {
Node::Record(fields) if fixed => {
pending.extend(fields.iter().map(|(_, child)| (*child, child_layout)));
}
Node::Tuple(items) => {
let child_layout = if fixed { child_layout } else { layout };
pending.extend(items.iter().map(|&item| (item, child_layout)));
}
Node::ExtensionRecord { fields, extensions } if projected => {
pending.extend(fields.iter().map(|(_, child)| (*child, Projected)));
pending.extend(extensions.iter().map(|entry| (entry.child, Projected)));
}
Node::ExtensionTuple { items, extensions } if projected => {
pending.extend(items.iter().map(|&item| (item, Projected)));
pending.extend(extensions.iter().map(|entry| (entry.child, Projected)));
}
Node::List { item, .. } | Node::Array { item, .. } | Node::Option(item) => {
pending.push((*item, layout))
}
Node::Alias(item) => pending.push((*item, child_layout)),
Node::Ref(root) => pending.push((self.roots[*root], layout)),
Node::Result { ok, err } => {
pending.extend([(*ok, layout), (*err, layout)]);
}
Node::Enum(variants) => {
let child_layout = if projected { Projected } else { child_layout };
pending.extend(variants.iter().map(|(_, _, child)| (*child, child_layout)));
}
Node::Record(_)
| Node::ExtensionRecord { .. }
| Node::ExtensionTuple { .. }
| Node::OpenVariant { .. }
| Node::Recover(_) => return Err(GenerationError::Schema),
Node::Unit
| Node::Bool
| Node::Integer { .. }
| Node::Float { .. }
| Node::Text { .. }
| Node::Bytes { .. }
| Node::Packed { .. } => {}
}
}
Ok(())
}
fn validate_aliases(&self) -> Result<(), GenerationError> {
let mut state = vec![0_u8; self.nodes.len()];
let mut path = Vec::new();
for start in 0..self.nodes.len() {
let mut current = start;
path.clear();
loop {
match state[current] {
1 => return Err(GenerationError::Schema),
2 => break,
_ => {}
}
state[current] = 1;
path.push(current);
match self.nodes[current] {
Node::Alias(next) => current = next,
Node::Ref(root) => current = self.roots[root],
_ => break,
}
}
for node in &path {
state[*node] = 2;
}
}
Ok(())
}
}
struct Importer {
nodes: Vec<Node>,
annotations: BTreeMap<usize, Annotations>,
names: BTreeMap<String, usize>,
remaining: usize,
name_bytes: usize,
depth: usize,
}
impl Importer {
fn name(&mut self, name: &str) -> Result<String, GenerationError> {
self.name_bytes = self
.name_bytes
.checked_sub(name.len())
.ok_or(GenerationError::Complexity)?;
Ok(name.to_string())
}
fn parse_extensions<'a>(
&mut self,
value: &'a Value,
depth: usize,
names: &mut BTreeSet<&'a str>,
tuple_core_slots: Option<u32>,
) -> Result<Vec<ExtensionField>, GenerationError> {
let entries = value.as_array().ok_or(GenerationError::Schema)?;
if entries.len() > self.remaining {
return Err(GenerationError::Complexity);
}
let mut extensions = Vec::new();
let mut previous = tuple_core_slots.unwrap_or(0);
for entry in entries {
keys(entry, &["name", "id", "value", "required"])?;
let name = text(entry, "name")?;
let id = entry["id"]
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.ok_or(GenerationError::Schema)?;
let required = entry["required"].as_bool().ok_or(GenerationError::Schema)?;
if id <= previous
|| (tuple_core_slots.is_some() && (required || previous.checked_add(1) != Some(id)))
|| !names.insert(name)
{
return Err(GenerationError::Schema);
}
previous = id;
extensions.push(ExtensionField {
id,
name: self.name(name)?,
child: self.parse(&entry["value"], depth + 1)?,
required,
});
}
Ok(extensions)
}
fn parse(&mut self, value: &Value, depth: usize) -> Result<usize, GenerationError> {
if depth > self.depth {
return Err(GenerationError::Complexity);
}
self.remaining = self
.remaining
.checked_sub(1)
.ok_or(GenerationError::Complexity)?;
let kind = text(value, "k")?;
let allowed: &[&str] = match kind {
"unit" | "bool" => &["k", "check"],
"u" | "i" | "float" => &["k", "check", "bits", "min", "max"],
"text" => &["k", "check", "max"],
"packed" => &["k", "check", "word", "nonzero", "max"],
"bytes" => &["k", "check", "min", "max"],
"list" | "array" => &["k", "check", "item", "max"],
"tuple" => &["k", "check", "items", "fixed"],
"result" => &["k", "check", "ok", "err"],
"option" | "recover" => &["k", "check", "item"],
"newtype" => &["k", "check", "item", "fixed"],
"ref" => &["k", "check", "name"],
"record" => &["k", "check", "fields", "fixed"],
"enum" => &["k", "check", "variants", "projected"],
"extension-record" => &["k", "check", "fields", "extensions", "projected"],
"extension-tuple" => &["k", "check", "items", "extensions", "projected"],
"open-variant" => &["k", "check", "variants", "required"],
_ => return Err(GenerationError::Schema),
};
keys(value, allowed)?;
let node = match kind {
"unit" => Node::Unit,
"bool" => Node::Bool,
"float" => {
let bits = value["bits"].as_u64().ok_or(GenerationError::Schema)?;
if ![32, 64].contains(&bits) {
return Err(GenerationError::Schema);
}
Node::Float { bits: bits as u8 }
}
"u" | "i" => {
let bits = value["bits"].as_u64().ok_or(GenerationError::Schema)?;
if ![8, 16, 32, 64, 128].contains(&bits) {
return Err(GenerationError::Schema);
}
Node::Integer {
bits: bits as u8,
signed: kind == "i",
}
}
"text" => Node::Text {
max: bound(value, "max")?,
},
"bytes" => {
let min = bound(value, "min")?;
let max = bound(value, "max")?;
if min.zip(max).is_some_and(|(min, max)| min > max) {
return Err(GenerationError::Schema);
}
Node::Bytes { min, max }
}
"packed" => {
let word = text(value, "word")?;
let word = [
"i8",
"i16",
"u16",
"i32",
"u32",
"i64",
"u64",
"hash16",
"hash32",
"bool",
"finite-f32",
"finite-f64",
]
.into_iter()
.find(|candidate| *candidate == word)
.ok_or(GenerationError::Schema)?;
let nonzero = match value.get("nonzero") {
None => false,
Some(Value::Bool(true)) if word == "i64" => true,
_ => return Err(GenerationError::Schema),
};
let max = bound(value, "max")?;
let width = match word {
"bool" | "i8" => 1,
"i16" | "u16" => 2,
"i32" | "u32" | "finite-f32" => 4,
"i64" | "u64" | "finite-f64" => 8,
"hash16" => 16,
_ => 32,
};
if max.is_some_and(|n| n > MAX_SAFE_INTEGER / width) {
return Err(GenerationError::Complexity);
}
Node::Packed { word, nonzero, max }
}
"list" => Node::List {
max: bound(value, "max")?,
item: self.parse(&value["item"], depth + 1)?,
},
"array" => Node::Array {
len: bound(value, "max")?.ok_or(GenerationError::Schema)?,
item: self.parse(&value["item"], depth + 1)?,
},
"tuple" | "extension-tuple" => {
let items = value["items"].as_array().ok_or(GenerationError::Schema)?;
if items.len() > self.remaining {
return Err(GenerationError::Complexity);
}
let items = items
.iter()
.map(|item| self.parse(item, depth + 1))
.collect::<Result<Vec<_>, _>>()?;
if kind == "extension-tuple" {
let slots =
u32::try_from(items.len()).map_err(|_| GenerationError::Complexity)?;
Node::ExtensionTuple {
items,
extensions: self.parse_extensions(
&value["extensions"],
depth,
&mut BTreeSet::new(),
Some(slots),
)?,
}
} else {
Node::Tuple(items)
}
}
"result" => Node::Result {
ok: self.parse(&value["ok"], depth + 1)?,
err: self.parse(&value["err"], depth + 1)?,
},
"option" => Node::Option(self.parse(&value["item"], depth + 1)?),
"recover" => Node::Recover(self.parse(&value["item"], depth + 1)?),
"newtype" => Node::Alias(self.parse(&value["item"], depth + 1)?),
"ref" => Node::Ref(
*self
.names
.get(text(value, "name")?)
.ok_or(GenerationError::Schema)?,
),
"record" | "enum" | "extension-record" | "open-variant" => {
let is_open = kind == "open-variant";
let is_enum = kind == "enum" || is_open;
let fields = value[if is_enum { "variants" } else { "fields" }]
.as_array()
.ok_or(GenerationError::Schema)?;
if kind == "enum" && fields.is_empty() {
return Err(GenerationError::Schema);
}
if fields.len() > self.remaining {
return Err(GenerationError::Complexity);
}
let mut seen = BTreeSet::new();
let mut ids = BTreeSet::new();
let mut record = Vec::new();
let mut variants = Vec::new();
for field in fields {
keys(
field,
if is_enum {
&["name", "id", "value"]
} else {
&["name", "value"]
},
)?;
let name = text(field, "name")?;
if !seen.insert(name) {
return Err(GenerationError::Schema);
}
let name = self.name(name)?;
let child = self.parse(&field["value"], depth + 1)?;
if is_enum {
let id = field["id"]
.as_u64()
.and_then(|id| u32::try_from(id).ok())
.ok_or(GenerationError::Schema)?;
if (is_open && !(1..=u32::MAX >> 1).contains(&id)) || !ids.insert(id) {
return Err(GenerationError::Schema);
}
variants.push((name, id, child));
} else {
record.push((name, child));
}
}
match kind {
"enum" => Node::Enum(variants),
"open-variant" => Node::OpenVariant {
variants,
required: match value.get("required") {
Some(required) => required.as_bool().ok_or(GenerationError::Schema)?,
None => false,
},
},
"extension-record" => Node::ExtensionRecord {
fields: record,
extensions: self.parse_extensions(
&value["extensions"],
depth,
&mut seen,
None,
)?,
},
_ => Node::Record(record),
}
}
_ => return Err(GenerationError::Schema),
};
let id = self.nodes.len();
let check = value
.get("check")
.map(|check| self.name(check.as_str().ok_or(GenerationError::Schema)?))
.transpose()?;
let bounds = if matches!(kind, "u" | "i" | "float")
&& (value.get("min").is_some() || value.get("max").is_some())
{
Some(scalar_bounds(value, kind != "float")?)
} else {
None
};
let fixed = match value.get("fixed") {
None => false,
Some(Value::Bool(true)) => true,
Some(_) => return Err(GenerationError::Schema),
};
let projected = match value.get("projected") {
None => false,
Some(Value::Bool(true)) => true,
Some(_) => return Err(GenerationError::Schema),
};
if check.is_some() || bounds.is_some() || fixed || projected {
self.annotations.insert(
id,
Annotations {
check,
bounds,
fixed,
projected,
},
);
}
self.nodes.push(node);
Ok(id)
}
}
fn text<'a>(value: &'a Value, key: &str) -> Result<&'a str, GenerationError> {
value[key].as_str().ok_or(GenerationError::Schema)
}
fn keys(value: &Value, allowed: &[&str]) -> Result<(), GenerationError> {
if value
.as_object()
.ok_or(GenerationError::Schema)?
.keys()
.any(|key| !allowed.contains(&key.as_str()))
{
return Err(GenerationError::Schema);
}
Ok(())
}
fn bound(value: &Value, key: &str) -> Result<Option<u64>, GenerationError> {
value
.get(key)
.map(|n| {
let n = n.as_u64().ok_or(GenerationError::Schema)?;
if n > MAX_SAFE_INTEGER {
return Err(GenerationError::Complexity);
}
Ok(n)
})
.transpose()
}
fn identifier(name: &str) -> Result<(), GenerationError> {
if name.is_empty()
|| !name
.bytes()
.enumerate()
.all(|(i, b)| b.is_ascii_alphabetic() || b == b'_' || (i > 0 && b.is_ascii_digit()))
{
return Err(GenerationError::Schema);
}
if RESERVED.contains(&name) {
return Err(GenerationError::Schema);
}
Ok(())
}
const RESERVED: &[&str] = &[
"as",
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"enum",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"import",
"in",
"instanceof",
"new",
"null",
"return",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"var",
"void",
"while",
"with",
"implements",
"interface",
"let",
"package",
"private",
"protected",
"public",
"static",
"yield",
"await",
"any",
"boolean",
"bigint",
"never",
"number",
"object",
"string",
"symbol",
"undefined",
"unknown",
"eval",
"arguments",
];
fn scalar_bounds(value: &Value, integer: bool) -> Result<ScalarBounds, GenerationError> {
let read = |key| -> Result<Option<Number>, GenerationError> {
value
.get(key)
.map(|value| {
let number = value.as_number().ok_or(GenerationError::Schema)?;
let n = number
.as_f64()
.filter(|n| n.is_finite())
.ok_or(GenerationError::Schema)?;
if integer {
if n % 1.0 != 0.0 {
return Err(GenerationError::Schema);
}
if n.abs() > 9_007_199_254_740_991.0 {
return Err(GenerationError::Complexity);
}
}
Ok(number.clone())
})
.transpose()
};
let bounds = ScalarBounds {
min: read("min")?,
max: read("max")?,
};
if bounds
.min
.as_ref()
.zip(bounds.max.as_ref())
.is_some_and(|(min, max)| min.as_f64() > max.as_f64())
{
return Err(GenerationError::Schema);
}
Ok(bounds)
}