pub struct SyncClient { /* private fields */ }Implementations§
Source§impl SyncClient
impl SyncClient
Sourcepub const SYNC_IDLE_TIMEOUT_MS: u64 = 60_000
pub const SYNC_IDLE_TIMEOUT_MS: u64 = 60_000
§7.8: one idle drive’s default total deadline, the TS client’s value.
pub fn new_with_identity( client_id: Option<String>, schema_json: &Value, limits: ClientLimits, ) -> Result<Self, String>
pub fn new( client_id: String, schema_json: &Value, limits: ClientLimits, ) -> Result<Self, String>
Sourcepub fn open_path(
client_id: String,
schema_json: &Value,
limits: ClientLimits,
path: &str,
) -> Result<Self, String>
pub fn open_path( client_id: String, schema_json: &Value, limits: ClientLimits, path: &str, ) -> Result<Self, String>
Build a client backed by an on-disk SQLite database at path — the
seam a native host (Tauri plugin, FFI file-DB variant) uses to persist
across process restarts. create_tables runs IF NOT EXISTS, so
re-opening the same file reuses the persisted rows. Keeps rusqlite out
of the command router’s dependency set (the router only holds a path).
Sourcepub fn open_path_with_identity(
client_id: Option<String>,
schema_json: &Value,
limits: ClientLimits,
path: &str,
) -> Result<Self, String>
pub fn open_path_with_identity( client_id: Option<String>, schema_json: &Value, limits: ClientLimits, path: &str, ) -> Result<Self, String>
Open a file replica and resolve its client id. Native targets require
WAL for the independent snapshot reader; wasm32-unknown-unknown
accepts the sqlite-wasm worker journal instead.
Sourcepub fn reset_replica(path: &str) -> Result<(), String>
pub fn reset_replica(path: &str) -> Result<(), String>
Delete a file replica at path, including its -journal, -wal, and
-shm sidecars, through the VFS that owns it. Use this after
client.storage_corrupt: an OPFS SAH pool stores those files under
opaque names, so deleting the pool directory behind SQLite bypasses the
pool’s slot accounting.
Close the client and every FileQuerySnapshotReader on path first;
a VFS cannot delete a file another handle still owns. A file that does
not exist counts as deleted, so a cleanly closed replica without
sidecars resets. The next open
creates a fresh replica (new client id) and re-bootstraps from the
server. A memory replica has nothing to delete and fails with
sync.invalid_request.
pub fn client_id(&self) -> &str
Sourcepub fn reset_client_id(
&mut self,
transport: &mut dyn Transport,
) -> Result<String, String>
pub fn reset_client_id( &mut self, transport: &mut dyn Transport, ) -> Result<String, String>
Rotate the caller’s client id (§1.5) and return the new one. Use it
after a sync.invalid_client_id refusal (recommendedAction: resetClientId): the next round carries the new id. A live realtime
socket is closed so the next connection registers with the new id.
The replica and its outbox stay in place; wipe them yourself when the
stored data belongs to the account that signed out.
Sourcepub fn with_connection(
client_id: String,
schema_json: &Value,
limits: ClientLimits,
conn: Connection,
) -> Result<Self, String>
pub fn with_connection( client_id: String, schema_json: &Value, limits: ClientLimits, conn: Connection, ) -> Result<Self, String>
Build a client over a caller-supplied rusqlite connection — the seam a
native host (Tauri plugin, FFI file-DB variant) uses to back the core
with an on-disk database (Connection::open(path)) rather than the
default :memory:. The connection MUST be fresh (no pre-existing
syncular tables); create_tables runs IF NOT EXISTS, so re-opening
the same file across process restarts reuses the persisted rows.
Sourcepub fn set_now_ms(&mut self, now_ms: i64)
pub fn set_now_ms(&mut self, now_ms: i64)
Pin the client clock (epoch ms) — the §5.4 expiry check runs against this instead of system time (conformance virtual clock).
Sourcepub fn set_encryption(&mut self, encryption: EncryptionConfig)
pub fn set_encryption(&mut self, encryption: EncryptionConfig)
§5.11: install the client-side encryption keys (keyId → key bytes).
The command router parses these from the create command’s
encryption config (keys as {$bytes: hex}).
pub fn security_lifecycle(&self) -> &'static str
pub fn security_preflight(&self) -> bool
Sourcepub fn set_transport_enabled(
&mut self,
transport: &mut dyn Transport,
enabled: bool,
)
pub fn set_transport_enabled( &mut self, transport: &mut dyn Transport, enabled: bool, )
Host-owned, non-persisted network gate. Local operations remain available.
pub fn transport_enabled(&self) -> bool
Sourcepub fn begin_security_preflight(&mut self) -> Result<(), String>
pub fn begin_security_preflight(&mut self) -> Result<(), String>
Quarantine this replica: enter the fail-closed gate, release all
core-owned key material, and record the gate in the database so
reopening re-enters preflight until activate_security clears it.
Use SyncClient::seal_security_on_teardown for the shutdown barrier,
which must NOT leave that durable mark.
Sourcepub fn seal_security_on_teardown(&mut self)
pub fn seal_security_on_teardown(&mut self)
Release core-owned key material as a host tears the client down, WITHOUT recording a quarantine.
Shutting an activated client down is not a quarantine event. Persisting
the gate here marks every cleanly closed replica as pending, and the
next plain create is then refused permanently: the reopen path
restores the flag from the marker and the create guard rejects it. The
in-memory flag still closes the gate for anything still holding this
instance, which is all a teardown barrier needs.
Sourcepub fn activate_security(
&mut self,
encryption: EncryptionConfig,
) -> Result<(), String>
pub fn activate_security( &mut self, encryption: EncryptionConfig, ) -> Result<(), String>
Install the post-authentication keyring and release the host loop.
pub fn local_revision(&self) -> Result<u64, String>
Sourcepub fn snapshot_read(
&mut self,
request: &SnapshotReadRequest<'_>,
owner: Option<QueryOwner<'_>>,
) -> Result<SnapshotRead, QueryReadFailure>
pub fn snapshot_read( &mut self, request: &SnapshotReadRequest<'_>, owner: Option<QueryOwner<'_>>, ) -> Result<SnapshotRead, QueryReadFailure>
§7.5: resolve a snapshot read on the mutable owner connection through
the same primitive the read-only sidecar uses, so the command surface
and the file sidecar return one revision, rows, coverage, catch-up, and
delivery shape. The structured QueryReadFailure is preserved; an
owner records its failure (and its next success) in diagnostics.
pub fn status_snapshot(&self) -> SyncStatusSnapshot
Sourcepub fn previous_version_snapshot(
&self,
spec: &PreviousVersionReadSpec,
) -> Result<PreviousVersionSnapshot, String>
pub fn previous_version_snapshot( &self, spec: &PreviousVersionReadSpec, ) -> Result<PreviousVersionSnapshot, String>
RFC 0005 D7: read captured rows from the previous local schema. state
is always previousVersion; the container never makes
query_snapshot() coverage complete. Lease stop/expiry, scope
revocation, coverage completion and the TTL DISCARD the container and
close the read with their own reason.
Sourcepub fn previous_version_audit(
&self,
) -> Result<Option<PreviousVersionAudit>, String>
pub fn previous_version_audit( &self, ) -> Result<Option<PreviousVersionAudit>, String>
RFC 0005 D6: the advisory pre-reset compatibility audit.
Sourcepub fn previous_version_discard(
&self,
) -> Result<PreviousVersionDiscardOutcome, String>
pub fn previous_version_discard( &self, ) -> Result<PreviousVersionDiscardOutcome, String>
RFC 0005 A2/D9: the executable downgrade step. Drop the container file and both metadata records, and report whether anything was present. Idempotent: absence is a successful no-op.
pub fn diagnostics_snapshot(&self) -> Result<ClientDiagnosticsSnapshot, String>
pub fn drain_change_batches(&mut self) -> Vec<ClientChangeBatch>
pub fn drain_sync_intents(&mut self) -> Vec<SyncIntent>
Sourcepub fn upgrading(&self) -> bool
pub fn upgrading(&self) -> bool
§7.4.5: true while a schema-bump reset + first re-bootstrap runs.
Sourcepub fn recreate_with_schema(
&mut self,
schema_json: &Value,
) -> Result<(), String>
pub fn recreate_with_schema( &mut self, schema_json: &Value, ) -> Result<(), String>
§7.4.2 “app ships new code”: swap to a NEW generated schema while keeping this client’s local database (identity, outbox, tables). The §7.4.1 marker check then fires the wipe/re-bootstrap flow when the version increases. Recreation runs the same marker guard as opening a durable replica, holds the guard and every write it authorizes under one write transaction, and preserves the current client (compiled schema, outbox, tables) on refusal.
pub fn commit_outcome( &self, client_commit_id: &str, ) -> Result<Option<CommitOutcome>, String>
pub fn prove_current_base( &mut self, transport: &mut dyn Transport, client_commit_id: &str, sequence: i64, max_rounds: Option<u32>, ) -> CurrentBaseProof
pub fn commit_outcomes( &self, query: CommitOutcomeQuery, ) -> Result<Vec<CommitOutcome>, String>
Sourcepub fn units(&self) -> Result<Vec<UnitRecord>, String>
pub fn units(&self) -> Result<Vec<UnitRecord>, String>
Every registered unit in registration order (§4.1).
pub fn unit(&self, id: &str) -> Result<Option<UnitRecord>, String>
Sourcepub fn subscribe(&mut self, scopes: UnitScopes) -> Result<String, String>
pub fn subscribe(&mut self, scopes: UnitScopes) -> Result<String, String>
Register one unit (§4.1) and return its id.
Sourcepub fn subscribe_many(
&mut self,
units: Vec<UnitScopes>,
) -> Result<Vec<String>, String>
pub fn subscribe_many( &mut self, units: Vec<UnitScopes>, ) -> Result<Vec<String>, String>
Register several units in one local transaction and return their ids: one commit for all of them (on OPFS a commit costs milliseconds, so a cold start with hundreds of units pays it once). An error rolls back every registration of the call. Registering an active unit again changes nothing; a revoked unit re-arms (§3.3). A call that registers or re-arms a unit raises sync-needed with an interactive intent.
Sourcepub fn unsubscribe(&mut self, id: &str) -> Result<(), String>
pub fn unsubscribe(&mut self, id: &str) -> Result<(), String>
Release the explicit reference to a unit. The unit leaves the registration list when no window base holds it (§4.1); its rows stay.
Sourcepub fn set_window(
&mut self,
base: &WindowBase,
units: &[String],
) -> Result<CommandEffects, String>
pub fn set_window( &mut self, base: &WindowBase, units: &[String], ) -> Result<CommandEffects, String>
§4.8: set the windowed-in values of a base, one unit per value. Added values take a reference on their unit (a new unit bootstraps on the next sync); removed values release theirs, and a unit no reference holds leaves the registration list fused with its first eviction chunk (E1–E4). Idempotent; re-entry cancels a deferred eviction.
Sourcepub fn window_state(&self, base: &WindowBase) -> Result<WindowState, String>
pub fn window_state(&self, base: &WindowBase) -> Result<WindowState, String>
§4.8 completeness oracle: the windowed-in values of a base and those whose unit is not complete. A value is complete once its unit is active and no longer bootstrapping; registration alone is not completeness.
Sourcepub fn set_retain_failed_commits(&mut self, enabled: bool) -> Result<(), String>
pub fn set_retain_failed_commits(&mut self, enabled: bool) -> Result<(), String>
Select failed-intent retention; reload durable retained aggregates.
Sourcepub fn mutate(
&mut self,
mutations: Vec<Mutation>,
) -> Result<String, ClientError>
pub fn mutate( &mut self, mutations: Vec<Mutation>, ) -> Result<String, ClientError>
Record one commit of local mutations. The returned commit ID is the
§2.3 idempotency key. Failures are structured so callers read
code/message/details instead of parsing a string prefix.
Sourcepub fn patch(
&mut self,
table: &str,
row_id: &str,
partial: Map<String, Value>,
base_version: Option<i64>,
) -> Result<String, ClientError>
pub fn patch( &mut self, table: &str, row_id: &str, partial: Map<String, Value>, base_version: Option<i64>, ) -> Result<String, ClientError>
Record one §6.1 sparse upsert: the primary key plus the supplied
non-scope columns are present; every other column is absent and stays
untouched on the server and in the local overlay. An absent local base
refuses the whole batch with sync.row_missing before enqueueing (§7.1).
Failures are structured so callers read code/message/details.
pub fn pending_commit_ids(&self) -> Vec<String>
Sourcepub fn pending_payloads(&self) -> Result<Vec<Vec<u8>>, String>
pub fn pending_payloads(&self) -> Result<Vec<Vec<u8>>, String>
§6.1: the sparse push payload bytes of every pending upsert operation, FIFO — exactly what the next push round would put on the wire. Used by conformance B.21(h) to pin cross-core byte identity.
pub fn conflicts(&self) -> &[ConflictRecord]
pub fn rejections(&self) -> &[RejectionRecord]
pub fn resolve_commit_outcome( &mut self, input: ResolveCommitOutcomeInput, ) -> Result<CommitOutcome, String>
pub fn schema_floor(&self) -> Option<&SchemaFloor>
Sourcepub fn lease_state(&self) -> Option<&LeaseState>
pub fn lease_state(&self) -> Option<&LeaseState>
§7.3.5: the client’s opaque auth-lease state, if any.
pub fn sync_needed(&self) -> bool
pub fn read_rows(&self, table: &str) -> Result<Vec<RowState>, String>
Sourcepub fn query(
&self,
sql: &str,
params: &[QueryValue],
) -> Result<Vec<QueryRow>, String>
pub fn query( &self, sql: &str, params: &[QueryValue], ) -> Result<Vec<QueryRow>, String>
Run an arbitrary read-only SQL query against the local database and
return each row as a column-name → JSON value map. This is the seam
the React useSyncQuery live-query API needs (it takes app-authored
SQL over the visible tables/views, not a fixed table read like
[read_rows]).
Bound params are the driver value forms: JSON strings/numbers/bools/
null bind directly; a {"$bytes": hex} object binds as a BLOB — the
same envelope the command surface uses everywhere else. Output BLOB
columns come back as {"$bytes": hex} to round-trip cleanly.
The result column typing is dynamic (SQLite’s stored affinity), because
arbitrary SQL can alias, join, and compute — there is no schema column
to consult per output cell, unlike [read_rows].
One serialized, read-only authority observation, including durable coverage.
Sourcepub fn query_snapshot(
&mut self,
sql: &str,
params: &[QueryValue],
coverage: &[WindowCoverage],
owner: Option<QueryOwner<'_>>,
) -> Result<QuerySnapshot, String>
pub fn query_snapshot( &mut self, sql: &str, params: &[QueryValue], coverage: &[WindowCoverage], owner: Option<QueryOwner<'_>>, ) -> Result<QuerySnapshot, String>
Rows, coverage, and local revision from one SQLite read snapshot.
§7.5 atomic snapshot read. An owner records a failure in
diagnostics_snapshot().query_failures until its next successful read.
Sourcepub fn record_query_read(
&mut self,
owner: QueryOwner<'_>,
failure: Option<&QueryReadFailure>,
)
pub fn record_query_read( &mut self, owner: QueryOwner<'_>, failure: Option<&QueryReadFailure>, )
§7.6: record the outcome of one owned snapshot read, including reads a host ran on a separate connection. A success removes the owner’s entry; an identical failure leaves it unchanged; a changed failure moves last.
Sourcepub fn progress(&self) -> ProgressObserver
pub fn progress(&self) -> ProgressObserver
Cloneable observation handle; no client lock is needed to read it.
pub fn sync(&mut self, transport: &mut dyn Transport) -> SyncOutcome
Sourcepub fn prepare_sync_round(
&mut self,
url_capable: bool,
) -> Result<PreparedSyncRound, Box<SyncOutcome>>
pub fn prepare_sync_round( &mut self, url_capable: bool, ) -> Result<PreparedSyncRound, Box<SyncOutcome>>
Capture one request on the client owner. Mutations made after this call remain in the outbox for a later round; no network I/O occurs here.
Sourcepub fn cancel_sync_round(&mut self)
pub fn cancel_sync_round(&mut self)
Discard the reply of an old authorization or registration context. Its submitted commits stay durable and can be retried with the same ids.
Sourcepub fn apply_sync_round(
&mut self,
completed: CompletedSyncRound,
) -> AppliedSyncRound
pub fn apply_sync_round( &mut self, completed: CompletedSyncRound, ) -> AppliedSyncRound
Apply captured network results on the owner, preserving all normal version, schema, content-address and cursor checks. No network I/O.
pub fn sync_until_idle( &mut self, transport: &mut dyn Transport, max_rounds: Option<u32>, ) -> SyncOutcome
Sourcepub fn sync_until_idle_with_deadline(
&mut self,
transport: &mut dyn Transport,
max_rounds: Option<u32>,
timeout_ms: Option<u64>,
) -> SyncOutcome
pub fn sync_until_idle_with_deadline( &mut self, transport: &mut dyn Transport, max_rounds: Option<u32>, timeout_ms: Option<u64>, ) -> SyncOutcome
As SyncClient::sync_until_idle, with an explicit total deadline in
milliseconds (None disables it). The deadline is checked between
rounds; one blocking transport call is bounded by the transport’s own
whole-round deadline (§1.8).
Sourcepub fn purge_local_data(
&mut self,
input: &LocalDataPurgeInput,
) -> Result<LocalDataPurgeResult, String>
pub fn purge_local_data( &mut self, input: &LocalDataPurgeInput, ) -> Result<LocalDataPurgeResult, String>
Apply one host-authorized local security purge. The host MUST gate the corresponding subscriptions first; this primitive owns local SQLite cleanup and never grants/revokes server authority by itself.
Sourcepub fn rebootstrap_local_data(
&mut self,
input: &LocalDataRebootstrapInput,
) -> Result<LocalDataRebootstrapResult, String>
pub fn rebootstrap_local_data( &mut self, input: &LocalDataRebootstrapInput, ) -> Result<LocalDataRebootstrapResult, String>
Application-authorized recovery of the replicated projection. Unlike a local security purge, this retains the entire outbox, device identity, lease, outcomes, unit registrations, and protected bookkeeping. The projection reset, unit rewind, optimistic replay, and idempotency marker share one savepoint for interruption safety.
Sourcepub fn upload_blob(
&mut self,
bytes: &[u8],
media_type: Option<String>,
name: Option<String>,
) -> Result<Value, String>
pub fn upload_blob( &mut self, bytes: &[u8], media_type: Option<String>, name: Option<String>, ) -> Result<Value, String>
§5.9.7: hash bytes into the content address, cache them, queue the
upload (flushed before the next push, B4). Returns the canonical
BlobRef JSON {blobId, byteLength, mediaType?} for a blob_ref
column value.
Sourcepub fn fetch_blob_bytes(
&mut self,
transport: &mut dyn Transport,
blob_id_or_ref: &str,
) -> Result<FetchedBlob, (String, String)>
pub fn fetch_blob_bytes( &mut self, transport: &mut dyn Transport, blob_id_or_ref: &str, ) -> Result<FetchedBlob, (String, String)>
§5.9.7: resolve an owned blob body without driver encoding. A content-addressed cache hit serves with no fetch (B1); a miss downloads (§5.9.5), verifies the address, caches the bytes, and returns them.
Sourcepub fn realtime_policy(&self) -> RealtimePolicy
pub fn realtime_policy(&self) -> RealtimePolicy
§8.8: the configured realtime policy.
Sourcepub fn realtime_state(&self) -> RealtimeState
pub fn realtime_state(&self) -> RealtimeState
§8.8: the explicit realtime availability state.
Sourcepub fn set_realtime_policy(
&mut self,
policy: RealtimePolicy,
) -> Result<(), String>
pub fn set_realtime_policy( &mut self, policy: RealtimePolicy, ) -> Result<(), String>
§8.8: set the realtime policy. Refused while the socket is connected: a policy change never silently re-routes an ownership state.
pub fn connect_realtime( &mut self, transport: &mut dyn Transport, ) -> Result<(), String>
pub fn disconnect_realtime(&mut self, transport: &mut dyn Transport)
Sourcepub fn realtime_lost(
&mut self,
transport: &mut dyn Transport,
error: &TransportError,
)
pub fn realtime_lost( &mut self, transport: &mut dyn Transport, error: &TransportError, )
§8.8: the host observed the socket end without disconnecting it (a
peer close, an I/O error, a failed send; the native transport reports
these as Inbound::Disconnected). Releases the transport, moves a
Connected state to Lost with the transport’s code as the reason, and schedules
one background retry intent so the host reconnects and catches up.
Sourcepub fn set_presence(
&mut self,
transport: &mut dyn Transport,
scope_key: &str,
doc: Option<&Value>,
) -> Result<(), String>
pub fn set_presence( &mut self, transport: &mut dyn Transport, scope_key: &str, doc: Option<&Value>, ) -> Result<(), String>
§8.6.2: publish (or clear, doc: None) this client’s presence
document for scope_key. Requires a live socket; the document is
ephemeral (lost on disconnect). Authorization is the connection’s
registration (§8.6.3) — an unheld key is rejected loudly by the
server with presence.forbidden.
Sourcepub fn presence(&self, scope_key: &str) -> Vec<PresencePeer>
pub fn presence(&self, scope_key: &str) -> Vec<PresencePeer>
§8.6: the peers currently present on a scope key (ephemeral).
Sourcepub fn on_realtime_text(&mut self, text: &str)
pub fn on_realtime_text(&mut self, text: &str)
Inbound JSON control message (§8.1). Unknown events are tolerated.
Sourcepub fn on_realtime_binary_queued(&mut self, bytes: &[u8]) -> Vec<String>
pub fn on_realtime_binary_queued(&mut self, bytes: &[u8]) -> Vec<String>
Inbound binary delta: a complete SSP2 response (§8.2), applied like a pull response per section; an unapplied delta is a wake-up. Mailbox hosts send durable acknowledgements on their I/O executor.
Sourcepub fn on_realtime_binary(
&mut self,
transport: &mut dyn Transport,
bytes: &[u8],
)
pub fn on_realtime_binary( &mut self, transport: &mut dyn Transport, bytes: &[u8], )
§8.2: a delta applies exactly like a live section and sets the replica
cursor to its throughSeq; one at or below the replica cursor is a
duplicate. A delta the client does not apply (no live unit, a status
other than active, a decode or apply failure) is a drop and raises
sync-needed.