1#![doc = include_str!("../README.md")]
2
3use neotales_dbapi::{
4 BufferedReader, Capabilities, DbError, DbFuture, DbType, ErrorKind, ExecuteOptions,
5 ImmediateTransaction, Parameter, Pool, PoolDefaults, QueryOptions, Reader, Row, RowLimit,
6 Session, Transaction, TxOptions, Value,
7};
8use std::{
9 fmt,
10 future::Future,
11 pin::Pin,
12 sync::{
13 Arc, OnceLock,
14 atomic::{AtomicBool, Ordering},
15 },
16 task::{Context, Poll},
17 time::Duration,
18};
19use tokio::sync::{OwnedSemaphorePermit, Semaphore};
20use tracing::dispatcher::{Dispatch, with_default};
21use url::{Host, Url};
22use zeroize::Zeroizing;
23
24use libsql::{
25 Builder, Connection, Transaction as LibsqlTransactionHandle, Value as LibsqlValue,
26 params_from_iter,
27};
28
29pub struct LibsqlConfig {
35 endpoint: String,
36 token: Zeroizing<String>,
37 plaintext: bool,
38 max_connections: u32,
39 acquire_timeout: Duration,
40}
41
42impl LibsqlConfig {
43 #[must_use]
48 pub fn remote(endpoint: impl Into<String>, token: impl Into<String>) -> Self {
49 Self {
50 endpoint: endpoint.into(),
51 token: Zeroizing::new(token.into()),
52 plaintext: false,
53 max_connections: 8,
54 acquire_timeout: Duration::from_secs(5),
55 }
56 }
57
58 pub fn plaintext_loopback(
67 endpoint: impl Into<String>,
68 token: impl Into<String>,
69 ) -> Result<Self, DbError> {
70 let config = Self {
71 endpoint: endpoint.into(),
72 token: Zeroizing::new(token.into()),
73 plaintext: true,
74 max_connections: 8,
75 acquire_timeout: Duration::from_secs(5),
76 };
77 config.validate()?;
78 Ok(config)
79 }
80
81 #[must_use]
83 pub fn max_connections(mut self, count: u32) -> Self {
84 self.max_connections = count;
85 self
86 }
87
88 #[must_use]
91 pub fn acquire_timeout(mut self, timeout: Duration) -> Self {
92 self.acquire_timeout = timeout;
93 self
94 }
95
96 fn validate(&self) -> Result<(), DbError> {
97 let millis = self.acquire_timeout.as_millis();
98 if self.endpoint.is_empty()
99 || self.endpoint.len() > 2048
100 || self.endpoint.as_bytes().contains(&0)
101 || self.token.as_bytes().contains(&0)
102 || self.token.len() > 8192
103 || self.max_connections == 0
104 || self.max_connections > 1024
105 || millis == 0
106 || millis > i32::MAX as u128
107 {
108 return Err(invalid());
109 }
110 let url = Url::parse(&self.endpoint).map_err(|_| invalid())?;
111 if url.username() != ""
112 || url.password().is_some()
113 || url.fragment().is_some()
114 || url.query().is_some()
115 || url.port() == Some(0)
116 || !matches!(url.path(), "" | "/")
117 {
118 return Err(invalid());
119 }
120 let Some(host) = url.host() else {
121 return Err(invalid());
122 };
123 if self.plaintext {
124 if url.scheme() != "http" || !is_loopback(&host) {
125 return Err(invalid());
126 }
127 } else if !matches!(url.scheme(), "libsql" | "https") {
128 return Err(invalid());
129 }
130 Ok(())
131 }
132
133 fn endpoint(&self) -> &str {
134 &self.endpoint
135 }
136
137 fn token(&self) -> &str {
138 self.token.as_str()
139 }
140}
141
142impl fmt::Debug for LibsqlConfig {
143 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
144 formatter
145 .debug_struct("LibsqlConfig")
146 .field("endpoint", &"[redacted]")
147 .field("token", &"[redacted]")
148 .field("plaintext", &self.plaintext)
149 .field("max_connections", &self.max_connections)
150 .field("acquire_timeout", &self.acquire_timeout)
151 .finish_non_exhaustive()
152 }
153}
154
155fn is_loopback(host: &Host<&str>) -> bool {
156 match host {
157 Host::Ipv4(address) => address.is_loopback(),
158 Host::Ipv6(address) => address.is_loopback(),
159 Host::Domain(_) => false,
160 }
161}
162
163fn invalid() -> DbError {
164 DbError::new(ErrorKind::InvalidArgument)
165}
166
167fn overflow() -> DbError {
168 DbError::new(ErrorKind::Overflow)
169}
170
171fn connection_error() -> DbError {
172 DbError::new(ErrorKind::Connection)
173}
174
175fn map_code(code: i32) -> DbError {
176 match code & 0xff {
177 1 | 21 | 25 => invalid(),
178 3 | 8 => DbError::new(ErrorKind::Unsupported),
179 5 | 6 => DbError::new(ErrorKind::Busy),
180 9 => DbError::new(ErrorKind::Cancelled),
181 18 => overflow(),
182 19 => DbError::new(ErrorKind::Constraint),
183 20 => DbError::new(ErrorKind::Decode),
184 _ => connection_error(),
185 }
186}
187
188#[allow(clippy::needless_pass_by_value)]
189fn map_error(error: libsql::Error) -> DbError {
190 use libsql::Error;
191 match error {
192 Error::SqliteFailure(code, _) | Error::RemoteSqliteFailure(code, _, _) => map_code(code),
193 Error::Misuse(_)
194 | Error::Sqlite3SyntaxError(_, _, _)
195 | Error::Sqlite3ParserError(_)
196 | Error::TransactionalBatchError(_)
197 | Error::ToSqlConversionFailure(_) => invalid(),
198 Error::Sqlite3UnsupportedStatement | Error::ReservedBytesNotSupported => {
199 DbError::new(ErrorKind::Unsupported)
200 }
201 Error::NullValue
202 | Error::QueryReturnedNoRows
203 | Error::ExecuteReturnedRows
204 | Error::InvalidColumnName(_)
205 | Error::ColumnNotFound(_)
206 | Error::InvalidColumnIndex
207 | Error::InvalidColumnType
208 | Error::InvalidBlobSize(_) => DbError::new(ErrorKind::Decode),
209 Error::WalConflict => DbError::new(ErrorKind::Busy),
210 _ => connection_error(),
211 }
212}
213
214fn map_write_error(error: libsql::Error) -> DbError {
215 let mapped = map_error(error);
216 match mapped.kind() {
217 ErrorKind::Connection | ErrorKind::Timeout | ErrorKind::Cancelled => {
218 DbError::new(ErrorKind::WriteOutcomeUnknown)
219 }
220 _ => mapped,
221 }
222}
223
224fn budget(options: ExecuteOptions) -> Result<Option<Duration>, DbError> {
225 match options.timeout_ms {
226 None => Ok(None),
227 Some(0) => Err(invalid()),
228 Some(millis) => Ok(Some(Duration::from_millis(millis))),
229 }
230}
231
232struct Silent<F> {
239 inner: Pin<Box<F>>,
240}
241
242impl<F: Future> Silent<F> {
243 fn new(future: F) -> Self {
244 Self {
245 inner: Box::pin(future),
246 }
247 }
248}
249
250impl<F: Future> Future for Silent<F> {
251 type Output = F::Output;
252
253 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
254 let this = self.get_mut();
255 with_default(no_trace(), || this.inner.as_mut().poll(context))
256 }
257}
258
259fn no_trace() -> &'static Dispatch {
260 static NO_TRACE: OnceLock<Dispatch> = OnceLock::new();
261 NO_TRACE.get_or_init(Dispatch::none)
262}
263
264fn silent<F: Future>(future: F) -> Silent<F> {
265 Silent::new(future)
266}
267
268#[derive(Clone)]
270pub struct LibsqlPoolProvider {
271 database: Arc<libsql::Database>,
272 permits: Arc<Semaphore>,
273 acquire_timeout: Duration,
274}
275
276impl fmt::Debug for LibsqlPoolProvider {
277 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
278 formatter
279 .debug_struct("LibsqlPoolProvider")
280 .field("acquire_timeout", &self.acquire_timeout)
281 .finish_non_exhaustive()
282 }
283}
284
285impl LibsqlPoolProvider {
286 pub async fn connect(config: LibsqlConfig) -> Result<Self, DbError> {
295 config.validate()?;
296 let endpoint = config.endpoint().to_owned();
297 let token = config.token().to_owned();
298 let database = match silent(Builder::new_remote(endpoint, token).build()).await {
299 Ok(database) => Arc::new(database),
300 Err(error) => return Err(map_error(error)),
301 };
302 let probe = async {
303 let connection = database.connect().map_err(map_error)?;
304 silent(connection.query("SELECT 1", ()))
305 .await
306 .map_err(map_error)?;
307 Ok::<(), DbError>(())
308 };
309 match tokio::time::timeout(config.acquire_timeout, probe).await {
310 Ok(result) => result?,
311 Err(_) => return Err(DbError::new(ErrorKind::Timeout)),
312 }
313 Ok(Self {
314 database,
315 permits: Arc::new(Semaphore::new(config.max_connections as usize)),
316 acquire_timeout: config.acquire_timeout,
317 })
318 }
319
320 pub async fn acquire_libsql_session(&self) -> Result<LibsqlSession, DbError> {
329 let permit = match tokio::time::timeout(
330 self.acquire_timeout,
331 Arc::clone(&self.permits).acquire_owned(),
332 )
333 .await
334 {
335 Ok(Ok(permit)) => permit,
336 Ok(Err(_)) => return Err(connection_error()),
337 Err(_) => return Err(DbError::new(ErrorKind::Timeout)),
338 };
339 let connection = self.database.connect().map_err(map_error)?;
340 Ok(LibsqlSession {
341 connection: Some(connection),
342 _permit: permit,
343 interrupted: Arc::new(AtomicBool::new(false)),
344 poisoned: false,
345 })
346 }
347
348 pub async fn acquire_libsql(&self) -> Result<Box<dyn ImmediateTransaction>, DbError> {
354 Ok(Box::new(self.acquire_libsql_session().await?))
355 }
356}
357
358impl Pool for LibsqlPoolProvider {
359 fn capabilities(&self) -> Capabilities {
360 Capabilities {
361 transactions: true,
362 isolation_level: false,
363 read_only_transactions: false,
364 trusted_scripts: true,
365 }
366 }
367
368 fn acquire_async(&self) -> DbFuture<'_, Box<dyn Session>> {
369 Box::pin(
370 async move { Ok(Box::new(self.acquire_libsql_session().await?) as Box<dyn Session>) },
371 )
372 }
373}
374
375pub struct LibsqlSession {
380 connection: Option<Connection>,
381 _permit: OwnedSemaphorePermit,
382 interrupted: Arc<AtomicBool>,
383 poisoned: bool,
384}
385
386impl fmt::Debug for LibsqlSession {
387 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
388 formatter
389 .debug_struct("LibsqlSession")
390 .field("poisoned", &self.poisoned)
391 .finish_non_exhaustive()
392 }
393}
394
395impl LibsqlSession {
396 fn ensure_live(&mut self) -> Result<(), DbError> {
397 if self.poisoned || self.interrupted.load(Ordering::Acquire) {
398 self.discard();
399 return Err(connection_error());
400 }
401 Ok(())
402 }
403
404 fn live(&mut self) -> Result<Connection, DbError> {
405 self.ensure_live()?;
406 self.connection.clone().ok_or_else(|| {
407 self.discard();
408 connection_error()
409 })
410 }
411
412 fn discard(&mut self) {
413 self.poisoned = true;
414 self.interrupted.store(true, Ordering::Release);
415 self.connection = None;
416 }
417
418 async fn fetch_inner(
425 connection: &Connection,
426 sql: &str,
427 parameters: &[Parameter],
428 limit: RowLimit,
429 ) -> Result<Vec<Row>, DbError> {
430 let mut rows = connection
431 .query(sql, to_params(parameters))
432 .await
433 .map_err(map_write_error)?;
434 let mut result = Vec::new();
435 let mut bytes = 0usize;
436 loop {
437 let Some(row) = rows.next().await.map_err(map_write_error)? else {
438 break;
439 };
440 if result.len() == limit.rows() {
441 return Err(overflow());
442 }
443 let mut cells = Vec::with_capacity(usize::try_from(row.column_count()).unwrap_or(0));
444 for index in 0..row.column_count() {
445 let name = row.column_name(index).unwrap_or_default().to_owned();
446 bytes = bytes.checked_add(name.len()).ok_or_else(overflow)?;
447 let value = decode(
448 row.get_value(index)
449 .map_err(|_| DbError::new(ErrorKind::Decode))?,
450 )?;
451 bytes = bytes
452 .checked_add(value_bytes(&value))
453 .ok_or_else(overflow)?;
454 if bytes > limit.bytes() {
455 return Err(overflow());
456 }
457 cells.push((name, value));
458 }
459 result.push(Row::new(cells)?);
460 }
461 Ok(result)
462 }
463}
464
465impl Session for LibsqlSession {
466 fn execute_async<'a>(
467 &'a mut self,
468 sql: &'a str,
469 mut options: QueryOptions,
470 ) -> DbFuture<'a, u64> {
471 Box::pin(async move {
472 options.prepare_execute_provider(PoolDefaults::default())?;
473 let budget = budget(options.provider_execute_options())?;
474 let parameters = options.parameters.as_slice();
475 validate_statement(sql, parameters)?;
476 let connection = self.live()?;
477 let flight = Flight::new(&self.interrupted);
478 match execute_inner(&connection, sql, parameters, budget).await {
479 Ok(rows) => {
480 flight.disarm();
481 Ok(rows)
482 }
483 Err(error) => {
484 self.discard();
485 Err(error)
486 }
487 }
488 })
489 }
490
491 fn fetch_async<'a>(
492 &'a mut self,
493 sql: &'a str,
494 mut options: QueryOptions,
495 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
496 Box::pin(async move {
497 let limit = options.prepare_provider(PoolDefaults::default())?;
498 let budget = budget(options.provider_execute_options())?;
499 let parameters = options.parameters.as_slice();
500 validate_statement(sql, parameters)?;
501 let connection = self.live()?;
502 let flight = Flight::new(&self.interrupted);
503 match fetch_with_budget(&connection, sql, parameters, limit, budget).await {
504 Ok(rows) => {
505 flight.disarm();
506 Ok(Box::new(BufferedReader::new(rows)) as Box<dyn Reader + 'a>)
507 }
508 Err(error) => {
509 self.discard();
510 Err(error)
511 }
512 }
513 })
514 }
515
516 fn execute_trusted_script_async<'a>(
517 &'a mut self,
518 sql: &'a str,
519 mut options: QueryOptions,
520 ) -> DbFuture<'a, ()> {
521 Box::pin(async move {
522 options.prepare_script_provider(PoolDefaults::default())?;
523 let budget = budget(options.provider_execute_options())?;
524 check_sql(sql)?;
525 let connection = self.live()?;
526 let flight = Flight::new(&self.interrupted);
527 match script_with_budget(&connection, sql, budget).await {
528 Ok(()) => {
529 flight.disarm();
530 Ok(())
531 }
532 Err(error) => {
533 self.discard();
534 Err(error)
535 }
536 }
537 })
538 }
539
540 fn begin_async<'a>(
541 &'a mut self,
542 options: TxOptions,
543 ) -> DbFuture<'a, Box<dyn Transaction<'a> + 'a>> {
544 Box::pin(async move {
545 check_tx_options(options)?;
546 let connection = self.live()?;
547 let flight = Flight::new(&self.interrupted);
548 let tx = match silent(
549 connection.transaction_with_behavior(libsql::TransactionBehavior::Deferred),
550 )
551 .await
552 {
553 Ok(tx) => tx,
554 Err(error) => {
555 self.discard();
556 return Err(map_error(error));
557 }
558 };
559 flight.disarm();
560 Ok(Box::new(LibsqlTransaction {
561 session: self,
562 tx: Some(tx),
563 done: false,
564 }) as Box<dyn Transaction<'a>>)
565 })
566 }
567}
568
569impl ImmediateTransaction for LibsqlSession {
570 fn begin_immediate_async<'a>(&'a mut self) -> DbFuture<'a, Box<dyn Transaction<'a> + 'a>> {
571 Box::pin(async move {
572 let connection = self.live()?;
573 let flight = Flight::new(&self.interrupted);
574 let tx = match silent(
575 connection.transaction_with_behavior(libsql::TransactionBehavior::Immediate),
576 )
577 .await
578 {
579 Ok(tx) => tx,
580 Err(error) => {
581 self.discard();
582 return Err(map_error(error));
583 }
584 };
585 flight.disarm();
586 Ok(Box::new(LibsqlTransaction {
587 session: self,
588 tx: Some(tx),
589 done: false,
590 }) as Box<dyn Transaction<'a>>)
591 })
592 }
593}
594
595struct LibsqlTransaction<'session> {
596 session: &'session mut LibsqlSession,
597 tx: Option<LibsqlTransactionHandle>,
598 done: bool,
599}
600
601impl LibsqlTransaction<'_> {
602 fn live(&self) -> Result<&LibsqlTransactionHandle, DbError> {
603 if self.done {
604 return Err(connection_error());
605 }
606 self.tx.as_ref().ok_or_else(connection_error)
607 }
608}
609
610impl<'session> Transaction<'session> for LibsqlTransaction<'session> {
611 fn execute_async<'a>(
612 &'a mut self,
613 sql: &'a str,
614 mut options: QueryOptions,
615 ) -> DbFuture<'a, u64> {
616 Box::pin(async move {
617 options.prepare_execute_provider(PoolDefaults::default())?;
618 let budget = budget(options.provider_execute_options())?;
619 let parameters = options.parameters.as_slice();
620 validate_statement(sql, parameters)?;
621 self.session.ensure_live()?;
622 let flight = Flight::new(&self.session.interrupted);
623 let result = {
624 let tx = self.live()?;
625 execute_inner(tx, sql, parameters, budget).await
626 };
627 match result {
628 Ok(rows) => {
629 flight.disarm();
630 Ok(rows)
631 }
632 Err(error) => {
633 self.session.discard();
634 Err(error)
635 }
636 }
637 })
638 }
639
640 fn fetch_async<'a>(
641 &'a mut self,
642 sql: &'a str,
643 mut options: QueryOptions,
644 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
645 Box::pin(async move {
646 let limit = options.prepare_provider(PoolDefaults::default())?;
647 let budget = budget(options.provider_execute_options())?;
648 let parameters = options.parameters.as_slice();
649 validate_statement(sql, parameters)?;
650 self.session.ensure_live()?;
651 let flight = Flight::new(&self.session.interrupted);
652 let result = {
653 let tx = self.live()?;
654 fetch_with_budget(tx, sql, parameters, limit, budget).await
655 };
656 match result {
657 Ok(rows) => {
658 flight.disarm();
659 Ok(Box::new(BufferedReader::new(rows)) as Box<dyn Reader + 'a>)
660 }
661 Err(error) => {
662 self.session.discard();
663 Err(error)
664 }
665 }
666 })
667 }
668
669 fn execute_trusted_script_async<'a>(
670 &'a mut self,
671 sql: &'a str,
672 mut options: QueryOptions,
673 ) -> DbFuture<'a, ()> {
674 Box::pin(async move {
675 options.prepare_script_provider(PoolDefaults::default())?;
676 let budget = budget(options.provider_execute_options())?;
677 check_sql(sql)?;
678 self.session.ensure_live()?;
679 let flight = Flight::new(&self.session.interrupted);
680 let result = {
681 let tx = self.live()?;
682 script_with_budget(tx, sql, budget).await
683 };
684 match result {
685 Ok(()) => {
686 flight.disarm();
687 Ok(())
688 }
689 Err(error) => {
690 self.session.discard();
691 Err(error)
692 }
693 }
694 })
695 }
696
697 fn commit_async(self: Box<Self>) -> DbFuture<'session, ()> {
698 Box::pin(async move {
699 let mut this = *self;
700 if let Err(error) = this.session.ensure_live() {
701 this.done = true;
702 this.session.discard();
703 return Err(error);
704 }
705 let Some(tx) = this.tx.take() else {
706 this.done = true;
707 this.session.discard();
708 return Err(connection_error());
709 };
710 let result = silent(tx.commit()).await;
711 this.done = true;
712 if let Ok(()) = result {
713 Ok(())
714 } else {
715 this.session.discard();
716 Err(DbError::new(ErrorKind::CommitOutcomeUnknown))
717 }
718 })
719 }
720
721 fn rollback_async(self: Box<Self>) -> DbFuture<'session, ()> {
722 Box::pin(async move {
723 let mut this = *self;
724 if let Err(error) = this.session.ensure_live() {
725 this.done = true;
726 this.session.discard();
727 return Err(error);
728 }
729 let Some(tx) = this.tx.take() else {
730 this.done = true;
731 this.session.discard();
732 return Err(connection_error());
733 };
734 let result = silent(tx.rollback()).await;
735 this.done = true;
736 if let Ok(()) = result {
737 Ok(())
738 } else {
739 this.session.discard();
740 Err(connection_error())
741 }
742 })
743 }
744}
745
746impl Drop for LibsqlTransaction<'_> {
747 fn drop(&mut self) {
748 if !self.done {
749 self.done = true;
750 self.tx.take();
751 self.session.discard();
752 }
753 }
754}
755
756async fn execute_inner(
757 connection: &Connection,
758 sql: &str,
759 parameters: &[Parameter],
760 budget: Option<Duration>,
761) -> Result<u64, DbError> {
762 let future = silent(connection.execute(sql, to_params(parameters)));
763 match budget {
764 None => future.await.map_err(map_write_error),
765 Some(duration) => match tokio::time::timeout(duration, future).await {
766 Ok(result) => result.map_err(map_write_error),
767 Err(_) => Err(DbError::new(ErrorKind::WriteOutcomeUnknown)),
768 },
769 }
770}
771
772async fn fetch_with_budget(
773 connection: &Connection,
774 sql: &str,
775 parameters: &[Parameter],
776 limit: RowLimit,
777 budget: Option<Duration>,
778) -> Result<Vec<Row>, DbError> {
779 let future = silent(LibsqlSession::fetch_inner(
780 connection, sql, parameters, limit,
781 ));
782 match budget {
783 None => future.await,
784 Some(duration) => match tokio::time::timeout(duration, future).await {
785 Ok(result) => result,
786 Err(_) => Err(DbError::new(ErrorKind::WriteOutcomeUnknown)),
787 },
788 }
789}
790
791async fn script_with_budget(
794 connection: &Connection,
795 sql: &str,
796 budget: Option<Duration>,
797) -> Result<(), DbError> {
798 let future = silent(connection.execute_batch(sql));
799 match budget {
800 None => future.await.map(|_| ()).map_err(map_write_error),
801 Some(duration) => match tokio::time::timeout(duration, future).await {
802 Ok(result) => result.map(|_| ()).map_err(map_write_error),
803 Err(_) => Err(DbError::new(ErrorKind::WriteOutcomeUnknown)),
804 },
805 }
806}
807
808fn to_params(parameters: &[Parameter]) -> impl libsql::params::IntoParams + '_ {
809 params_from_iter(parameters.iter().map(|parameter| match parameter.value() {
810 Value::Null(_) => LibsqlValue::Null,
811 Value::Bool(value) => LibsqlValue::Integer(i64::from(*value)),
812 Value::I64(value) => LibsqlValue::Integer(*value),
813 Value::F64(value) => LibsqlValue::Real(*value),
814 Value::Text(value) => LibsqlValue::Text(value.clone()),
815 Value::Bytes(value) => LibsqlValue::Blob(value.clone()),
816 }))
817}
818
819fn decode(value: LibsqlValue) -> Result<Value, DbError> {
820 match value {
821 LibsqlValue::Null => Ok(Value::Null(DbType::Text)),
822 LibsqlValue::Integer(value) => Ok(Value::I64(value)),
823 LibsqlValue::Real(value) if value.is_finite() => Ok(Value::F64(value)),
824 LibsqlValue::Real(_) => Err(DbError::new(ErrorKind::Decode)),
825 LibsqlValue::Text(value) => Ok(Value::Text(value)),
826 LibsqlValue::Blob(value) => Ok(Value::Bytes(value)),
827 }
828}
829
830fn value_bytes(value: &Value) -> usize {
831 match value {
832 Value::Text(text) => text.len(),
833 Value::Bytes(bytes) => bytes.len(),
834 _ => 0,
835 }
836}
837
838fn check_tx_options(options: TxOptions) -> Result<(), DbError> {
839 if options.isolation.is_some() || options.read_only == Some(true) {
840 Err(DbError::new(ErrorKind::Unsupported))
841 } else {
842 Ok(())
843 }
844}
845
846fn validate_statement(sql: &str, parameters: &[Parameter]) -> Result<(), DbError> {
847 check_sql(sql)?;
848 check_one_statement(sql)?;
849 check_not_transaction_control(sql)?;
850 check_arity(sql, parameters)
851}
852
853fn check_sql(sql: &str) -> Result<(), DbError> {
854 if sql.as_bytes().contains(&0) {
855 Err(invalid())
856 } else {
857 Ok(())
858 }
859}
860
861fn check_one_statement(sql: &str) -> Result<(), DbError> {
862 #[derive(Clone, Copy)]
863 enum State {
864 Normal,
865 Single,
866 Double,
867 Backtick,
868 Bracket,
869 LineComment,
870 BlockComment,
871 }
872
873 let bytes = sql.as_bytes();
874 let mut state = State::Normal;
875 let mut index = 0;
876 let mut has_code = false;
877 let mut terminated = false;
878 while index < bytes.len() {
879 let byte = bytes[index];
880 match state {
881 State::Normal => match byte {
882 b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' => {}
883 b'-' if bytes.get(index + 1) == Some(&b'-') => {
884 state = State::LineComment;
885 index += 1;
886 }
887 b'/' if bytes.get(index + 1) == Some(&b'*') => {
888 state = State::BlockComment;
889 index += 1;
890 }
891 b';' => {
892 if !terminated {
893 if !has_code {
894 return Err(invalid());
895 }
896 terminated = true;
897 }
898 }
899 b'\'' | b'"' | b'`' | b'[' => {
900 if terminated {
901 return Err(invalid());
902 }
903 has_code = true;
904 state = match byte {
905 b'\'' => State::Single,
906 b'"' => State::Double,
907 b'`' => State::Backtick,
908 _ => State::Bracket,
909 };
910 }
911 _ => {
912 if terminated {
913 return Err(invalid());
914 }
915 has_code = true;
916 }
917 },
918 State::Single if byte == b'\'' => {
919 if bytes.get(index + 1) == Some(&b'\'') {
920 index += 1;
921 } else {
922 state = State::Normal;
923 }
924 }
925 State::Double if byte == b'"' => {
926 if bytes.get(index + 1) == Some(&b'"') {
927 index += 1;
928 } else {
929 state = State::Normal;
930 }
931 }
932 State::Backtick if byte == b'`' => {
933 if bytes.get(index + 1) == Some(&b'`') {
934 index += 1;
935 } else {
936 state = State::Normal;
937 }
938 }
939 State::Bracket if byte == b']' => state = State::Normal,
940 State::LineComment if byte == b'\n' => state = State::Normal,
941 State::BlockComment if byte == b'*' && bytes.get(index + 1) == Some(&b'/') => {
942 state = State::Normal;
943 index += 1;
944 }
945 _ => {}
946 }
947 index += 1;
948 }
949 if !matches!(state, State::Normal | State::LineComment) || !has_code {
950 return Err(invalid());
951 }
952 Ok(())
953}
954
955fn leading_command(sql: &str) -> Result<&[u8], DbError> {
956 let bytes = sql.as_bytes();
957 let mut index = 0;
958 loop {
959 while bytes
960 .get(index)
961 .is_some_and(|byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c'))
962 {
963 index += 1;
964 }
965 if bytes.get(index..index + 2) == Some(b"--") {
966 index += 2;
967 while bytes.get(index).is_some_and(|byte| *byte != b'\n') {
968 index += 1;
969 }
970 continue;
971 }
972 if bytes.get(index..index + 2) == Some(b"/*") {
973 index += 2;
974 while index + 1 < bytes.len() && bytes.get(index..index + 2) != Some(b"*/") {
975 index += 1;
976 }
977 if index + 1 >= bytes.len() {
978 return Err(invalid());
979 }
980 index += 2;
981 continue;
982 }
983 break;
984 }
985
986 if !bytes.get(index).is_some_and(u8::is_ascii_alphabetic) {
987 return Err(invalid());
988 }
989 let start = index;
990 while bytes
991 .get(index)
992 .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
993 {
994 index += 1;
995 }
996 Ok(&bytes[start..index])
997}
998
999fn check_not_transaction_control(sql: &str) -> Result<(), DbError> {
1000 let token = leading_command(sql)?;
1001 if token.eq_ignore_ascii_case(b"BEGIN")
1002 || token.eq_ignore_ascii_case(b"COMMIT")
1003 || token.eq_ignore_ascii_case(b"END")
1004 || token.eq_ignore_ascii_case(b"ROLLBACK")
1005 || token.eq_ignore_ascii_case(b"SAVEPOINT")
1006 || token.eq_ignore_ascii_case(b"RELEASE")
1007 {
1008 Err(invalid())
1009 } else {
1010 Ok(())
1011 }
1012}
1013
1014fn check_arity(sql: &str, parameters: &[Parameter]) -> Result<(), DbError> {
1015 #[derive(Clone, Copy)]
1016 enum State {
1017 Normal,
1018 Single,
1019 Double,
1020 Backtick,
1021 Bracket,
1022 LineComment,
1023 BlockComment,
1024 }
1025 let bytes = sql.as_bytes();
1026 let mut state = State::Normal;
1027 let mut index = 0;
1028 let mut maximum = 0usize;
1029 let mut indexed = false;
1030 let mut anonymous = false;
1031 while index < bytes.len() {
1032 let byte = bytes[index];
1033 match state {
1034 State::Normal => match byte {
1035 b'\'' => state = State::Single,
1036 b'"' => state = State::Double,
1037 b'`' => state = State::Backtick,
1038 b'[' => state = State::Bracket,
1039 b'-' if bytes.get(index + 1) == Some(&b'-') => {
1040 state = State::LineComment;
1041 index += 1;
1042 }
1043 b'/' if bytes.get(index + 1) == Some(&b'*') => {
1044 state = State::BlockComment;
1045 index += 1;
1046 }
1047 b'?' => {
1048 index += 1;
1049 let start = index;
1050 while bytes.get(index).is_some_and(u8::is_ascii_digit) {
1051 index += 1;
1052 }
1053 let number = if index > start {
1054 indexed = true;
1055 std::str::from_utf8(&bytes[start..index])
1056 .ok()
1057 .and_then(|digits| digits.parse::<usize>().ok())
1058 .ok_or_else(invalid)?
1059 } else {
1060 anonymous = true;
1061 maximum.checked_add(1).ok_or_else(invalid)?
1062 };
1063 if number == 0 {
1064 return Err(invalid());
1065 }
1066 maximum = maximum.max(number);
1067 continue;
1068 }
1069 b':' | b'@' | b'$' => return Err(DbError::new(ErrorKind::Unsupported)),
1070 _ => {}
1071 },
1072 State::Single if byte == b'\'' => {
1073 if bytes.get(index + 1) == Some(&b'\'') {
1074 index += 1;
1075 } else {
1076 state = State::Normal;
1077 }
1078 }
1079 State::Double if byte == b'"' => {
1080 if bytes.get(index + 1) == Some(&b'"') {
1081 index += 1;
1082 } else {
1083 state = State::Normal;
1084 }
1085 }
1086 State::Backtick if byte == b'`' => state = State::Normal,
1087 State::Bracket if byte == b']' => state = State::Normal,
1088 State::LineComment if byte == b'\n' => state = State::Normal,
1089 State::BlockComment if byte == b'*' && bytes.get(index + 1) == Some(&b'/') => {
1090 state = State::Normal;
1091 index += 1;
1092 }
1093 _ => {}
1094 }
1095 index += 1;
1096 }
1097 if indexed && anonymous {
1098 return Err(invalid());
1099 }
1100 if maximum == parameters.len() {
1101 Ok(())
1102 } else {
1103 Err(invalid())
1104 }
1105}
1106
1107struct Flight {
1108 interrupted: Arc<AtomicBool>,
1109 armed: bool,
1110}
1111
1112impl Flight {
1113 fn new(interrupted: &Arc<AtomicBool>) -> Self {
1114 interrupted.store(false, Ordering::Release);
1115 Self {
1116 interrupted: Arc::clone(interrupted),
1117 armed: true,
1118 }
1119 }
1120
1121 fn disarm(mut self) {
1122 self.armed = false;
1123 }
1124}
1125
1126impl Drop for Flight {
1127 fn drop(&mut self) {
1128 if self.armed {
1129 self.interrupted.store(true, Ordering::Release);
1130 }
1131 }
1132}
1133
1134#[cfg(test)]
1135mod tests {
1136 use super::{
1137 LibsqlConfig, budget, check_arity, check_one_statement, check_tx_options, map_error,
1138 map_write_error, silent,
1139 };
1140 use neotales_dbapi::{
1141 DbType, ErrorKind, ExecuteOptions, IsolationLevel, Parameter, TxOptions, Value,
1142 };
1143 use std::sync::{
1144 Arc,
1145 atomic::{AtomicUsize, Ordering},
1146 };
1147 use tracing_subscriber::{Layer, layer::SubscriberExt};
1148
1149 struct CountLayer(Arc<AtomicUsize>);
1150
1151 impl<S: tracing::Subscriber> Layer<S> for CountLayer {
1152 fn on_event(
1153 &self,
1154 _event: &tracing::Event<'_>,
1155 _context: tracing_subscriber::layer::Context<'_, S>,
1156 ) {
1157 self.0.fetch_add(1, Ordering::Relaxed);
1158 }
1159 }
1160
1161 fn parameter() -> Parameter {
1162 Parameter::new(DbType::I64, Value::I64(1)).unwrap()
1163 }
1164
1165 #[test]
1166 fn config_rejects_insecure_and_ambiguous_endpoints() {
1167 for endpoint in [
1168 "http://db.example.com",
1169 "ws://127.0.0.1:8080",
1170 "wss://db.example.com",
1171 "https://user:password@db.example.com",
1172 "https://db.example.com/path",
1173 "https://db.example.com?token=secret",
1174 "https://db.example.com#fragment",
1175 "https://db.example.com:0",
1176 "not a url",
1177 ] {
1178 assert!(
1179 LibsqlConfig::remote(endpoint, "token").validate().is_err(),
1180 "{endpoint}"
1181 );
1182 }
1183 assert!(
1184 LibsqlConfig::remote("libsql://db.example.com", "token")
1185 .validate()
1186 .is_ok()
1187 );
1188 assert!(
1189 LibsqlConfig::remote("https://db.example.com", "token")
1190 .validate()
1191 .is_ok()
1192 );
1193 }
1194
1195 #[test]
1196 fn plaintext_requires_a_numeric_loopback_host() {
1197 assert!(
1198 LibsqlConfig::plaintext_loopback("http://127.0.0.1:8080", "")
1199 .unwrap()
1200 .validate()
1201 .is_ok()
1202 );
1203 assert!(
1204 LibsqlConfig::plaintext_loopback("http://[::1]:8080", "")
1205 .unwrap()
1206 .validate()
1207 .is_ok()
1208 );
1209 for endpoint in [
1210 "http://localhost:8080",
1211 "http://192.0.2.1:8080",
1212 "https://127.0.0.1:8080",
1213 "libsql://127.0.0.1:8080",
1214 ] {
1215 assert!(
1216 LibsqlConfig::plaintext_loopback(endpoint, "").is_err(),
1217 "{endpoint}"
1218 );
1219 }
1220 }
1221
1222 #[test]
1223 fn config_debug_redacts_the_endpoint_and_token() {
1224 let config = LibsqlConfig::remote("https://secret.example.com", "very-secret-token");
1225 let rendered = format!("{config:?}");
1226 assert!(!rendered.contains("secret.example.com"));
1227 assert!(!rendered.contains("very-secret-token"));
1228 assert!(rendered.contains("[redacted]"));
1229 }
1230
1231 #[test]
1232 fn scanner_accepts_one_statement_with_quoted_semicolons() {
1233 for sql in [
1234 "SELECT 1",
1235 "SELECT ';'",
1236 "SELECT \"a;b\"",
1237 "SELECT `a;b`",
1238 "SELECT [a;b]",
1239 "SELECT 1; -- trailing comment",
1240 "/* leading ; */ SELECT 1;;;",
1241 ] {
1242 assert!(check_one_statement(sql).is_ok(), "{sql}");
1243 }
1244 for sql in [
1245 "",
1246 ";",
1247 "SELECT 1; SELECT 2",
1248 "SELECT 'unterminated",
1249 "SELECT 1 /* unterminated",
1250 ] {
1251 assert!(check_one_statement(sql).is_err(), "{sql}");
1252 }
1253 }
1254
1255 #[test]
1256 fn arity_counts_only_unquoted_placeholders() {
1257 let sql = "SELECT ?, '?', \"?\", `?col`, ? -- ?\n, /* ? */ ?";
1258 let parameters = [parameter(), parameter(), parameter()];
1259 assert!(check_arity(sql, ¶meters).is_ok());
1260 assert!(check_arity(sql, ¶meters[..2]).is_err());
1261
1262 let indexed = "SELECT ?2, ?1";
1263 assert!(check_arity(indexed, ¶meters[..2]).is_ok());
1264 assert!(check_arity(indexed, ¶meters[..1]).is_err());
1265 assert!(check_arity("SELECT ?, ?1", ¶meters[..2]).is_err());
1266 assert!(check_arity("SELECT ?0", &[]).is_err());
1267 assert_eq!(
1268 check_arity("SELECT :name", &[]).unwrap_err().kind(),
1269 ErrorKind::Unsupported
1270 );
1271 }
1272
1273 #[test]
1274 fn transaction_options_are_rejected_before_dispatch() {
1275 assert!(check_tx_options(TxOptions::default()).is_ok());
1276 assert!(
1277 check_tx_options(TxOptions {
1278 isolation: Some(IsolationLevel::Serializable),
1279 read_only: None,
1280 })
1281 .is_err()
1282 );
1283 assert!(
1284 check_tx_options(TxOptions {
1285 isolation: None,
1286 read_only: Some(true),
1287 })
1288 .is_err()
1289 );
1290 assert!(
1291 check_tx_options(TxOptions {
1292 isolation: None,
1293 read_only: Some(false),
1294 })
1295 .is_ok()
1296 );
1297 }
1298
1299 #[test]
1300 fn zero_timeout_is_rejected() {
1301 assert!(
1302 budget(ExecuteOptions {
1303 timeout_ms: Some(0),
1304 })
1305 .is_err()
1306 );
1307 assert!(
1308 budget(ExecuteOptions {
1309 timeout_ms: Some(1),
1310 })
1311 .unwrap()
1312 .is_some()
1313 );
1314 }
1315
1316 #[test]
1317 fn errors_discard_driver_text() {
1318 let error = map_error(libsql::Error::SqliteFailure(
1319 19,
1320 "secret constraint name".to_owned(),
1321 ));
1322 assert_eq!(error.kind(), ErrorKind::Constraint);
1323 assert!(!format!("{error:?}").contains("secret"));
1324
1325 let error = map_write_error(libsql::Error::ConnectionFailed(
1326 "token secret and endpoint".to_owned(),
1327 ));
1328 assert_eq!(error.kind(), ErrorKind::WriteOutcomeUnknown);
1329 assert!(!format!("{error:?}").contains("secret"));
1330 }
1331
1332 #[test]
1333 fn silent_future_suppresses_vendor_events() {
1334 let count = Arc::new(AtomicUsize::new(0));
1335 let subscriber = tracing_subscriber::registry()
1336 .with(tracing_subscriber::filter::LevelFilter::TRACE)
1337 .with(CountLayer(Arc::clone(&count)));
1338 tracing::subscriber::with_default(subscriber, || {
1339 let runtime = tokio::runtime::Builder::new_current_thread()
1340 .build()
1341 .unwrap();
1342 runtime.block_on(async {
1343 silent(async {
1344 tracing::trace!("SELECT secret FROM table");
1345 })
1346 .await;
1347 });
1348 });
1349 assert_eq!(count.load(Ordering::Relaxed), 0);
1350 }
1351}