Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
use std::{
    future::Future,
    io::ErrorKind,
    pin::Pin,
    sync::{Arc, Mutex},
    task::{Context, Poll, Waker},
    time::Duration,
};

use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::{header::AUTHORIZATION, Request};
use hyper_tls::HttpsConnector;
use hyper_util::{
    client::legacy::{connect::HttpConnector, Client},
    rt::TokioExecutor,
};
use tokio::sync::mpsc;

use crate::{connection::Connection, Error, Result};

// Public re-exports of sync types for users of this crate.
pub use turso_sync_sdk_kit::rsapi::DatabaseSyncStats;
pub use turso_sync_sdk_kit::rsapi::PartialBootstrapStrategy;
pub use turso_sync_sdk_kit::rsapi::PartialSyncOpts;

// Constants used across the sync module
const DEFAULT_CLIENT_NAME: &str = "turso-sync-rust";

/// Encryption cipher for Turso Cloud remote encryption.
/// These match the server-side encryption settings.
#[derive(Debug, Clone, Copy)]
pub enum RemoteEncryptionCipher {
    Aes256Gcm,
    Aes128Gcm,
    ChaCha20Poly1305,
    Aegis128L,
    Aegis128X2,
    Aegis128X4,
    Aegis256,
    Aegis256X2,
    Aegis256X4,
}

impl RemoteEncryptionCipher {
    /// Returns the total reserved bytes as required by the server
    pub fn reserved_bytes(&self) -> usize {
        match self {
            Self::Aes256Gcm | Self::Aes128Gcm | Self::ChaCha20Poly1305 => 28,
            Self::Aegis128L | Self::Aegis128X2 | Self::Aegis128X4 => 32,
            Self::Aegis256 | Self::Aegis256X2 | Self::Aegis256X4 => 48,
        }
    }
}

impl std::str::FromStr for RemoteEncryptionCipher {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "aes256gcm" | "aes-256-gcm" => Ok(Self::Aes256Gcm),
            "aes128gcm" | "aes-128-gcm" => Ok(Self::Aes128Gcm),
            "chacha20poly1305" | "chacha20-poly1305" => Ok(Self::ChaCha20Poly1305),
            "aegis128l" | "aegis-128l" => Ok(Self::Aegis128L),
            "aegis128x2" | "aegis-128x2" => Ok(Self::Aegis128X2),
            "aegis128x4" | "aegis-128x4" => Ok(Self::Aegis128X4),
            "aegis256" | "aegis-256" => Ok(Self::Aegis256),
            "aegis256x2" | "aegis-256x2" => Ok(Self::Aegis256X2),
            "aegis256x4" | "aegis-256x4" => Ok(Self::Aegis256X4),
            _ => Err(format!(
                "unknown cipher: '{s}'. Supported: aes256gcm, aes128gcm, chacha20poly1305, \
                 aegis128l, aegis128x2, aegis128x4, aegis256, aegis256x2, aegis256x4"
            )),
        }
    }
}

// Builder for a synced database.
pub struct Builder {
    // Absolute or relative path to local database file (":memory:" is supported).
    path: String,
    // Remote URL base. Supports https://, http:// and libsql:// (translated to https://).
    remote_url: Option<String>,
    // Optional authorization token (e.g., Bearer token).
    auth_token: Option<String>,
    // Optional custom client identifier used by the sync engine for telemetry/tracing.
    client_name: Option<String>,
    // Optional long-poll timeout when waiting for server changes.
    long_poll_timeout: Option<Duration>,
    // Whether to bootstrap a database if it's empty (download schema and initial data).
    bootstrap_if_empty: bool,
    // Partial sync configuration (EXPERIMENTAL).
    partial_sync_config_experimental: Option<PartialSyncOpts>,
    // Encryption key (base64-encoded) for the Turso Cloud database
    remote_encryption_key: Option<String>,
    // Encryption cipher for the Turso Cloud database
    remote_encryption_cipher: Option<RemoteEncryptionCipher>,
}

impl Builder {
    // Create a new Builder for a synced database.
    pub fn new_remote(path: &str) -> Self {
        Self {
            path: path.to_string(),
            remote_url: None,
            auth_token: None,
            client_name: None,
            long_poll_timeout: None,
            bootstrap_if_empty: true,
            partial_sync_config_experimental: None,
            remote_encryption_key: None,
            remote_encryption_cipher: None,
        }
    }

    // Set remote_url for HTTP requests.
    // If remote_url omitted in configuration - tursodb will try to load it from the metadata file
    pub fn with_remote_url(mut self, remote_url: impl Into<String>) -> Self {
        self.remote_url = Some(remote_url.into());
        self
    }

    // Set optional authorization token for HTTP requests.
    pub fn with_auth_token(mut self, token: impl Into<String>) -> Self {
        self.auth_token = Some(token.into());
        self
    }

    // Set custom client name (defaults to 'turso-sync-rust').
    pub fn with_client_name(mut self, name: impl Into<String>) -> Self {
        self.client_name = Some(name.into());
        self
    }

    // Set long poll timeout for waiting remote changes.
    pub fn with_long_poll_timeout(mut self, timeout: Duration) -> Self {
        self.long_poll_timeout = Some(timeout);
        self
    }

    // Configure bootstrap behavior for empty databases.
    pub fn bootstrap_if_empty(mut self, enable: bool) -> Self {
        self.bootstrap_if_empty = enable;
        self
    }

