1use std::collections::BTreeMap;
34use std::path::Path;
35
36use ed25519_dalek::{Signer as _, SigningKey};
37use serde::{Deserialize, Serialize};
38use serde_json::{Map, Value, json};
39
40use super::HiveError;
41use super::events::build::{EVENT_SCHEMA, Place, Signer};
42use super::events::hlc::{self, Stamp};
43use super::events::sealed_body::{self, SealKey};
44use super::events::{ids, sign};
45use super::replica::Replica;
46use super::replica::converted::Original;
47use super::state::write_private;
48
49pub const SOURCE: &str = "v2_plain";
50pub const SEAL_CONVERT_ROLE: &str = "seal-convert";
52pub const SEAL_CONVERT_HOST: &str = "engine";
54pub const DONE_DOMAIN: &str = "leanctx.hive.conversion_done.v1\n";
55pub const BATCH: usize = 200;
57pub const PART: usize = 10_000;
59const RENEW_AFTER_MS: u64 = 5 * 60 * 1000;
61
62pub trait ConvertApi {
65 fn answer(
66 &self,
67 method: &str,
68 path: &str,
69 body: Option<&Value>,
70 ) -> Result<(u16, Value), HiveError>;
71}
72
73impl ConvertApi for crate::core::hive::auth::Session {
74 fn answer(
75 &self,
76 method: &str,
77 path: &str,
78 body: Option<&Value>,
79 ) -> Result<(u16, Value), HiveError> {
80 self.with_client(|c| c.send_answer(method, path, body, 8 * 1024 * 1024))
81 }
82}
83
84pub struct Conversion<'a> {
86 pub vault_id: &'a str,
87 pub place: &'a Place,
89 pub seal: &'a SealKey,
90 pub signer: &'a Signer<'a>,
92 pub instance_key: &'a SigningKey,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum Outcome {
99 Done { events_written: u64, parts: usize },
101 Waiting { holder_expires_at: Option<u64> },
103 NotPending,
105}
106
107#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(default)]
110pub struct Cursor {
111 pub last_seq: u64,
113 pub events_written: u64,
114 pub mismatches: BTreeMap<u64, u32>,
116 pub incomplete: u32,
118}
119
120fn cursor_path(data_dir: &Path, vault_id: &str) -> std::path::PathBuf {
121 data_dir.join("convert").join(format!("{vault_id}.cursor"))
122}
123
124pub fn load_cursor(data_dir: &Path, vault_id: &str) -> Cursor {
125 std::fs::read(cursor_path(data_dir, vault_id))
126 .ok()
127 .and_then(|b| serde_json::from_slice(&b).ok())
128 .unwrap_or_default()
129}
130
131fn save_cursor(data_dir: &Path, vault_id: &str, cursor: &Cursor) -> Result<(), HiveError> {
132 let bytes = serde_json::to_vec(cursor).map_err(|e| HiveError::Local(e.to_string()))?;
133 write_private(
134 &data_dir.join("convert"),
135 &format!("{vault_id}.cursor"),
136 &bytes,
137 )
138}
139
140fn local(e: impl std::fmt::Display) -> HiveError {
141 HiveError::Local(e.to_string())
142}
143
144fn reason(body: &Value) -> &str {
145 body["error"]["reason"]
146 .as_str()
147 .or_else(|| body["error"]["code"].as_str())
148 .unwrap_or_default()
149}
150
151fn refused(status: u16, body: &Value) -> HiveError {
152 HiveError::Refused(format!(
153 "conversion refused: {} ({status})",
154 match reason(body) {
155 "" => "unknown",
156 r => r,
157 }
158 ))
159}
160
161enum Lease {
162 Held { from_seq: u64 },
163 Waiting(Option<u64>),
164 NotPending,
165}
166
167fn take_lease(api: &dyn ConvertApi, vault_id: &str) -> Result<Lease, HiveError> {
168 let (status, body) = api.answer(
169 "POST",
170 &format!("/vaults/{vault_id}/conversion/lease"),
171 Some(&json!({ "source": SOURCE })),
172 )?;
173 match (status, reason(&body)) {
174 (200..=299, _) => {
175 if body["source"].as_str() != Some(SOURCE) {
176 return Err(HiveError::Protocol(
177 "conversion lease for another source".into(),
178 ));
179 }
180 body["conversion_from_seq"]
181 .as_u64()
182 .map(|from_seq| Lease::Held { from_seq })
183 .ok_or_else(|| HiveError::Protocol("conversion lease without from_seq".into()))
184 }
185 (409, "conversion_leased") => {
186 Ok(Lease::Waiting(body["error"]["holder_expires_at"].as_u64()))
187 }
188 (409, "conversion_done") => Ok(Lease::NotPending),
189 _ => Err(refused(status, &body)),
190 }
191}
192
193fn copyable(o: &Original) -> bool {
196 !o.purged && !o.sig_invalid && o.op != "purge" && o.body.is_some()
197}
198
199pub fn sealed_copy(
201 c: &Conversion<'_>,
202 original: &Original,
203 stamp: Stamp,
204) -> Result<Value, HiveError> {
205 let env = original
206 .envelope
207 .as_object()
208 .ok_or_else(|| local("stored envelope is not an object"))?;
209 let body = original
210 .body
211 .clone()
212 .ok_or_else(|| local("no content to copy"))?;
213 let mut e = Map::new();
214 e.insert("schema".into(), EVENT_SCHEMA.into());
215 e.insert(
216 "event_id".into(),
217 ids::seal_conversion_event_id(&c.place.pk_id, original.seq, &original.event_id).into(),
218 );
219 e.insert(
220 "place".into(),
221 json!({"kind": c.place.kind, "id": c.place.id}),
222 );
223 e.insert("op".into(), original.op.clone().into());
224 for key in ["target", "node_type"] {
225 if let Some(v) = env.get(key) {
226 e.insert(key.into(), v.clone());
227 }
228 }
229 e.insert(
230 "body_commit".into(),
231 sign::body_commit(&c.place.pk_id, &body)
232 .map_err(local)?
233 .into(),
234 );
235 e.insert("body".into(), body.clone());
236 e.insert(
237 "hlc".into(),
238 json!({"wall_ms": stamp.wall_ms, "counter": stamp.counter, "node": c.signer.hlc_node}),
239 );
240 e.insert("causal_base".into(), c.place.causal_base.into());
241 e.insert("actor".into(), json!({"kind": "worker"}));
242 e.insert("worker_id".into(), c.signer.worker_id.clone().into());
243 e.insert("provenance_claim".into(), "workspace".into());
244 e.insert(
245 "capture".into(),
246 env.get("capture").cloned().unwrap_or_else(|| {
247 json!({
248 "gate_version": 0,
249 "evidence": "observed",
250 "reasons_passed_hash": blake3::hash(b"leanctx.hive.seal-convert.v1")
251 .to_hex()
252 .to_string(),
253 })
254 }),
255 );
256 e.insert(
257 "screening".into(),
258 env.get("screening").cloned().unwrap_or_else(|| {
259 json!({
260 "counts": {"forbidden": 0, "local_path": 0, "pii": 0, "redaction": 0, "secret": 0},
261 "scanner_version": crate::core::hive::knowledge::screening::SCANNER_VERSION,
262 })
263 }),
264 );
265 let commands = body
266 .get("commands")
267 .and_then(Value::as_array)
268 .is_some_and(|c| !c.is_empty());
269 e.insert(
270 "flags".into(),
271 env.get("flags")
272 .cloned()
273 .unwrap_or_else(|| json!({ "commands": commands })),
274 );
275 let mut event = Value::Object(e);
277 sign::sign(&mut event, c.signer.key).map_err(local)?;
278 sealed_body::seal_event(&mut event, c.seal, c.signer.key)?;
279 Ok(event)
280}
281
282pub fn seq_digests(originals: &[Original]) -> Result<Vec<(u64, String)>, HiveError> {
284 originals
285 .iter()
286 .filter(|o| !o.purged)
287 .map(|o| Ok((o.seq, sign::envelope_digest(&o.envelope).map_err(local)?)))
288 .collect()
289}
290
291pub fn done_bodies(
293 key: &SigningKey,
294 events_written: u64,
295 last_seq: u64,
296 digests: &[(u64, String)],
297) -> Result<Vec<Value>, HiveError> {
298 let chunks: Vec<&[(u64, String)]> = if digests.is_empty() {
299 vec![&[]]
300 } else {
301 digests.chunks(PART).collect()
302 };
303 let parts = chunks.len();
304 chunks
305 .into_iter()
306 .enumerate()
307 .map(|(i, chunk)| {
308 let mut body = json!({
309 "source": SOURCE,
310 "events_written": events_written,
311 "last_seq": last_seq,
312 "seq_digests": chunk
313 .iter()
314 .map(|(seq, digest)| json!({"seq": seq, "envelope_digest": digest}))
315 .collect::<Vec<_>>(),
316 "part": i + 1,
317 "parts": parts,
318 "key_id": sign::key_id(key.verifying_key().as_bytes()),
319 });
320 let input =
321 lean_ctx_protocol::hive::signing_input_without_signature(DONE_DOMAIN, &body)
322 .map_err(local)?;
323 body["signature"] = hex::encode(key.sign(&input).to_bytes()).into();
324 Ok(body)
325 })
326 .collect()
327}
328
329#[allow(clippy::too_many_arguments)]
332fn push_copies(
333 api: &dyn ConvertApi,
334 c: &Conversion<'_>,
335 originals: &[Original],
336 cursor: &mut Cursor,
337 data_dir: &Path,
338 now: &dyn Fn() -> u64,
339 lease_at: &mut u64,
340) -> Result<(), HiveError> {
341 let todo: Vec<&Original> = originals
342 .iter()
343 .filter(|o| o.seq > cursor.last_seq && copyable(o))
344 .collect();
345 let mut clock = Stamp::default();
346 let place_ref = format!("{}:{}", c.place.kind, c.place.id);
347 for batch in todo.chunks(BATCH) {
348 if now().saturating_sub(*lease_at) > RENEW_AFTER_MS {
349 match take_lease(api, c.vault_id)? {
350 Lease::Held { .. } => *lease_at = now(),
351 _ => return Err(HiveError::Refused("conversion lease lost".into())),
352 }
353 }
354 let mut events = Vec::with_capacity(batch.len());
355 for original in batch {
356 clock = hlc::send(clock, now());
357 events.push(sealed_copy(c, original, clock)?);
358 }
359 let (from, to) = (batch[0].seq, batch[batch.len() - 1].seq);
360 let request = json!({
361 "events": events,
362 "conversion": {"vault": c.vault_id, "source": SOURCE, "from_seq": from, "to_seq": to},
363 });
364 let (status, body) = api.answer(
365 "POST",
366 &format!("/places/{place_ref}/events"),
367 Some(&request),
368 )?;
369 if !(200..300).contains(&status) {
370 return Err(refused(status, &body));
371 }
372 let (results, _) = super::sync::push::results(&body).map_err(HiveError::Protocol)?;
373 for (id, outcome) in &results {
374 match outcome {
375 super::sync::push::Outcome::Accepted { .. }
376 | super::sync::push::Outcome::Duplicate { .. }
377 | super::sync::push::Outcome::Held { .. } => cursor.events_written += 1,
378 super::sync::push::Outcome::Refused { code, reason, .. } => {
379 return Err(HiveError::Refused(format!(
380 "conversion push refused {id}: {code}{}",
381 reason
382 .as_deref()
383 .map(|r| format!(" {r}"))
384 .unwrap_or_default()
385 )));
386 }
387 }
388 }
389 cursor.last_seq = to;
390 save_cursor(data_dir, c.vault_id, cursor)?;
391 }
392 Ok(())
393}
394
395pub fn run(
399 api: &dyn ConvertApi,
400 replica: &Replica,
401 data_dir: &Path,
402 c: &Conversion<'_>,
403 now: &dyn Fn() -> u64,
404) -> Result<Outcome, HiveError> {
405 let from_seq = match take_lease(api, c.vault_id)? {
406 Lease::Held { from_seq } => from_seq,
407 Lease::Waiting(at) => {
408 return Ok(Outcome::Waiting {
409 holder_expires_at: at,
410 });
411 }
412 Lease::NotPending => {
413 let _ = std::fs::remove_file(cursor_path(data_dir, c.vault_id));
414 return Ok(Outcome::NotPending);
415 }
416 };
417 let mut lease_at = now();
418 if replica.cursor()?.unwrap_or(0) < from_seq {
419 return Err(HiveError::Local(format!(
420 "the replica holds the log only to seq {}, conversion needs {from_seq}: sync first",
421 replica.cursor()?.unwrap_or(0)
422 )));
423 }
424 let originals = replica.originals_upto(from_seq)?;
425 let mut cursor = load_cursor(data_dir, c.vault_id);
426 loop {
427 push_copies(
428 api,
429 c,
430 &originals,
431 &mut cursor,
432 data_dir,
433 now,
434 &mut lease_at,
435 )?;
436 let digests = seq_digests(&originals)?;
437 let bodies = done_bodies(c.instance_key, cursor.events_written, from_seq, &digests)?;
438 let parts = bodies.len();
439 let mut retry = false;
440 for body in &bodies {
441 let (status, answer) = api.answer(
442 "POST",
443 &format!("/vaults/{}/conversion/done", c.vault_id),
444 Some(body),
445 )?;
446 match (status, reason(&answer)) {
447 (204, _) => {
448 let _ = std::fs::remove_file(cursor_path(data_dir, c.vault_id));
449 return Ok(Outcome::Done {
450 events_written: cursor.events_written,
451 parts,
452 });
453 }
454 (200..=299, _) => continue,
455 (409, "conversion_done") => {
456 let _ = std::fs::remove_file(cursor_path(data_dir, c.vault_id));
457 return Ok(Outcome::NotPending);
458 }
459 (409, "conversion_incomplete") => {
460 cursor.incomplete += 1;
462 if cursor.incomplete > 1 {
463 save_cursor(data_dir, c.vault_id, &cursor)?;
464 return Err(refused(status, &answer));
465 }
466 cursor.last_seq = 0;
467 cursor.events_written = 0;
468 retry = true;
469 }
470 (409, "conversion_digest_mismatch") => {
471 let seq = answer["error"]["seq"].as_u64().unwrap_or(0);
472 let seen = cursor.mismatches.entry(seq).or_insert(0);
473 *seen += 1;
474 if *seen > 1 {
475 save_cursor(data_dir, c.vault_id, &cursor)?;
476 return Err(HiveError::Refused(format!(
477 "conversion refused at seq {seq}"
478 )));
479 }
480 retry = true;
481 }
482 (409, "conversion_leased") => match take_lease(api, c.vault_id)? {
483 Lease::Held { .. } => {
484 lease_at = now();
485 retry = true;
486 }
487 Lease::Waiting(at) => {
488 return Ok(Outcome::Waiting {
489 holder_expires_at: at,
490 });
491 }
492 Lease::NotPending => return Ok(Outcome::NotPending),
493 },
494 _ => return Err(refused(status, &answer)),
495 }
496 if retry {
497 break;
498 }
499 }
500 save_cursor(data_dir, c.vault_id, &cursor)?;
501 if !retry {
502 return Err(HiveError::Protocol(
503 "conversion done: the last part was not answered 204".into(),
504 ));
505 }
506 }
507}
508
509const META_SETTLED: &str = "conversion_settled";
511
512pub fn sync_conversion(
519 session: &crate::core::hive::auth::Session,
520 record: &crate::core::hive::vault::VaultRecord,
521 replica: &Replica,
522) -> Result<Option<Outcome>, HiveError> {
523 use crate::core::hive::workers::card::{Availability, Budget, WorkerCard};
524 use crate::core::hive::workers::{self, register};
525 if replica.meta(META_SETTLED)?.is_some() || replica.cursor()?.is_none() {
526 return Ok(None);
527 }
528 let vault_id = record.vault_id.as_str();
529 match take_lease(session, vault_id)? {
530 Lease::NotPending => {
531 replica.set_meta(META_SETTLED, b"1")?;
532 return Ok(Some(Outcome::NotPending));
533 }
534 Lease::Waiting(at) => {
535 return Ok(Some(Outcome::Waiting {
536 holder_expires_at: at,
537 }));
538 }
539 Lease::Held { .. } => {}
540 }
541 let store = &session.store;
542 let crate::core::hive::sealed::SealingKey::Ready(epoch, key) =
543 crate::core::hive::sealed::sealing_key(session, vault_id, 0)?
544 else {
545 return Err(HiveError::Refused("sealed_key_missing".into()));
546 };
547 let secret = crate::core::hive::sealed::ensure_place_secret(store, vault_id)?
548 .ok_or_else(|| HiveError::Refused("sealed_key_missing".into()))?;
549 let pk_id = ids::sealed_pk_id(&secret);
550 let place_ref = format!("vault:{vault_id}");
551 let keys = crate::core::hive::instance_key::InstanceKeys::load(store)?;
552 let alias = workers::WorkerAliasKey::of(&keys);
553 let card = WorkerCard::new(
554 SEAL_CONVERT_HOST,
555 None,
556 Vec::new(),
557 Budget::default(),
558 Availability::Online,
559 );
560 let name = workers::default_name(
561 &session.instance.label,
562 &workers::attach::host_display(SEAL_CONVERT_HOST),
563 SEAL_CONVERT_ROLE,
564 );
565 let reg = register::Registration {
566 instance_id: &session.instance.instance_id,
567 host_app: SEAL_CONVERT_HOST,
568 role: SEAL_CONVERT_ROLE,
569 name: &name,
570 card: &card,
571 alias_place: Some(&place_ref),
572 };
573 match session.with_client(|client| register::register(client, &keys, ®)) {
574 Ok(_) | Err(HiveError::Conflict { .. }) => {}
575 Err(error) => return Err(error),
576 }
577 let alias_key = workers::alias_signing_key(&keys, &place_ref);
578 let signer = Signer::alias(
579 &alias_key,
580 &keys,
581 &place_ref,
582 &alias.worker_id(SEAL_CONVERT_HOST, SEAL_CONVERT_ROLE, &place_ref),
583 );
584 let place = Place {
585 kind: "vault".into(),
586 id: vault_id.to_string(),
587 pk_id,
588 causal_base: replica.cursor()?.unwrap_or(0),
589 };
590 let seal = SealKey { epoch, key };
591 let conversion = Conversion {
592 vault_id,
593 place: &place,
594 seal: &seal,
595 signer: &signer,
596 instance_key: keys.signing_key(),
597 };
598 let now = || chrono::Utc::now().timestamp_millis().unsigned_abs();
599 let outcome = run(session, replica, store.data_dir(), &conversion, &now)?;
600 if matches!(outcome, Outcome::Done { .. } | Outcome::NotPending) {
601 replica.set_meta(META_SETTLED, b"1")?;
602 }
603 Ok(Some(outcome))
604}
605
606pub fn settle_converted(replica: &Replica, pk_id: &[u8; 32]) -> Result<usize, HiveError> {
610 let mut done = Vec::new();
611 for (seq, id) in replica.unconverted_ids()? {
612 if replica.has_event(&ids::seal_conversion_event_id(pk_id, seq, &id))? {
613 done.push(seq);
614 }
615 }
616 replica.mark_converted(&done)
617}
618
619#[cfg(test)]
620#[path = "convert_tests.rs"]
621mod tests;