1use crate::firstparty;
12use bynk_syntax::CompileError;
13use bynk_syntax::span::Span;
14use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18pub const MANIFEST: &str = "bynk.toml";
20pub const EXPERIMENTAL: &str = "bynk.stability.experimental";
22pub const NOT_EXPERIMENTAL: &str = "bynk.project.unstable_not_experimental";
24pub const UNKNOWN_ITEM: &str = "bynk.project.unstable_unknown_item";
26
27#[derive(Debug, Clone, Default, PartialEq, Eq)]
31pub struct UnitStability {
32 pub policy: Arc<StabilityPolicy>,
33 pub blocked_imports: HashMap<String, String>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct StabilityPolicy {
40 pub allow: Vec<String>,
42 pub experimental: Vec<String>,
45 pub pg_sql: bool,
51}
52
53impl Default for StabilityPolicy {
54 fn default() -> Self {
61 Self::permissive()
62 }
63}
64
65impl StabilityPolicy {
66 pub fn for_project(project_root: Option<&Path>, overlay: &HashMap<PathBuf, String>) -> Self {
70 let allow = project_root
71 .map(|root| bynk_project::read_unstable_config(root, overlay).allow)
72 .unwrap_or_default();
73 let pg_sql = project_root.is_some_and(|root| {
74 let schema = root.join(bynk_project::PG_SCHEMA_FILE);
75 overlay.contains_key(&schema) || schema.is_file()
76 });
77 Self {
78 allow,
79 experimental: firstparty::experimental_items(),
80 pg_sql,
81 }
82 }
83
84 pub fn permissive() -> Self {
87 Self {
88 allow: Vec::new(),
89 experimental: Vec::new(),
90 pg_sql: false,
91 }
92 }
93
94 pub fn is_experimental(&self, path: &str) -> bool {
96 self.experimental
97 .iter()
98 .any(|item| firstparty::covers(item, path))
99 }
100
101 pub fn blocks(&self, path: &str) -> bool {
104 self.is_experimental(path) && !firstparty::allows(&self.allow, path)
105 }
106
107 pub fn check(&self, path: &str, span: Span) -> Option<CompileError> {
109 self.blocks(path).then(|| {
110 CompileError::new(
111 EXPERIMENTAL,
112 span,
113 format!("`{path}` is experimental: it may change or disappear in any release"),
114 )
115 .with_note(format!(
116 "to use it anyway, add \"{path}\" to `[unstable] allow` in `bynk.toml`"
117 ))
118 })
119 }
120
121 pub fn manifest_diagnostics(&self) -> Vec<CompileError> {
128 let mut out = Vec::new();
129 for entry in &self.allow {
130 if !firstparty::names_first_party_item(entry) {
131 out.push(CompileError::new(
132 UNKNOWN_ITEM,
133 Span::default(),
134 format!(
135 "`bynk.toml`'s `[unstable] allow` lists `{entry}`, which names no standard-library item"
136 ),
137 )
138 .with_note(
139 "an entry is a unit (`bynk.cloudflare`), an item it exports (`bynk.cloudflare.Kv`) or an operation (`bynk.cloudflare.Kv.list`)",
140 ));
141 } else if !firstparty::allow_entry_is_live(&self.experimental, entry) {
142 out.push(CompileError::new(
143 NOT_EXPERIMENTAL,
144 Span::default(),
145 format!(
146 "`bynk.toml`'s `[unstable] allow` lists `{entry}`, but nothing it covers is experimental"
147 ),
148 )
149 .with_note("it is stable now; remove it from `[unstable] allow`"));
150 }
151 }
152 out
153 }
154
155 pub fn blocked_imports(
160 &self,
161 imported_from: &HashMap<String, String>,
162 ) -> HashMap<String, String> {
163 imported_from
164 .iter()
165 .filter(|(_, unit)| firstparty::unit(unit).is_some())
166 .map(|(name, unit)| (name.clone(), format!("{unit}.{name}")))
167 .filter(|(_, path)| self.blocks(path))
168 .collect()
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175
176 fn policy(allow: &[&str], experimental: &[&str]) -> StabilityPolicy {
177 StabilityPolicy {
178 allow: allow.iter().map(|s| s.to_string()).collect(),
179 experimental: experimental.iter().map(|s| s.to_string()).collect(),
180 pg_sql: false,
181 }
182 }
183
184 #[test]
185 fn an_experimental_item_is_blocked_until_allowed() {
186 let p = policy(&[], &["bynk.cloudflare.Kv.putTtl"]);
187 assert!(p.blocks("bynk.cloudflare.Kv.putTtl"));
188 assert!(!p.blocks("bynk.cloudflare.Kv.put"));
189 assert!(
190 !p.blocks("bynk.cloudflare.Kv"),
191 "its capability stays stable"
192 );
193 let err = p
194 .check("bynk.cloudflare.Kv.putTtl", Span::default())
195 .unwrap();
196 assert_eq!(err.category, "bynk.stability.experimental");
197 assert!(err.notes[0].contains("\"bynk.cloudflare.Kv.putTtl\""));
198
199 for allow in [
200 "bynk.cloudflare.Kv.putTtl",
201 "bynk.cloudflare.Kv",
202 "bynk.cloudflare",
203 ] {
204 assert!(
205 !policy(&[allow], &["bynk.cloudflare.Kv.putTtl"])
206 .blocks("bynk.cloudflare.Kv.putTtl"),
207 "{allow}"
208 );
209 }
210 }
211
212 #[test]
213 fn manifest_entries_are_checked_for_existence_and_staleness() {
214 let p = policy(
215 &[
216 "bynk.cloudflare.Kv.putTtl",
217 "bynk.cloudflare",
218 "bynk.list",
219 "bynk.cloudflare.Kvv",
220 "user.thing",
221 ],
222 &["bynk.cloudflare.Kv.putTtl"],
223 );
224 let found: Vec<(String, String)> = p
225 .manifest_diagnostics()
226 .into_iter()
227 .map(|e| (e.category.to_string(), e.message.clone()))
228 .collect();
229 let codes: Vec<&str> = found.iter().map(|(c, _)| c.as_str()).collect();
230 assert_eq!(codes, [NOT_EXPERIMENTAL, UNKNOWN_ITEM, UNKNOWN_ITEM]);
231 assert!(found[0].1.contains("`bynk.list`"), "stale: {found:?}");
232 assert!(found[1].1.contains("`bynk.cloudflare.Kvv`"));
233 assert!(found[2].1.contains("`user.thing`"));
234 }
235
236 #[test]
237 fn blocked_imports_are_first_party_experimental_and_unallowed() {
238 let imported = HashMap::from([
239 ("join".to_string(), "bynk.string".to_string()),
240 ("reverse".to_string(), "bynk.list".to_string()),
241 ("Money".to_string(), "app.money".to_string()),
242 ]);
243 let p = policy(&[], &["bynk.string.join", "app.money"]);
244 assert_eq!(
245 p.blocked_imports(&imported),
246 HashMap::from([("join".to_string(), "bynk.string.join".to_string())]),
247 "a user unit is never experimental, whatever the list says"
248 );
249 assert!(
250 policy(&["bynk.string"], &["bynk.string.join"])
251 .blocked_imports(&imported)
252 .is_empty()
253 );
254 }
255
256 const PROJECT: &[(&str, &str)] = &[
261 (
262 "app/probe.test.bynk",
263 "suite app.probe\n\ncase \"a case calls an operation\" {\n\tlet _ <- Kv.putTtl(\"k\", \"v\", 120)\n\texpect Kv.putTtl called once\n}\n",
264 ),
265 (
266 "app/qual.bynk",
267 "context app.qual\n\nconsumes bynk\n\nservice ping {\n\ton call() -> Effect[Int] by Caller given bynk.Clock {\n\t\tlet _ <- bynk.Clock.now()\n\t\tEffect.pure(1)\n\t}\n}\n",
268 ),
269 (
270 "app/probe.bynk",
271 "context app.probe\n\nuses bynk.string\nuses bynk.locale.types\nconsumes bynk { Random }\nconsumes bynk.cloudflare { Kv }\n\nservice probe {\n\ton call(xs: List[String]) -> Effect[String] by Caller given Kv {\n\t\tlet _ <- Kv.putTtl(\"k\", \"v\", 120)\n\t\tlet joiner: (List[String], String) -> String = join\n\t\tEffect.pure(join(xs, \",\"))\n\t}\n}\n",
272 ),
273 ];
274
275 fn experimental_uses(policy: StabilityPolicy) -> Vec<(String, String)> {
278 let analysed = crate::testkit::analyse_with(PROJECT, Some(policy));
279 let mut out: Vec<(String, String)> = analysed
280 .analysis
281 .errors
282 .iter()
283 .filter(|a| a.error.category == "bynk.stability.experimental")
284 .map(|a| {
285 let path = a.error.message.split('`').nth(1).unwrap_or("").to_string();
286 let (start, end) = (a.error.span.start, a.error.span.end);
287 let file = a.source_path.as_deref().expect("a use is in a file");
288 let (_, text) = PROJECT
289 .iter()
290 .find(|(rel, _)| file.ends_with(rel))
291 .expect("a project file");
292 (path, text[start..end].to_string())
293 })
294 .collect();
295 out.sort();
296 out
297 }
298
299 #[test]
303 fn every_reference_point_refuses_an_experimental_item() {
304 let experimental = &[
305 "bynk.Clock.now",
306 "bynk.Random",
307 "bynk.locale.types",
308 "bynk.string.join",
309 "bynk.cloudflare.Kv.putTtl",
310 ];
311 assert_eq!(
312 experimental_uses(policy(&[], experimental)),
313 [
314 ("bynk.Clock.now".to_string(), "now".to_string()),
315 ("bynk.Random".to_string(), "Random".to_string()),
316 (
317 "bynk.cloudflare.Kv.putTtl".to_string(),
318 "putTtl".to_string()
319 ),
320 (
321 "bynk.locale.types".to_string(),
322 "bynk.locale.types".to_string()
323 ),
324 ("bynk.string.join".to_string(), "join".to_string()),
325 ("bynk.string.join".to_string(), "join".to_string()),
326 ],
327 "a consumes selection, a uses, a capability operation (flattened and qualified), and a function called and passed as a value in a handler; never in a suite case"
328 );
329 assert!(
330 experimental_uses(policy(
331 &[
332 "bynk.Clock",
333 "bynk.Random",
334 "bynk.locale",
335 "bynk.string",
336 "bynk.cloudflare.Kv"
337 ],
338 experimental
339 ))
340 .is_empty(),
341 "allow entries cover their path and everything under it"
342 );
343 assert!(
344 experimental_uses(StabilityPolicy::default()).is_empty(),
345 "the default fails open"
346 );
347 }
348
349 fn codes(source: &str) -> Vec<&'static str> {
351 crate::testkit::analyse(&[("app/probe.bynk", source)])
352 .analysis
353 .errors
354 .iter()
355 .map(|a| a.error.category)
356 .collect()
357 }
358
359 const FETCH_MATCH: &str = "context app.probe\n\nconsumes bynk { Fetch, Request, Method, FetchError }\n\nservice probe {\n\ton call(url: String) -> Effect[String] by Caller given Fetch {\n\t\tlet res <- Fetch.send(Request { method: Get, url: url, contentType: None, authorization: None, headers: Map.empty(), body: None })\n\t\tmatch res {\n\t\t\tOk(r) => Effect.pure(\"ok\")\n\t\t\tErr(Network) => Effect.pure(\"network\")\n\t\t\tErr(Timeout) => Effect.pure(\"timeout\")\n\t\t\tErr(InvalidHeader) => Effect.pure(\"header\")\n\t\t\tErr(InvalidBody) => Effect.pure(\"body\")\nWILDCARD\t\t}\n\t}\n}\n";
360
361 #[test]
365 fn an_extensible_enum_needs_a_wildcard_which_is_then_reachable() {
366 assert_eq!(
367 codes(&FETCH_MATCH.replace("WILDCARD", "")),
368 ["bynk.types.extensible_match_needs_wildcard"]
369 );
370 assert_eq!(
371 codes(&FETCH_MATCH.replace("WILDCARD", "\t\t\tErr(_) => Effect.pure(\"later\")\n")),
372 Vec::<&str>::new(),
373 "a wildcard satisfies it, and is not `bynk.types.unreachable_arm`"
374 );
375 assert_eq!(
376 codes(&FETCH_MATCH.replace("WILDCARD", "\t\t\tother => Effect.pure(\"later\")\n")),
377 Vec::<&str>::new(),
378 "so does a binding"
379 );
380 }
381
382 #[test]
385 fn a_users_own_enum_of_the_same_name_is_not_extensible() {
386 assert_eq!(
387 codes(
388 "context app.probe\n\ntype FetchError = enum { Network, Timeout, InvalidHeader }\n\nfn label(e: FetchError) -> String {\n\tmatch e {\n\t\tNetwork => \"n\"\n\t\tTimeout => \"t\"\n\t\tInvalidHeader => \"h\"\n\t}\n}\n\nservice probe {\n\ton call() -> Effect[String] by Caller {\n\t\tEffect.pure(label(Network))\n\t}\n}\n"
389 ),
390 Vec::<&str>::new()
391 );
392 }
393
394 #[test]
398 fn the_default_policy_fails_open() {
399 assert_eq!(StabilityPolicy::default(), StabilityPolicy::permissive());
400 assert_eq!(
401 UnitStability::default().policy.experimental,
402 Vec::<String>::new()
403 );
404 }
405
406 #[test]
411 fn the_shipped_policy_blocks_only_the_experimental_items() {
412 let p = StabilityPolicy::for_project(None, &HashMap::new());
413 let mut shipped = p.experimental.clone();
415 shipped.retain(|i| i != bynk_std::TESTING_UNIT);
416 assert_eq!(
417 shipped,
418 [
419 "bynk.Fetch.sendWith",
420 "bynk.Fetch.receiveBytes",
421 "bynk.Fetch.sendBytes",
422 "bynk.Fetch.receiveStream",
423 "bynk.Fetch.sendStream",
424 "bynk.Logger.log",
425 "bynk.cloudflare.Service",
426 "bynk.cloudflare.R2",
427 "bynk.cloudflare.RateLimit",
428 "bynk.cloudflare.EdgeCache",
429 "bynk.cloudflare.Queue",
430 "bynk.cloudflare.Analytics",
431 "bynk.cloudflare.Version",
432 "bynk.cloudflare.Ai",
433 "bynk.cloudflare.Images",
434 "bynk.cloudflare.StoredSecret",
435 "bynk.cloudflare.Email",
436 "bynk.cloudflare.Postgres",
437 "bynk.cloudflare.MySql",
438 "bynk.cloudflare.Vectorize",
439 "bynk.cloudflare.Container",
440 "bynk.cloudflare.AiSearch",
441 "bynk.cloudflare.MtlsCertificate",
442 "bynk.cloudflare.AnalyticsSql",
443 "bynk.cloudflare.RequestCf",
444 "bynk.cloudflare.Kv.getWith",
445 "bynk.cloudflare.Kv.putWith",
446 "bynk.cloudflare.Kv.getBytes",
447 "bynk.cloudflare.Kv.putBytes",
448 "bynk.cloudflare.Kv.listPage",
449 "bynk.crypto"
450 ]
451 );
452 assert!(!p.blocks("bynk.cloudflare.Kv.list"));
453 assert!(p.blocks("bynk.cloudflare.Version.current"));
455 assert!(!p.blocks("bynk.cloudflare.WorkerVersion"));
456 assert!(p.blocks("bynk.cloudflare.StoredSecret.get"));
458 assert!(p.blocks("bynk.cloudflare.Email.send"));
460 assert!(!p.blocks("bynk.cloudflare.Message"));
461 assert!(p.blocks("bynk.cloudflare.Postgres.all"));
464 assert!(!p.blocks("bynk.cloudflare.PgValue"));
465 assert!(p.blocks("bynk.cloudflare.MySql.all"));
467 assert!(!p.blocks("bynk.cloudflare.MySqlValue"));
468 assert!(p.blocks("bynk.Fetch.sendWith"));
470 assert!(!p.blocks("bynk.Fetch.send"));
471 assert!(!p.blocks("bynk.FetchOptions"));
472 assert!(p.blocks("bynk.Fetch.receiveBytes"));
474 assert!(p.blocks("bynk.Fetch.sendBytes"));
475 assert!(!p.blocks("bynk.BytesResponse"));
476 assert!(p.blocks("bynk.Fetch.receiveStream"));
478 assert!(p.blocks("bynk.Fetch.sendStream"));
479 assert!(!p.blocks("bynk.StreamResponse"));
480 assert!(p.blocks("bynk.Logger.log"));
481 assert!(!p.blocks("bynk.Logger.warn"));
482 assert!(p.blocks("bynk.cloudflare.Kv.putWith"));
484 assert!(p.blocks("bynk.cloudflare.Kv.listPage"));
485 assert!(!p.blocks("bynk.cloudflare.Kv.put"));
486 assert!(!p.blocks("bynk.cloudflare.KvPut"));
487 assert!(p.blocks("bynk.cloudflare.Service"));
488 assert!(p.blocks("bynk.cloudflare.Service.send"));
489 assert!(p.blocks("bynk.cloudflare.R2"));
490 assert!(p.blocks("bynk.cloudflare.R2.putWith"));
491 assert!(!p.blocks("bynk.cloudflare.R2Put"));
492 assert!(p.blocks("bynk.cloudflare.RateLimit.allow"));
493 assert!(p.blocks("bynk.cloudflare.Queue.sendBatch"));
494 assert!(!p.blocks("bynk.cloudflare.QueueSend"));
495 assert!(p.blocks("bynk.cloudflare.Analytics.write"));
496 assert!(!p.blocks("bynk.cloudflare.DataPoint"));
497 assert!(p.blocks("bynk.cloudflare.EdgeCache.purge"));
498 assert!(!p.blocks("bynk.cloudflare.D1"));
500 assert!(!p.blocks("bynk.cloudflare.D1.batch"));
501 assert!(!p.blocks("bynk.cloudflare.SqlValue"));
502 assert!(p.manifest_diagnostics().is_empty());
503 }
504}