buffa_codegen/adapters/config.rs
1//! Typed manifest for process-local adapters. No entry contains Rust source.
2
3use std::io::Read;
4
5use serde::Deserialize;
6
7use super::{AdapterError, ErrorReason};
8
9/// Maximum encoded size of an adapter manifest (1 MiB).
10pub const MAX_MANIFEST_BYTES: usize = 1024 * 1024;
11
12/// Opt-in, descriptor-checked adapter declarations.
13///
14/// This metadata contains names and paths only; never put keys or application
15/// data in it. Unknown JSON members and duplicate members are rejected.
16#[derive(Debug, Clone, Deserialize)]
17#[serde(deny_unknown_fields)]
18pub struct AdapterConfig {
19 /// Manifest format. Currently must be 1.
20 pub version: u32,
21 /// Closed selectors with checked wire conversions.
22 #[serde(default)]
23 pub selectors: Vec<ClosedSelector>,
24 /// Copy payload selectors. Payloads name a declared descriptor field.
25 #[serde(default)]
26 pub payloads: Vec<PayloadSelector>,
27 /// Borrowed enums; never implement a wire codec or own caller buffers.
28 #[serde(default)]
29 pub borrowed: Vec<BorrowedAdapter>,
30 /// Process-local provider traits, explicitly declared by the application.
31 #[serde(default)]
32 pub ports: Vec<CapabilityPort>,
33}
34
35impl AdapterConfig {
36 /// Decode a bounded manifest without exposing input in diagnostics.
37 ///
38 /// # Errors
39 /// Returns a fixed reason for oversized, malformed or unsupported input.
40 pub fn from_json(bytes: &[u8]) -> Result<Self, AdapterError> {
41 if bytes.len() > MAX_MANIFEST_BYTES {
42 return Err(ErrorReason::ManifestTooLarge.into());
43 }
44 let config: Self =
45 serde_json::from_slice(bytes).map_err(|_| ErrorReason::InvalidManifest)?;
46 if config.version != 1 {
47 return Err(ErrorReason::UnsupportedVersion.into());
48 }
49 Ok(config)
50 }
51
52 /// Read a manifest with the same bound as [`Self::from_json`].
53 ///
54 /// # Errors
55 /// Returns a fixed I/O, size or manifest error, without retaining paths.
56 pub fn read_json(path: impl AsRef<std::path::Path>) -> Result<Self, AdapterError> {
57 let limit = MAX_MANIFEST_BYTES
58 .checked_add(1)
59 .and_then(|n| u64::try_from(n).ok())
60 .ok_or(ErrorReason::ManifestTooLarge)?;
61 let file = std::fs::File::open(path).map_err(|_| ErrorReason::ManifestIo)?;
62 let mut bytes = Vec::new();
63 file.take(limit)
64 .read_to_end(&mut bytes)
65 .map_err(|_| ErrorReason::ManifestIo)?;
66 Self::from_json(&bytes)
67 }
68}
69
70/// Domain error construction using paths only, never expressions or messages.
71#[derive(Debug, Clone, Deserialize)]
72#[serde(deny_unknown_fields)]
73pub struct ErrorMapping {
74 /// Domain error type, e.g. `crate::ContractError`.
75 pub rust_type: String,
76 /// Fixed enum variant or constant, converted with `Into` to `rust_type`.
77 pub value: String,
78}
79
80/// Descriptor enum and its already-generated Rust wire type.
81#[derive(Debug, Clone, Deserialize)]
82#[serde(deny_unknown_fields)]
83pub struct WireEnum {
84 /// Fully-qualified descriptor name, including its leading dot.
85 pub source: String,
86 /// Rust path to the corresponding wire enum.
87 pub rust_type: String,
88}
89
90/// A nonzero canonical selector case.
91#[derive(Debug, Clone, Deserialize)]
92#[serde(deny_unknown_fields)]
93pub struct SelectorVariant {
94 /// Exact descriptor value name, without the enclosing enum name.
95 pub source: String,
96 /// Public native variant name.
97 pub name: String,
98 /// Compatibility associated constants for this native variant.
99 #[serde(default)]
100 pub aliases: Vec<String>,
101 /// Optional external protocol identity, distinct from the protobuf number.
102 pub identifier: Option<i64>,
103}
104
105/// Explicit normalization of a legacy value to an existing canonical case.
106#[derive(Debug, Clone, Deserialize)]
107#[serde(deny_unknown_fields)]
108pub struct Normalization {
109 /// Descriptor value name in this source enum.
110 pub source: String,
111 /// Canonical native variant name.
112 pub target: String,
113}
114
115/// Additional legacy wire enum accepted by a closed selector.
116#[derive(Debug, Clone, Deserialize)]
117#[serde(deny_unknown_fields)]
118pub struct LegacySelector {
119 /// Descriptor enum and Rust type for the legacy input.
120 pub wire: WireEnum,
121 /// Every accepted nonzero legacy case.
122 pub normalizations: Vec<Normalization>,
123 /// Nonzero cases deliberately rejected, rather than silently omitted.
124 #[serde(default)]
125 pub rejected: Vec<String>,
126}
127
128/// Closed native enum; zero and unknown values always fail conversion.
129#[derive(Debug, Clone, Deserialize)]
130#[serde(deny_unknown_fields)]
131pub struct ClosedSelector {
132 /// Bare sibling `.rs` filename, included explicitly by the application.
133 pub file: String,
134 /// Native Rust enum name.
135 pub name: String,
136 /// Authoritative wire enum.
137 pub wire: WireEnum,
138 /// Fixed error for unspecified, rejected and unknown inputs.
139 pub error: ErrorMapping,
140 /// Preserve an extensible public Rust matching surface.
141 #[serde(default)]
142 pub non_exhaustive: bool,
143 /// Canonical cases in public `ALL` order.
144 pub variants: Vec<SelectorVariant>,
145 /// Deprecated inputs accepted as canonical values.
146 #[serde(default)]
147 pub normalizations: Vec<Normalization>,
148 /// Nonzero cases intentionally unsupported by this adapter.
149 #[serde(default)]
150 pub rejected: Vec<String>,
151 /// Additional checked conversions from legacy wire enums.
152 #[serde(default)]
153 pub legacy: Vec<LegacySelector>,
154 /// Error for `from_identifier`; required if identities are supplied.
155 pub identifier_error: Option<ErrorMapping>,
156}
157
158/// A declared schema field reached through singular message fields.
159#[derive(Debug, Clone, Deserialize)]
160#[serde(deny_unknown_fields)]
161pub struct FieldSource {
162 /// Fully-qualified root message name.
163 pub message: String,
164 /// Nonempty field-name path, e.g. `["ecdsa_prehash", "digest"]`.
165 pub path: Vec<String>,
166}
167
168/// Restricted representation of a payload field.
169#[derive(Debug, Clone, Deserialize)]
170#[serde(from = "PayloadTypeJson")]
171pub enum PayloadType {
172 /// Borrow the original bytes without copying or exposing `Debug` output.
173 Bytes,
174 /// An application-supplied representation of this descriptor field.
175 ///
176 /// The generator checks the descriptor shape, path syntax and generated
177 /// `Copy` bound. It cannot resolve Rust type identity or inspect an opaque
178 /// value's fields; the application must preserve the declared native-type,
179 /// validation and ownership invariants. `Copy` alone permits references.
180 /// The generated Eq/Hash/Debug bounds also apply to owning payload enums.
181 Value {
182 /// Fully-qualified descriptor enum or message represented by the type.
183 source: String,
184 /// Plain Rust path; generic arguments and reference syntax are rejected.
185 /// For an enum field, the terminal identifier must match a configured
186 /// selector's name for `source`; renamed aliases are not resolved.
187 rust_type: String,
188 },
189}
190
191// serde ignores `deny_unknown_fields` on internally tagged unit variants, so
192// the JSON forms use empty struct variants: a members-free kind then rejects
193// any member other than `kind`, as the protobuf option front end does.
194#[derive(Deserialize)]
195#[serde(tag = "kind", deny_unknown_fields)]
196enum PayloadTypeJson {
197 Bytes {},
198 Value { source: String, rust_type: String },
199}
200
201impl From<PayloadTypeJson> for PayloadType {
202 fn from(value: PayloadTypeJson) -> Self {
203 match value {
204 PayloadTypeJson::Bytes {} => Self::Bytes,
205 PayloadTypeJson::Value { source, rust_type } => Self::Value { source, rust_type },
206 }
207 }
208}
209
210/// One payload field and its checked representation.
211#[derive(Debug, Clone, Deserialize)]
212#[serde(deny_unknown_fields)]
213pub struct PayloadField {
214 /// Name used in a struct variant; also validated for tuple payloads.
215 pub name: String,
216 /// Canonical source field.
217 pub source: FieldSource,
218 /// Restricted field representation.
219 pub representation: PayloadType,
220}
221
222/// Shape of one native enum alternative.
223#[derive(Debug, Clone, Deserialize)]
224#[serde(from = "PayloadJson")]
225pub enum Payload {
226 /// No payload.
227 Unit,
228 /// A single tuple field.
229 Tuple { field: PayloadField },
230 /// Named fields.
231 Struct { fields: Vec<PayloadField> },
232 /// A borrowed provider capability; never a portable field.
233 Port { name: String },
234}
235
236// JSON form of `Payload`; see `PayloadTypeJson`.
237#[derive(Deserialize)]
238#[serde(tag = "kind", deny_unknown_fields)]
239enum PayloadJson {
240 Unit {},
241 Tuple { field: PayloadField },
242 Struct { fields: Vec<PayloadField> },
243 Port { name: String },
244}
245
246impl From<PayloadJson> for Payload {
247 fn from(value: PayloadJson) -> Self {
248 match value {
249 PayloadJson::Unit {} => Self::Unit,
250 PayloadJson::Tuple { field } => Self::Tuple { field },
251 PayloadJson::Struct { fields } => Self::Struct { fields },
252 PayloadJson::Port { name } => Self::Port { name },
253 }
254 }
255}
256
257/// Native case covering one or more authoritative descriptor alternatives.
258#[derive(Debug, Clone, Deserialize)]
259#[serde(deny_unknown_fields)]
260pub struct PayloadVariant {
261 /// Public Rust variant name.
262 pub name: String,
263 /// Descriptor enum value names, or oneof member names.
264 pub cases: Vec<String>,
265 /// Checked payload shape.
266 pub payload: Payload,
267}
268
269/// Copy enum combining a selector with an explicitly validated native value.
270#[derive(Debug, Clone, Deserialize)]
271#[serde(deny_unknown_fields)]
272pub struct PayloadSelector {
273 /// Bare sibling output filename.
274 pub file: String,
275 /// Public Rust enum name.
276 pub name: String,
277 /// Fully-qualified descriptor enum name.
278 pub source: String,
279 /// Complete nonzero case coverage.
280 pub variants: Vec<PayloadVariant>,
281}
282
283/// Authoritative cases for a borrowed adapter.
284#[derive(Debug, Clone, Deserialize)]
285#[serde(tag = "kind", deny_unknown_fields)]
286pub enum BorrowedSource {
287 /// All nonzero values of a descriptor enum.
288 Enum { source: String },
289 /// Every alternative of an explicit oneof. Its entire message must consist
290 /// of that oneof, so unrelated wire fields cannot silently disappear.
291 Oneof { message: String, name: String },
292}
293
294/// Lifetime-bearing adapter. It deliberately has no derived diagnostics.
295#[derive(Debug, Clone, Deserialize)]
296#[serde(deny_unknown_fields)]
297pub struct BorrowedAdapter {
298 /// Bare sibling output filename.
299 pub file: String,
300 /// Public Rust enum name.
301 pub name: String,
302 /// Authoritative enum or oneof cases.
303 pub source: BorrowedSource,
304 /// Complete case and (for a oneof) payload-field coverage.
305 pub variants: Vec<PayloadVariant>,
306}
307
308/// Process-local capability supplied by the application, never serialized.
309#[derive(Debug, Clone, Deserialize)]
310#[serde(deny_unknown_fields)]
311pub struct CapabilityPort {
312 /// Manifest-local port name.
313 pub name: String,
314 /// Plain path to an existing object-safe Rust trait.
315 pub rust_trait: String,
316}