syncular_client/transport.rs
1//! The transport seam handed TO the client by its host (the conformance
2//! harness, an app shell, …). Bytes and strings only — mirroring the
3//! `ClientEndpoints` inversion of the conformance driver contract. The
4//! client is synchronous: the driver protocol is request/response.
5
6/// A transport-level or request-level failure (§1.1 HTTP-JSON surface).
7#[derive(Debug, Clone)]
8pub struct TransportError {
9 pub code: String,
10 pub message: String,
11 pub details: Option<serde_json::Value>,
12}
13
14impl TransportError {
15 pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
16 TransportError {
17 code: code.into(),
18 message: message.into(),
19 details: None,
20 }
21 }
22}
23
24/// Direct-endpoint segment fetch (§5.5). Signed-URL descriptors never
25/// reach this call: the §5.4 resolution lives in the client core, which
26/// routes url-carrying descriptors through `fetch_url` instead.
27#[derive(Debug, Clone)]
28pub struct SegmentRequest {
29 pub segment_id: String,
30 pub table: String,
31 /// Canonical JSON (§11.2) of the requested scope map (§5.5).
32 pub requested_scopes_json: String,
33 /// The descriptor's `byteLength` (§5.4): the transport stops reading once
34 /// the body exceeds it, and the client rejects the longer body.
35 pub byte_length: u64,
36}
37
38/// One segment body fetch of a response's batch: the direct endpoint (§5.5) or
39/// a signed URL (§5.4). The client resolves §5.4 descriptor routing before the
40/// batch, so a URL arm here is always fetchable (never at/past expiry).
41#[derive(Debug, Clone)]
42pub enum SegmentFetch {
43 /// Direct-endpoint request (§5.5).
44 Direct(SegmentRequest),
45 /// Plain GET of a signed URL; the URL is the entire grant (§5.4).
46 /// `byte_length` caps the read as on [`SegmentRequest`].
47 Url { url: String, byte_length: u64 },
48}
49
50/// A §5.9.5 blob download result: inline bytes, or a presigned url the client
51/// fetches directly (always-issue). `url_expires_at_ms` is present iff `url`.
52#[derive(Debug, Clone)]
53pub enum BlobDownload {
54 Bytes(Vec<u8>),
55 Url {
56 url: String,
57 url_expires_at_ms: Option<i64>,
58 },
59}
60
61/// A §5.9.3 presigned-upload grant: a single PUT url, an already-present
62/// marker (skip the PUT), or none (stream through the direct endpoint).
63#[derive(Debug, Clone)]
64pub enum BlobUploadGrant {
65 Url {
66 url: String,
67 url_expires_at_ms: Option<i64>,
68 },
69 Present,
70 None,
71}
72
73pub trait Transport {
74 /// One combined push+pull round trip (§1.5) over the request/response
75 /// binding (`POST /sync`, loopback, …).
76 fn sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError>;
77 /// One registered authoritative query or command request. Hosts that do
78 /// not expose `<mount>/operations` keep the default fail-loud behavior.
79 fn remote_operation(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError> {
80 let _ = request;
81 Err(TransportError::new(
82 "client.remote_operations_unconfigured",
83 "this transport has no remote operation endpoint",
84 ))
85 }
86 /// One combined push+pull round over the realtime socket (§8.7). The
87 /// host owns the WS-binding mechanics — channel tags, chunk assembly
88 /// to the response's END — and returns the assembled response bytes.
89 /// The client calls this instead of `sync` whenever realtime is
90 /// connected (the socket IS the sync-round
91 /// transport, not a fallback pair); the server registers the round's
92 /// live units on the connection at round end, so no reconnect is
93 /// needed after registration changes (§8.7).
94 fn realtime_sync(&mut self, request: &[u8]) -> Result<Vec<u8>, TransportError>;
95 /// Segment download via the direct endpoint (§5.5).
96 fn download_segment(
97 &mut self,
98 request: &SegmentRequest,
99 _on_progress: &mut dyn FnMut(u64),
100 ) -> Result<Vec<u8>, TransportError>;
101 /// Every eligible segment body of one response, in wire order (§5.4 / §5.5).
102 /// `on_progress` receives the fetch index and that fetch's cumulative
103 /// decoded bytes.
104 ///
105 /// Returns one result per attempted fetch, in the same order. The default
106 /// runs the single `download_segment` / `fetch_url` calls in order and
107 /// stops after the first error, so a shorter result list means the
108 /// remaining fetches were not attempted. A host that overlaps the fetches
109 /// may attempt all of them; the client still stops consuming at the first
110 /// error, at that descriptor's position in the wire order.
111 fn download_segments(
112 &mut self,
113 fetches: &[SegmentFetch],
114 on_progress: &mut (dyn FnMut(usize, u64) + Send),
115 ) -> Vec<Result<Vec<u8>, TransportError>> {
116 let mut results = Vec::new();
117 for (index, fetch) in fetches.iter().enumerate() {
118 let mut report = |bytes| on_progress(index, bytes);
119 let result = match fetch {
120 SegmentFetch::Direct(request) => self.download_segment(request, &mut report),
121 SegmentFetch::Url { url, byte_length } => {
122 self.fetch_url(url, *byte_length, &mut report)
123 }
124 };
125 let failed = result.is_err();
126 results.push(result);
127 if failed {
128 break;
129 }
130 }
131 results
132 }
133 /// §5.4 direct URL fetch capability: `true` makes the client
134 /// advertise accept bit 3 (capability negotiation, §4.2). Default:
135 /// not capable.
136 fn supports_url_fetch(&self) -> bool {
137 false
138 }
139 /// Plain GET of a signed URL (§5.4). The URL is the entire grant —
140 /// implementations MUST NOT attach sync-server authentication or the
141 /// `X-Syncular-Scopes` header. Only called when `supports_url_fetch`
142 /// returned `true`. Reading stops once the body exceeds `byte_length`.
143 fn fetch_url(
144 &mut self,
145 url: &str,
146 byte_length: u64,
147 _on_progress: &mut dyn FnMut(u64),
148 ) -> Result<Vec<u8>, TransportError> {
149 let _ = (url, byte_length);
150 Err(TransportError::new(
151 "sync.invalid_request",
152 "this transport has no direct URL fetch (§5.4)",
153 ))
154 }
155 /// The I/O executor records when a signed segment fetch began. Apply
156 /// checks expiry against that instant, preserving the fetch-start rule.
157 fn segment_fetch_started_at(&self, _url: &str) -> Option<i64> {
158 None
159 }
160 /// §5.9.3 blob upload: host-authenticated `PUT <mount>/blobs/{blobId}`.
161 /// The server verifies the content address. Default: unsupported.
162 fn blob_upload(
163 &mut self,
164 blob_id: &str,
165 bytes: &[u8],
166 media_type: Option<&str>,
167 ) -> Result<(), TransportError> {
168 let _ = (blob_id, bytes, media_type);
169 Err(TransportError::new(
170 "sync.invalid_request",
171 "this transport has no blob upload (§5.9)",
172 ))
173 }
174 /// §5.9.5 blob download: host-authenticated `GET <mount>/blobs/{blobId}`,
175 /// re-authorized server-side against referencing rows. Returns inline
176 /// bytes OR (always-issue, presign configured) a signed url the client
177 /// fetches directly. `byte_length` is the BlobRef's declared size when the
178 /// caller has one; reading inline bytes stops once the body exceeds it.
179 /// Default: none.
180 fn blob_download(
181 &mut self,
182 blob_id: &str,
183 byte_length: Option<u64>,
184 ) -> Result<BlobDownload, TransportError> {
185 let _ = (blob_id, byte_length);
186 Err(TransportError::new(
187 "blob.not_found",
188 "this transport has no blob download (§5.9)",
189 ))
190 }
191 /// §5.9.5 presigned-download fetch: a bare GET of the signed url. MUST
192 /// attach NO host authentication — the url is the entire grant (§5.4).
193 /// Only called when `blob_download` returned a `Url` arm. Reading stops
194 /// once the body exceeds `byte_length`.
195 fn fetch_blob_url(
196 &mut self,
197 url: &str,
198 byte_length: Option<u64>,
199 ) -> Result<Vec<u8>, TransportError> {
200 let _ = (url, byte_length);
201 Err(TransportError::new(
202 "sync.invalid_request",
203 "this transport has no blob url fetch (§5.9.5)",
204 ))
205 }
206 /// §5.9.3 presigned-upload grant: `POST /blobs/{blobId}/upload-grant` with
207 /// the declared size. Absent (`None`) ⇒ the client always streams through
208 /// `blob_upload`. A `Url` grant is PUT via `blob_put_url`.
209 fn blob_upload_grant(
210 &mut self,
211 blob_id: &str,
212 byte_length: u64,
213 media_type: Option<&str>,
214 ) -> Result<BlobUploadGrant, TransportError> {
215 let _ = (blob_id, byte_length, media_type);
216 Ok(BlobUploadGrant::None)
217 }
218 /// §5.9.3 direct-to-storage PUT of the granted url. MUST attach NO host
219 /// authentication — the presigned url is the entire grant (§5.4). Only
220 /// called when `blob_upload_grant` returned a `Url` arm.
221 fn blob_put_url(
222 &mut self,
223 blob_id: &str,
224 url: &str,
225 bytes: &[u8],
226 media_type: Option<&str>,
227 ) -> Result<(), TransportError> {
228 let _ = (blob_id, url, bytes, media_type);
229 Err(TransportError::new(
230 "sync.invalid_request",
231 "this transport has no blob put url (§5.9.3)",
232 ))
233 }
234 /// Realtime attach (§8.1). Inbound traffic is delivered by the host via
235 /// `SyncClient::on_realtime_text` / `on_realtime_binary`.
236 /// Legacy host-configured realtime connection. Implementations which do
237 /// not bind identity at the URL layer may implement only this method.
238 fn realtime_connect(&mut self) -> Result<(), TransportError>;
239 /// Open realtime for this exact persisted client identity. Native socket
240 /// servers bind registrations/cursors to the URL-level client id before
241 /// any protocol frame is exchanged, so client-owned hosts override this.
242 /// The default preserves compatibility with connectors that already close
243 /// over their identity.
244 fn realtime_connect_for_client(&mut self, _client_id: &str) -> Result<(), TransportError> {
245 self.realtime_connect()
246 }
247 /// The whole-round network deadline this transport would apply, as a
248 /// budget. `None` (the default) means no round deadline. The client
249 /// anchors the returned budget once per round and scopes it to each
250 /// `PreparedSyncRound::exchange`, so a reused transport never carries
251 /// stale deadline state.
252 fn round_deadline(&self) -> Option<std::time::Duration> {
253 None
254 }
255 /// Scope the transport to one absolute round deadline for the duration of
256 /// a single exchange; `None` clears it. The default ignores it.
257 fn set_round_deadline(&mut self, _deadline: Option<std::time::Instant>) {}
258 /// Client → server JSON control message (acks, §8.2).
259 fn realtime_send(&mut self, text: &str) -> Result<(), TransportError>;
260 fn realtime_close(&mut self) -> Result<(), TransportError>;
261 /// §12: open (or reopen) the host-configured local authority with the
262 /// client's schema before the client opens its replica at `replica_path`.
263 /// A transport without a local authority has nothing to open.
264 fn open_local_authority(
265 &mut self,
266 schema: &serde_json::Value,
267 replica_path: Option<&str>,
268 ) -> Result<(), TransportError> {
269 let _ = (schema, replica_path);
270 Ok(())
271 }
272 /// §12.3 state of the opened local authority (`local`, `attaching`,
273 /// `attached`); `None` when the host configured none or it is not open.
274 fn local_authority_state(&self) -> Option<&'static str> {
275 None
276 }
277 /// §12.3 attach: upload the local authority's rows to the remote server.
278 fn attach_local_authority(&mut self) -> Result<(), TransportError> {
279 Err(TransportError::new(
280 crate::LOCAL_AUTHORITY_UNCONFIGURED_CODE,
281 "this transport has no local authority",
282 ))
283 }
284 /// §12.3 abandon: roll a stopped attach back and serve the client locally.
285 fn abandon_local_authority_attach(&mut self) -> Result<(), TransportError> {
286 Err(TransportError::new(
287 crate::LOCAL_AUTHORITY_UNCONFIGURED_CODE,
288 "this transport has no local authority",
289 ))
290 }
291}