Merge 'cli: serve a directory of databases with --sync-dir' from

Teaches the CLI sync server to serve a directory of databases from one
process and one port. Today `tursodb --sync-server <addr> <file>` serves
exactly one database; running N local databases means N processes and N
ports.
```bash
tursodb --sync-server 127.0.0.1:8080 --sync-dir ./dbs
```
Each database is addressed by name beneath `/db/{name}`:
```
http://localhost:8080/db/{name}/v2/pipeline
http://localhost:8080/db/{name}/pull-updates
```
A request to `/db/db1` reads and writes `./dbs/db1/data` — each database
gets its own directory, so on disk the files appear as `data`, `data-
wal`, `data-shm` (and `data.db-log` under MVCC), matching sqld's per-
database layout. Databases are created on first request (matching
single-database mode, which also auto-creates), except under
`--readonly`, where a missing database is a `404`. Single-database mode
is unchanged, and `/db/...` returns `404` there.
Names must match `^[A-Za-z0-9_-]+$` (max 128 chars). Since `.`, `/`,
`\`, and `%` are all outside the charset, path traversal — including
percent-encoded traversal — is rejected without ever URL-decoding.
Windows reserved device names (`con`, `nul`, `com1`…) are rejected on
every platform. A URL segment never reaches the filesystem unvalidated,
and this is unit-tested.
One commit per idea, in review order:
1. **`cli/sync_server: thread a database handle through request
handlers`** — pure refactor, no behavior change: replaces the server's
global `conn` + `db_path` with a `DbHandle` passed through the handlers.
The per-database `Mutex` this introduces is the same guard single-
database mode has today.
2. **`cli/sync_server: parse request routes into a Route enum`** — pure
functions plus unit tests, no wiring.
3. **`cli: serve a directory of databases with --sync-dir`** — the
feature: a lazy-opening, cached database registry keyed by validated
name, the clap flag, and integration tests.
4. **`cli: cap the databases a --sync-dir server keeps open`** —
`--sync-max-databases` (default 256); a request that would exceed it
gets `503` rather than exhausting file descriptors.
5. **`bindings/rust: exercise the sync test suite against --sync-dir`**
— the env-gated `LOCAL_SYNC_SERVER` sync suite gains a
`LOCAL_SYNC_SERVER_DIR` mode so every existing sync test (page-based and
MVCC logical-log) also runs against directory mode; CI runs it on Linux.
6. **`docs: document --sync-dir multi-database sync serving`** — CLI
reference, getting-started, and README, including the limitations below.
7. **`cli/sync_server: log client statement failures at debug, not
error`** — a client's bad SQL is not a server error; keeps multi-client
server logs readable. (Happy to split this into its own PR if
preferred.)
### Known limitations (documented in the CLI reference)
- Requests are handled one at a time across all databases — same serial
loop as today's server. Per-database concurrency is a planned follow-up
PR (thread-per-connection; the per-database mutex from commit 1 is
already the right lock), kept out of this one so each PR argues one
idea.
- Open handles are cached for the process lifetime, never evicted or
revalidated; deleting a served database's directory requires a restart.
- Any client that can reach the port can create databases by requesting
new names; there is no auth or multi-tenancy. Directory mode targets
local and development use.
- **Open question for reviewers:** with `--experimental-attach`, a
client can `ATTACH` an arbitrary filesystem path, escaping the served
directory. The docs currently warn about the combination — should the
CLI reject `--experimental-attach --sync-dir` outright instead?
The sync server is the local/dev story for Turso sync, and one-database-
per-process stops being workable as soon as an app or test suite has
more than one database. This lets you point one server at a folder and
address each database by name — the same shape the hosted service
exposes — with no new dependencies and no protocol changes.
## Testing
- Unit tests for route parsing, name validation (traversal, encoding,
device names), and path resolution — including that two databases can
never resolve to the same `.db`/`.db-log` paths (the guard against one
database serving another's logical log).
- `cli/tests/multi_sync.rs`: 7 integration tests spawning the real
binary — two-database isolation (pipeline and pull-updates), invalid-
name rejection, single-mode `/db/...` 404, the open-handle cap, and the
flag coupling (`--sync-dir` requires `--sync-server` and rejects a
positional database).
- The full env-gated bindings sync suite passes in **both** modes
locally (19 tests each, single-database and `--sync-dir`), demonstrating
the handler refactor changed no behavior and directory mode serves the
existing protocol faithfully; CI now also runs the directory-mode pass
on Linux.
- `cargo fmt`, `cargo clippy --workspace --all-features --all-targets --
--deny=warnings`, and the `turso_cli` test suites all pass on the
rebased branch (rebased onto `main` after #8071 merged; the two
histories touched the same request-parsing code).
This PR was developed with Claude Code driving most of the design
exploration, implementation, tests, and docs under my direction, over
multiple sessions: an initial design spec verified against the code,
implementation in reviewable commits, an adversarial pre-PR review pass
that cut ~50 non-test lines, and a rebase after the prerequisite header-
hardening PR merged. I reviewed and take responsibility for every line.

Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Reviewed-by: Pere Diaz Bou <pere-altea@homail.com>

Closes #8346
This commit is contained in:
Mikaël Francoeur
2026-09-11 09:39:08 -04:00
committed by GitHub
10 changed files with 903 additions and 61 deletions

View File

@@ -126,6 +126,15 @@ jobs:
LOCAL_SYNC_SERVER: "../../target/debug/tursodb"
run: cargo nextest run --workspace --all-features --locked --no-fail-fast --exclude memory-benchmark -E 'not binary(fuzz_tests) and not binary(pending_byte_tests)' --failure-output=final
timeout-minutes: 30
# Same suite against a --sync-dir server, so directory mode's per-database
# routing gets the coverage the single-database run above provides.
- name: Test sync suite against --sync-dir
if: runner.os == 'Linux'
env:
LOCAL_SYNC_SERVER: "../../target/debug/tursodb"
LOCAL_SYNC_SERVER_DIR: "1"
run: cargo nextest run -p turso --all-features --locked --no-fail-fast -E 'test(/^sync::/)' --no-tests=fail --failure-output=final
timeout-minutes: 20
- name: Test doctests
env:
LOCAL_SYNC_SERVER: "../../target/debug/tursodb"

View File

@@ -1134,7 +1134,9 @@ mod tests {
user_url: String,
db_url: String,
host: String,
db_prefix: String,
server: Option<Child>,
_sync_dir_created_by_harness: Option<TempDir>,
client: Client,
}
@@ -1174,12 +1176,19 @@ mod tests {
user_url: USER_URL.to_string(),
db_url: format!("{}://{}--{}--{}.{}", tokens[0], name, name, name, tokens[1]),
host: format!("{name}--{name}--{name}.localhost"),
db_prefix: String::new(),
server: None,
_sync_dir_created_by_harness: None,
client,
})
} else {
let server_bin = env::var("LOCAL_SYNC_SERVER").unwrap();
let sync_dir = env::var("LOCAL_SYNC_SERVER_DIR")
.is_ok()
.then(|| TempDir::new().context("failed to create --sync-dir tempdir"))
.transpose()?;
// The random port can be unusable: Windows runners reserve
// large chunks of 10_000..=65_535 for Hyper-V (bind fails with
// WSAEACCES), and concurrently running tests can collide on
@@ -1192,13 +1201,19 @@ mod tests {
for attempt in 1..=SPAWN_ATTEMPTS {
let port: u16 = rand::rng().random_range(10_000..=65_535);
let mut args = vec!["--sync-server".to_string(), format!("0.0.0.0:{port}")];
if let Some(dir) = &sync_dir {
args.push("--sync-dir".to_string());
args.push(dir.path().to_string_lossy().into_owned());
}
// IMPORTANT: do not use Stdio::piped() here. Nothing reads from
// those pipes, so once the kernel pipe buffer (~64 KiB on Linux)
// fills, the child blocks forever inside write() and stops
// servicing HTTP requests, deadlocking sync operations in
// long-running tests like test_sync_parallel_writes_with_sync_ops.
let mut child = Command::new(&server_bin)
.args(["--sync-server", &format!("0.0.0.0:{port}")])
.args(&args)
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
@@ -1210,11 +1225,19 @@ mod tests {
let started = Instant::now();
loop {
if client.get(&user_url).send().await.is_ok() {
let db_prefix = if sync_dir.is_some() {
format!("/db/{}", random_str().to_ascii_lowercase())
} else {
String::new()
};
let db_url = format!("{user_url}{db_prefix}");
return Ok(Self {
user_url: user_url.clone(),
db_url: user_url,
user_url,
db_url,
host: String::new(),
db_prefix,
server: Some(child),
_sync_dir_created_by_harness: sync_dir,
client,
});
}
@@ -1258,7 +1281,7 @@ mod tests {
pub async fn db_sql(&self, sql: &str) -> Result<Vec<Vec<Value>>> {
let resp = self
.client
.post(format!("{}/v2/pipeline", self.user_url))
.post(format!("{}{}/v2/pipeline", self.user_url, self.db_prefix))
.header("Host", &self.host)
.json(&json!({
"requests": [{

View File

@@ -8,8 +8,8 @@ use crate::{
dot_command::tokenize_dot_command,
helper::LimboHelper,
input::{
get_io, get_writer, ApplyWriter, DbLocation, NoopProgress, OutputMode, ProgressSink,
Settings, StderrProgress,
get_io, get_writer, open_flags, ApplyWriter, DbLocation, NoopProgress, OutputMode,
ProgressSink, Settings, StderrProgress,
},
manual,
opcodes_dictionary::OPCODE_DESCRIPTIONS,
@@ -85,6 +85,20 @@ pub struct Opts {
help = "Start sync server instead of interactive shell and listen at given address (e.g. 0.0.0.0:8080)"
)]
pub sync_server: Option<String>,
#[clap(
long,
requires = "sync_server",
conflicts_with = "database",
help = "Serve every database under PATH over the sync server, addressed as /db/{name}"
)]
pub sync_dir: Option<PathBuf>,
#[clap(
long,
requires = "sync_dir",
default_value_t = 256,
help = "Most databases held open at once under --sync-dir, one connection each; more may exist on disk"
)]
pub sync_max_databases: usize,
#[clap(long, help = "Enable experimental encryption feature")]
pub experimental_encryption: bool,
#[clap(long, help = "Enable experimental index method feature")]
@@ -129,7 +143,7 @@ pub struct Limbo {
pub interrupt_count: Arc<AtomicUsize>,
input_buff: ManuallyDrop<String>,
pub(crate) opts: Settings,
db_opts: turso_core::DatabaseOpts,
pub(crate) db_opts: turso_core::DatabaseOpts,
read_state: ReadState,
pub rl: Option<Editor<LimboHelper, DefaultHistory>>,
config: Option<Config>,
@@ -260,11 +274,7 @@ impl Limbo {
let (io, conn) = if db_file.starts_with("file:") {
Connection::from_uri(&db_file, db_opts, Arc::new(SqliteDialect))?
} else {
let flags = if opts.readonly {
OpenFlags::default().union(OpenFlags::ReadOnly)
} else {
OpenFlags::default()
};
let flags = open_flags(opts.readonly);
let (io, db) = Database::open_new(
&db_file,
opts.vfs.as_ref(),

View File

@@ -3,9 +3,10 @@ use clap::ValueEnum;
use std::{
fmt::{Display, Formatter},
io::{self, Write},
path::PathBuf,
sync::Arc,
};
use turso_core::LimboError;
use turso_core::{LimboError, OpenFlags};
#[derive(Copy, Clone)]
pub enum DbLocation {
@@ -91,9 +92,19 @@ pub struct Settings {
pub headers: bool,
pub mcp: bool,
pub sync_server_address: Option<String>,
pub sync_dir: Option<PathBuf>,
pub sync_max_databases: usize,
pub vfs: Option<String>,
pub flags: OpenFlags,
pub stats: bool,
}
pub fn open_flags(readonly: bool) -> OpenFlags {
let mut flags = OpenFlags::default();
flags.set(OpenFlags::ReadOnly, readonly);
flags
}
impl From<Opts> for Settings {
fn from(opts: Opts) -> Self {
Self {
@@ -120,6 +131,10 @@ impl From<Opts> for Settings {
headers: false,
mcp: opts.mcp,
sync_server_address: opts.sync_server,
sync_dir: opts.sync_dir,
sync_max_databases: opts.sync_max_databases,
flags: open_flags(opts.readonly),
vfs: opts.vfs,
stats: false,
}
}

View File

@@ -22,7 +22,7 @@ use std::{
sync::{atomic::Ordering, LazyLock},
};
use crate::sync_server::TursoSyncServer;
use crate::sync_server::{OpenConfig, TursoSyncServer};
#[cfg(all(feature = "mimalloc", not(target_family = "wasm"), not(miri)))]
#[global_allocator]
@@ -50,10 +50,27 @@ fn run_mcp_server(app: app::Limbo) -> anyhow::Result<()> {
fn run_sync_server(app: app::Limbo) -> anyhow::Result<()> {
let address = app.opts.sync_server_address.clone().unwrap();
let conn = app.get_connection();
let db_path = app.opts.db_file.clone();
let interrupt_count = app.get_interrupt_count();
let sync_server = TursoSyncServer::new(address, db_path, conn, interrupt_count)?;
let sync_server = match app.opts.sync_dir.clone() {
Some(dir) => TursoSyncServer::new_dir(
address,
dir,
interrupt_count,
OpenConfig {
vfs: app.opts.vfs.clone(),
flags: app.opts.flags,
db_opts: app.db_opts,
max_open: app.opts.sync_max_databases,
},
)?,
None => TursoSyncServer::new(
address,
app.opts.db_file.clone(),
app.get_connection(),
interrupt_count,
)?,
};
sync_server.run()
}

View File

@@ -1,7 +1,7 @@
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
@@ -12,7 +12,9 @@ use prost::Message;
use roaring::RoaringBitmap;
use tracing::{debug, error, info};
use turso_core::{Connection, Value as CoreValue};
use turso_core::{
Connection, Database, DatabaseOpts, OpenFlags, SqliteDialect, Value as CoreValue,
};
use turso_sync_engine::server_proto::{
BatchCond, BatchResult, BatchStep, BatchStreamReq, BatchStreamResp, Col, Error,
ExecuteStreamReq, ExecuteStreamResp, MvccLogicalLogMetadataProto, MvccLogicalLogRangeProto,
@@ -39,10 +41,35 @@ const MVCC_TX_TRAILER_SIZE: usize = 8;
const MVCC_TX_FRAME_FLAG_HAS_EXTENSION_BLOCK: u32 = 1 << 0;
const MAX_HEADER_BYTES: usize = 32 * 1024;
pub struct OpenConfig {
pub vfs: Option<String>,
pub flags: OpenFlags,
pub db_opts: DatabaseOpts,
pub max_open: usize,
}
struct DbHandle {
conn: Mutex<Arc<Connection>>,
path: String,
}
struct OpenHandles {
handles: HashMap<String, Arc<DbHandle>>,
capacity: usize,
}
enum DbSource {
Single(Arc<DbHandle>),
Dir {
base: PathBuf,
config: OpenConfig,
open_handles: Mutex<OpenHandles>,
},
}
pub struct TursoSyncServer {
address: String,
db_path: String,
conn: Arc<Mutex<Arc<Connection>>>,
source: DbSource,
interrupt_count: Arc<AtomicUsize>,
}
@@ -57,12 +84,90 @@ impl TursoSyncServer {
Ok(Self {
address,
db_path,
conn: Arc::new(Mutex::new(conn)),
source: DbSource::Single(Arc::new(DbHandle {
conn: Mutex::new(conn),
path: db_path,
})),
interrupt_count,
})
}
pub fn new_dir(
address: String,
base: PathBuf,
interrupt_count: Arc<AtomicUsize>,
config: OpenConfig,
) -> Result<Self> {
if !base.is_dir() {
return Err(anyhow!(
"sync dir path does not exist or is not a directory: {}",
base.display()
));
}
let open_handles = Mutex::new(OpenHandles::new(config.max_open));
Ok(Self {
address,
source: DbSource::Dir {
base: base.canonicalize()?,
config,
open_handles,
},
interrupt_count,
})
}
fn resolve_db(
&self,
requested: Option<&str>,
) -> std::result::Result<Arc<DbHandle>, HttpResponse> {
match (&self.source, requested) {
(DbSource::Single(h), None) => Ok(h.clone()),
(DbSource::Single(_), Some(_)) => Err(text_response(404, "Not Found")),
(DbSource::Dir { .. }, None) => Err(text_response(404, "Not Found")),
(
DbSource::Dir {
base,
config,
open_handles,
},
Some(name),
) => {
if !validate_db_name(name) {
return Err(text_response(400, "Invalid database name"));
}
let mut open_handles = open_handles.lock().unwrap();
open_handles.get_or_open(name, || {
let path = db_path_for(base, name);
let dir = path.parent().expect("database path has a parent directory");
if !config.flags.contains(OpenFlags::ReadOnly) {
if let Err(err) = std::fs::create_dir_all(dir) {
error!("failed to create directory for database {name}: {err}");
return Err(text_response(
500,
&format!("Internal Server Error: {err}"),
));
}
}
if !dir.canonicalize().is_ok_and(|dir| dir.starts_with(base)) {
return Err(text_response(404, "Not Found"));
}
match open_db_handle(&path, config) {
Ok(handle) => Ok(handle),
// Sync clients retry a 500 forever but can act on a 404.
Err(err) if path.exists() => {
error!("failed to open database {name}: {err}");
Err(text_response(500, &format!("Internal Server Error: {err}")))
}
Err(err) => {
debug!("no database named {name}: {err}");
Err(text_response(404, "Not Found"))
}
}
})
}
}
}
pub fn run(&self) -> Result<()> {
info!("Starting TursoSyncServer on {}", self.address);
@@ -152,27 +257,25 @@ impl TursoSyncServer {
let (method, path, body) = parse_http_request(&request_data)?;
info!("Request: {} {}", method, path);
let response = match (method.as_str(), path.as_str()) {
("OPTIONS", _) => Ok(HttpResponse {
status: 204,
content_type: "text/plain".to_string(),
body: Vec::new(),
}),
("POST", "/v2/pipeline") => {
debug!("Handling /v2/pipeline request");
self.handle_pipeline(&body)
}
("POST", "/pull-updates") => {
debug!("Handling /pull-updates request");
self.handle_pull_updates(&body)
}
_ => {
let response = match parse_route(&method, &path) {
Route::Options => Ok(text_response(204, "")),
Route::Pipeline { db } => match self.resolve_db(db) {
Ok(handle) => {
debug!("Handling /v2/pipeline request");
self.handle_pipeline(&handle, &body)
}
Err(resp) => Ok(resp),
},
Route::PullUpdates { db } => match self.resolve_db(db) {
Ok(handle) => {
debug!("Handling /pull-updates request");
self.handle_pull_updates(&handle, &body)
}
Err(resp) => Ok(resp),
},
Route::NotFound => {
info!("Unknown endpoint: {} {}", method, path);
Ok(HttpResponse {
status: 404,
content_type: "text/plain".to_string(),
body: b"Not Found".to_vec(),
})
Ok(text_response(404, "Not Found"))
}
};
@@ -195,13 +298,13 @@ impl TursoSyncServer {
Ok(())
}
fn handle_pipeline(&self, body: &[u8]) -> Result<HttpResponse> {
fn handle_pipeline(&self, db: &DbHandle, body: &[u8]) -> Result<HttpResponse> {
let req: PipelineReqBody = serde_json::from_slice(body)
.map_err(|e| anyhow!("Failed to parse pipeline request: {}", e))?;
debug!("Pipeline request: {:?}", req);
let conn = self.conn.lock().unwrap();
let conn = db.conn.lock().unwrap();
let mut results = Vec::new();
@@ -483,7 +586,7 @@ impl TursoSyncServer {
}
}
fn handle_pull_updates(&self, body: &[u8]) -> Result<HttpResponse> {
fn handle_pull_updates(&self, db: &DbHandle, body: &[u8]) -> Result<HttpResponse> {
let req = <PullUpdatesReqProtoBody as Message>::decode(body)
.map_err(|e| anyhow!("Failed to decode PullUpdatesRequest: {}", e))?;
@@ -502,18 +605,19 @@ impl TursoSyncServer {
if PullUpdatesStreamKind::try_from(req.stream_kind).unwrap_or(PullUpdatesStreamKind::Pages)
== PullUpdatesStreamKind::MvccLogicalLog
{
return self.handle_logical_pull_updates(&req);
return self.handle_logical_pull_updates(db, &req);
}
self.handle_page_pull_updates(&req, PullUpdatesApplyMode::Incremental)
self.handle_page_pull_updates(db, &req, PullUpdatesApplyMode::Incremental)
}
fn handle_page_pull_updates(
&self,
db: &DbHandle,
req: &PullUpdatesReqProtoBody,
apply_mode: PullUpdatesApplyMode,
) -> Result<HttpResponse> {
let conn = self.conn.lock().unwrap();
let conn = db.conn.lock().unwrap();
let wal_state = conn.wal_state()?;
debug!("WAL state: max_frame={}", wal_state.max_frame);
@@ -643,9 +747,13 @@ impl TursoSyncServer {
})
}
fn handle_logical_pull_updates(&self, req: &PullUpdatesReqProtoBody) -> Result<HttpResponse> {
fn handle_logical_pull_updates(
&self,
db: &DbHandle,
req: &PullUpdatesReqProtoBody,
) -> Result<HttpResponse> {
let (db_size, fallback_revision, legacy_current_revision) = {
let conn = self.conn.lock().unwrap();
let conn = db.conn.lock().unwrap();
let wal_state = conn.wal_state()?;
(
current_db_size_pages(&conn, wal_state.max_frame)?,
@@ -653,13 +761,13 @@ impl TursoSyncServer {
wal_state.max_frame.to_string(),
)
};
let log_path = match logical_log_path(&self.db_path) {
let log_path = match logical_log_path(&db.path) {
Ok(path) => path,
Err(_) if is_in_memory_db_path(&self.db_path) => {
Err(_) if is_in_memory_db_path(&db.path) => {
info!(
"logical pull requested for in-memory sync server database; returning incremental pages"
);
return self.handle_page_pull_updates(req, PullUpdatesApplyMode::Incremental);
return self.handle_page_pull_updates(db, req, PullUpdatesApplyMode::Incremental);
}
Err(err) => return Err(err),
};
@@ -671,6 +779,7 @@ impl TursoSyncServer {
log_path.display()
);
return self.handle_logical_fallback(
db,
req,
fallback_revision,
&legacy_current_revision,
@@ -686,6 +795,7 @@ impl TursoSyncServer {
"logical pull requested but MVCC log is not portable; returning replace-base pages: {err}"
);
return self.handle_logical_fallback(
db,
req,
fallback_revision,
&legacy_current_revision,
@@ -765,6 +875,7 @@ impl TursoSyncServer {
fn handle_logical_fallback(
&self,
db: &DbHandle,
req: &PullUpdatesReqProtoBody,
server_revision: String,
legacy_current_revision: &str,
@@ -777,7 +888,7 @@ impl TursoSyncServer {
return self.handle_empty_logical_pull(req.client_revision.clone(), db_size);
}
self.handle_replace_base_pages(server_revision)
self.handle_replace_base_pages(db, server_revision)
}
fn handle_empty_logical_pull(
@@ -807,8 +918,12 @@ impl TursoSyncServer {
})
}
fn handle_replace_base_pages(&self, server_revision: String) -> Result<HttpResponse> {
let (db_size, pages) = self.read_replace_base_pages()?;
fn handle_replace_base_pages(
&self,
db: &DbHandle,
server_revision: String,
) -> Result<HttpResponse> {
let (db_size, pages) = self.read_replace_base_pages(db)?;
let header = PullUpdatesRespProtoBody {
server_revision,
@@ -843,8 +958,8 @@ impl TursoSyncServer {
}
#[allow(clippy::type_complexity)]
fn read_replace_base_pages(&self) -> Result<(u64, Vec<(u64, Vec<u8>)>)> {
let conn = self.conn.lock().unwrap();
fn read_replace_base_pages(&self, db: &DbHandle) -> Result<(u64, Vec<(u64, Vec<u8>)>)> {
let conn = db.conn.lock().unwrap();
let wal_state = conn.wal_state()?;
let frame_watermark = Some(wal_state.max_frame);
let db_size = current_snapshot_db_size_pages(&conn, wal_state.max_frame)?;
@@ -1186,12 +1301,22 @@ fn parse_http_request(data: &[u8]) -> Result<(String, String, Vec<u8>)> {
Ok((method, path, body))
}
fn text_response(status: u16, body: &str) -> HttpResponse {
HttpResponse {
status,
content_type: "text/plain".to_string(),
body: body.as_bytes().to_vec(),
}
}
fn format_http_response(resp: &HttpResponse) -> Vec<u8> {
let status_text = match resp.status {
200 => "OK",
204 => "No Content",
400 => "Bad Request",
404 => "Not Found",
500 => "Internal Server Error",
503 => "Service Unavailable",
_ => "Unknown",
};
@@ -1216,6 +1341,100 @@ fn format_http_response(resp: &HttpResponse) -> Vec<u8> {
result
}
#[derive(Debug, PartialEq, Eq)]
enum Route<'a> {
Pipeline { db: Option<&'a str> },
PullUpdates { db: Option<&'a str> },
Options,
NotFound,
}
fn parse_route<'a>(method: &str, path: &'a str) -> Route<'a> {
if method == "OPTIONS" {
return Route::Options;
}
if method != "POST" {
return Route::NotFound;
}
match path {
"/v2/pipeline" => return Route::Pipeline { db: None },
"/pull-updates" => return Route::PullUpdates { db: None },
_ => {}
}
let Some(rest) = path.strip_prefix("/db/") else {
return Route::NotFound;
};
let Some((name, tail)) = rest.split_once('/') else {
return Route::NotFound;
};
match tail {
"v2/pipeline" => Route::Pipeline { db: Some(name) },
"pull-updates" => Route::PullUpdates { db: Some(name) },
_ => Route::NotFound,
}
}
fn validate_db_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 128
&& name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
}
fn db_path_for(base: &Path, name: &str) -> PathBuf {
// Extensionless like sqld's layout: the files appear as data, data-wal,
// data-shm (and data.db-log under MVCC) inside the database's directory.
base.join(name).join("data")
}
impl OpenHandles {
fn new(capacity: usize) -> Self {
Self {
handles: HashMap::new(),
capacity,
}
}
fn get_or_open(
&mut self,
name: &str,
open: impl FnOnce() -> std::result::Result<Arc<DbHandle>, HttpResponse>,
) -> std::result::Result<Arc<DbHandle>, HttpResponse> {
if let Some(handle) = self.handles.get(name) {
return Ok(handle.clone());
}
if self.handles.len() >= self.capacity {
error!(
"refusing to open {name}: {} databases are open",
self.capacity
);
return Err(text_response(503, "Too many open databases"));
}
let handle = open()?;
self.handles.insert(name.to_string(), handle.clone());
Ok(handle)
}
}
fn open_db_handle(path: &Path, config: &OpenConfig) -> Result<Arc<DbHandle>> {
let path_str = path.to_string_lossy().to_string();
let (_io, db) = Database::open_new(
&path_str,
config.vfs.as_deref(),
config.flags,
config.db_opts,
None,
Arc::new(SqliteDialect),
)?;
let conn = db.connect()?;
conn.wal_auto_actions_disable();
Ok(Arc::new(DbHandle {
conn: Mutex::new(conn),
path: path_str,
}))
}
fn encode_length_delimited(output: &mut Vec<u8>, data: &[u8]) {
let mut len = data.len();
while len >= 0x80 {
@@ -1258,6 +1477,31 @@ fn convert_core_to_value(value: CoreValue) -> Value {
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn validates_database_names() {
for ok in ["db1", "a-b_c", "x", "nul", "con", &"n".repeat(128)] {
assert!(validate_db_name(ok), "expected {ok:?} to be valid");
}
for bad in [
"",
"..",
"../x",
"a/b",
"a\\b",
".hidden",
"a.b",
"a%2fb",
"a b",
"A1",
"Db1",
"DB1",
&"n".repeat(129),
] {
assert!(!validate_db_name(bad), "expected {bad:?} to be rejected");
}
}
/// Mirrors the read loop: the terminator must be found whatever the chunk
/// boundaries, including when it straddles two reads.
@@ -1286,4 +1530,113 @@ mod tests {
assert!(request_end(0, usize::MAX).is_err());
assert_eq!(request_end(10, 5).unwrap(), 19);
}
#[test]
fn parses_single_and_multi_routes() {
assert_eq!(
parse_route("POST", "/v2/pipeline"),
Route::Pipeline { db: None }
);
assert_eq!(
parse_route("POST", "/pull-updates"),
Route::PullUpdates { db: None }
);
assert_eq!(
parse_route("POST", "/db/db1/v2/pipeline"),
Route::Pipeline { db: Some("db1") }
);
assert_eq!(
parse_route("POST", "/db/db1/pull-updates"),
Route::PullUpdates { db: Some("db1") }
);
assert_eq!(parse_route("OPTIONS", "/anything"), Route::Options);
assert_eq!(parse_route("GET", "/v2/pipeline"), Route::NotFound);
assert_eq!(parse_route("POST", "/nope"), Route::NotFound);
assert_eq!(parse_route("POST", "/db/a/b/v2/pipeline"), Route::NotFound);
assert_eq!(
parse_route("POST", "/db//v2/pipeline"),
Route::Pipeline { db: Some("") }
);
}
#[test]
fn each_database_resolves_its_own_files() {
let base = Path::new("/tmp/dbs");
let db1 = db_path_for(base, "db1");
let db2 = db_path_for(base, "db2");
assert_eq!(db1, Path::new("/tmp/dbs/db1/data"));
assert_ne!(db1, db2);
let log1 = logical_log_path(&db1.to_string_lossy()).unwrap();
let log2 = logical_log_path(&db2.to_string_lossy()).unwrap();
assert_ne!(log1, log2, "databases must not share a logical log");
assert_eq!(log1, Path::new("/tmp/dbs/db1/data.db-log"));
}
const TEST_MAX_OPEN: usize = 4;
fn dir_server(base: &Path) -> TursoSyncServer {
TursoSyncServer::new_dir(
"127.0.0.1:0".to_string(),
base.to_path_buf(),
Arc::new(AtomicUsize::new(0)),
OpenConfig {
vfs: None,
flags: OpenFlags::default(),
db_opts: DatabaseOpts::new(),
max_open: TEST_MAX_OPEN,
},
)
.unwrap()
}
#[test]
fn refuses_new_databases_once_the_open_map_is_full() {
let base = tempfile::TempDir::new().unwrap();
let server = dir_server(base.path());
for i in 0..TEST_MAX_OPEN {
let name = format!("db{i}");
if let Err(resp) = server.resolve_db(Some(&name)) {
panic!(
"opening {name} under the cap must succeed, got {}",
resp.status
);
}
}
assert!(
server.resolve_db(Some("db0")).is_ok(),
"an already open database stays reachable at capacity"
);
let Err(refused) = server.resolve_db(Some("overflow")) else {
panic!("a full open map must refuse an unknown database");
};
assert_eq!(refused.status, 503);
assert!(
!base.path().join("overflow").exists(),
"a refused database must not reach the filesystem"
);
}
#[test]
fn refuses_a_database_directory_that_escapes_the_served_tree() {
let base = tempfile::TempDir::new().unwrap();
let outside = tempfile::TempDir::new().unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(outside.path(), base.path().join("escaped")).unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_dir(outside.path(), base.path().join("escaped")).unwrap();
let server = dir_server(base.path());
let Err(refused) = server.resolve_db(Some("escaped")) else {
panic!("a symlinked database directory must be refused");
};
assert_eq!(refused.status, 404);
assert!(
!outside.path().join("data").exists(),
"a refused name must not create files outside the served tree"
);
}
}

372
cli/tests/multi_sync.rs Normal file
View File

@@ -0,0 +1,372 @@
use std::io::{Read, Write};
use std::net::TcpStream;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU16, Ordering};
use std::time::{Duration, Instant};
struct Server {
child: Child,
port: u16,
dir: std::path::PathBuf,
}
impl Drop for Server {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
let _ = std::fs::remove_dir_all(&self.dir);
}
}
// Asking the OS for `:0` and closing the listener lets a concurrent test in this
// binary be handed the same port, connect to the wrong server, and see its
// requests reset when that server is dropped. Hand out a distinct port per call
// instead; `start` retries when another process holds one.
fn free_port() -> u16 {
static NEXT: AtomicU16 = AtomicU16::new(0);
let base = 20_000 + (std::process::id() as u16 % 20_000);
base + NEXT.fetch_add(1, Ordering::Relaxed) % 1_000
}
const START_ATTEMPTS: u32 = 5;
const READY_TIMEOUT: Duration = Duration::from_secs(10);
fn start(extra: &[&str], dir: &std::path::Path) -> Server {
let mut last_failure = String::new();
for attempt in 1..=START_ATTEMPTS {
let port = free_port();
let mut args = vec!["--sync-server".to_string(), format!("127.0.0.1:{port}")];
args.extend(extra.iter().map(|s| s.to_string()));
// IMPORTANT: Stdio::null(), never piped(). Nothing drains the pipes, so a full
// buffer would block the child inside write() and stall HTTP handling.
let mut child = Command::new(env!("CARGO_BIN_EXE_tursodb"))
.args(&args)
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn tursodb");
let deadline = Instant::now() + READY_TIMEOUT;
loop {
if TcpStream::connect(("127.0.0.1", port)).is_ok() {
return Server {
child,
port,
dir: dir.to_path_buf(),
};
}
if let Some(status) = child.try_wait().expect("poll child status") {
last_failure = format!(
"attempt {attempt}/{START_ATTEMPTS}: tursodb exited before serving on port {port}: {status}"
);
break;
}
if Instant::now() >= deadline {
last_failure = format!(
"attempt {attempt}/{START_ATTEMPTS}: tursodb did not start serving on port {port} within {READY_TIMEOUT:?}"
);
let _ = child.kill();
let _ = child.wait();
break;
}
std::thread::sleep(Duration::from_millis(50));
}
}
panic!("tursodb failed to start after {START_ATTEMPTS} attempts: {last_failure}");
}
/// Returns (status_code, body) with the headers stripped, so a substring
/// assertion cannot be satisfied by a header value such as `Content-Length`.
fn post_bytes(port: u16, path: &str, content_type: &str, body: &[u8]) -> (u16, Vec<u8>) {
let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap();
let head = format!(
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: {content_type}\r\n\
Content-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
s.write_all(head.as_bytes()).unwrap();
s.write_all(body).unwrap();
let mut raw = Vec::new();
s.read_to_end(&mut raw).unwrap();
let status = String::from_utf8_lossy(&raw[..raw.len().min(64)])
.split_whitespace()
.nth(1)
.and_then(|c| c.parse().ok())
.unwrap_or(0);
let header_end = find(&raw, b"\r\n\r\n")
.unwrap_or_else(|| panic!("response has no header terminator: {raw:?}"));
(status, raw[header_end + 4..].to_vec())
}
fn post(port: u16, path: &str, json: &str) -> (u16, String) {
let (status, body) = post_bytes(port, path, "application/json", json.as_bytes());
(status, String::from_utf8_lossy(&body).into_owned())
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|w| w == needle)
}
fn sql(stmt: &str) -> String {
format!(r#"{{"requests":[{{"type":"execute","stmt":{{"sql":"{stmt}"}}}}]}}"#)
}
fn tmpdir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("turso-multi-sync-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn databases_are_isolated() {
let dir = tmpdir("iso");
let srv = start(&["--sync-dir", dir.to_str().unwrap()], &dir);
assert_eq!(
post(srv.port, "/db/db1/v2/pipeline", &sql("CREATE TABLE t1(x)")).0,
200
);
assert_eq!(
post(srv.port, "/db/db2/v2/pipeline", &sql("CREATE TABLE t2(x)")).0,
200
);
// `handle_pipeline` answers 200 even when a statement fails, so read each
// table back before checking that neither database sees the other's.
let (_, own1) = post(srv.port, "/db/db1/v2/pipeline", &sql("SELECT * FROM t1"));
assert!(
!own1.contains("error"),
"db1 must see its own table: {own1}"
);
let (_, own2) = post(srv.port, "/db/db2/v2/pipeline", &sql("SELECT * FROM t2"));
assert!(
!own2.contains("error"),
"db2 must see its own table: {own2}"
);
let (_, a) = post(srv.port, "/db/db1/v2/pipeline", &sql("SELECT * FROM t2"));
assert!(a.contains("error"), "db1 must not see db2's table: {a}");
let (_, b) = post(srv.port, "/db/db2/v2/pipeline", &sql("SELECT * FROM t1"));
assert!(b.contains("error"), "db2 must not see db1's table: {b}");
assert_eq!(
post(
srv.port,
"/db/db1/v2/pipeline",
&sql("INSERT INTO t1(x) VALUES (111)")
)
.0,
200
);
assert_eq!(
post(
srv.port,
"/db/db2/v2/pipeline",
&sql("INSERT INTO t2(x) VALUES (222)")
)
.0,
200
);
let (_, read1) = post(srv.port, "/db/db1/v2/pipeline", &sql("SELECT x FROM t1"));
assert!(
read1.contains("111"),
"db1 must read back its value: {read1}"
);
assert!(
!read1.contains("222"),
"db1 must not see db2's value: {read1}"
);
let (_, read2) = post(srv.port, "/db/db2/v2/pipeline", &sql("SELECT x FROM t2"));
assert!(
read2.contains("222"),
"db2 must read back its value: {read2}"
);
assert!(
!read2.contains("111"),
"db2 must not see db1's value: {read2}"
);
assert!(dir.join("db1").join("data").exists());
assert!(dir.join("db2").join("data").exists());
}
#[test]
fn rejects_unsafe_database_names() {
let dir = tmpdir("bad");
let srv = start(&["--sync-dir", dir.to_str().unwrap()], &dir);
// The 404s never reach `validate_db_name`: their tails match no known route.
for (path, expected_status) in [
("/db/../x/v2/pipeline", 404),
("/db/a/b/v2/pipeline", 404),
("/db//v2/pipeline", 400),
("/db/.hidden/v2/pipeline", 400),
("/db/../v2/pipeline", 400),
("/db/Db1/v2/pipeline", 400),
("/db/DB1/v2/pipeline", 400),
] {
let (status, _) = post(srv.port, path, &sql("SELECT 1"));
assert_eq!(status, expected_status, "unexpected status for {path}");
}
let leaked: Vec<_> = std::fs::read_dir(&dir)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert!(
leaked.is_empty(),
"rejected names must not create files: {leaked:?}"
);
}
#[test]
fn single_database_mode_rejects_db_routes() {
let dir = tmpdir("single");
let file = dir.join("one.db");
let srv = start(&[file.to_str().unwrap()], &dir);
assert_eq!(
post(srv.port, "/v2/pipeline", &sql("CREATE TABLE t(x)")).0,
200
);
assert_eq!(
post(srv.port, "/db/one/v2/pipeline", &sql("SELECT 1")).0,
404
);
}
#[test]
fn sync_max_databases_caps_open_handles() {
let dir = tmpdir("cap");
let srv = start(
&[
"--sync-dir",
dir.to_str().unwrap(),
"--sync-max-databases",
"2",
],
&dir,
);
assert_eq!(
post(srv.port, "/db/a/v2/pipeline", &sql("CREATE TABLE t(x)")).0,
200
);
assert_eq!(
post(srv.port, "/db/b/v2/pipeline", &sql("CREATE TABLE t(x)")).0,
200
);
assert_eq!(
post(srv.port, "/db/c/v2/pipeline", &sql("CREATE TABLE t(x)")).0,
503
);
assert_eq!(post(srv.port, "/db/a/v2/pipeline", &sql("SELECT 1")).0, 200);
assert!(
!dir.join("c").exists(),
"a refused database must not reach the filesystem"
);
}
#[test]
fn pull_updates_are_scoped_to_one_database() {
let dir = tmpdir("pull");
let srv = start(&["--sync-dir", dir.to_str().unwrap()], &dir);
for (db, table, marker) in [("db1", "t1", "marker-one"), ("db2", "t2", "marker-two")] {
let route = format!("/db/{db}/v2/pipeline");
assert_eq!(
post(srv.port, &route, &sql(&format!("CREATE TABLE {table}(x)"))).0,
200
);
assert_eq!(
post(
srv.port,
&route,
&sql(&format!("INSERT INTO {table}(x) VALUES ('{marker}')"))
)
.0,
200
);
}
// A default-valued request pulls every page frame, so each response carries
// the frames its own database wrote and nothing from the other.
for (db, own, other) in [
("db1", "marker-one", "marker-two"),
("db2", "marker-two", "marker-one"),
] {
let (status, frames) = post_bytes(
srv.port,
&format!("/db/{db}/pull-updates"),
"application/protobuf",
&[],
);
assert_eq!(status, 200, "pull-updates for {db}");
assert!(
find(&frames, own.as_bytes()).is_some(),
"{db} must pull its own frames ({} bytes)",
frames.len()
);
assert!(
find(&frames, other.as_bytes()).is_none(),
"{db} must not pull the other database's frames"
);
}
}
#[test]
fn sync_dir_requires_sync_server() {
let dir = tmpdir("no-server");
let output = Command::new(env!("CARGO_BIN_EXE_tursodb"))
.args(["--sync-dir", dir.to_str().unwrap()])
.output()
.expect("spawn tursodb");
assert!(
!output.status.success(),
"expected nonzero exit, got {:?}",
output.status
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("--sync-server"),
"unexpected stderr: {stderr}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn sync_dir_rejects_positional_database() {
let dir = tmpdir("conflict");
let port = free_port();
let output = Command::new(env!("CARGO_BIN_EXE_tursodb"))
.args([
"--sync-server",
&format!("127.0.0.1:{port}"),
"--sync-dir",
dir.to_str().unwrap(),
dir.join("explicit.db").to_str().unwrap(),
])
.output()
.expect("spawn tursodb");
assert!(
!output.status.success(),
"expected nonzero exit, got {:?}",
output.status
);
assert_eq!(output.status.code(), Some(2), "expected clap's usage exit");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("the argument '--sync-dir <SYNC_DIR>' cannot be used with '[DATABASE]'"),
"unexpected stderr: {stderr}"
);
let _ = std::fs::remove_dir_all(&dir);
}

View File

@@ -131,6 +131,31 @@ Start a sync server for database replication, listening at the given address.
tursodb --sync-server 0.0.0.0:8080 mydata.db
```
### `--sync-dir <PATH>`
Serve every database file under `PATH` over the sync server, instead of a single database. `PATH` must already exist as a directory. Requires `--sync-server`, and cannot be combined with a positional `DATABASE` argument.
```bash
tursodb --sync-server 127.0.0.1:8080 --sync-dir ./dbs
```
Each database is addressed by name in the URL, beneath `/db/{name}`:
```
http://localhost:8080/db/{name}/v2/pipeline
http://localhost:8080/db/{name}/pull-updates
```
A request to `/db/db1` reads and writes `./dbs/db1/data`: each database gets its own directory, so its WAL and logical log stay grouped with it as `data-wal`, `data-shm`, and so on — the same layout `sqld` uses. Databases are created on first request, except under `--readonly`: a read-only server cannot create a file, so a request for a database that does not already exist fails with `404 Not Found`. Opened handles are cached for the process lifetime and never revalidated against the filesystem, so removing a database's directory is safe only while the server is stopped; deleting it while the server is running leaves that handle reading and writing the deleted files, and the server must be restarted before the name can be served correctly again.
Names must match `^[a-z0-9_-]+$` and are capped at 128 characters — no uppercase, dots, slashes, or percent-encoding — and anything else is rejected with `400 Bad Request`. Names are lowercase only so that one name is one database on case-insensitive filesystems as well.
`--readonly`, `--vfs`, and the `--experimental-*` flags apply to every database served this way, the same as they would for a single database.
<Warning>
Directory mode handles one request at a time across all databases, so distinct databases do not progress independently. WAL retention follows the same behavior as the single-database sync server. Opened database handles stay cached for the life of the process without eviction, and at most `--sync-max-databases` may be open at once (default 256); beyond that, a request for a database that is not already open is refused with `503 Service Unavailable` until the server restarts. Any client that can reach the port can create a database simply by requesting a new valid name, so disk space and inodes still accumulate without bound. The name restrictions above do not confine a client to the served directory: `VACUUM INTO` can write a copy to any path the server process can reach, and with `--experimental-attach` a client can `ATTACH DATABASE` an arbitrary filesystem path. There is no authentication or multi-tenancy; directory mode is intended for local and development use.
</Warning>
## Experimental Feature Flags
These flags enable features that are still under development. They may change or be removed in future releases.

