1#![forbid(unsafe_code)]
51#![warn(clippy::pedantic)]
52
53mod api;
54
55use std::borrow::Cow;
56use std::sync::Arc;
57use std::time::Duration;
58
59use futures_core::future::BoxFuture;
60use futures_util::StreamExt as _;
61use ruprizzle::executor::{BoxRowStream, Executor, RawRow, RowBatch};
62use ruprizzle::value::Value;
63use ruprizzle_dialect::{DbDialect, SqliteDialect};
64use thiserror::Error;
65
66use api::{Envelope, QueryRequest};
67
68static SQLITE_DIALECT: SqliteDialect = SqliteDialect;
70
71const DEFAULT_ENDPOINT: &str = "https://api.cloudflare.com/client/v4";
73
74const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
76
77#[derive(Debug, Error)]
79#[non_exhaustive]
80pub enum D1Error {
81 #[error("d1 configuration error: {0}")]
83 Config(String),
84
85 #[error("d1 transport error: {0}")]
87 Transport(String),
88
89 #[error("d1 protocol error: {0}")]
91 Protocol(String),
92
93 #[error("d1 query error: {0}")]
95 Query(String),
96
97 #[error("unsupported by the D1 HTTP adapter: {0}")]
99 Unsupported(String),
100}
101
102impl From<D1Error> for ruprizzle::Error {
103 fn from(err: D1Error) -> Self {
104 ruprizzle::Error::Message(err.to_string())
105 }
106}
107
108#[derive(Debug, Default)]
110pub struct D1PoolBuilder {
111 account_id: Option<String>,
112 database_id: Option<String>,
113 api_token: Option<String>,
114 endpoint: Option<String>,
115 timeout: Option<Duration>,
116}
117
118impl D1PoolBuilder {
119 #[must_use]
121 pub fn new() -> Self {
122 Self::default()
123 }
124
125 #[must_use]
127 pub fn account_id(mut self, id: impl Into<String>) -> Self {
128 self.account_id = Some(id.into());
129 self
130 }
131
132 #[must_use]
134 pub fn database_id(mut self, id: impl Into<String>) -> Self {
135 self.database_id = Some(id.into());
136 self
137 }
138
139 #[must_use]
143 pub fn api_token(mut self, token: impl Into<String>) -> Self {
144 self.api_token = Some(token.into());
145 self
146 }
147
148 #[must_use]
150 pub fn endpoint(mut self, url: impl Into<String>) -> Self {
151 self.endpoint = Some(url.into());
152 self
153 }
154
155 #[must_use]
157 pub fn timeout(mut self, timeout: Duration) -> Self {
158 self.timeout = Some(timeout);
159 self
160 }
161
162 pub fn build(self) -> Result<D1Pool, D1Error> {
173 let account_id = self
174 .account_id
175 .ok_or_else(|| D1Error::Config("no `account_id` was configured".into()))?;
176 let database_id = self
177 .database_id
178 .ok_or_else(|| D1Error::Config("no `database_id` was configured".into()))?;
179 let api_token = self.api_token.ok_or_else(|| {
180 D1Error::Config("no `api_token` was configured; the D1 REST API is not open".into())
181 })?;
182
183 let root = self.endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned());
184 let query_url = format!(
185 "{}/accounts/{account_id}/d1/database/{database_id}/query",
186 root.trim_end_matches('/')
187 );
188
189 let http = reqwest::Client::builder()
190 .timeout(self.timeout.unwrap_or(DEFAULT_TIMEOUT))
191 .build()
192 .map_err(|e| D1Error::Config(format!("cannot build the HTTP client: {e}")))?;
193
194 Ok(D1Pool {
195 inner: Arc::new(D1PoolInner {
196 http,
197 query_url,
198 account_id,
199 database_id,
200 api_token,
201 }),
202 })
203 }
204}
205
206struct D1PoolInner {
207 http: reqwest::Client,
208 query_url: String,
210 account_id: String,
211 database_id: String,
212 api_token: String,
213}
214
215impl std::fmt::Debug for D1PoolInner {
220 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221 f.debug_struct("D1PoolInner")
222 .field("query_url", &self.query_url)
223 .field("account_id", &self.account_id)
224 .field("database_id", &self.database_id)
225 .field("api_token", &"<redacted>")
226 .finish_non_exhaustive()
229 }
230}
231
232#[derive(Debug, Clone)]
237pub struct D1Pool {
238 inner: Arc<D1PoolInner>,
239}
240
241impl D1Pool {
242 #[must_use]
244 pub fn builder() -> D1PoolBuilder {
245 D1PoolBuilder::new()
246 }
247
248 #[must_use]
250 pub fn account_id(&self) -> &str {
251 &self.inner.account_id
252 }
253
254 #[must_use]
256 pub fn database_id(&self) -> &str {
257 &self.inner.database_id
258 }
259
260 async fn query(&self, sql: &str, binds: &[Value]) -> Result<api::QueryResult, D1Error> {
262 let params = binds
263 .iter()
264 .map(api::to_json)
265 .collect::<Result<Vec<_>, _>>()?;
266
267 let response = self
268 .inner
269 .http
270 .post(&self.inner.query_url)
271 .bearer_auth(&self.inner.api_token)
272 .json(&QueryRequest {
273 sql: sql.to_owned(),
274 params,
275 })
276 .send()
277 .await
278 .map_err(|e| D1Error::Transport(e.to_string()))?;
279
280 let status = response.status();
281 let text = response
282 .text()
283 .await
284 .map_err(|e| D1Error::Transport(format!("cannot read the response body: {e}")))?;
285
286 match serde_json::from_str::<Envelope>(&text) {
290 Ok(envelope) => envelope.single_result(),
291 Err(e) if status.is_success() => Err(D1Error::Protocol(format!(
292 "cannot parse the D1 response: {e}; body was {}",
293 truncate(&text, 512)
294 ))),
295 Err(_) => Err(D1Error::Protocol(format!(
296 "Cloudflare answered {status}: {}",
297 truncate(&text, 512)
298 ))),
299 }
300 }
301}
302
303fn truncate(text: &str, limit: usize) -> Cow<'_, str> {
305 match text.char_indices().nth(limit) {
306 Some((end, _)) => Cow::Owned(format!("{}…", &text[..end])),
307 None => Cow::Borrowed(text),
308 }
309}
310
311impl Executor for D1Pool {
312 fn dialect(&self) -> &dyn DbDialect {
313 &SQLITE_DIALECT
314 }
315
316 fn fetch_all_raw(
317 &self,
318 sql: Cow<'static, str>,
319 binds: Vec<Value>,
320 ) -> BoxFuture<'_, Result<RowBatch, ruprizzle::Error>> {
321 Box::pin(async move {
322 let result = self.query(&sql, &binds).await?;
323 Ok(RowBatch::Edge(result.into_edge_rows()))
324 })
325 }
326
327 fn execute_raw(
328 &self,
329 sql: Cow<'static, str>,
330 binds: Vec<Value>,
331 ) -> BoxFuture<'_, Result<u64, ruprizzle::Error>> {
332 Box::pin(async move { Ok(self.query(&sql, &binds).await?.meta.changes) })
333 }
334
335 fn stream_raw(&self, sql: Cow<'static, str>, binds: Vec<Value>) -> BoxRowStream<'_> {
336 Box::pin(
340 futures_util::stream::once(self.fetch_all_raw(sql, binds)).flat_map(|batch| {
341 let rows = match batch {
342 Ok(RowBatch::Edge(rows)) => {
343 rows.into_iter().map(RawRow::Edge).map(Ok).collect()
344 }
345 Ok(_) => vec![Err(ruprizzle::Error::Message(
346 "the D1 adapter only produces edge rows".into(),
347 ))],
348 Err(e) => vec![Err(e)],
349 };
350 futures_util::stream::iter(rows)
351 }),
352 )
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 fn pool() -> D1Pool {
361 D1Pool::builder()
362 .account_id("acct")
363 .database_id("db-uuid")
364 .api_token("secret-token")
365 .build()
366 .unwrap()
367 }
368
369 #[test]
370 fn the_query_url_is_built_from_the_account_and_database() {
371 let pool = pool();
372 assert_eq!(
373 pool.inner.query_url,
374 "https://api.cloudflare.com/client/v4/accounts/acct/d1/database/db-uuid/query"
375 );
376 }
377
378 #[test]
379 fn an_overridden_endpoint_keeps_the_path_shape() {
380 let pool = D1Pool::builder()
381 .account_id("a")
382 .database_id("b")
383 .api_token("t")
384 .endpoint("http://127.0.0.1:9999/")
385 .build()
386 .unwrap();
387 assert_eq!(
388 pool.inner.query_url,
389 "http://127.0.0.1:9999/accounts/a/d1/database/b/query"
390 );
391 }
392
393 #[test]
394 fn every_credential_is_required() {
395 assert!(matches!(
396 D1Pool::builder().database_id("b").api_token("t").build(),
397 Err(D1Error::Config(_))
398 ));
399 assert!(matches!(
400 D1Pool::builder().account_id("a").api_token("t").build(),
401 Err(D1Error::Config(_))
402 ));
403 assert!(matches!(
404 D1Pool::builder().account_id("a").database_id("b").build(),
405 Err(D1Error::Config(_))
406 ));
407 }
408
409 #[test]
410 fn the_api_token_is_not_in_debug_output() {
411 let rendered = format!("{:?}", pool());
412 assert!(
413 !rendered.contains("secret-token"),
414 "the API token must not be in Debug output: {rendered}"
415 );
416 }
417
418 #[test]
419 fn the_dialect_is_sqlite() {
420 assert_eq!(pool().dialect().name(), "sqlite");
421 }
422}