Skip to main content

bynk_emit/emitter/workers_entry/
field_specs.rs

1//! The request field specs of the Worker entry: the field-spec tables the router reads a query,
2//! form, multipart or cookie body by, and the leaf kinds they are built from.
3
4use crate::emitter::serialisation;
5use crate::ts_build::{bool_lit, str_lit};
6use bynk_check::symbols::UnitTable;
7use bynk_syntax::ast::{Handler, LimitsPolicy, TypeRef};
8use bynk_ts::TsExpr;
9
10/// One field of a record read off a query string, a form, a `Cookie` header or a
11/// multipart body: `(name, leaf kind, list, option, wire name)`. The wire name is
12/// the `@name("…")` rename (#3343), `None` when the field reads under its own name.
13pub(crate) type FieldSpec = (String, &'static str, bool, bool, Option<String>);
14
15/// The `QueryField` object the runtime's readers take for one field.
16fn field_spec_expr((name, kind, list, option, wire): &FieldSpec) -> TsExpr {
17    let mut props = vec![("name".to_string(), str_lit(name.clone()))];
18    if let Some(wire) = wire {
19        props.push(("wire".to_string(), str_lit(wire.clone())));
20    }
21    props.push(("kind".to_string(), str_lit(*kind)));
22    props.push(("list".to_string(), bool_lit(*list)));
23    props.push(("option".to_string(), bool_lit(*option)));
24    TsExpr::object(props)
25}
26
27/// The same object as TypeScript source (`{ name: "sid", wire: "__Host-sid", kind: … }`),
28/// for the system-tier drivers and the `Form` lowering, which write text.
29pub fn field_spec_source((name, kind, list, option, wire): &FieldSpec) -> String {
30    let wire = wire
31        .as_ref()
32        .map(|w| format!(" wire: {w:?},"))
33        .unwrap_or_default();
34    format!("{{ name: {name:?},{wire} kind: {kind:?}, list: {list}, option: {option} }}")
35}
36
37/// #3343: the `QueryField` array a system-tier driver passes the request writers
38/// (`__queryString`, `__cookieString`) for a typed record parameter, when a field of
39/// the record is renamed by `@name`; `None` otherwise (the writers need no table).
40pub fn renamed_specs_source(
41    type_ref: &TypeRef,
42    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
43) -> Option<String> {
44    use bynk_syntax::ast::TypeBody;
45    let TypeRef::Named(id) = type_ref else {
46        return None;
47    };
48    let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
49        return None;
50    };
51    let specs = record_field_specs(rec, types, false);
52    if specs.iter().all(|s| s.4.is_none()) {
53        return None;
54    }
55    let items: Vec<String> = specs.iter().map(field_spec_source).collect();
56    Some(format!("[{}] as const", items.join(", ")))
57}
58
59pub(super) fn field_specs_exprs(fields: &[FieldSpec]) -> Vec<TsExpr> {
60    fields.iter().map(field_spec_expr).collect()
61}
62
63/// #3276: what the router needs to read a `@multipart` body.
64#[derive(Debug, Clone)]
65pub(super) struct MultipartSpec {
66    pub(super) fields: Vec<FieldSpec>,
67    /// The per-file byte cap (`@limit(maxFile:)`, else `limits { maxFile }`), if any.
68    pub(super) max_file: Option<i64>,
69    /// The part-count cap (`@limit(maxParts:)`, else `limits { maxParts }`, else 64).
70    pub(super) max_parts: i64,
71    /// Whether the record has a `File` field, whose real values are laid over
72    /// the decoded record.
73    pub(super) has_files: bool,
74}
75
76/// #2854: the wire kind of one query-string value of type `r`, as the runtime's
77/// `QueryField.kind` names it.
78pub(crate) fn query_leaf_kind(
79    r: &TypeRef,
80    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
81    allow_file: bool,
82) -> &'static str {
83    use bynk_syntax::ast::{BaseType, TypeBody};
84    let of_base = |b: &BaseType| match b {
85        BaseType::Int => "int",
86        BaseType::Bool => "bool",
87        // #3276: a `Decimal` is read as text (its own codec parses it), but is not a
88        // plain `String`: a form's empty value is absent for it.
89        BaseType::Decimal => "decimal",
90        BaseType::String
91        | BaseType::Float
92        | BaseType::Duration
93        | BaseType::Instant
94        | BaseType::Bytes => "string",
95    };
96    match r {
97        TypeRef::Base(b, _) => of_base(b),
98        // #3276: the `File` a `@multipart` body names a part with.
99        // The checker admits only the std `File` as a multipart file field
100        // (`bynk.http.form_field_not_stringy` refuses a user type of that name), so
101        // the name is enough here, on the multipart path alone.
102        TypeRef::Named(id) if allow_file && id.name == "File" => "file",
103        TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
104            Some(TypeBody::Refined { base, .. }) | Some(TypeBody::Opaque { base, .. }) => {
105                of_base(base)
106            }
107            Some(TypeBody::Sum(_)) => "enum",
108            _ => "string",
109        },
110        TypeRef::Result(..)
111        | TypeRef::Option(..)
112        | TypeRef::Effect(..)
113        | TypeRef::HttpResult(..)
114        | TypeRef::QueueResult(_)
115        | TypeRef::Asset(_)
116        | TypeRef::RequestHeaders(_)
117        | TypeRef::RequestQuery(_)
118        | TypeRef::RequestCookies(_)
119        | TypeRef::TokenClaims(_)
120        | TypeRef::BoundaryRejection(_)
121        | TypeRef::List(..)
122        | TypeRef::Map(..)
123        | TypeRef::Set(..)
124        | TypeRef::Query(..)
125        | TypeRef::Stream(..)
126        | TypeRef::Connection(..)
127        | TypeRef::History(..)
128        | TypeRef::ValidationError(_)
129        | TypeRef::DecodeError(_)
130        | TypeRef::Unit(_)
131        | TypeRef::Fn(..)
132        | TypeRef::App { .. } => "string",
133    }
134}
135
136/// #2854: the fields of a handler's typed `query` record, or `None` when the
137/// handler has no `query` parameter, or it is the raw `RequestQuery` view (or a
138/// path parameter named `query`).
139pub(super) fn query_field_specs(
140    h: &Handler,
141    path: &str,
142    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
143) -> Option<Vec<FieldSpec>> {
144    use bynk_syntax::ast::TypeBody;
145    if path.split('/').any(|seg| seg == ":query") {
146        return None;
147    }
148    let p = h.params.iter().find(|p| p.name.name == "query")?;
149    let TypeRef::Named(id) = &p.type_ref else {
150        return None;
151    };
152    let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
153        return None;
154    };
155    Some(record_field_specs(rec, types, false))
156}
157
158/// #3276: the fields of a `@form` handler's `body` record, as `formObject` reads
159/// them. `None` when the handler is not a `@form` route.
160pub(super) fn form_field_specs(
161    h: &Handler,
162    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
163) -> Option<Vec<FieldSpec>> {
164    use bynk_syntax::ast::TypeBody;
165    if !h.annotations.iter().any(|a| a.name.name == "form") {
166        return None;
167    }
168    let p = h.params.iter().find(|p| p.name.name == "body")?;
169    let TypeRef::Named(id) = &p.type_ref else {
170        return None;
171    };
172    let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
173        return None;
174    };
175    Some(record_field_specs(rec, types, false))
176}
177
178/// #3277: the fields of a handler's `cookies` record, or `None` when it has no
179/// `cookies` parameter (or a `:cookies` path segment binds the name).
180pub(super) fn cookies_field_specs(
181    h: &Handler,
182    path: &str,
183    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
184) -> Option<Vec<FieldSpec>> {
185    use bynk_syntax::ast::TypeBody;
186    if path.split('/').any(|seg| seg == ":cookies") {
187        return None;
188    }
189    let p = h.params.iter().find(|p| p.name.name == "cookies")?;
190    let TypeRef::Named(id) = &p.type_ref else {
191        return None;
192    };
193    let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
194        return None;
195    };
196    Some(record_field_specs(rec, types, false))
197}
198
199/// #3276: the body field spec of a `@form` or `@multipart` handler, as the system
200/// test drivers write the body (`(name, wire kind, list, option)`).
201pub fn form_body_specs(
202    h: &Handler,
203    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
204) -> Option<Vec<FieldSpec>> {
205    form_field_specs(h, types).or_else(|| multipart_spec(None, h, types).map(|m| m.fields))
206}
207
208/// #3276: a `@multipart` handler's body spec, or `None` when it is not one.
209pub(super) fn multipart_spec(
210    service_limits: Option<&LimitsPolicy>,
211    h: &Handler,
212    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
213) -> Option<MultipartSpec> {
214    use bynk_syntax::ast::TypeBody;
215    if !h.annotations.iter().any(|a| a.name.name == "multipart") {
216        return None;
217    }
218    let p = h.params.iter().find(|p| p.name.name == "body")?;
219    let TypeRef::Named(id) = &p.type_ref else {
220        return None;
221    };
222    let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
223        return None;
224    };
225    let fields = record_field_specs(rec, types, true);
226    let has_files = fields.iter().any(|(_, kind, _, _, _)| *kind == "file");
227    Some(MultipartSpec {
228        fields,
229        max_file: h
230            .limit_max_file()
231            .or_else(|| service_limits.and_then(|p| p.max_file())),
232        max_parts: h
233            .limit_max_parts()
234            .or_else(|| service_limits.and_then(|p| p.max_parts()))
235            .unwrap_or(bynk_syntax::ast::DEFAULT_MAX_PARTS),
236        has_files,
237    })
238}
239
240/// The wire shape of each field of a record read off a query string or a form:
241/// `(name, leaf kind, list, option)`.
242pub(crate) fn record_field_specs(
243    rec: &bynk_syntax::ast::RecordBody,
244    types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
245    allow_file: bool,
246) -> Vec<FieldSpec> {
247    rec.fields
248        .iter()
249        .map(|f| {
250            let (inner, list, option) = serialisation::peel_list_option(&f.type_ref);
251            (
252                f.name.name.clone(),
253                query_leaf_kind(inner, types, allow_file),
254                list,
255                option,
256                f.wire_name(),
257            )
258        })
259        .collect()
260}
261
262/// #2858: whether any `from http` route in `table` writes plain JSON, so the
263/// generated `Option` encoders carry the plain branch.
264pub fn table_has_plain_json(table: &UnitTable) -> bool {
265    table.services.values().any(|svc| {
266        svc.handlers.iter().any(|h| {
267            bynk_syntax::ast::effective_json_options(svc.json.as_ref(), h)
268                == bynk_syntax::ast::JsonOptions::Plain
269        })
270    })
271}
272
273/// v0.142 (ADR 0165): resolve a route's effective request-body ceiling in bytes.
274/// A route's `@limit(maxBody:)` annotation wins over the service's `limits { }`
275/// default (DECISION B); with neither, the route has no cap (`None`). Project
276/// validation (`bynk.http.limit_*` / `limits_*`) has already rejected a malformed
277/// or misplaced `@limit`/`limits`, so a bad/absent value here simply yields no
278/// cap. Only a body-taking method can carry a cap — a `@limit` on a GET/DELETE is
279/// a checker error, so it never reaches a live route here. The route-annotation
280/// half is `bynk-emit::ir`'s own [`bynk_model::lower_route_limit_ir`]
281/// (#1228); only the service-wide fallback composition stays here.
282pub(super) fn effective_max_body(
283    service_limits: Option<&LimitsPolicy>,
284    h: &Handler,
285) -> Option<i64> {
286    h.limit_max_body()
287        .or_else(|| service_limits.and_then(|p| p.max_body()))
288}