    // Set experimental partial sync configuration.
    pub fn with_partial_sync_opts_experimental(mut self, opts: PartialSyncOpts) -> Self {
        self.partial_sync_config_experimental = Some(opts);
        self
    }

    /// Set encryption key (base64-encoded) and cipher for the Turso Cloud database.
    /// The cipher is used to calculate the correct reserved_bytes for the database.
    pub fn with_remote_encryption(
        mut self,
        base64_key: impl Into<String>,
        cipher: RemoteEncryptionCipher,
    ) -> Self {
        self.remote_encryption_key = Some(base64_key.into());
        self.remote_encryption_cipher = Some(cipher);
        self
    }

    /// Set encryption key (base64-encoded) for the Turso Cloud database.
    /// The key will be sent as x-turso-encryption-key header with sync HTTP requests.
    /// Note: For deferred sync (no initial bootstrap), use with_remote_encryption() instead
    /// to also specify the cipher for correct reserved_bytes calculation.
    pub fn with_remote_encryption_key(mut self, base64_key: impl Into<String>) -> Self {
        self.remote_encryption_key = Some(base64_key.into());
        self
    }

    // Build the synced database object, initialize and open it.
    pub async fn build(self) -> Result<Database> {
        // Build core database config for the embedded engine.
        let db_config = turso_sdk_kit::rsapi::TursoDatabaseConfig {
            path: self.path.clone(),
            experimental_features: None,
            // IMPORTANT: async IO must be turned on to delegate IO to this layer.
            async_io: true,
            encryption: None,
            vfs: None,
            io: None,
            db_file: None,
        };

        let url = if let Some(remote_url) = &self.remote_url {
            Some(normalize_base_url(remote_url).map_err(Error::Error)?)
        } else {
            None
        };

        // Calculate reserved_bytes from cipher if provided.
        let reserved_bytes = self
            .remote_encryption_cipher
            .map(|cipher| cipher.reserved_bytes());

        // Build sync engine config.
        let sync_config = turso_sync_sdk_kit::rsapi::TursoDatabaseSyncConfig {
            path: self.path.clone(),
            remote_url: url.clone(),
            client_name: self
                .client_name
                .clone()
                .unwrap_or_else(|| DEFAULT_CLIENT_NAME.to_string()),
            long_poll_timeout_ms: self
                .long_poll_timeout
                .map(|d| d.as_millis().min(u32::MAX as u128) as u32),
            bootstrap_if_empty: self.bootstrap_if_empty,
            reserved_bytes,
            partial_sync_opts: self.partial_sync_config_experimental.clone(),
            remote_encryption_key: self.remote_encryption_key.clone(),
        };

        // Create sync wrapper.
        let sync =
            turso_sync_sdk_kit::rsapi::TursoDatabaseSync::<Bytes>::new(db_config, sync_config)
                .map_err(Error::from)?;

        // IO worker will process SyncEngine IO queue on a dedicated tokio thread.
        let io_worker = IoWorker::spawn(sync.clone(), url, self.auth_token.clone());

        // Create (bootstrap + open) database in one go.
        let op = sync.create();
        drive_operation(op, io_worker.clone()).await?;

        Ok(Database {
            sync,
            io: io_worker,
        })
    }
}

// Synced Database handle.
#[derive(Clone)]
pub struct Database {
    sync: Arc<turso_sync_sdk_kit::rsapi::TursoDatabaseSync<Bytes>>,
    io: Arc<IoWorker>,
}

impl Database {
    // Push local changes to the remote.
    pub async fn push(&self) -> Result<()> {
        let op = self.sync.push_changes();
        drive_operation(op, self.io.clone()).await?;
        Ok(())
    }

    // Pull remote changes; returns true if any changes were applied.
    pub async fn pull(&self) -> Result<bool> {
        // First, wait for changes...
        let op = self.sync.wait_changes();
        let result = drive_operation_result(op, self.io.clone()).await?;
        let mut has_changes = false;

        if let Some(
            turso_sync_sdk_kit::turso_async_operation::TursoAsyncOperationResult::Changes {
                changes,
            },
        ) = result
        {
            if !changes.empty() {
                has_changes = true;
                // Then, apply them.
                let op_apply = self.sync.apply_changes(changes);
                drive_operation(op_apply, self.io.clone()).await?;
            }
        }

        Ok(has_changes)
    }

    // Force WAL checkpoint for the main database.
    pub async fn checkpoint(&self) -> Result<()> {
        let op = self.sync.checkpoint();
        drive_operation(op, self.io.clone()).await?;
        Ok(())
    }

    // Retrieve sync statistics for the database.
    pub async fn stats(&self) -> Result<DatabaseSyncStats> {
        let op = self.sync.stats();
        let result = drive_operation_result(op, self.io.clone()).await?;
        match result {
            Some(turso_sync_sdk_kit::turso_async_operation::TursoAsyncOperationResult::Stats {
                stats,
            }) => Ok(stats),
            _ => Err(Error::Misuse(
                "unexpected result type from stats operation".to_string(),
            )),
        }
    }

    // Create a SQL connection to the synced database.
    pub async fn connect(&self) -> Result<Connection> {
        let op = self.sync.connect();
        let result = drive_operation_result(op, self.io.clone()).await?;
        match result {
            Some(
                turso_sync_sdk_kit::turso_async_operation::TursoAsyncOperationResult::Connection {
                    connection,
                },
            ) => {
                // Provide extra_io callback to kick IO worker when driver needs to make progress.
                let io = self.io.clone();
                let extra_io = Arc::new(move |waker| {
                    io.register(waker);
                    io.kick();
                    Ok(())
                });
                Ok(Connection::create(connection, Some(extra_io)))
            }
            _ => Err(Error::Misuse(
                "unexpected result type from connect operation".to_string(),
            )),
        }
    }
}

// Drive an operation that has no result (returns None when done).
async fn drive_operation(
    op: Box<turso_sync_sdk_kit::turso_async_operation::TursoDatabaseAsyncOperation>,
    io: Arc<IoWorker>,
) -> Result<()> {
    let fut = AsyncOpFuture::new(op, io);
    fut.await.map(|_| ())
}

// Drive an operation and retrieve its result (if any).
async fn drive_operation_result(
    op: Box<turso_sync_sdk_kit::turso_async_operation::TursoDatabaseAsyncOperation>,
    io: Arc<IoWorker>,
) -> Result<Option<turso_sync_sdk_kit::turso_async_operation::TursoAsyncOperationResult>> {
    let fut = AsyncOpFuture::new(op, io);
    fut.await
}

// Custom Future that integrates with TursoDatabaseAsyncOperation and our IO worker.
struct AsyncOpFuture {
    op: Option<Box<turso_sync_sdk_kit::turso_async_operation::TursoDatabaseAsyncOperation>>,
    io: Arc<IoWorker>,
}

impl AsyncOpFuture {
    fn new(
        op: Box<turso_sync_sdk_kit::turso_async_operation::TursoDatabaseAsyncOperation>,
        io: Arc<IoWorker>,
    ) -> Self {
        Self { op: Some(op), io }
    }
}

impl Future for AsyncOpFuture {
    type Output =
        Result<Option<turso_sync_sdk_kit::turso_async_operation::TursoAsyncOperationResult>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = unsafe { self.get_unchecked_mut() };
        let Some(op) = &this.op else {
            return Poll::Ready(Err(Error::Misuse(
                "operation future has been already completed".to_string(),
            )));
        };

        this.io.register(cx.waker().clone());

        // Try to resume the operation.
        match op.resume() {
            Ok(turso_sdk_kit::rsapi::TursoStatusCode::Done) => {
                // Try to take the result (may be None).
                let result = op.take_result().map(Some).or_else(|err| match err {
                    turso_sdk_kit::rsapi::TursoError::Misuse(msg)
                        if msg.contains("operation has no result") =>
                    {
                        Ok(None)
                    }
                    other => Err(Error::from(other)),
                })?;
                // Drop the op and complete.
                this.op.take();
                Poll::Ready(Ok(result))
            }
            Ok(turso_sdk_kit::rsapi::TursoStatusCode::Io) => {
                // Kick IO worker to process queued IO.
                this.io.kick();
                // Wait until IO worker makes progress and wakes us.
                Poll::Pending
            }
            Ok(turso_sdk_kit::rsapi::TursoStatusCode::Row) => {
                // Not expected from top-level sync operations.
                Poll::Ready(Err(Error::Misuse(
                    "unexpected row status in sync operation".to_string(),
                )))
            }
            Err(e) => Poll::Ready(Err(Error::from(e))),
        }
    }
}

// Normalize remote base URL, mapping libsql:// to https:// and validating allowed schemes.
fn normalize_base_url(input: &str) -> std::result::Result<String, String> {
    let s = input.trim();
    let s = if let Some(rest) = s.strip_prefix("libsql://") {
        format!("https://{rest}")
    } else {
        s.to_string()
    };
    // Accept http or https only
    if !(s.starts_with("https://") || s.starts_with("http://")) {
        return Err(format!("unsupported remote URL scheme: {input}"));
    }
    // Ensure no trailing slash to make join predictable.
    let base = s.trim_end_matches('/').to_string();
    Ok(base)
}

// The IO worker owns a dedicated Tokio runtime on a separate thread, and processes
// the SyncEngine IO queue (HTTP and atomic file operations).
struct IoWorker {
    // Reference to the sync database to pull IO items from its queue.
    sync: Arc<turso_sync_sdk_kit::rsapi::TursoDatabaseSync<Bytes>>,
    // Normalized base URL (http/https).
    base_url: Option<String>,
    // Optional auth token.
    auth_token: Option<String>,
    // Channel to wake the worker to process IO.
    tx: mpsc::UnboundedSender<()>,
    // Wakers to notify pending futures when IO makes progress.
    wakers: Arc<Mutex<Vec<Waker>>>,
}

impl IoWorker {
    fn spawn(
        sync: Arc<turso_sync_sdk_kit::rsapi::TursoDatabaseSync<Bytes>>,
        base_url: Option<String>,
        auth_token: Option<String>,
    ) -> Arc<Self> {
        let (tx, rx) = mpsc::unbounded_channel::<()>();
        let wakers = Arc::new(Mutex::new(Vec::new()));

        let worker = Arc::new(Self {
            sync,
            base_url,
            auth_token,
            tx,
            wakers: wakers.clone(),
        });

        // Spin a separate Tokio runtime on its own thread to process IO queue.
        let worker_clone = worker.clone();
        std::thread::Builder::new()
            .name("turso-sync-io".to_string())
            .spawn(move || {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .expect("failed to build IO runtime");

                rt.block_on(async move {
                    IoWorker::run_loop(worker_clone, rx, wakers).await;
                });
            })
            .expect("failed to spawn IO worker thread");

        worker
    }

    // Register a waker to be awakened upon IO progress.
    fn register(&self, waker: Waker) {
        let mut wakers = self.wakers.lock().unwrap();
        wakers.push(waker);
    }

    // Kick the IO worker to process IO queue.
    fn kick(&self) {
        let _ = self.tx.send(());
    }

    // Called from the IO thread once progress has been made to notify all pending futures.
    fn notify_progress(wakers: &Arc<Mutex<Vec<Waker>>>) {
        let wakers = {
            let mut guard = wakers.lock().unwrap();
            std::mem::take(&mut *guard)
        };
        for w in wakers {
            w.wake();
        }
    }

    async fn run_loop(
        this: Arc<IoWorker>,
        mut rx: mpsc::UnboundedReceiver<()>,
        wakers: Arc<Mutex<Vec<Waker>>>,
    ) {
        // Create HTTPS-capable Hyper client.
        let mut http_connector = HttpConnector::new();
        http_connector.enforce_http(false);
        let https: HttpsConnector<HttpConnector> = HttpsConnector::new();
        let client: Client<HttpsConnector<HttpConnector>, Full<Bytes>> =
            Client::builder(TokioExecutor::new()).build::<_, Full<Bytes>>(https);

        while rx.recv().await.is_some() {
            // Process all pending items in the sync IO queue.
            let mut made_progress = false;
            loop {
                let item = this.sync.take_io_item();
                let Some(item) = item else {
                    this.sync.step_io_callbacks();
                    IoWorker::notify_progress(&wakers);
                    break;
                };

                made_progress = true;

                match item.get_request() {
                    turso_sync_sdk_kit::sync_engine_io::SyncEngineIoRequest::Http {
                        url,
                        method,
                        path,
                        body,
                        headers,
                    } => {
                        IoWorker::process_http(
                            &this,
                            &client,
                            url.as_deref(),
                            method,
                            path,
                            body.as_ref().map(|v| Bytes::from(v.clone())),
                            headers,
                            item.get_completion().clone(),
                        )
                        .await;
                    }
                    turso_sync_sdk_kit::sync_engine_io::SyncEngineIoRequest::FullRead { path } => {
                        IoWorker::process_full_read(
                            path,
                            item.get_completion().clone(),
                            &this.sync,
                        )
                        .await;
                    }
                    turso_sync_sdk_kit::sync_engine_io::SyncEngineIoRequest::FullWrite {
                        path,
                        content,
                    } => {
                        IoWorker::process_full_write(
                            path,
                            content,
                            item.get_completion().clone(),
                            &this.sync,
                        )
                        .await;
                    }
                }
            }

            // Run queued IO callbacks and wake all pending ops, yielding control
            // to allow them to make progress before we loop again.
            if made_progress {
                this.sync.step_io_callbacks();
                IoWorker::notify_progress(&wakers);
                // Let waiting tasks run on their executors.
                tokio::task::yield_now().await;
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    async fn process_http(
        this: &Arc<IoWorker>,
        client: &Client<HttpsConnector<HttpConnector>, Full<Bytes>>,
        url: Option<&str>,
        method: &str,
        path: &str,
        body: Option<Bytes>,
        headers: &[(String, String)],
        completion: turso_sync_sdk_kit::sync_engine_io::SyncEngineIoCompletion<Bytes>,
    ) {
        // Build full URL.
        let full_url = if path.starts_with("http://") || path.starts_with("https://") {
            path.to_string()
        } else {
            // Ensure the path begins with '/'
            let p = if path.starts_with('/') {
                path.to_string()
            } else {
                format!("/{path}")
            };
            let Some(url) = this.base_url.as_deref().or(url) else {
                completion.poison("remote_url is not available".to_string());
                return;
            };
            format!("{url}{p}")
        };

        let mut builder = Request::builder().method(method).uri(&full_url);

        // Set headers from request
        if let Some(headers_map) = builder.headers_mut() {
            for (k, v) in headers {
                if let Ok(name) = hyper::header::HeaderName::try_from(k.as_str()) {
                    if let Ok(value) = hyper::header::HeaderValue::try_from(v.as_str()) {
                        headers_map.insert(name, value);
                    }
                }
            }
            // Add Authorization header if not already set
            if let Some(token) = &this.auth_token {
                if !headers_map.contains_key(AUTHORIZATION) {
                    let value = format!("Bearer {token}");
                    if let Ok(hv) = hyper::header::HeaderValue::try_from(value.as_str()) {
                        headers_map.insert(AUTHORIZATION, hv);
                    }
                }
            }
        }

        // Body must be Full<Bytes> to match the client type.
        let req_body = Full::new(body.unwrap_or_default());

        let request = match builder.body(req_body) {
            Ok(r) => r,
            Err(err) => {
                completion.poison(format!("failed to build request: {err}"));
                this.sync.step_io_callbacks();
                return;
            }
        };

        let mut response = match client.request(request).await {
            Ok(r) => r,
            Err(err) => {
                completion.poison(format!("http request failed: {err}"));
                this.sync.step_io_callbacks();
                return;
            }
        };

        // Propagate status
        let status = response.status().as_u16();
        completion.status(status as u32);
        this.sync.step_io_callbacks();
        IoWorker::notify_progress(&this.wakers);

        // Stream response body in chunks
        while let Some(frame_res) = response.body_mut().frame().await {
            match frame_res {
                Ok(frame) => {
                    if let Some(chunk) = frame.data_ref() {
                        completion.push_buffer(chunk.clone());
                        this.sync.step_io_callbacks();
                        IoWorker::notify_progress(&this.wakers);
                    }
                }
                Err(err) => {
                    completion.poison(format!("error reading response body: {err}"));
                    this.sync.step_io_callbacks();
                    IoWorker::notify_progress(&this.wakers);
                    return;
                }
            }
        }

        // Done streaming
        completion.done();
        this.sync.step_io_callbacks();
        IoWorker::notify_progress(&this.wakers);
    }

    async fn process_full_read(
        path: &str,
        completion: turso_sync_sdk_kit::sync_engine_io::SyncEngineIoCompletion<Bytes>,
        sync: &Arc<turso_sync_sdk_kit::rsapi::TursoDatabaseSync<Bytes>>,
    ) {
        match tokio::fs::read(path).await {
            Ok(content) => {
                completion.push_buffer(Bytes::from(content));
                completion.done();
            }
            Err(err) if err.kind() == ErrorKind::NotFound => completion.done(),
            Err(err) => {
                completion.poison(format!("full read failed for {path}: {err}"));
            }
        }
        // Step callbacks after progress.
        sync.step_io_callbacks();
    }

    async fn process_full_write(
        path: &str,
        content: &Vec<u8>,
        completion: turso_sync_sdk_kit::sync_engine_io::SyncEngineIoCompletion<Bytes>,
        sync: &Arc<turso_sync_sdk_kit::rsapi::TursoDatabaseSync<Bytes>>,
    ) {
        // Write the whole content in one go (non-chunked)
        match tokio::fs::write(path, content).await {
            Ok(_) => {
                // For full write there is no data to stream back; just finish.
                completion.done();
            }
            Err(err) => {
                completion.poison(format!("full write failed for {path}: {err}"));
            }
        }
        // Step callbacks after progress.
        sync.step_io_callbacks();
    }
}

#[cfg(test)]
mod tests {
    use anyhow::{anyhow, Context, Result};
    use rand::{distr::Alphanumeric, Rng};
    use reqwest::Client;
    use serde_json::json;
    use std::{
        env,
        process::{Child, Command, Stdio},
        thread::sleep,
        time::Duration,
    };
    use tempfile::TempDir;
    use turso_sync_sdk_kit::rsapi::PartialBootstrapStrategy;

    use crate::sync::PartialSyncOpts;
    use crate::{Rows, Value};

    const ADMIN_URL: &str = "http://localhost:8081";
    const USER_URL: &str = "http://localhost:8080";

    fn random_str() -> String {
        rand::rng()
            .sample_iter(&Alphanumeric)
            .take(8)
            .map(char::from)
            .collect()
    }

    async fn handle_response(resp: reqwest::Response) -> Result<()> {
        let status = resp.status();
        let text = resp.text().await.unwrap_or_default();

        if status == 400 && text.contains("already exists") {
            return Ok(());
        }

        if !status.is_success() {
            return Err(anyhow!("request failed: {status} {text}"));
        }

        Ok(())
    }

    pub struct TursoServer {
        user_url: String,
        db_url: String,
        host: String,
        server: Option<Child>,
        client: Client,
    }

    impl TursoServer {
        pub async fn new() -> Result<Self> {
            let client = Client::new();

            if env::var("LOCAL_SYNC_SERVER").is_err() {
                let name = random_str();
                let tokens: Vec<&str> = USER_URL.split("://").collect();

                handle_response(
                    client
                        .post(format!("{ADMIN_URL}/v1/tenants/{name}"))
                        .send()
                        .await?,
                )
                .await?;
                handle_response(
                    client
                        .post(format!("{ADMIN_URL}/v1/tenants/{name}/groups/{name}"))
                        .send()
                        .await?,
                )
                .await?;
                handle_response(
                    client
                        .post(format!(
                            "{ADMIN_URL}/v1/tenants/{name}/groups/{name}/databases/{name}"
                        ))
                        .send()
                        .await?,
                )
                .await?;

                Ok(Self {
                    user_url: USER_URL.to_string(),
                    db_url: format!("{}://{}--{}--{}.{}", tokens[0], name, name, name, tokens[1]),
                    host: format!("{name}--{name}--{name}.localhost"),
                    server: None,
                    client,
                })
            } else {
                let port: u16 = rand::rng().random_range(10_000..=65_535);
                let server_bin = env::var("LOCAL_SYNC_SERVER").unwrap();

                let child = Command::new(server_bin)
                    .args(["--sync-server", &format!("0.0.0.0:{port}")])
                    .stdout(Stdio::piped())
                    .stderr(Stdio::piped())
                    .spawn()
                    .context("failed to spawn local sync server")?;

                let user_url = format!("http://localhost:{port}");

                // wait for server readiness
                loop {
                    if client.get(&user_url).send().await.is_ok() {
                        break;
                    }
                    sleep(Duration::from_millis(100));
                }

                Ok(Self {
                    user_url: user_url.clone(),
                    db_url: user_url,
                    host: String::new(),
                    server: Some(child),
                    client,
                })
            }
        }

        pub fn db_url(&self) -> &str {
            &self.db_url
        }

        pub async fn db_sql(&self, sql: &str) -> Result<Vec<Vec<Value>>> {
            let resp = self
                .client
                .post(format!("{}/v2/pipeline", self.user_url))
                .header("Host", &self.host)
                .json(&json!({
                    "requests": [{
                        "type": "execute",
                        "stmt": { "sql": sql }
                    }]
                }))
                .send()
                .await?
                .error_for_status()?;

            let value: serde_json::Value = resp.json().await?;

            let result = &value["results"][0];
            if result["type"] != "ok" {
                return Err(anyhow!("remote sql execution failed: {value}"));
            }

            let rows = result["response"]["result"]["rows"]
                .as_array()
                .ok_or_else(|| anyhow!("invalid response shape"))?;

            Ok(rows
                .iter()
                .map(|row| {
                    row.as_array()
                        .unwrap()
                        .iter()
                        .map(|cell| match cell["value"].clone() {
                            serde_json::Value::Null => Value::Null,
                            serde_json::Value::Number(number) => {
                                if number.is_i64() {
                                    Value::Integer(number.as_i64().unwrap())
                                } else {
                                    Value::Real(number.as_f64().unwrap())
                                }
                            }
                            serde_json::Value::String(s) => Value::Text(s),
                            _ => panic!("unexpected json output"),
                        })
                        .collect()
                })
                .collect())
        }
    }

    impl Drop for TursoServer {
        fn drop(&mut self) {
            if let Some(child) = &mut self.server {
                let _ = child.kill();
            }
        }
    }

    async fn all_rows(mut rows: Rows) -> Result<Vec<Vec<Value>>> {
        let mut result = Vec::new();
        while let Some(row) = rows.next().await? {
            result.push(row.values.into_iter().map(|x| x.into()).collect());
        }
        Ok(result)
    }

    #[tokio::test]
    pub async fn test_sync_bootstrap() {
        let _ = tracing_subscriber::fmt::try_init();
        let server = TursoServer::new().await.unwrap();
        server.db_sql("CREATE TABLE t(x)").await.unwrap();
        server
            .db_sql("INSERT INTO t VALUES ('hello'), ('turso'), ('sync')")
            .await
            .unwrap();
        server.db_sql("SELECT * FROM t").await.unwrap();
        let db = crate::sync::Builder::new_remote(":memory:")
            .with_remote_url(server.db_url())
            .build()
            .await
            .unwrap();
        let conn = db.connect().await.unwrap();
        let rows = conn.query("SELECT * FROM t", ()).await.unwrap();
        let all = all_rows(rows).await.unwrap();
        assert_eq!(
            all,
            vec![
                vec![Value::Text("hello".to_string())],
                vec![Value::Text("turso".to_string())],
                vec![Value::Text("sync".to_string())],
            ]
        );
    }

    #[tokio::test]
    pub async fn test_sync_bootstrap_persistence() {
        let _ = tracing_subscriber::fmt::try_init();
        let dir = TempDir::new().unwrap();
        let server = TursoServer::new().await.unwrap();
        server.db_sql("CREATE TABLE t(x)").await.unwrap();
        server
            .db_sql("INSERT INTO t VALUES ('hello'), ('turso'), ('sync')")
            .await
            .unwrap();
        server.db_sql("SELECT * FROM t").await.unwrap();
        let db = crate::sync::Builder::new_remote(dir.path().join("local.db").to_str().unwrap())
            .with_remote_url(server.db_url())
            .build()
            .await
            .unwrap();
        let conn = db.connect().await.unwrap();
        let rows = conn.query("SELECT * FROM t", ()).await.unwrap();
        let all = all_rows(rows).await.unwrap();
        assert_eq!(
            all,
            vec![
                vec![Value::Text("hello".to_string())],
                vec![Value::Text("turso".to_string())],
                vec![Value::Text("sync".to_string())],
            ]
        );
    }

    #[tokio::test]
    pub async fn test_sync_config_persistence() {
        let _ = tracing_subscriber::fmt::try_init();
        let dir = TempDir::new().unwrap();
        let server = TursoServer::new().await.unwrap();
        server.db_sql("CREATE TABLE t(x)").await.unwrap();
        server.db_sql("INSERT INTO t VALUES (42)").await.unwrap();
        {
            let db1 =
                crate::sync::Builder::new_remote(dir.path().join("local.db").to_str().unwrap())
                    .with_remote_url(server.db_url())
                    .build()
                    .await
                    .unwrap();
            let conn = db1.connect().await.unwrap();
            let rows = conn.query("SELECT * FROM t", ()).await.unwrap();
            let all = all_rows(rows).await.unwrap();
            assert_eq!(all, vec![vec![Value::Integer(42)],]);
        }
        server.db_sql("INSERT INTO t VALUES (41)").await.unwrap();
        {
            let db2 =
                crate::sync::Builder::new_remote(dir.path().join("local.db").to_str().unwrap())
                    .build()
                    .await
                    .unwrap();
            db2.pull().await.unwrap();
            let conn = db2.connect().await.unwrap();
            let rows = conn.query("SELECT * FROM t", ()).await.unwrap();
            let all = all_rows(rows).await.unwrap();
            assert_eq!(
                all,
                vec![vec![Value::Integer(42)], vec![Value::Integer(41)],]
            );
        }
    }

    #[tokio::test]
    pub async fn test_sync_pull() {
        let _ = tracing_subscriber::fmt::try_init();
        let server = TursoServer::new().await.unwrap();
        server.db_sql("CREATE TABLE t(x)").await.unwrap();
        server
            .db_sql("INSERT INTO t VALUES ('hello'), ('turso'), ('sync')")
            .await
            .unwrap();
        server.db_sql("SELECT * FROM t").await.unwrap();
        let db = crate::sync::Builder::new_remote(":memory:")
            .with_remote_url(server.db_url())
            .build()
            .await
            .unwrap();
        let conn = db.connect().await.unwrap();
        let rows = conn.query("SELECT * FROM t", ()).await.unwrap();
        let all = all_rows(rows).await.unwrap();
        assert_eq!(
            all,
            vec![
                vec![Value::Text("hello".to_string())],
                vec![Value::Text("turso".to_string())],
                vec![Value::Text("sync".to_string())],
            ]
        );

        server
            .db_sql("INSERT INTO t VALUES ('pull works')")
            .await
            .unwrap();

        let rows = conn.query("SELECT * FROM t", ()).await.unwrap();
        let all = all_rows(rows).await.unwrap();
        assert_eq!(
            all,
            vec![
                vec![Value::Text("hello".to_string())],
                vec![Value::Text("turso".to_string())],
                vec![Value::Text("sync".to_string())],
            ]
        );

        db.pull().await.unwrap();

        let rows = conn.query("SELECT * FROM t", ()).await.unwrap();
        let all = all_rows(rows).await.unwrap();
        assert_eq!(
            all,
            vec![
                vec![Value::Text("hello".to_string())],
                vec![Value::Text("turso".to_string())],
                vec![Value::Text("sync".to_string())],
                vec![Value::Text("pull works".to_string())],
            ]
        );
    }

    #[tokio::test]
    pub async fn test_sync_push() {
        let _ = tracing_subscriber::fmt::try_init();
        let server = TursoServer::new().await.unwrap();
        server.db_sql("CREATE TABLE t(x)").await.unwrap();
        server
            .db_sql("INSERT INTO t VALUES ('hello'), ('turso'), ('sync')")
            .await
            .unwrap();
        server.db_sql("SELECT * FROM t").await.unwrap();
        let db = crate::sync::Builder::new_remote(":memory:")
            .with_remote_url(server.db_url())
            .build()
            .await
            .unwrap();
        let conn = db.connect().await.unwrap();
        let rows = conn.query("SELECT * FROM t", ()).await.unwrap();
        let all = all_rows(rows).await.unwrap();
        assert_eq!(
            all,
            vec![
                vec![Value::Text("hello".to_string())],
                vec![Value::Text("turso".to_string())],
                vec![Value::Text("sync".to_string())],
            ]
        );

        conn.execute("INSERT INTO t VALUES ('push works')", ())
            .await
            .unwrap();

        let all = server.db_sql("SELECT * FROM t").await.unwrap();
        assert_eq!(
            all,
            vec![
                vec![Value::Text("hello".to_string())],
                vec![Value::Text("turso".to_string())],
                vec![Value::Text("sync".to_string())],
            ]
        );

        db.push().await.unwrap();

        let rows = conn.query("SELECT * FROM t", ()).await.unwrap();
        let all = all_rows(rows).await.unwrap();
        assert_eq!(
            all,
            vec![
                vec![Value::Text("hello".to_string())],
                vec![Value::Text("turso".to_string())],
                vec![Value::Text("sync".to_string())],
                vec![Value::Text("push works".to_string())],
            ]
        );
    }

    #[tokio::test]
    pub async fn test_sync_checkpoint() {
        let _ = tracing_subscriber::fmt::try_init();
        let server = TursoServer::new().await.unwrap();
        let db = crate::sync::Builder::new_remote(":memory:")
            .with_remote_url(server.db_url())
            .build()
            .await
            .unwrap();
        let conn = db.connect().await.unwrap();
        conn.execute("CREATE TABLE t(x)", ()).await.unwrap();
        for i in 0..1024 {
            conn.execute("INSERT INTO t VALUES (?)", (i,))
                .await
                .unwrap();
        }

        let stats1 = db.stats().await.unwrap();
        assert!(stats1.main_wal_size > 1024 * 1024);
        db.checkpoint().await.unwrap();
        let stats2 = db.stats().await.unwrap();
        assert!(stats2.main_wal_size < 8 * 1024);
    }

    #[tokio::test]
    pub async fn test_sync_partial() {
        let _ = tracing_subscriber::fmt::try_init();
        let server = TursoServer::new().await.unwrap();
        server.db_sql("CREATE TABLE t(x)").await.unwrap();
        server
            .db_sql("INSERT INTO t SELECT randomblob(1024) FROM generate_series(1, 2000)")
            .await
            .unwrap();
        {
            let full_db = crate::sync::Builder::new_remote(":memory:")
                .with_remote_url(server.db_url())
                .build()
                .await
                .unwrap();
            let conn = full_db.connect().await.unwrap();
            let _ = all_rows(
                conn.query("SELECT LENGTH(x) FROM t LIMIT 1", ())
                    .await
                    .unwrap(),
            )
            .await
            .unwrap();
            assert!(full_db.stats().await.unwrap().network_received_bytes > 2000 * 1024);
        }
        {
            let partial_db = crate::sync::Builder::new_remote(":memory:")
                .with_remote_url(server.db_url())
                .with_partial_sync_opts_experimental(PartialSyncOpts {
                    bootstrap_strategy: Some(PartialBootstrapStrategy::Prefix {
                        length: 128 * 1024,
                    }),
                    segment_size: 128 * 1024,
                    prefetch: false,
                })
                .build()
                .await
                .unwrap();
            let conn = partial_db.connect().await.unwrap();
            let _ = all_rows(
                conn.query("SELECT LENGTH(x) FROM t LIMIT 1", ())
                    .await
                    .unwrap(),
            )
            .await
            .unwrap();
            assert!(partial_db.stats().await.unwrap().network_received_bytes < 256 * (1024 + 10));
            let before = tokio::time::Instant::now();
            let all = all_rows(
                conn.query("SELECT SUM(LENGTH(x)) FROM t", ())
                    .await
                    .unwrap(),
            )
            .await
            .unwrap();
            println!(
                "duration: {:?}",
                tokio::time::Instant::now().duration_since(before)
            );
            assert_eq!(all, vec![vec![Value::Integer(2000 * 1024)]]);
            assert!(partial_db.stats().await.unwrap().network_received_bytes > 2000 * 1024);
        }
    }

    #[tokio::test]
    pub async fn test_sync_partial_segment_size() {
        let _ = tracing_subscriber::fmt::try_init();
        let server = TursoServer::new().await.unwrap();
        server.db_sql("CREATE TABLE t(x)").await.unwrap();
        server
            .db_sql("INSERT INTO t SELECT randomblob(1024) FROM generate_series(1, 256)")
            .await
            .unwrap();
        {
            let full_db = crate::sync::Builder::new_remote(":memory:")
                .with_remote_url(server.db_url())
                .build()
                .await
                .unwrap();
            let conn = full_db.connect().await.unwrap();
            let _ = all_rows(
                conn.query("SELECT LENGTH(x) FROM t LIMIT 1", ())
                    .await
                    .unwrap(),
            )
            .await
            .unwrap();
            assert!(full_db.stats().await.unwrap().network_received_bytes > 256 * 1024);
        }
        {
            let partial_db = crate::sync::Builder::new_remote(":memory:")
                .with_remote_url(server.db_url())
                .with_partial_sync_opts_experimental(PartialSyncOpts {
                    bootstrap_strategy: Some(PartialBootstrapStrategy::Prefix {
                        length: 128 * 1024,
                    }),
                    segment_size: 4 * 1024,
                    prefetch: false,
                })
                .build()
                .await
                .unwrap();
            let conn = partial_db.connect().await.unwrap();
            let _ = all_rows(
                conn.query("SELECT LENGTH(x) FROM t LIMIT 1", ())
                    .await
                    .unwrap(),
            )
            .await
            .unwrap();
            assert!(partial_db.stats().await.unwrap().network_received_bytes < 128 * 1024 * 3 / 2);
            let before = tokio::time::Instant::now();
            let all = all_rows(
                conn.query("SELECT SUM(LENGTH(x)) FROM t", ())
                    .await
                    .unwrap(),
            )
            .await
            .unwrap();
            println!(
                "duration segment size: {:?}",
                tokio::time::Instant::now().duration_since(before)
            );
            assert_eq!(all, vec![vec![Value::Integer(256 * 1024)]]);
            assert!(partial_db.stats().await.unwrap().network_received_bytes > 256 * 1024);
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    pub async fn test_sync_partial_prefetch() {
        let _ = tracing_subscriber::fmt::try_init();
        let server = TursoServer::new().await.unwrap();
        server.db_sql("CREATE TABLE t(x)").await.unwrap();
        server
            .db_sql("INSERT INTO t SELECT randomblob(1024) FROM generate_series(1, 2000)")
            .await
            .unwrap();
        {
            let full_db = crate::sync::Builder::new_remote(":memory:")
                .with_remote_url(server.db_url())
                .build()
                .await
                .unwrap();
            let conn = full_db.connect().await.unwrap();
            let _ = all_rows(
                conn.query("SELECT LENGTH(x) FROM t LIMIT 1", ())
                    .await
                    .unwrap(),
            )
            .await
            .unwrap();
            assert!(full_db.stats().await.unwrap().network_received_bytes > 2000 * 1024);
        }
        {
            let partial_db = crate::sync::Builder::new_remote(":memory:")
                .with_remote_url(server.db_url())
                .with_partial_sync_opts_experimental(PartialSyncOpts {
                    bootstrap_strategy: Some(PartialBootstrapStrategy::Prefix {
                        length: 128 * 1024,
                    }),
                    segment_size: 128 * 1024,
                    prefetch: true,
                })
                .build()
                .await
                .unwrap();
            let conn = partial_db.connect().await.unwrap();
            let _ = all_rows(
                conn.query("SELECT LENGTH(x) FROM t LIMIT 1", ())
                    .await
                    .unwrap(),
            )
            .await
            .unwrap();
            assert!(partial_db.stats().await.unwrap().network_received_bytes < 1300 * (1024 + 10));
            let before = tokio::time::Instant::now();
            let all = all_rows(
                conn.query("SELECT SUM(LENGTH(x)) FROM t", ())
                    .await
                    .unwrap(),
            )
            .await
            .unwrap();
            println!(
                "duration prefetch: {:?}",
                tokio::time::Instant::now().duration_since(before)
            );
            assert_eq!(all, vec![vec![Value::Integer(2000 * 1024)]]);
            assert!(partial_db.stats().await.unwrap().network_received_bytes > 2000 * 1024);
        }
    }
}