1use std::path::{Path, PathBuf};
2use std::time::{SystemTime, UNIX_EPOCH};
3
4use ed25519_dalek::SigningKey;
5use qualia_core_db::crdt::SuspendedTransactionQueue;
6use qualia_core_db::git_bridge::DagStore;
7use qualia_core_db::wal::{commit_semantic_mutation, WalHandoffResult, WriteAheadLog};
8use qualia_core_db::NQuin;
9use wellfare_core::record::{RecordEnvelope, SensitivityClass};
10
11use super::checkpoint_store::{self, load_dag, load_meta};
12use super::consent_store::ConsentStore;
13use super::graph_store::GraphStore;
14use super::journal::{JournalEntry, WellfairJournal};
15use super::receipt::{ReceiptLog, ReceiptRecord};
16use super::sync_outbox::{SyncOutbox, SyncOutboxEntry};
17
18pub struct VaultService {
20 wal: WriteAheadLog,
21 dag: DagStore,
22 graph: GraphStore,
23 suspended: SuspendedTransactionQueue,
24 author_did: u64,
25 storage_root: PathBuf,
26 journal: WellfairJournal,
27 receipts: ReceiptLog,
28 consents: ConsentStore,
29 sync_outbox: SyncOutbox,
30 last_checkpoint_hash: Option<[u8; 32]>,
31}
32
33impl VaultService {
34 pub fn open<W: AsRef<Path>, S: AsRef<Path>>(
36 wal_path: W,
37 storage_root: S,
38 author_did: u64,
39 ) -> std::io::Result<Self> {
40 let storage_root = storage_root.as_ref().to_path_buf();
41 let wal = WriteAheadLog::open(wal_path)?;
42 let dag = load_dag(&storage_root);
43 let graph = GraphStore::open(&storage_root)?;
44 let suspended = SuspendedTransactionQueue::new();
45 let journal = WellfairJournal::open(&storage_root)?;
46 let receipts = ReceiptLog::open(&storage_root)?;
47 let consents = ConsentStore::open(&storage_root)?;
48 let sync_outbox = SyncOutbox::open(&storage_root)?;
49
50 let last_checkpoint_hash = if wal.prev_dag_hash != [0u8; 32] {
51 Some(wal.prev_dag_hash)
52 } else if let Some(meta) = load_meta(&storage_root) {
53 hex::decode(&meta.last_hash_hex)
54 .ok()
55 .and_then(|b| b.try_into().ok())
56 } else {
57 None
58 };
59
60 Ok(Self {
61 wal,
62 dag,
63 graph,
64 suspended,
65 author_did,
66 storage_root,
67 journal,
68 receipts,
69 consents,
70 sync_outbox,
71 last_checkpoint_hash,
72 })
73 }
74
75 pub fn graph_quin_count(&self) -> usize {
77 self.graph.count()
78 }
79
80 pub fn list_graph_quins(&self, limit: usize) -> std::io::Result<Vec<NQuin>> {
82 self.graph.list_recent(limit)
83 }
84
85 pub fn graph_coverage(
87 &self,
88 journal_limit: usize,
89 ) -> std::io::Result<Vec<super::graph_query::GraphCoverageRow>> {
90 let journal = self.journal.list_recent(journal_limit)?;
91 let quin_limit = journal.len().saturating_mul(8).max(64);
92 let quins = self.graph.list_recent(quin_limit)?;
93 Ok(super::graph_query::coverage_for_journal(&journal, &quins))
94 }
95
96 pub fn journal_count(&self) -> std::io::Result<usize> {
98 self.journal.count()
99 }
100
101 pub fn list_health_records(&self, limit: usize) -> std::io::Result<Vec<JournalEntry>> {
103 self.journal.list_recent(limit)
104 }
105
106 pub fn list_receipts(&self, limit: usize) -> std::io::Result<Vec<ReceiptRecord>> {
108 self.receipts.list_recent(limit)
109 }
110
111 pub fn list_outbox(&self, limit: usize) -> std::io::Result<Vec<SyncOutboxEntry>> {
113 self.sync_outbox.list_recent(limit)
114 }
115
116 pub fn outbox_queued_count(&self) -> std::io::Result<usize> {
118 self.sync_outbox.count_queued()
119 }
120
121 pub fn list_active_consents(
123 &self,
124 now_unix: u64,
125 ) -> std::io::Result<Vec<super::consent_store::ConsentGrantRecord>> {
126 self.consents.list_active(now_unix)
127 }
128
129 pub fn append_consent(
131 &self,
132 grant: &super::consent_store::ConsentGrantRecord,
133 ) -> std::io::Result<()> {
134 self.consents.append(grant)
135 }
136
137 pub fn revoke_consent(&self, grant_id: &str) -> std::io::Result<bool> {
139 self.consents.revoke(grant_id)
140 }
141
142 pub fn wal_buffered_quins(&mut self) -> std::io::Result<usize> {
144 self.wal.buffered_count()
145 }
146
147 pub fn commit_quin(
149 &mut self,
150 mut quin: NQuin,
151 signing_key: &SigningKey,
152 principal_did_hash: u64,
153 ) -> std::io::Result<WalHandoffResult> {
154 commit_semantic_mutation(
155 &mut self.wal,
156 &mut quin,
157 principal_did_hash,
158 self.author_did,
159 signing_key,
160 &mut self.suspended,
161 )
162 }
163
164 pub fn checkpoint(&mut self) -> std::io::Result<[u8; 32]> {
166 let timestamp_ms = SystemTime::now()
167 .duration_since(UNIX_EPOCH)
168 .map(|d| d.as_millis() as u64)
169 .unwrap_or(0);
170 let hash = self
171 .wal
172 .checkpoint_to_dag(&mut self.dag, self.author_did, timestamp_ms)?;
173 let committed = self.wal.recover()?;
174 if !committed.is_empty() {
175 self.graph.append_quins(&committed)?;
176 checkpoint_store::persist_checkpoint(
177 &self.storage_root,
178 &self.dag,
179 hash,
180 self.graph.count(),
181 &committed,
182 self.author_did,
183 )?;
184 } else if self.dag.nodes().len() > 0 {
185 checkpoint_store::save_dag(&self.storage_root, &self.dag)?;
186 }
187 self.wal.truncate()?;
188 self.last_checkpoint_hash = Some(hash);
189 Ok(hash)
190 }
191
192 pub fn last_checkpoint_hash(&self) -> Option<[u8; 32]> {
194 self.last_checkpoint_hash
195 }
196
197 pub fn checkpoint_meta(&self) -> Option<checkpoint_store::CheckpointMeta> {
199 load_meta(&self.storage_root)
200 }
201
202 pub fn commit_envelope(
204 &mut self,
205 envelope: &RecordEnvelope,
206 signing_key: &SigningKey,
207 principal_did_hash: u64,
208 source: &str,
209 summary: Option<String>,
210 ) -> std::io::Result<usize> {
211 let mut buffer = [wellfare_core::record::NQuin::default(); 8];
212 let count = envelope.compile_to_quins(&mut buffer);
213 let mut committed = 0;
214 for i in 0..count {
215 let src = &buffer[i];
216 let q = NQuin {
217 subject: src.subject,
218 predicate: src.predicate,
219 object: src.object,
220 context: src.context,
221 metadata: src.metadata,
222 parity: src.parity,
223 };
224 self.commit_quin(q, signing_key, principal_did_hash)?;
225 committed += 1;
226 }
227
228 let committed_unix = SystemTime::now()
229 .duration_since(UNIX_EPOCH)
230 .map(|d| d.as_secs() as u32)
231 .unwrap_or(0);
232 let entry = JournalEntry::from_envelope(envelope, source, committed_unix, summary);
233 self.journal.append(&entry)?;
234 if envelope.sensitivity != SensitivityClass::Classified {
239 let outbox_entry = SyncOutboxEntry::from_envelope(envelope, committed_unix);
240 self.sync_outbox.enqueue(&outbox_entry)?;
241 }
242 Ok(committed)
243 }
244
245 pub fn append_receipt(&self, receipt: &ReceiptRecord) -> std::io::Result<()> {
247 self.receipts.append(receipt)
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 use ed25519_dalek::SigningKey;
255 use wellfare_core::record::{EpistemicStatus, EvidenceType, RecordEnvelope, SensitivityClass};
256
257 #[test]
258 fn checkpoint_persists_graph_and_meta() {
259 let dir = tempfile::tempdir().unwrap();
260 let wal_path = dir.path().join("test.wal");
261 let mut vault = VaultService::open(&wal_path, dir.path(), 0xBEEF).unwrap();
262 let signing_key = SigningKey::from_bytes(&[7u8; 32]);
263 let envelope = RecordEnvelope {
264 id: "urn:wellfair:weight:chk".into(),
265 owner_did: "did:wf:owner".into(),
266 author_did: "did:wf:owner".into(),
267 proxy_did: None,
268 epistemic_status: EpistemicStatus::Asserted,
269 evidence_type: EvidenceType::DeviceMeasured,
270 sensitivity: SensitivityClass::Restricted,
271 asserted_time_unix: 1_700_000_000,
272 asserted_instant: None,
273 valid_time_start_unix: None,
274 valid_time_start_instant: None,
275 valid_time_end_unix: None,
276 valid_time_end_instant: None,
277 predecessor_id: None,
278 blob_hash: Some("abc".into()),
279 tombstone: false,
280 };
281 vault
282 .commit_envelope(&envelope, &signing_key, 1, "test", None)
283 .unwrap();
284 let hash = vault.checkpoint().unwrap();
285 assert_ne!(hash, [0u8; 32]);
286 assert!(vault.graph_quin_count() > 0);
287 assert!(dir.path().join(checkpoint_store::META_FILE).exists());
288 assert!(dir.path().join(checkpoint_store::DAG_FILE).exists());
289
290 let wal_path2 = dir.path().join("test2.wal");
291 std::fs::copy(&wal_path, &wal_path2).unwrap();
292 let graph_before = vault.graph_quin_count();
293 let meta_before = vault.checkpoint_meta().unwrap();
294 let reopened = VaultService::open(&wal_path2, dir.path(), 0xBEEF).unwrap();
295 assert_eq!(reopened.graph_quin_count(), graph_before);
296 let meta_after = reopened.checkpoint_meta().unwrap();
297 assert_eq!(meta_after.graph_quin_count, meta_before.graph_quin_count);
298 assert_eq!(meta_after.last_hash_hex, meta_before.last_hash_hex);
299 #[cfg(not(target_arch = "wasm32"))]
300 assert!(dir.path().join(checkpoint_store::Q42_FILE).exists());
301 }
302
303 #[test]
304 fn classified_records_excluded_from_sync_outbox() {
305 let dir = tempfile::tempdir().unwrap();
306 let wal_path = dir.path().join("sanct.wal");
307 let mut vault = VaultService::open(&wal_path, dir.path(), 0xBEEF).unwrap();
308 let signing_key = SigningKey::from_bytes(&[3u8; 32]);
309
310 let restricted = RecordEnvelope {
311 id: "urn:wellfair:weight:r1".into(),
312 owner_did: "did:wf:owner".into(),
313 author_did: "did:wf:owner".into(),
314 proxy_did: None,
315 epistemic_status: EpistemicStatus::Asserted,
316 evidence_type: EvidenceType::DeviceMeasured,
317 sensitivity: SensitivityClass::Restricted,
318 asserted_time_unix: 1_700_000_000,
319 asserted_instant: None,
320 valid_time_start_unix: None,
321 valid_time_start_instant: None,
322 valid_time_end_unix: None,
323 valid_time_end_instant: None,
324 predecessor_id: None,
325 blob_hash: None,
326 tombstone: false,
327 };
328 let classified = RecordEnvelope {
329 id: "urn:wellfair:sanctuary_note:s1".into(),
330 owner_did: "did:wf:owner".into(),
331 author_did: "did:wf:owner".into(),
332 proxy_did: None,
333 epistemic_status: EpistemicStatus::Asserted,
334 evidence_type: EvidenceType::SelfReported,
335 sensitivity: SensitivityClass::Classified,
336 asserted_time_unix: 1_700_000_100,
337 asserted_instant: None,
338 valid_time_start_unix: None,
339 valid_time_start_instant: None,
340 valid_time_end_unix: None,
341 valid_time_end_instant: None,
342 predecessor_id: None,
343 blob_hash: None,
344 tombstone: false,
345 };
346
347 vault
348 .commit_envelope(&restricted, &signing_key, 1, "test", None)
349 .unwrap();
350 vault
351 .commit_envelope(&classified, &signing_key, 1, "test", None)
352 .unwrap();
353
354 assert_eq!(vault.journal_count().unwrap(), 2);
356 let outbox = vault.list_outbox(16).unwrap();
358 assert_eq!(outbox.len(), 1);
359 assert_eq!(outbox[0].record_id, "urn:wellfair:weight:r1");
360 assert!(outbox
361 .iter()
362 .all(|e| e.record_id != "urn:wellfair:sanctuary_note:s1"));
363 }
364}