View File

@@ -142,3 +142,13 @@ Start a sync server for database replication:
tursodb --sync-server 0.0.0.0:8080 mydata.db
```
### Sync Server for a Directory of Databases
Serve every database under a directory instead of a single file, with each database addressed by name at `/db/{name}`:
```bash
tursodb --sync-server 127.0.0.1:8080 --sync-dir ./dbs
```
A client syncing against `http://localhost:8080/db/db1` reads and writes `./dbs/db1/data`, which is created on first request unless the server was started with `--readonly`. Database names must match `^[a-z0-9_-]+$` and be at most 128 characters. See [Command-Line Options](./command-line-options.mdx) for the full details and limitations.

View File

@@ -37,7 +37,7 @@ Turso is a drop-in replacement for SQLite, but adds features that SQLite doesn't
- **Native Vector Search** — `vector32`/`vector64` types with distance functions (`vector_distance_cos`, `vector_distance_l2`)
- **Change Data Capture** — track row-level changes per connection with `PRAGMA capture_data_changes_conn`
- **MCP Server** — run as a [Model Context Protocol](https://modelcontextprotocol.io/) server for AI assistants (`--mcp`)
- **Local Sync Server** — serve a database over HTTP for client SDKs to sync against (`--sync-server`)
- **Local Sync Server** — serve a database over HTTP for client SDKs to sync against (`--sync-server`), or serve a whole directory of databases at once (`--sync-dir`)
- **Array Types** — array columns in STRICT tables with operators like `@>`, `<@`, `||`
- **Built-in Extensions** — crypto, regexp, fuzzy matching, IP address functions, CSV, percentile
@@ -113,6 +113,14 @@ Start a local HTTP server that implements the Turso sync protocol. The `@tursoda
npx turso myapp.db --sync-server "0.0.0.0:8080"
```
To serve a directory of databases instead of a single file, pass `--sync-dir`. Each database is addressed by name at `/db/{name}` and created on first request:
```bash
npx turso --sync-server "127.0.0.1:8080" --sync-dir ./dbs
```
A client syncing against `http://localhost:8080/db/db1` reads and writes `./dbs/db1/data`. Names must match `^[a-z0-9_-]+$`. This mode has no authentication and is meant for local development; see the [CLI documentation](https://docs.turso.tech) for the full details and limits.
### MCP Server
Start an [MCP](https://modelcontextprotocol.io/) server so AI assistants can query your databases: