-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathinterface.rs
More file actions
222 lines (199 loc) · 7.51 KB
/
interface.rs
File metadata and controls
222 lines (199 loc) · 7.51 KB
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
use core::cell::RefCell;
use core::ffi::{c_int, c_void};
use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::rc::Rc;
use alloc::string::ToString;
use alloc::sync::Arc;
use alloc::{string::String, vec::Vec};
use serde::{Deserialize, Serialize};
use sqlite::{ResultCode, Value};
use sqlite_nostd::{self as sqlite, ColumnType};
use sqlite_nostd::{Connection, Context};
use crate::error::SQLiteError;
use crate::schema::Schema;
use crate::state::DatabaseState;
use super::streaming_sync::SyncClient;
use super::sync_status::DownloadSyncStatus;
/// Payload provided by SDKs when requesting a sync iteration.
#[derive(Default, Deserialize)]
pub struct StartSyncStream {
/// Bucket parameters to include in the request when opening a sync stream.
#[serde(default)]
pub parameters: Option<serde_json::Map<String, serde_json::Value>>,
#[serde(default)]
pub schema: Schema,
}
/// A request sent from a client SDK to the [SyncClient] with a `powersync_control` invocation.
pub enum SyncControlRequest<'a> {
/// The client requests to start a sync iteration.
///
/// Earlier iterations are implicitly dropped when receiving this request.
StartSyncStream(StartSyncStream),
/// The client requests to stop the current sync iteration.
StopSyncStream,
/// The client is forwading a sync event to the core extension.
SyncEvent(SyncEvent<'a>),
}
pub enum SyncEvent<'a> {
/// A synthetic event forwarded to the [SyncClient] after being started.
Initialize,
/// An event requesting the sync client to shut down.
TearDown,
/// Notifies the sync client that a token has been refreshed.
///
/// In response, we'll stop the current iteration to begin another one with the new token.
DidRefreshToken,
/// Notifies the sync client that the current CRUD upload (for which the client SDK is
/// responsible) has finished.
///
/// If pending CRUD entries have previously prevented a sync from completing, this even can be
/// used to try again.
UploadFinished,
/// Forward a text line (JSON) received from the sync service.
TextLine { data: &'a str },
/// Forward a binary line (BSON) received from the sync service.
BinaryLine { data: &'a [u8] },
}
/// An instruction sent by the core extension to the SDK.
#[derive(Serialize)]
pub enum Instruction {
LogLine {
severity: LogSeverity,
line: Cow<'static, str>,
},
/// Update the download status for the ongoing sync iteration.
UpdateSyncStatus {
status: Rc<RefCell<DownloadSyncStatus>>,
},
/// Connect to the sync service using the [StreamingSyncRequest] created by the core extension,
/// and then forward received lines via [SyncEvent::TextLine] and [SyncEvent::BinaryLine].
EstablishSyncStream { request: StreamingSyncRequest },
FetchCredentials {
/// Whether the credentials currently used have expired.
///
/// If false, this is a pre-fetch.
did_expire: bool,
},
// These are defined like this because deserializers in Kotlin can't support either an
// object or a literal value
/// Close the websocket / HTTP stream to the sync service.
CloseSyncStream {},
/// Flush the file-system if it's non-durable (only applicable to the Dart SDK).
FlushFileSystem {},
/// Notify that a sync has been completed, prompting client SDKs to clear earlier errors.
DidCompleteSync {},
}
#[derive(Serialize)]
pub enum LogSeverity {
DEBUG,
INFO,
WARNING,
}
#[derive(Serialize)]
pub struct StreamingSyncRequest {
pub buckets: Vec<BucketRequest>,
pub include_checksum: bool,
pub raw_data: bool,
pub binary_data: bool,
pub client_id: String,
pub parameters: Option<serde_json::Map<String, serde_json::Value>>,
}
#[derive(Serialize)]
pub struct BucketRequest {
pub name: String,
pub after: String,
}
/// Wrapper around a [SyncClient].
///
/// We allocate one instance of this per database (in [register]) - the [SyncClient] has an initial
/// empty state that doesn't consume any resources.
struct SqlController {
client: SyncClient,
}
pub fn register(db: *mut sqlite::sqlite3, state: Arc<DatabaseState>) -> Result<(), ResultCode> {
extern "C" fn control(
ctx: *mut sqlite::context,
argc: c_int,
argv: *mut *mut sqlite::value,
) -> () {
let result = (|| -> Result<(), SQLiteError> {
debug_assert!(!ctx.db_handle().get_autocommit());
let controller = unsafe { ctx.user_data().cast::<SqlController>().as_mut() }
.ok_or_else(|| SQLiteError::from(ResultCode::INTERNAL))?;
let args = sqlite::args!(argc, argv);
let [op, payload] = args else {
return Err(ResultCode::MISUSE.into());
};
if op.value_type() != ColumnType::Text {
return Err(SQLiteError(
ResultCode::MISUSE,
Some("First argument must be a string".to_string()),
));
}
let op = op.text();
let event = match op {
"start" => SyncControlRequest::StartSyncStream({
if payload.value_type() == ColumnType::Text {
serde_json::from_str(payload.text())?
} else {
StartSyncStream::default()
}
}),
"stop" => SyncControlRequest::StopSyncStream,
"line_text" => SyncControlRequest::SyncEvent(SyncEvent::TextLine {
data: if payload.value_type() == ColumnType::Text {
payload.text()
} else {
return Err(SQLiteError(
ResultCode::MISUSE,
Some("Second argument must be a string".to_string()),
));
},
}),
"line_binary" => SyncControlRequest::SyncEvent(SyncEvent::BinaryLine {
data: if payload.value_type() == ColumnType::Blob {
payload.blob()
} else {
return Err(SQLiteError(
ResultCode::MISUSE,
Some("Second argument must be a byte array".to_string()),
));
},
}),
"refreshed_token" => SyncControlRequest::SyncEvent(SyncEvent::DidRefreshToken),
"completed_upload" => SyncControlRequest::SyncEvent(SyncEvent::UploadFinished),
_ => {
return Err(SQLiteError(
ResultCode::MISUSE,
Some("Unknown operation".to_string()),
))
}
};
let instructions = controller.client.push_event(event)?;
let formatted = serde_json::to_string(&instructions)?;
ctx.result_text_transient(&formatted);
Ok(())
})();
if let Err(e) = result {
e.apply_to_ctx("powersync_control", ctx);
}
}
unsafe extern "C" fn destroy(ptr: *mut c_void) {
drop(Box::from_raw(ptr.cast::<SqlController>()));
}
let controller = Box::new(SqlController {
client: SyncClient::new(db, state),
});
db.create_function_v2(
"powersync_control",
2,
sqlite::UTF8 | sqlite::DIRECTONLY,
Some(Box::into_raw(controller).cast()),
Some(control),
None,
None,
Some(destroy),
)?;
Ok(())
}