//! Drives sync clients through `turso_sync_sdk_kit` one step at a time, on the calling //! thread. An operation or a statement is a [`Task`]. One call of [`Task::poll`] advances //! the task to its next yield point: //! //! - a sync operation yields each time the sync engine waits for IO (HTTP, file or database //! IO); //! - a statement yields each time the database waits for IO; //! - an `exec` with several statements also yields between two statements. //! //! The IO that a task waits for runs at the start of its next poll. Thus other tasks can //! run while the request is "in flight", and the server sees the request only after them. //! //! With [`IoKind::Yield`], the database file IO of a client completes only when the client //! steps its IO, so a task also yields at each page read and write. use anyhow::{Context, Result, anyhow, bail}; use std::collections::VecDeque; use std::sync::Arc; use std::time::Duration; use turso_core::IO; use turso_sdk_kit::rsapi::{ Numeric, TursoConnection, TursoDatabaseConfig, TursoError, TursoStatement, TursoStatusCode, Value, }; use turso_sync_sdk_kit::rsapi::{TursoDatabaseSync, TursoDatabaseSyncConfig}; use turso_sync_sdk_kit::sync_engine_io::SyncEngineIoRequest; use turso_sync_sdk_kit::turso_async_operation::{ TursoAsyncOperationResult, TursoDatabaseAsyncOperation, }; type Sync = TursoDatabaseSync>; /// The database IO of the clients. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum IoKind { /// Files in memory. Each read, write and sync completes at the next IO step. Yield, /// Files on disk, through the platform IO. Platform, } impl IoKind { pub fn create(self) -> Result> { Ok(match self { IoKind::Yield => Arc::new(turso_core::MemoryYieldIO::new()), IoKind::Platform => { Arc::new(turso_core::PlatformIO::new().context("failed to create database IO")?) } }) } } /// What a task produced: rows (the columns of a row joined by `|`), or an error message. pub type Output = std::result::Result, String>; pub enum Poll { Pending, Ready(Output), } /// The IO of one client: the sync engine queue (HTTP and whole-file reads and writes) and /// the database IO. pub struct ClientIo { sync: Arc, core_io: Arc, port: u16, timeout: Duration, } impl ClientIo { /// Runs all IO that the client waits for. fn pump(&self) -> Result<()> { while let Some(item) = self.sync.take_io_item() { let (request, completion) = item.into_parts(); match request { SyncEngineIoRequest::Http { method, path, body, headers, .. } => { let path = local_path(&path); match crate::http::request( self.port, &method, &path, &headers, body.as_deref().unwrap_or_default(), self.timeout, ) { Ok(response) => { completion.status(response.status as u32); completion.push_buffer(response.body); completion.done(); } Err(error) => completion.poison(format!("{error:#}")), } } SyncEngineIoRequest::FullRead { path } => match std::fs::read(&path) { Ok(content) => { completion.push_buffer(content); completion.done(); } Err(error) if error.kind() == std::io::ErrorKind::NotFound => completion.done(), Err(error) => completion.poison(format!("full read of {path} failed: {error}")), }, SyncEngineIoRequest::FullWrite { path, content } => { match std::fs::write(&path, content) { Ok(()) => completion.done(), Err(error) => { completion.poison(format!("full write of {path} failed: {error}")) } } } } self.sync.step_io_callbacks(); } self.core_io.step().context("database IO failed")?; self.sync.step_io_callbacks(); Ok(()) } } /// Removes the scheme and host from an absolute URL. All requests go to the local server. fn local_path(path: &str) -> String { let rest = path .strip_prefix("http://") .or_else(|| path.strip_prefix("https://")); match rest { Some(rest) => match rest.find('/') { Some(slash) => rest[slash..].to_string(), None => "/".to_string(), }, None if path.starts_with('/') => path.to_string(), None => format!("/{path}"), } } /// A sync client: a local database that syncs with the server. pub struct Client { pub path: String, /// The connections do not check the sync busy gate of the SDK. pub ungated: bool, io: Arc, } impl Client { /// Creates the local database (or opens it, if its files exist) and bootstraps it from /// the server. `core_io` holds the database files: give the same IO to open the client /// again. pub fn open( path: &str, name: &str, port: u16, timeout: Duration, core_io: Arc, ungated: bool, ) -> Result { let db_config = TursoDatabaseConfig { path: path.to_string(), experimental_features: None, async_io: true, encryption: None, vfs: Default::default(), io: Some(core_io.clone()), db_file: None, page_codec: None, open_flags: Default::default(), }; let sync_config = TursoDatabaseSyncConfig { cipher: None, remote_url: Some(format!("http://127.0.0.1:{port}")), path: path.to_string(), client_name: name.to_string(), long_poll_timeout_ms: None, bootstrap_if_empty: true, reserved_bytes: None, partial_sync_opts: None, remote_encryption_key: None, push_operations_threshold: None, pull_bytes_threshold: None, pull_parallel_requests: None, logical_mvcc_pull: None, busy_timeout_ms: None, }; let sync = Sync::new(db_config, sync_config).map_err(sdk_error)?; let io = Arc::new(ClientIo { sync, core_io, port, timeout, }); run_operation(&io, &io.sync.create()).context("failed to create the client database")?; Ok(Self { path: path.to_string(), ungated, io, }) } /// Opens a new connection to the local database. pub fn connect(&self) -> Result> { let op = if self.ungated { self.io.sync.connect_ungated() } else { self.io.sync.connect() }; match run_operation(&self.io, &op)? { Some(TursoAsyncOperationResult::Connection { connection }) => Ok(connection), _ => bail!("connect returned no connection"), } } pub fn operation(&self, steps: &[SyncStep]) -> Task { Task::Sync(SyncTask { io: self.io.clone(), plan: steps.iter().copied().collect(), current: None, waits_for_io: false, pulled: None, }) } } /// Runs an operation to its end without yielding. fn run_operation( io: &ClientIo, op: &TursoDatabaseAsyncOperation, ) -> Result> { loop { match op.resume().map_err(sdk_error)? { TursoStatusCode::Done => return Ok(op.take_result()), TursoStatusCode::Io => io.pump()?, TursoStatusCode::Row => bail!("unexpected row from a sync operation"), } } } fn sdk_error(error: TursoError) -> anyhow::Error { anyhow!("{error}") } /// One sync engine call of a client operation. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SyncStep { Push, /// `wait_changes`, then `apply_changes` if the server has changes. Pull, Checkpoint, } pub enum Task { Sync(SyncTask), Statements(StatementTask), } impl Task { pub fn statements(connection: Arc, sql: &str) -> Task { Task::Statements(StatementTask { connection, sql: sql.to_string(), offset: 0, statement: None, waits_for_io: false, rows: Vec::new(), }) } pub fn poll(&mut self) -> Poll { let result = match self { Task::Sync(task) => task.poll(), Task::Statements(task) => task.poll(), }; match result { Ok(Some(rows)) => Poll::Ready(Ok(rows)), Ok(None) => Poll::Pending, Err(error) => { if let Task::Statements(task) = self { task.abandon(); } Poll::Ready(Err(format!("{error:#}"))) } } } } pub struct SyncTask { io: Arc, plan: VecDeque, current: Option<(SyncStep, Box)>, waits_for_io: bool, /// The result of the pull: `true` if changes were applied. pulled: Option, } impl SyncTask { fn poll(&mut self) -> Result>> { if std::mem::take(&mut self.waits_for_io) { self.io.pump()?; } loop { if self.current.is_none() { let Some(step) = self.plan.pop_front() else { return Ok(Some( self.pulled.map(|p| p.to_string()).into_iter().collect(), )); }; let op = match step { SyncStep::Push => self.io.sync.push_changes(), SyncStep::Pull => self.io.sync.wait_changes(), SyncStep::Checkpoint => self.io.sync.checkpoint(), }; self.current = Some((step, op)); } let (step, op) = self.current.as_ref().unwrap(); match op.resume().map_err(sdk_error)? { TursoStatusCode::Io => { self.waits_for_io = true; return Ok(None); } TursoStatusCode::Row => bail!("unexpected row from a sync operation"), TursoStatusCode::Done => {} } let step = *step; let result = op.take_result(); self.current = None; if step != SyncStep::Pull || self.pulled.is_some() { continue; } // `wait_changes` ended. Apply the changes, if any, as the next operation. match result { Some(TursoAsyncOperationResult::Changes { changes }) if !changes.empty() => { self.pulled = Some(true); self.current = Some((step, self.io.sync.apply_changes(changes))); } _ => self.pulled = Some(false), } } } } pub struct StatementTask { connection: Arc, sql: String, /// Start of the SQL that is not prepared yet. offset: usize, statement: Option>, waits_for_io: bool, rows: Vec, } impl StatementTask { fn poll(&mut self) -> Result>> { loop { if self.statement.is_none() { let rest = &self.sql[self.offset..]; match self.connection.prepare_first(rest).map_err(sdk_error)? { Some((statement, consumed)) => { self.offset += consumed; self.statement = Some(statement); } None => return Ok(Some(std::mem::take(&mut self.rows))), } } let statement = self.statement.as_mut().unwrap(); if std::mem::take(&mut self.waits_for_io) { statement.run_io().map_err(sdk_error)?; } match statement.step(None).map_err(sdk_error)? { TursoStatusCode::Io => { self.waits_for_io = true; return Ok(None); } TursoStatusCode::Row => { let values = (0..statement.column_count()) .map(|i| statement.row_value(i).map(|v| format_value(&v))) .collect::, _>>() .map_err(sdk_error)?; self.rows.push(values.join("|")); } TursoStatusCode::Done => { let mut statement = self.statement.take().unwrap(); finalize(&mut statement)?; // Yield between statements, so other tasks can run in between. if !self.sql[self.offset..].trim().is_empty() { return Ok(None); } } } } } /// Releases the current statement after an error. fn abandon(&mut self) { if let Some(mut statement) = self.statement.take() { let _ = finalize(&mut statement); } } } fn finalize(statement: &mut TursoStatement) -> Result<()> { loop { match statement.finalize(None).map_err(sdk_error)? { TursoStatusCode::Io => statement.run_io().map_err(sdk_error)?, _ => return Ok(()), } } } fn format_value(value: &Value) -> String { match value { Value::Null => String::new(), Value::Numeric(Numeric::Integer(i)) => i.to_string(), Value::Numeric(Numeric::Float(f)) => crate::runner::format_real(f64::from(*f)), Value::Text(text) => text.as_str().to_string(), Value::Blob(blob) => String::from_utf8_lossy(blob).into_owned(), } } #[cfg(test)] mod tests { #[test] fn local_path_drops_scheme_and_host() { assert_eq!( super::local_path("http://h:1/pull-updates"), "/pull-updates" ); assert_eq!(super::local_path("/v2/pipeline"), "/v2/pipeline"); assert_eq!(super::local_path("info"), "/info"); } }