1pub mod pb {
20 tonic::include_proto!("kivi.v1");
21}
22mod verify;
23
24pub use verify::{ChainChecker, RecordIntegrityChecker};
25
26use futures_core::Stream;
27use pb::kivi_client::KiviClient as RawKiviClient;
28use serde_json::Value;
29use std::pin::Pin;
30use std::sync::{Arc, Mutex};
31use tonic::metadata::MetadataValue;
32use tonic::service::Interceptor;
33use tonic::transport::Channel;
34use tonic::{Request, Status};
35
36#[derive(Debug)]
38pub enum KiviError {
39 NotFound(String),
40 Unauthenticated(String),
41 PreconditionFailed(String),
42 InvalidArgument(String),
43 Unavailable(String),
44 RateLimited(String),
45 Verification(String),
46 Other(String),
47}
48
49impl std::fmt::Display for KiviError {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 let (kind, msg) = match self {
52 KiviError::NotFound(m) => ("not found", m),
53 KiviError::Unauthenticated(m) => ("unauthenticated", m),
54 KiviError::PreconditionFailed(m) => ("precondition failed", m),
55 KiviError::InvalidArgument(m) => ("invalid argument", m),
56 KiviError::Unavailable(m) => ("unavailable", m),
57 KiviError::RateLimited(m) => ("rate limited", m),
58 KiviError::Verification(m) => ("verification failed — the server or the wire lied", m),
59 KiviError::Other(m) => ("error", m),
60 };
61 write!(f, "kivi: {kind}: {msg}")
62 }
63}
64impl std::error::Error for KiviError {}
65
66impl From<Status> for KiviError {
67 fn from(s: Status) -> Self {
68 let msg = s.message().to_string();
69 match s.code() {
70 tonic::Code::NotFound => KiviError::NotFound(msg),
71 tonic::Code::Unauthenticated => KiviError::Unauthenticated(msg),
72 tonic::Code::FailedPrecondition => KiviError::PreconditionFailed(msg),
73 tonic::Code::InvalidArgument => KiviError::InvalidArgument(msg),
74 tonic::Code::Unavailable => KiviError::Unavailable(msg),
75 tonic::Code::ResourceExhausted => KiviError::RateLimited(msg),
76 _ => KiviError::Other(format!("{}: {}", s.code(), msg)),
77 }
78 }
79}
80
81fn json_err(e: serde_json::Error) -> KiviError {
82 KiviError::Other(format!("json: {e}"))
83}
84
85pub fn body_as<T: serde::de::DeserializeOwned>(rec: &Value) -> Result<T, KiviError> {
91 let body = rec.get("body").cloned().unwrap_or(Value::Null);
92 serde_json::from_value(body).map_err(json_err)
93}
94
95#[derive(Debug, Clone)]
97pub struct Receipt {
98 pub no: i64,
99 pub offset: i64,
100 pub hash: String,
101}
102
103#[derive(Debug, Clone)]
107pub struct TracedAnswer {
108 pub value: Value,
109 pub trace: Vec<i64>,
110 pub scope: i64,
111}
112
113impl TracedAnswer {
114 pub fn new(value: Value, trace: Vec<i64>, scope: i64) -> Result<Self, KiviError> {
115 if trace.is_empty() {
116 return Err(KiviError::Verification(
117 "an answer without a trace is unrepresentable".into(),
118 ));
119 }
120 Ok(TracedAnswer {
121 value,
122 trace,
123 scope,
124 })
125 }
126}
127
128#[derive(Debug, Clone)]
130pub struct ViewState {
131 pub state: Value,
132 pub scope: i64,
133 pub hash: String,
134}
135
136#[derive(Debug, Clone)]
138pub struct VerifyReport {
139 pub ok: bool,
140 pub records: i64,
141 pub seals: i64,
142 pub unsealed_tail: i64,
143 pub torn_tail: bool,
144 pub has_defect: bool,
145 pub defect_no: i64,
146 pub defect_reason: String,
147}
148
149#[derive(Debug, Clone)]
151pub struct Head {
152 pub no: i64,
153 pub hash: String,
154}
155
156#[derive(Debug, Clone)]
158pub struct Session {
159 pub token: String,
160 pub role: String,
161 pub expires_unix: i64,
162}
163
164#[derive(Debug, Clone)]
167pub struct SimilarHit {
168 pub no: i64,
169 pub score: f32,
170 pub record: Option<Value>,
171}
172
173#[derive(Debug, Clone)]
174pub struct SimilarAnswer {
175 pub hits: Vec<SimilarHit>,
176 pub scope: i64,
177 pub model: String,
178}
179
180#[derive(Debug, Clone)]
182pub struct ViewEntry {
183 pub key: String,
184 pub value: Value,
185}
186
187#[derive(Debug, Clone)]
189pub struct GraphEdge {
190 pub relation: String,
191 pub target: String,
192 pub no: i64,
193}
194
195#[derive(Debug, Clone)]
198pub struct GraphReached {
199 pub node: String,
200 pub depth: i64,
201 pub trace: Vec<i64>,
202}
203
204#[derive(Debug, Clone)]
206pub struct GraphHop {
207 pub from: String,
208 pub relation: String,
209 pub to: String,
210 pub no: i64,
211}
212
213#[derive(Debug, Clone)]
217pub struct ViewPage {
218 pub entries: Vec<ViewEntry>,
219 pub next_key: String,
220 pub scope: i64,
221 pub hash: String,
222}
223
224#[derive(Clone)]
228struct BearerInterceptor {
229 token: Arc<Mutex<String>>,
230}
231
232impl Interceptor for BearerInterceptor {
233 fn call(&mut self, mut req: Request<()>) -> Result<Request<()>, Status> {
234 let token = self.token.lock().unwrap().clone();
235 if !token.is_empty() {
236 let val = MetadataValue::try_from(format!("Bearer {token}"))
237 .map_err(|_| Status::invalid_argument("bad bearer token"))?;
238 req.metadata_mut().insert("authorization", val);
239 }
240 Ok(req)
241 }
242}
243
244type Stub =
245 RawKiviClient<tonic::service::interceptor::InterceptedService<Channel, BearerInterceptor>>;
246
247#[derive(Clone)]
256pub struct Client {
257 channel: Channel,
258 token: Arc<Mutex<String>>,
259 pub verify_streams: bool,
260}
261
262impl Client {
263 pub async fn connect(addr: &str, token: impl Into<String>) -> Result<Self, KiviError> {
266 let endpoint = if addr.starts_with("http") {
267 addr.to_string()
268 } else {
269 format!("http://{addr}")
270 };
271 let channel = Channel::from_shared(endpoint)
272 .map_err(|e| KiviError::Other(e.to_string()))?
273 .connect()
274 .await
275 .map_err(|e| KiviError::Unavailable(e.to_string()))?;
276 Ok(Client {
277 channel,
278 token: Arc::new(Mutex::new(token.into())),
279 verify_streams: true,
280 })
281 }
282
283 fn stub(&self) -> Stub {
284 RawKiviClient::with_interceptor(
285 self.channel.clone(),
286 BearerInterceptor {
287 token: self.token.clone(),
288 },
289 )
290 }
291
292 pub fn without_stream_verification(mut self) -> Self {
295 self.verify_streams = false;
296 self
297 }
298
299 pub fn set_token(&self, token: impl Into<String>) {
301 *self.token.lock().unwrap() = token.into();
302 }
303
304 pub fn with_bearer(&self, token: impl Into<String>) -> Self {
308 Client {
309 channel: self.channel.clone(),
310 token: Arc::new(Mutex::new(token.into())),
311 verify_streams: self.verify_streams,
312 }
313 }
314
315 pub async fn login(&self, username: &str, password: &str) -> Result<Session, KiviError> {
322 let r = self
323 .stub()
324 .login(pb::LoginRequest {
325 username: username.into(),
326 password: password.into(),
327 })
328 .await?
329 .into_inner();
330 self.set_token(r.token.clone());
331 Ok(Session {
332 token: r.token,
333 role: r.role,
334 expires_unix: r.expires_unix,
335 })
336 }
337
338 pub async fn append(&self, event_type: &str, body: &Value) -> Result<Receipt, KiviError> {
341 let r = self
342 .stub()
343 .append(pb::AppendRequest {
344 r#type: event_type.into(),
345 body_json: body.to_string(),
346 ..Default::default()
347 })
348 .await?
349 .into_inner();
350 Ok(Receipt {
351 no: r.no,
352 offset: r.offset,
353 hash: r.hash,
354 })
355 }
356
357 pub async fn append_typed<T: serde::Serialize>(
362 &self,
363 event_type: &str,
364 entity: &T,
365 ) -> Result<Receipt, KiviError> {
366 let body = serde_json::to_value(entity).map_err(json_err)?;
367 self.append(event_type, &body).await
368 }
369
370 pub async fn append_private(
371 &self,
372 event_type: &str,
373 body: &Value,
374 ) -> Result<Receipt, KiviError> {
375 let r = self
376 .stub()
377 .append_private(pb::AppendRequest {
378 r#type: event_type.into(),
379 body_json: body.to_string(),
380 ..Default::default()
381 })
382 .await?
383 .into_inner();
384 Ok(Receipt {
385 no: r.no,
386 offset: r.offset,
387 hash: r.hash,
388 })
389 }
390
391 pub async fn append_private_typed<T: serde::Serialize>(
395 &self,
396 event_type: &str,
397 entity: &T,
398 ) -> Result<Receipt, KiviError> {
399 let body = serde_json::to_value(entity).map_err(json_err)?;
400 self.append_private(event_type, &body).await
401 }
402
403 pub async fn erase(&self, no: i64, reason: &str) -> Result<Receipt, KiviError> {
406 let r = self
407 .stub()
408 .erase(pb::EraseRequest {
409 no,
410 reason: reason.into(),
411 })
412 .await?
413 .into_inner();
414 Ok(Receipt {
415 no: r.no,
416 offset: r.offset,
417 hash: r.hash,
418 })
419 }
420
421 pub async fn seal(&self) -> Result<Receipt, KiviError> {
422 let r = self.stub().seal(pb::Empty {}).await?.into_inner();
423 Ok(Receipt {
424 no: r.no,
425 offset: r.offset,
426 hash: r.hash,
427 })
428 }
429
430 pub async fn verify_ledger(&self) -> Result<VerifyReport, KiviError> {
433 let r = self.stub().verify(pb::Empty {}).await?.into_inner();
434 Ok(VerifyReport {
435 ok: r.ok,
436 records: r.records,
437 seals: r.seals,
438 unsealed_tail: r.unsealed_tail,
439 torn_tail: r.torn_tail,
440 has_defect: r.has_defect,
441 defect_no: r.defect_no,
442 defect_reason: r.defect_reason,
443 })
444 }
445
446 pub async fn head(&self) -> Result<Head, KiviError> {
450 let r = self.stub().head(pb::Empty {}).await?.into_inner();
451 Ok(Head {
452 no: r.head_no,
453 hash: r.head_hash,
454 })
455 }
456
457 pub async fn table(&self, subject: &str, attribute: &str) -> Result<TracedAnswer, KiviError> {
459 self.table_at(subject, attribute, None).await
460 }
461
462 pub async fn table_at(
465 &self,
466 subject: &str,
467 attribute: &str,
468 as_of: Option<i64>,
469 ) -> Result<TracedAnswer, KiviError> {
470 let r = self
471 .stub()
472 .query_table(pb::TableRequest {
473 subject: subject.into(),
474 attribute: attribute.into(),
475 as_of,
476 })
477 .await?
478 .into_inner();
479 let value: Value = serde_json::from_str(&r.value_json).map_err(json_err)?;
480 TracedAnswer::new(value, r.trace, r.scope)
481 }
482
483 pub async fn subject(&self, subject: &str) -> Result<TracedAnswer, KiviError> {
488 self.subject_at(subject, None).await
489 }
490
491 pub async fn subject_at(
493 &self,
494 subject: &str,
495 as_of: Option<i64>,
496 ) -> Result<TracedAnswer, KiviError> {
497 let r = self
498 .stub()
499 .query_subject(pb::SubjectRequest {
500 subject: subject.into(),
501 as_of,
502 })
503 .await?
504 .into_inner();
505 let value: Value = serde_json::from_str(&r.value_json).map_err(json_err)?;
506 TracedAnswer::new(value, r.trace, r.scope)
507 }
508
509 pub async fn why(&self, trace: &[i64]) -> Result<Vec<Value>, KiviError> {
511 let r = self
512 .stub()
513 .why(pb::WhyRequest {
514 trace: trace.to_vec(),
515 })
516 .await?
517 .into_inner();
518 r.records
519 .into_iter()
520 .map(|x| serde_json::from_str(&x.record_json).map_err(json_err))
521 .collect()
522 }
523
524 pub async fn get_record(&self, no: i64, unseal: bool) -> Result<Value, KiviError> {
527 let r = self
528 .stub()
529 .get_record(pb::GetRecordRequest { no, unseal })
530 .await?
531 .into_inner();
532 serde_json::from_str(&r.record_json).map_err(json_err)
533 }
534
535 pub async fn get_record_as<T: serde::de::DeserializeOwned>(
538 &self,
539 no: i64,
540 unseal: bool,
541 ) -> Result<T, KiviError> {
542 body_as(&self.get_record(no, unseal).await?)
543 }
544
545 pub async fn graph(&self) -> Result<ViewState, KiviError> {
546 let r = self.stub().query_graph(pb::Empty {}).await?.into_inner();
547 Ok(ViewState {
548 state: serde_json::from_str(&r.state_json).map_err(json_err)?,
549 scope: r.scope,
550 hash: r.hash,
551 })
552 }
553
554 pub async fn graph_neighbors(
557 &self,
558 node: &str,
559 as_of: Option<i64>,
560 ) -> Result<(Vec<GraphEdge>, bool), KiviError> {
561 let r = self
562 .stub()
563 .graph_neighbors(pb::GraphNeighborsRequest {
564 node: node.into(),
565 as_of,
566 })
567 .await?
568 .into_inner();
569 let edges = r
570 .edges
571 .into_iter()
572 .map(|e| GraphEdge {
573 relation: e.relation,
574 target: e.target,
575 no: e.no,
576 })
577 .collect();
578 Ok((edges, r.truncated))
579 }
580
581 pub async fn graph_reachable(
585 &self,
586 node: &str,
587 depth: i64,
588 limit: i64,
589 as_of: Option<i64>,
590 ) -> Result<(Vec<GraphReached>, bool), KiviError> {
591 let r = self
592 .stub()
593 .graph_reachable(pb::GraphReachableRequest {
594 node: node.into(),
595 depth,
596 limit,
597 as_of,
598 })
599 .await?
600 .into_inner();
601 let nodes = r
602 .nodes
603 .into_iter()
604 .map(|n| GraphReached {
605 node: n.node,
606 depth: n.depth,
607 trace: n.trace,
608 })
609 .collect();
610 Ok((nodes, r.truncated))
611 }
612
613 pub async fn graph_path(
616 &self,
617 from: &str,
618 to: &str,
619 depth: i64,
620 as_of: Option<i64>,
621 ) -> Result<(Vec<GraphHop>, bool, bool), KiviError> {
622 let r = self
623 .stub()
624 .graph_path(pb::GraphPathRequest {
625 from: from.into(),
626 to: to.into(),
627 depth,
628 as_of,
629 })
630 .await?
631 .into_inner();
632 let hops = r
633 .hops
634 .into_iter()
635 .map(|h| GraphHop {
636 from: h.from,
637 relation: h.relation,
638 to: h.to,
639 no: h.no,
640 })
641 .collect();
642 Ok((hops, r.found, r.truncated))
643 }
644
645 pub async fn series(&self, series: &str) -> Result<ViewState, KiviError> {
646 let r = self
647 .stub()
648 .query_series(pb::SeriesRequest {
649 series: series.into(),
650 })
651 .await?
652 .into_inner();
653 Ok(ViewState {
654 state: serde_json::from_str(&r.state_json).map_err(json_err)?,
655 scope: r.scope,
656 hash: r.hash,
657 })
658 }
659
660 pub async fn view_page(
663 &self,
664 view: &str,
665 after_key: &str,
666 limit: i64,
667 ) -> Result<ViewPage, KiviError> {
668 self.view_page_at(view, after_key, limit, None).await
669 }
670
671 pub async fn view_page_at(
675 &self,
676 view: &str,
677 after_key: &str,
678 limit: i64,
679 as_of: Option<i64>,
680 ) -> Result<ViewPage, KiviError> {
681 let r = self
682 .stub()
683 .query_view_page(pb::ViewPageRequest {
684 view: view.into(),
685 after_key: after_key.into(),
686 limit,
687 as_of,
688 })
689 .await?
690 .into_inner();
691 let mut entries = Vec::with_capacity(r.entries.len());
692 for e in r.entries {
693 entries.push(ViewEntry {
694 key: e.key,
695 value: serde_json::from_str(&e.value_json).map_err(json_err)?,
696 });
697 }
698 Ok(ViewPage {
699 entries,
700 next_key: r.next_key,
701 scope: r.scope,
702 hash: r.hash,
703 })
704 }
705
706 pub async fn similar(&self, query: &str, k: i64) -> Result<SimilarAnswer, KiviError> {
709 let r = self
710 .stub()
711 .similar(pb::SimilarRequest {
712 query: query.into(),
713 k,
714 })
715 .await?
716 .into_inner();
717 let mut hits = Vec::with_capacity(r.hits.len());
718 for h in r.hits {
719 let record = if h.record_json.is_empty() {
720 None
721 } else {
722 Some(serde_json::from_str(&h.record_json).map_err(json_err)?)
723 };
724 hits.push(SimilarHit {
725 no: h.no,
726 score: h.score,
727 record,
728 });
729 }
730 Ok(SimilarAnswer {
731 hits,
732 scope: r.scope,
733 model: r.model,
734 })
735 }
736
737 pub async fn replay(
745 &self,
746 start: i64,
747 follow: bool,
748 ) -> Result<Pin<Box<dyn Stream<Item = Result<Value, KiviError>> + Send>>, KiviError> {
749 let verify = self.verify_streams;
750 let inbound = self
751 .stub()
752 .replay(pb::ReplayRequest {
753 from: start,
754 follow,
755 })
756 .await?
757 .into_inner();
758 let mut checker = ChainChecker::new(true);
759 let out = async_stream::try_stream! {
760 tokio::pin!(inbound);
761 use tokio_stream::StreamExt;
762 while let Some(msg) = inbound.next().await {
763 let reply = msg.map_err(KiviError::from)?;
764 if verify {
765 checker.check(&reply.record_json)?;
766 }
767 let v: Value = serde_json::from_str(&reply.record_json).map_err(json_err)?;
768 yield v;
769 }
770 };
771 Ok(Box::pin(out))
772 }
773
774 pub async fn subscribe(
788 &self,
789 start: i64,
790 follow: bool,
791 types: Vec<String>,
792 ) -> Result<Pin<Box<dyn Stream<Item = Result<Value, KiviError>> + Send>>, KiviError> {
793 let verify = self.verify_streams;
794 let inbound = self
795 .stub()
796 .subscribe(pb::SubscribeRequest {
797 from: start,
798 follow,
799 types,
800 })
801 .await?
802 .into_inner();
803 let mut checker = RecordIntegrityChecker::new(true);
804 let out = async_stream::try_stream! {
805 tokio::pin!(inbound);
806 use tokio_stream::StreamExt;
807 while let Some(msg) = inbound.next().await {
808 let reply = msg.map_err(KiviError::from)?;
809 if verify {
810 checker.check(&reply.record_json)?;
811 }
812 let v: Value = serde_json::from_str(&reply.record_json).map_err(json_err)?;
813 yield v;
814 }
815 };
816 Ok(Box::pin(out))
817 }
818}