client_core/sync/writer.rs
1//! Long-lived WS-driven sync writer.
2//!
3//! `Writer::start` acquires the advisory lockfile so only one writer runs per
4//! machine, performs an initial REST backfill, then subscribes to the relay
5//! WebSocket. Incoming `new_clip` events are decrypted (when an encryption key
6//! is available) and inserted into the local store. On disconnect the loop
7//! receives `WsStatus::Disconnected` and `ws::run` reconnects automatically
8//! with exponential backoff.
9//!
10//! `Writer::shutdown` signals the background task to stop and awaits it.
11
12use std::path::PathBuf;
13use std::sync::Arc;
14
15use tokio::sync::{mpsc, Notify};
16use tokio::task::JoinHandle;
17use tracing::warn;
18
19use super::lockfile::{LockKind, Lockfile};
20use super::{map, reader};
21use crate::http::RestClient;
22use crate::store::{queries, Store};
23use crate::ws::{self, DecryptFailReason, WsConfig, WsEvent, WsStatus};
24
25/// Long-lived WS-driven sync writer. One per machine, coordinated by the
26/// `~/.cinch/sync.lock` advisory lockfile.
27pub struct Writer {
28 handle: Option<JoinHandle<()>>,
29 stop: Arc<Notify>,
30 _lock: Lockfile, // released on Drop
31}
32
33impl Writer {
34 /// Try to start a writer. Returns `Ok(None)` if another writer already
35 /// holds the lock.
36 ///
37 /// The caller must supply a `WsConfig` (relay URL + bearer token +
38 /// optional 32-byte AES key). The same `RestClient` is used for the
39 /// initial REST backfill.
40 pub async fn start(
41 store: Arc<Store>,
42 client: Arc<RestClient>,
43 ws_cfg: WsConfig,
44 lock_path: PathBuf,
45 kind: LockKind,
46 ) -> std::io::Result<Option<Self>> {
47 let lock = match Lockfile::try_acquire(&lock_path, kind)? {
48 Some(l) => l,
49 None => return Ok(None),
50 };
51
52 let stop = Arc::new(Notify::new());
53 let stop_clone = stop.clone();
54 let store_clone = store.clone();
55 let client_clone = client.clone();
56 let enc_key = ws_cfg.encryption_key;
57
58 let handle = tokio::spawn(async move {
59 // Initial REST backfill — bring the store up to date before
60 // the WebSocket stream takes over.
61 let _ = reader::backfill_once(
62 &store_clone,
63 &client_clone,
64 reader::BackfillBudget::default(),
65 enc_key.as_ref(),
66 )
67 .await;
68
69 // Channel for WsEvent from the background ws::run task.
70 let (tx, mut rx) = mpsc::channel::<WsEvent>(64);
71
72 // ws::run already reconnects internally with exponential backoff,
73 // so we just run it once and read from the channel until stop.
74 let _ws_handle = tokio::spawn(ws::run(ws_cfg, tx));
75
76 loop {
77 tokio::select! {
78 _ = stop_clone.notified() => return,
79 maybe = rx.recv() => {
80 match maybe {
81 None => {
82 // Channel closed — ws::run exited (should not
83 // happen while the sender is alive).
84 return;
85 }
86 Some(event) => handle_ws_event(&store_clone, &client_clone, event, enc_key).await,
87 }
88 }
89 }
90 }
91 });
92
93 Ok(Some(Self {
94 handle: Some(handle),
95 stop,
96 _lock: lock,
97 }))
98 }
99
100 /// Signal the writer to stop and wait for it to finish.
101 pub async fn shutdown(mut self) {
102 self.stop.notify_waiters();
103 if let Some(h) = self.handle.take() {
104 let _ = h.await;
105 }
106 }
107}
108
109/// Process a single [`WsEvent`] from the relay subscription.
110///
111/// `NewClip` results in a store write. `KeyExchangeRequested` triggers
112/// the ECDH bearer responder (when this device holds the encryption
113/// key). Status changes are logged at debug level; decrypt failures
114/// emit a warning. All other event kinds are no-ops pending Phase 5
115/// handling.
116async fn handle_ws_event(
117 store: &Store,
118 client: &RestClient,
119 event: WsEvent,
120 enc_key: Option<[u8; 32]>,
121) {
122 match event {
123 WsEvent::NewClip { clip, plaintext: _ } => {
124 // `ws::run` has already attempted decryption using the key supplied
125 // in `WsConfig`. After a successful decrypt `clip.encrypted` is
126 // `false` and `clip.content` holds the decoded text (or base64 for
127 // binary clips). The `enc_key` was passed to `WsConfig` upstream so
128 // decryption happens before the event reaches us here.
129 let _ = enc_key; // consumed upstream by ws::decode_message via WsConfig
130 let clip = *clip; // unbox
131 // After a successful decrypt, ws::run sets clip.encrypted = false
132 // and clip.content to the decoded string. If the clip is still
133 // marked encrypted here, the decrypt failed and we should not store
134 // ciphertext — the event type would be ClipDecryptFailed, not
135 // NewClip. So any NewClip with encrypted=false is safe to store.
136 if clip.encrypted {
137 // Should not happen: ws::run converts decrypt-failed clips to
138 // WsEvent::ClipDecryptFailed. Guard here anyway.
139 warn!(
140 clip_id = %clip.clip_id,
141 "writer: received NewClip with encrypted=true — skipping"
142 );
143 return;
144 }
145 // Use plaintext bytes for the content so binary clips (which have
146 // base64 in clip.content after re-encoding) are stored as raw bytes.
147 // The map function accepts clip.content as a String — for text clips
148 // plaintext == clip.content.as_bytes(), so the lossy conversion is
149 // a no-op. For binary clips the store already accepts the base64
150 // form (same as the REST path).
151 match map::clip_wire_to_stored(&clip) {
152 Ok(Some(stored)) => {
153 if let Err(e) = queries::insert_clip(store, &stored) {
154 warn!(clip_id = %stored.id, error = %e, "writer: insert_clip failed");
155 } else if let Err(e) = queries::set_watermark(store, &stored.id) {
156 warn!(clip_id = %stored.id, error = %e, "writer: set_watermark failed");
157 }
158 }
159 Ok(None) => {
160 // Empty clip_id — silently skip.
161 }
162 Err(e) => {
163 warn!(clip_id = %clip.clip_id, error = %e, "writer: map_wire_to_stored failed");
164 }
165 }
166 }
167
168 WsEvent::ClipDecryptFailed { clip_id, reason } => {
169 let reason_str = match reason {
170 DecryptFailReason::MissingKey => "no encryption key available".into(),
171 DecryptFailReason::TagFailed(e) => format!("key mismatch: {e}"),
172 };
173 warn!(clip_id = %clip_id, reason = %reason_str, "writer: skipping encrypted clip — decrypt failed");
174 }
175
176 WsEvent::ClipDeleted { clip_id: _ } => {
177 // TODO(phase 5): propagate deletion to local store.
178 }
179
180 WsEvent::Revoked { reason } => {
181 warn!(
182 reason = ?reason,
183 "writer: device revoked by relay — writer will stop receiving events"
184 );
185 }
186
187 WsEvent::TokenRotated {
188 token: _,
189 device_id: _,
190 } => {
191 // TODO(phase 5): persist the rotated token via credstore.
192 }
193
194 WsEvent::KeyExchangeRequested { device_id } => {
195 log::info!(
196 "writer: received KeyExchangeRequested device_id={:?}",
197 device_id
198 );
199 let Some(did) = device_id else {
200 log::info!("writer: key_exchange_requested missing device_id — skipping");
201 return;
202 };
203 let Some(key) = enc_key else {
204 log::info!(
205 "writer: cannot bear key — no encryption key on this device (target_device_id={})",
206 did
207 );
208 return;
209 };
210 log::info!("writer: bearing key for target_device_id={}", did);
211 if let Err(e) = crate::key_exchange::handle_event(client, &did, &key).await {
212 log::warn!(
213 "writer: key_exchange responder failed: target_device_id={}, error={}",
214 did,
215 e
216 );
217 } else {
218 log::info!(
219 "writer: posted encrypted key bundle to peer target_device_id={}",
220 did
221 );
222 }
223 }
224
225 WsEvent::Status(WsStatus::Connected) => {
226 tracing::debug!("writer: WS connected");
227 }
228 WsEvent::Status(WsStatus::Disconnected) => {
229 tracing::debug!("writer: WS disconnected — ws::run will reconnect");
230 }
231 WsEvent::Status(WsStatus::Connecting) => {
232 tracing::debug!("writer: WS connecting");
233 }
234 }
235}