1use super::*;
17use std::collections::BTreeMap;
18
19const PEEK_TYPE: &str = "D1Peek";
25
26fn peek_type_name(participant: &str, cap: &str) -> String {
27 format!("{PEEK_TYPE}[{participant}.{cap}]")
28}
29
30fn parse_peek_type(name: &str) -> Option<(String, String)> {
32 let path = name
33 .strip_prefix(PEEK_TYPE)?
34 .strip_prefix('[')?
35 .strip_suffix(']')?;
36 let (participant, cap) = path.rsplit_once('.')?;
37 Some((participant.to_string(), cap.to_string()))
38}
39
40const READ_OPS: &[&str] = &["all", "first", "select", "firstAs"];
42
43const WRITE_OPS: &[&str] = &["run", "batch"];
46
47#[derive(Debug, Clone, Default)]
50pub struct PeekEnv {
51 pub participants: BTreeMap<String, BTreeMap<String, PeekCap>>,
52}
53
54#[derive(Debug, Clone)]
57pub struct PeekCap {
58 pub info: CapabilityInfo,
59 pub binding: Option<String>,
60}
61
62fn local_name(participant: &str, cap: &str) -> String {
67 format!("__peek_{}_{}", participant.replace('.', "_"), cap)
68}
69
70pub const LOCAL_PREFIX: &str = "__peek_";
73
74fn path_of(e: &Expr) -> Option<Vec<String>> {
76 match &e.kind {
77 ExprKind::Ident(id) => Some(vec![id.name.clone()]),
78 ExprKind::FieldAccess { receiver, field } => {
79 let mut head = path_of(receiver)?;
80 head.push(field.name.clone());
81 Some(head)
82 }
83 _ => None,
84 }
85}
86
87pub(crate) fn begins_with_write(sql: &str) -> bool {
92 let mut rest = sql;
93 loop {
94 rest = rest.trim_start();
95 if let Some(after) = rest.strip_prefix("--") {
96 rest = after.split_once('\n').map_or("", |(_, tail)| tail);
97 } else if let Some(after) = rest.strip_prefix("/*") {
98 rest = after.split_once("*/").map_or("", |(_, tail)| tail);
99 } else {
100 break;
101 }
102 }
103 let word: String = rest
104 .chars()
105 .take_while(char::is_ascii_alphabetic)
106 .collect::<String>()
107 .to_ascii_uppercase();
108 matches!(
109 word.as_str(),
110 "INSERT"
111 | "UPDATE"
112 | "DELETE"
113 | "REPLACE"
114 | "CREATE"
115 | "DROP"
116 | "ALTER"
117 | "VACUUM"
118 | "REINDEX"
119 | "ANALYZE"
120 | "ATTACH"
121 | "DETACH"
122 )
123}
124
125fn is_d1(info: &CapabilityInfo) -> bool {
126 matches!(&info.derived_from, Some((unit, base))
127 if unit == crate::firstparty::CLOUDFLARE_UNIT && base == "D1")
128}
129
130#[allow(clippy::too_many_arguments)]
133pub(super) fn check_peek_call(
134 receiver: &Expr,
135 method: &Ident,
136 type_args: &[TypeRef],
137 args: &[Expr],
138 span: Span,
139 expected: Option<TyId>,
140 expr_id: ExprId,
141 ctx: &mut Ctx,
142) -> Option<Option<TyId>> {
143 let ExprKind::Ident(root) = &receiver.kind else {
144 return None;
145 };
146 if let Some(ty) = ctx.lookup(&root.name) {
147 let handle = match &*ctx.tys.get(ty) {
148 Ty::Named { name, .. } => parse_peek_type(name),
149 _ => None,
150 }?;
151 return Some(check_handle_op(
152 &handle, root, method, type_args, args, span, expected, expr_id, ctx,
153 ));
154 }
155 if root.name == "D1" && method.name == "peek" && !ctx.input.types.contains_key("D1") {
156 return Some(check_create(args, span, expr_id, ctx));
157 }
158 None
159}
160
161fn refuse(code: &'static str, span: Span, message: String, note: &str, ctx: &mut Ctx) {
162 ctx.errors
163 .push(CompileError::new(code, span, message).with_note(note.to_string()));
164}
165
166fn check_create(args: &[Expr], span: Span, expr_id: ExprId, ctx: &mut Ctx) -> Option<TyId> {
167 let tys = ctx.tys;
168 let Some(env) = ctx.caps.peek_env.clone() else {
169 refuse(
170 "bynk.test.peek_outside_case",
171 span,
172 "`D1.peek` is only valid inside an `integration` or `system` case".to_string(),
173 "it reads a participant's test database, which only those tiers stand up; a `unit` case reads the capability it stubs, and the deployed app has no such handle",
174 ctx,
175 );
176 return None;
177 };
178 if ctx.caps.peek_let_value != Some(expr_id) {
181 refuse(
182 "bynk.test.peek_not_bound",
183 span,
184 "`D1.peek` is bound with `let`, and is used only through the handle it binds"
185 .to_string(),
186 "write `let db = D1.peek(<participant>.<Capability>)` and call `db.all(…)`",
187 ctx,
188 );
189 return None;
190 }
191 let [arg] = args else {
192 refuse(
193 "bynk.test.peek_unknown_capability",
194 span,
195 format!(
196 "`D1.peek` takes one argument, a participant's D1 capability, but {} were given",
197 args.len()
198 ),
199 "write `D1.peek(<participant>.<Capability>)`, for example `D1.peek(shop.orders.Orders)`",
200 ctx,
201 );
202 return None;
203 };
204 let Some(path) = path_of(arg).filter(|p| p.len() >= 2) else {
205 refuse(
206 "bynk.test.peek_unknown_capability",
207 arg.span,
208 "`D1.peek` names a capability by its participant, as `<participant>.<Capability>`"
209 .to_string(),
210 "for example `D1.peek(shop.orders.Orders)`",
211 ctx,
212 );
213 return None;
214 };
215 let (cap, participant) = (
216 path[path.len() - 1].clone(),
217 path[..path.len() - 1].join("."),
218 );
219 let Some(caps) = env.participants.get(&participant) else {
220 refuse(
221 "bynk.test.peek_unknown_capability",
222 arg.span,
223 format!("`{participant}` is not a participant of this suite"),
224 &format!(
225 "the participants here are: {}",
226 env.participants
227 .keys()
228 .cloned()
229 .collect::<Vec<_>>()
230 .join(", ")
231 ),
232 ctx,
233 );
234 return None;
235 };
236 let Some(PeekCap { info, binding }) = caps.get(&cap) else {
237 refuse(
238 "bynk.test.peek_unknown_capability",
239 arg.span,
240 format!("`{participant}` declares no capability `{cap}`"),
241 "name a capability the participant declares, `capability <Name> = D1`",
242 ctx,
243 );
244 return None;
245 };
246 if !is_d1(info) {
247 refuse(
248 "bynk.test.peek_not_a_database",
249 arg.span,
250 format!("`D1.peek` reads a D1 database, but `{participant}.{cap}` is not a D1 binding"),
251 "only a capability derived from `D1` has a test database to read",
252 ctx,
253 );
254 return None;
255 }
256 ctx.callees.insert(
257 expr_id,
258 Callee::D1Peek {
259 participant: participant.clone(),
260 binding: binding.clone().expect("a D1 capability has a binding"),
263 local: local_name(&participant, &cap),
264 },
265 );
266 Some(tys.intern(Ty::Named {
267 name: peek_type_name(&participant, &cap),
268 kind: NamedKind::Record,
269 args: Vec::new(),
270 }))
271}
272
273pub(super) fn expect_let(value: &Expr, ctx: &mut Ctx) {
275 ctx.caps.peek_let_value = Some(value.id);
276}
277
278#[allow(clippy::too_many_arguments)]
279fn check_handle_op(
280 handle: &(String, String),
281 receiver: &Ident,
282 method: &Ident,
283 type_args: &[TypeRef],
284 args: &[Expr],
285 span: Span,
286 expected: Option<TyId>,
287 expr_id: ExprId,
288 ctx: &mut Ctx,
289) -> Option<TyId> {
290 let (participant, cap) = handle;
291 let info = ctx
292 .caps
293 .peek_env
294 .as_ref()
295 .and_then(|e| e.participants.get(participant))
296 .and_then(|c| c.get(cap))
297 .map(|c| c.info.clone());
298 let info = info?;
299 if !READ_OPS.contains(&method.name.as_str()) {
300 if WRITE_OPS.contains(&method.name.as_str()) {
301 refuse(
302 "bynk.test.peek_write",
303 method.span,
304 format!("`{}` writes, and `D1.peek` is read-only", method.name),
305 "the handle offers `all`, `first`, `select[T]` and `firstAs[T]`; a case makes the app write by driving the app",
306 ctx,
307 );
308 } else {
309 refuse(
310 "bynk.capability.unknown_operation",
311 method.span,
312 format!(
313 "a `D1.peek` handle has no operation named `{}`",
314 method.name
315 ),
316 "the handle offers `all`, `first`, `select[T]` and `firstAs[T]`",
317 ctx,
318 );
319 }
320 for a in args {
321 let _ = type_of(a, None, ctx);
322 }
323 return None;
324 }
325 let local = local_name(participant, cap);
328 let present = ctx.caps.capabilities.insert(local.clone(), info);
329 let name = Ident {
330 name: local.clone(),
331 span: receiver.span,
332 };
333 let out = super::calls::check_static_call(
334 &name, method, type_args, args, span, expected, expr_id, ctx,
335 );
336 match present {
337 Some(p) => {
338 ctx.caps.capabilities.insert(local.clone(), p);
339 }
340 None => {
341 ctx.caps.capabilities.remove(&local);
342 }
343 }
344 if let Some(sql) = args.first()
347 && let Some(text) = super::d1::sql_literal_text(sql, ctx)
348 && begins_with_write(&text)
349 {
350 refuse(
351 "bynk.test.peek_write",
352 sql.span,
353 format!(
354 "the SQL of `D1.peek` reads, but this statement of `{}.{}` would write",
355 receiver.name, method.name
356 ),
357 "a peeked database is read-only: a case makes the app write by driving the app",
358 ctx,
359 );
360 }
361 if let Some(sql) = args.first()
364 && let Some(callee) = ctx.callees.get_mut(&sql.id)
365 {
366 let site = match callee {
367 Callee::D1Sql(site) => Some(site),
368 Callee::Const(_, Some(site)) => Some(site.as_mut()),
369 _ => None,
370 };
371 if let Some(site) = site {
372 site.peek = Some((participant.clone(), cap.clone()));
373 }
374 }
375 out
376}