1use std::sync::LazyLock;
4
5use ostrya_core::{Checksum, ObjectName, ObjectType};
6use ostrya_gvariant::{
7 ArrayIter, DictBuilder, GvDecode, GvEncode, GvType, Slice, Type, Value, encode_to_vec, to_bytes,
8};
9
10use super::{
11 Encoding, Expected, Kind, MAX_FRAME_LIMIT, MIN_FRAME_LIMIT, RefOutcome, RefState, RefUpdate,
12 checksum, have_type, header_type, maybe_value, object_name, object_name_value, protocol,
13};
14use crate::error::{Error, ErrorCode, Result};
15
16const SERVER_COMMIT_SIGNATURE: &str = "(sasas(ayay)ssa{sv}a(say)a{sv})";
18
19fn parse(signature: &str) -> Type {
20 Type::parse(signature).expect("valid signature")
21}
22
23static HELLO: LazyLock<Type> = LazyLock::new(|| parse("(ua{sv}as)"));
24static HELLO_REPLY: LazyLock<Type> = LazyLock::new(|| parse("(ua{sv}a(smay))"));
25static OBJECT_NAMES: LazyLock<Type> = LazyLock::new(|| parse("a(yay)"));
26static BYTES: LazyLock<Type> = LazyLock::new(|| parse("ay"));
27static OBJECT_HEADER: LazyLock<Type> = LazyLock::new(|| parse("(yayy)"));
28static OBJECTS_REPLY: LazyLock<Type> = LazyLock::new(|| parse("(ut)"));
29static UPDATES: LazyLock<Type> = LazyLock::new(|| parse("a(symaymay)"));
30static SERVER_COMMIT: LazyLock<Type> = LazyLock::new(|| parse(SERVER_COMMIT_SIGNATURE));
31static COMMIT_REPLY: LazyLock<Type> = LazyLock::new(|| parse("a(smaymay)"));
32static ERROR: LazyLock<Type> = LazyLock::new(|| parse("(ssa{sv})"));
33static STRV: LazyLock<Type> = LazyLock::new(|| parse("as"));
34static MAYBE_CHECKSUM: LazyLock<Type> = LazyLock::new(|| parse("may"));
35static PULL_HELLO: LazyLock<Type> = LazyLock::new(|| parse("(ua{sv})"));
36static GET_REPLY: LazyLock<Type> = LazyLock::new(|| parse("(bmt)"));
37static LIST_REFS: LazyLock<Type> = LazyLock::new(|| parse("(asa{sv})"));
38static VALUE_IN_COMMIT: LazyLock<Type> = LazyLock::new(|| parse("((v))"));
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Hello {
43 pub version: u32,
45 pub agent: Option<String>,
47 pub refs: Vec<String>,
53 pub one_way: bool,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct HelloReply {
67 pub version: u32,
69 pub mode: String,
71 pub collection_id: Option<String>,
75 pub max_frame: u32,
80 pub max_have: u32,
85 pub encodings: Vec<Encoding>,
90 pub parallel_uploads: u32,
96 pub refs: Vec<RefState>,
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct HaveReply {
107 pub bitmap: Vec<u8>,
109}
110
111impl HaveReply {
112 pub fn from_missing(missing: impl IntoIterator<Item = bool>) -> HaveReply {
117 let mut bitmap = Vec::new();
118 for (i, set) in missing.into_iter().enumerate() {
119 if i % 8 == 0 {
120 bitmap.push(0);
121 }
122 if set {
123 bitmap[i / 8] |= 1 << (i % 8);
124 }
125 }
126 HaveReply { bitmap }
127 }
128
129 pub fn is_missing(&self, index: usize) -> bool {
133 self.bitmap
134 .get(index / 8)
135 .is_some_and(|b| b & (1 << (index % 8)) != 0)
136 }
137
138 pub fn check_len(&self, entries: usize) -> Result<()> {
148 if self.bitmap.len() != entries.div_ceil(8) {
149 return Err(protocol(format!(
150 "HaveReply of {} bytes for {entries} entries",
151 self.bitmap.len()
152 )));
153 }
154 let tail = entries % 8;
155 if tail != 0 && self.bitmap[entries / 8] >> tail != 0 {
156 return Err(protocol("HaveReply sets a bit after the last entry"));
157 }
158 Ok(())
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct ObjectHeader {
166 pub name: ObjectName,
170 pub encoding: Encoding,
174}
175
176#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct ObjectsReply {
184 pub objects: u32,
186 pub payload_bytes: u64,
188}
189
190#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct CommitRequest {
193 pub updates: Vec<RefUpdate>,
198 pub force: bool,
203 pub server_commit: Option<Box<ServerCommit>>,
209}
210
211#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct ServerCommit {
226 pub branch: String,
229 pub tags: Vec<String>,
235 pub bind_refs: Vec<String>,
241 pub root_dirtree: Checksum,
243 pub root_dirmeta: Checksum,
245 pub subject: String,
247 pub body: String,
249 pub metadata: Vec<(String, Vec<u8>)>,
259 pub related: Vec<(String, Checksum)>,
269 pub timestamp: Option<u64>,
275 pub orphan: bool,
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
287pub struct ErrorMessage {
288 pub code: ErrorCode,
290 pub message: String,
292 pub missing: Vec<ObjectName>,
298 pub current: Option<RefState>,
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
309pub struct PullHello {
310 pub version: u32,
312 pub agent: Option<String>,
314}
315
316#[derive(Debug, Clone, PartialEq, Eq)]
321pub struct PullHelloReply {
322 pub version: u32,
327}
328
329#[derive(Debug, Clone, PartialEq, Eq)]
331pub struct GetReply {
332 pub found: bool,
337 pub len: Option<u64>,
343}
344
345#[derive(Debug, Clone, PartialEq, Eq, Default)]
357pub struct ListRefsRequest {
358 pub refs: Vec<String>,
361 pub collections: Option<Vec<String>>,
368}
369
370#[derive(Debug, Clone, PartialEq, Eq)]
374#[non_exhaustive]
375pub enum Message {
376 Hello(Hello),
378 HelloReply(HelloReply),
380 Have(Vec<ObjectName>),
384 HaveReply(HaveReply),
386 ObjectHeader(ObjectHeader),
388 ObjectsEnd,
390 ObjectsReply(ObjectsReply),
392 Commit(CommitRequest),
394 CommitReply(Vec<RefOutcome>),
397 Error(ErrorMessage),
399 Abort,
401 PullHello(PullHello),
403 PullHelloReply(PullHelloReply),
405 Get(String),
409 GetReply(GetReply),
411 ListRefs(ListRefsRequest),
413}
414
415impl Message {
416 pub fn kind(&self) -> Kind {
418 match self {
419 Message::Hello(_) => Kind::Hello,
420 Message::HelloReply(_) => Kind::HelloReply,
421 Message::Have(_) => Kind::Have,
422 Message::HaveReply(_) => Kind::HaveReply,
423 Message::ObjectHeader(_) => Kind::ObjectHeader,
424 Message::ObjectsEnd => Kind::ObjectsEnd,
425 Message::ObjectsReply(_) => Kind::ObjectsReply,
426 Message::Commit(_) => Kind::Commit,
427 Message::CommitReply(_) => Kind::CommitReply,
428 Message::Error(_) => Kind::Error,
429 Message::Abort => Kind::Abort,
430 Message::PullHello(_) => Kind::PullHello,
431 Message::PullHelloReply(_) => Kind::PullHelloReply,
432 Message::Get(_) => Kind::Get,
433 Message::GetReply(_) => Kind::GetReply,
434 Message::ListRefs(_) => Kind::ListRefs,
435 }
436 }
437
438 pub fn encode_body(&self) -> Result<Vec<u8>> {
458 let (ty, value): (&Type, Value) = match self {
459 Message::Commit(c) => return encode_commit(c),
460 Message::ObjectsEnd => return Ok(Vec::new()),
461 Message::Abort => return Ok(vec![0]),
462 Message::Hello(h) => {
463 let mut opts = DictBuilder::new();
464 if let Some(agent) = &h.agent {
465 opts.insert_str("agent", agent);
466 }
467 if h.one_way {
468 opts.insert_bool("one-way", true);
469 }
470 let refs = h.refs.iter().cloned().map(Value::Str).collect();
471 let v = Value::Tuple(vec![
472 Value::U32(h.version),
473 opts.build(),
474 Value::Array(refs),
475 ]);
476 (&HELLO, v)
477 }
478 Message::HelloReply(r) => {
479 check_limits(r.max_frame, r.max_have, r.parallel_uploads)?;
480 let mut opts = DictBuilder::new();
481 opts.insert_str("mode", &r.mode);
482 if let Some(id) = &r.collection_id {
483 opts.insert_str("collection-id", id);
484 }
485 let encodings: Vec<String> =
486 r.encodings.iter().map(|e| e.as_str().to_owned()).collect();
487 opts.insert("max-frame", Type::U32, Value::U32(r.max_frame))
488 .insert("max-have", Type::U32, Value::U32(r.max_have))
489 .insert_strv("encodings", &encodings)
490 .insert(
491 "parallel-uploads",
492 Type::U32,
493 Value::U32(r.parallel_uploads),
494 );
495 let refs = r
496 .refs
497 .iter()
498 .map(|s| Value::Tuple(vec![Value::Str(s.name.clone()), maybe_value(s.commit)]))
499 .collect();
500 let v = Value::Tuple(vec![
501 Value::U32(r.version),
502 opts.build(),
503 Value::Array(refs),
504 ]);
505 (&HELLO_REPLY, v)
506 }
507 Message::Have(names) => (&OBJECT_NAMES, object_names_value(names)?),
508 Message::HaveReply(r) => (&BYTES, Value::Bytes(r.bitmap.clone())),
509 Message::ObjectHeader(h) => {
510 check_header(&h.name, h.encoding)?;
511 let v = Value::Tuple(vec![
512 Value::Byte(h.name.ty.as_u32() as u8),
513 Value::Bytes(h.name.checksum.as_bytes().to_vec()),
514 Value::Byte(h.encoding.as_u8()),
515 ]);
516 (&OBJECT_HEADER, v)
517 }
518 Message::ObjectsReply(r) => {
519 let v = Value::Tuple(vec![Value::U32(r.objects), Value::U64(r.payload_bytes)]);
520 (&OBJECTS_REPLY, v)
521 }
522 Message::CommitReply(outcomes) => {
523 let v = outcomes
524 .iter()
525 .map(|o| {
526 Value::Tuple(vec![
527 Value::Str(o.name.clone()),
528 maybe_value(o.old),
529 maybe_value(o.new),
530 ])
531 })
532 .collect();
533 (&COMMIT_REPLY, Value::Array(v))
534 }
535 Message::Error(e) => {
536 check_error(e)?;
537 let mut detail = DictBuilder::new();
538 if !e.missing.is_empty() {
539 detail.insert(
540 "missing",
541 OBJECT_NAMES.clone(),
542 object_names_value(&e.missing)?,
543 );
544 }
545 if let Some(state) = &e.current {
546 detail.insert_str("ref", &state.name).insert(
547 "current",
548 MAYBE_CHECKSUM.clone(),
549 maybe_value(state.commit),
550 );
551 }
552 let v = Value::Tuple(vec![
553 Value::Str(e.code.as_str().to_owned()),
554 Value::Str(e.message.clone()),
555 detail.build(),
556 ]);
557 (&ERROR, v)
558 }
559 Message::PullHello(h) => {
560 let mut opts = DictBuilder::new();
561 if let Some(agent) = &h.agent {
562 opts.insert_str("agent", agent);
563 }
564 let v = Value::Tuple(vec![Value::U32(h.version), opts.build()]);
565 (&PULL_HELLO, v)
566 }
567 Message::PullHelloReply(r) => {
568 let v = Value::Tuple(vec![Value::U32(r.version), DictBuilder::new().build()]);
569 (&PULL_HELLO, v)
570 }
571 Message::Get(path) => (&Type::Str, Value::Str(path.clone())),
572 Message::GetReply(r) => {
573 check_get_reply(r)?;
574 let len = Value::Maybe(r.len.map(|n| Box::new(Value::U64(n))));
575 (&GET_REPLY, Value::Tuple(vec![Value::Bool(r.found), len]))
576 }
577 Message::ListRefs(r) => {
578 let mut opts = DictBuilder::new();
579 if let Some(collections) = &r.collections {
580 opts.insert_strv("collections", collections);
581 }
582 let refs = r.refs.iter().cloned().map(Value::Str).collect();
583 (
584 &LIST_REFS,
585 Value::Tuple(vec![Value::Array(refs), opts.build()]),
586 )
587 }
588 };
589 to_bytes(ty, &value).map_err(encode_error)
590 }
591
592 pub fn decode(kind: Kind, body: &[u8]) -> Result<Message> {
624 Ok(match kind {
625 Kind::ObjectsEnd => {
626 if !body.is_empty() {
627 return Err(protocol("ObjectsEnd body is not empty"));
628 }
629 Message::ObjectsEnd
630 }
631 Kind::Abort => {
632 if body != [0] {
633 return Err(protocol("Abort body is not the unit tuple"));
634 }
635 Message::Abort
636 }
637 Kind::Hello => {
638 let (version, opts, refs): (u32, Dict, ArrayIter<&str>) = parse_body(body)?;
639 let [agent, one_way] = dict(opts, ["agent", "one-way"])?;
640 let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
641 let one_way = field(one_way, "one-way", &Type::Bool)?.unwrap_or(false);
642 Message::Hello(Hello {
643 version,
644 agent: agent.map(str::to_owned),
645 refs: collect(refs, |r| Ok(r.to_owned()))?,
646 one_way,
647 })
648 }
649 Kind::HelloReply => Message::HelloReply(decode_hello_reply(body)?),
650 Kind::Have => Message::Have(object_names(parse_body(body)?)?),
651 Kind::HaveReply => {
652 let bitmap: &[u8] = parse_body(body)?;
653 Message::HaveReply(HaveReply {
654 bitmap: bitmap.to_vec(),
655 })
656 }
657 Kind::ObjectHeader => {
658 let (ty, sum, enc): (u8, &[u8], u8) = parse_body(body)?;
659 let name = object_name((ty, sum), header_type)?;
660 let encoding = Encoding::from_u8(enc)?;
661 check_header(&name, encoding)?;
662 Message::ObjectHeader(ObjectHeader { name, encoding })
663 }
664 Kind::ObjectsReply => {
665 let (objects, payload_bytes) = parse_body(body)?;
666 Message::ObjectsReply(ObjectsReply {
667 objects,
668 payload_bytes,
669 })
670 }
671 Kind::Commit => {
672 let (updates, opts): (ArrayIter<UpdateView>, Dict) = parse_body(body)?;
673 let updates = collect(updates, decode_update)?;
674 let [force, server_commit] = dict(opts, ["force", "server-commit"])?;
675 let force = field(force, "force", &Type::Bool)?.unwrap_or(false);
676 let server_commit = field(server_commit, "server-commit", &SERVER_COMMIT)?
677 .map(decode_server_commit)
678 .transpose()?
679 .map(Box::new);
680 Message::Commit(CommitRequest {
681 updates,
682 force,
683 server_commit,
684 })
685 }
686 Kind::CommitReply => {
687 let outcomes: ArrayIter<(&str, MaybeBytes, MaybeBytes)> = parse_body(body)?;
688 Message::CommitReply(collect(outcomes, |(name, old, new)| {
689 Ok(RefOutcome {
690 name: name.to_owned(),
691 old: maybe_checksum(old)?,
692 new: maybe_checksum(new)?,
693 })
694 })?)
695 }
696 Kind::Error => Message::Error(decode_error(body)?),
697 Kind::PullHello => {
698 let (version, opts): (u32, Dict) = parse_body(body)?;
699 let [agent] = dict(opts, ["agent"])?;
700 let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
701 Message::PullHello(PullHello {
702 version,
703 agent: agent.map(str::to_owned),
704 })
705 }
706 Kind::PullHelloReply => {
707 let (version, opts): (u32, Dict) = parse_body(body)?;
708 let [] = dict(opts, [])?;
709 Message::PullHelloReply(PullHelloReply { version })
710 }
711 Kind::Get => {
712 let path: &str = parse_body(body)?;
713 Message::Get(path.to_owned())
714 }
715 Kind::GetReply => {
716 let (found, len): (bool, MaybeU64) = parse_body(body)?;
717 let r = GetReply { found, len: len.0 };
718 check_get_reply(&r)?;
719 Message::GetReply(r)
720 }
721 Kind::ListRefs => {
722 let (refs, opts): (ArrayIter<&str>, Dict) = parse_body(body)?;
723 let [collections] = dict(opts, ["collections"])?;
724 let collections: Option<ArrayIter<&str>> =
725 field(collections, "collections", &STRV)?;
726 Message::ListRefs(ListRefsRequest {
727 refs: collect(refs, |e| Ok(e.to_owned()))?,
728 collections: collections
729 .map(|entries| collect(entries, |e| Ok(e.to_owned())))
730 .transpose()?,
731 })
732 }
733 })
734 }
735}
736
737fn check_limits(max_frame: u32, max_have: u32, parallel_uploads: u32) -> Result<()> {
743 if !(MIN_FRAME_LIMIT..=MAX_FRAME_LIMIT).contains(&max_frame) {
744 return Err(protocol(format!("max-frame {max_frame} is out of range")));
745 }
746 if max_have == 0 || parallel_uploads == 0 {
747 return Err(protocol("max-have and parallel-uploads must be at least 1"));
748 }
749 Ok(())
750}
751
752fn check_error(e: &ErrorMessage) -> Result<()> {
755 if e.code == ErrorCode::RefMismatch && e.current.is_none() {
756 return Err(protocol("ref-mismatch lacks ref and current"));
757 }
758 Ok(())
759}
760
761fn decode_hello_reply(body: &[u8]) -> Result<HelloReply> {
762 let (version, opts, refs): (u32, Dict, ArrayIter<(&str, MaybeBytes)>) = parse_body(body)?;
763 let [
764 mode,
765 collection_id,
766 max_frame,
767 max_have,
768 encodings,
769 parallel_uploads,
770 ] = dict(
771 opts,
772 [
773 "mode",
774 "collection-id",
775 "max-frame",
776 "max-have",
777 "encodings",
778 "parallel-uploads",
779 ],
780 )?;
781 let mode: &str = required(mode, "mode", &Type::Str)?;
782 let collection_id: Option<&str> = field(collection_id, "collection-id", &Type::Str)?;
783 let max_frame = required(max_frame, "max-frame", &Type::U32)?;
784 let max_have = required(max_have, "max-have", &Type::U32)?;
785 let parallel_uploads = required(parallel_uploads, "parallel-uploads", &Type::U32)?;
786 check_limits(max_frame, max_have, parallel_uploads)?;
787 let names: ArrayIter<&str> = required(encodings, "encodings", &STRV)?;
788 let mut encodings = Vec::new();
789 for name in names {
790 encodings.extend(Encoding::from_name(name.map_err(malformed)?));
791 }
792 let refs = collect(refs, |(name, commit)| {
793 Ok(RefState {
794 name: name.to_owned(),
795 commit: maybe_checksum(commit)?,
796 })
797 })?;
798 Ok(HelloReply {
799 version,
800 mode: mode.to_owned(),
801 collection_id: collection_id.map(str::to_owned),
802 max_frame,
803 max_have,
804 encodings,
805 parallel_uploads,
806 refs,
807 })
808}
809
810type UpdateView<'a> = (&'a str, u8, MaybeBytes<'a>, MaybeBytes<'a>);
812
813fn decode_update((name, state, expected, new): UpdateView) -> Result<RefUpdate> {
814 let expected = match (state, maybe_checksum(expected)?) {
815 (0, None) => Expected::Absent,
816 (1, Some(c)) => Expected::Commit(c),
817 (2, None) => Expected::Any,
818 (s @ 0..=2, _) => {
819 return Err(protocol(format!(
820 "expected state {s} does not match its commit"
821 )));
822 }
823 (s, _) => return Err(protocol(format!("unknown expected state {s}"))),
824 };
825 Ok(RefUpdate {
826 name: name.to_owned(),
827 expected,
828 new: maybe_checksum(new)?,
829 })
830}
831
832fn encode_error(e: ostrya_gvariant::Error) -> Error {
834 protocol(format!("encode: {e}"))
835}
836
837fn variant_bytes(ty: Type, value: Value) -> Result<Vec<u8>> {
839 to_bytes(&Type::Variant, &Value::variant(ty, value)).map_err(encode_error)
840}
841
842fn dict_entries<'a>(
845 entries: &'a [(&'static str, Vec<u8>)],
846) -> Vec<(&'static str, VariantSlice<'a>)> {
847 entries
848 .iter()
849 .map(|(key, value)| (*key, VariantSlice { inner: value }))
850 .collect()
851}
852
853fn encode_commit(c: &CommitRequest) -> Result<Vec<u8>> {
860 encode_commit_parts(&c.updates, c.force, c.server_commit.as_deref())
861}
862
863pub(crate) fn server_commit_frame_len(sc: &ServerCommit) -> Result<u64> {
869 Ok(encode_commit_parts(&[], false, Some(sc))?.len() as u64 + 1)
870}
871
872pub(crate) fn check_server_commit_metadata(sc: &ServerCommit) -> Result<()> {
886 for (key, value) in &sc.metadata {
887 let Err(deep) = ostrya_gvariant::validate(&VALUE_IN_COMMIT, value) else {
888 continue;
889 };
890 if let Err(e) = ostrya_gvariant::validate(&Type::Variant, value) {
891 return Err(protocol(format!("encode: metadata entry '{key}': {e}")));
892 }
893 return Err(Error::InvalidInput(format!(
894 "a commit cannot hold the metadata value under '{key}': {deep}"
895 )));
896 }
897 Ok(())
898}
899
900pub(crate) fn server_commit_reply_frame_len(sc: &ServerCommit) -> Result<u64> {
906 let any_commit = Some(Checksum::from_bytes([0; 32]));
907 let refs = std::iter::once(RefOutcome {
908 name: sc.branch.clone(),
909 old: any_commit,
910 new: any_commit,
911 })
912 .chain(sc.tags.iter().map(|tag| RefOutcome {
913 name: tag.clone(),
914 old: None,
915 new: any_commit,
916 }))
917 .collect();
918 Ok(Message::CommitReply(refs).encode_body()?.len() as u64 + 1)
919}
920
921fn encode_commit_parts(
923 updates: &[RefUpdate],
924 force: bool,
925 server_commit: Option<&ServerCommit>,
926) -> Result<Vec<u8>> {
927 let updates = updates
928 .iter()
929 .map(|u| {
930 let (state, expected) = match u.expected {
931 Expected::Absent => (0, None),
932 Expected::Commit(c) => (1, Some(c)),
933 Expected::Any => (2, None),
934 };
935 Value::Tuple(vec![
936 Value::Str(u.name.clone()),
937 Value::Byte(state),
938 maybe_value(expected),
939 maybe_value(u.new),
940 ])
941 })
942 .collect();
943 let updates = to_bytes(&UPDATES, &Value::Array(updates)).map_err(encode_error)?;
944 let mut opts = Vec::new();
945 if force {
946 opts.push(("force", variant_bytes(Type::Bool, Value::Bool(true))?));
947 }
948 if let Some(sc) = server_commit {
949 let mut value = server_commit_bytes(sc)?;
950 value.push(0);
951 value.extend_from_slice(SERVER_COMMIT_SIGNATURE.as_bytes());
952 opts.push(("server-commit", value));
953 }
954 encode_to_vec(&(updates.as_slice(), Slice(&dict_entries(&opts)))).map_err(encode_error)
955}
956
957fn server_commit_bytes(sc: &ServerCommit) -> Result<Vec<u8>> {
963 let tags: Vec<&str> = sc.tags.iter().map(String::as_str).collect();
964 let bind_refs: Vec<&str> = sc.bind_refs.iter().map(String::as_str).collect();
965 let metadata = sc
966 .metadata
967 .iter()
968 .map(|(key, value)| {
969 ostrya_gvariant::validate(&Type::Variant, value)
970 .map_err(|e| protocol(format!("encode: metadata entry '{key}': {e}")))?;
971 Ok((key.as_str(), VariantSlice { inner: value }))
972 })
973 .collect::<Result<Vec<_>>>()?;
974 if sc.related.iter().any(|(name, _)| name.is_empty()) {
975 return Err(protocol("encode: an attachment has an empty name"));
976 }
977 let mut opts = Vec::new();
978 if let Some(timestamp) = sc.timestamp {
979 opts.push((
980 "timestamp",
981 variant_bytes(Type::U64, Value::U64(timestamp))?,
982 ));
983 }
984 if sc.orphan {
985 opts.push(("orphan", variant_bytes(Type::Bool, Value::Bool(true))?));
986 }
987 encode_to_vec(&(
988 sc.branch.as_str(),
989 Slice(&tags),
990 Slice(&bind_refs),
991 (sc.root_dirtree, sc.root_dirmeta),
992 sc.subject.as_str(),
993 sc.body.as_str(),
994 Slice(&metadata),
995 Slice(&sc.related),
996 Slice(&dict_entries(&opts)),
997 ))
998 .map_err(encode_error)
999}
1000
1001type ServerCommitView<'a> = (
1003 &'a str,
1004 ArrayIter<'a, &'a str>,
1005 ArrayIter<'a, &'a str>,
1006 (&'a [u8], &'a [u8]),
1007 &'a str,
1008 &'a str,
1009 ArrayIter<'a, (&'a str, VariantSlice<'a>)>,
1010 ArrayIter<'a, (&'a str, &'a [u8])>,
1011 Dict<'a>,
1012);
1013
1014fn decode_server_commit(
1021 (branch, tags, bind_refs, (dirtree, dirmeta), subject, body, metadata, related, opts): ServerCommitView,
1022) -> Result<ServerCommit> {
1023 let [timestamp, orphan] = dict(opts, ["timestamp", "orphan"])?;
1024 let timestamp = field(timestamp, "timestamp", &Type::U64)?;
1025 let orphan = field(orphan, "orphan", &Type::Bool)?.unwrap_or(false);
1026 let metadata = collect(metadata, |(key, value)| {
1027 ostrya_gvariant::validate(&Type::Variant, value.inner).map_err(malformed)?;
1028 Ok((key.to_owned(), value.inner.to_vec()))
1029 })?;
1030 let mut attachments = Vec::new();
1034 for entry in related {
1035 let (name, sum) = entry.map_err(malformed)?;
1036 if name.is_empty() {
1037 return Err(protocol(
1038 "an attachment of a server commit has an empty name",
1039 ));
1040 }
1041 attachments.push((name.to_owned(), checksum(sum)?));
1042 }
1043 Ok(ServerCommit {
1044 branch: branch.to_owned(),
1045 tags: collect(tags, |t| Ok(t.to_owned()))?,
1046 bind_refs: collect(bind_refs, |n| Ok(n.to_owned()))?,
1047 root_dirtree: checksum(dirtree)?,
1048 root_dirmeta: checksum(dirmeta)?,
1049 subject: subject.to_owned(),
1050 body: body.to_owned(),
1051 metadata,
1052 related: attachments,
1053 timestamp,
1054 orphan,
1055 })
1056}
1057
1058fn decode_error(body: &[u8]) -> Result<ErrorMessage> {
1059 let (name, message, detail): (&str, &str, Dict) = parse_body(body)?;
1060 let code =
1061 ErrorCode::from_name(name).ok_or_else(|| protocol(format!("unknown error code {name}")))?;
1062 let [missing, ref_name, current] = dict(detail, ["missing", "ref", "current"])?;
1063 let missing = match field(missing, "missing", &OBJECT_NAMES)? {
1064 Some(names) => object_names(names)?,
1065 None => Vec::new(),
1066 };
1067 let ref_name: Option<&str> = field(ref_name, "ref", &Type::Str)?;
1068 let current = match (ref_name, field(current, "current", &MAYBE_CHECKSUM)?) {
1069 (Some(name), Some(commit)) => Some(RefState {
1070 name: name.to_owned(),
1071 commit: maybe_checksum(commit)?,
1072 }),
1073 (None, None) => None,
1074 _ => return Err(protocol("Error carries one of ref and current alone")),
1075 };
1076 let e = ErrorMessage {
1077 code,
1078 message: message.to_owned(),
1079 missing,
1080 current,
1081 };
1082 check_error(&e)?;
1083 Ok(e)
1084}
1085
1086fn check_get_reply(r: &GetReply) -> Result<()> {
1088 if !r.found && r.len.is_some() {
1089 return Err(protocol("GetReply with found false carries a length"));
1090 }
1091 Ok(())
1092}
1093
1094fn check_header(name: &ObjectName, encoding: Encoding) -> Result<()> {
1097 if !header_type(name.ty) {
1098 return Err(protocol(format!(
1099 "object type {} is not allowed in ObjectHeader",
1100 name.ty.as_u32()
1101 )));
1102 }
1103 if encoding == Encoding::Deflate && name.ty != ObjectType::File {
1104 return Err(protocol("deflate is allowed for a file object alone"));
1105 }
1106 Ok(())
1107}
1108
1109pub(super) const OBJECT_HEADER_FRAME: usize = 40;
1112
1113pub(super) fn object_header_frame(h: &ObjectHeader) -> Result<[u8; OBJECT_HEADER_FRAME]> {
1119 check_header(&h.name, h.encoding)?;
1120 let mut frame = [0u8; OBJECT_HEADER_FRAME];
1121 frame[..4].copy_from_slice(&(OBJECT_HEADER_FRAME as u32 - 4).to_be_bytes());
1122 frame[4] = Kind::ObjectHeader.as_u8();
1123 frame[5] = h.name.ty.as_u32() as u8;
1124 frame[6..38].copy_from_slice(h.name.checksum.as_bytes());
1125 frame[38] = h.encoding.as_u8();
1126 frame[39] = 33;
1127 Ok(frame)
1128}
1129
1130pub(super) const GET_REPLY_FRAME: usize = 21;
1133
1134pub(super) fn get_reply_frame(r: &GetReply) -> Result<([u8; GET_REPLY_FRAME], usize)> {
1145 check_get_reply(r)?;
1146 let mut frame = [0u8; GET_REPLY_FRAME];
1147 let used = match r.len {
1148 Some(len) => {
1149 frame[13..].copy_from_slice(&len.to_le_bytes());
1150 GET_REPLY_FRAME
1151 }
1152 None => 13,
1153 };
1154 frame[..4].copy_from_slice(&(used as u32 - 4).to_be_bytes());
1155 frame[4] = Kind::GetReply.as_u8();
1156 frame[5] = u8::from(r.found);
1157 Ok((frame, used))
1158}
1159
1160fn object_names_value(names: &[ObjectName]) -> Result<Value> {
1161 if let Some(bad) = names.iter().find(|n| !have_type(n.ty)) {
1162 return Err(protocol(format!(
1163 "object type {} is not allowed in an object list",
1164 bad.ty.as_u32()
1165 )));
1166 }
1167 Ok(Value::Array(names.iter().map(object_name_value).collect()))
1168}
1169
1170fn object_names(names: ArrayIter<(u8, &[u8])>) -> Result<Vec<ObjectName>> {
1171 collect(names, |e| object_name(e, have_type))
1172}
1173
1174fn malformed(e: ostrya_gvariant::Error) -> Error {
1175 protocol(format!("malformed body: {e}"))
1176}
1177
1178fn parse_body<'a, T: GvDecode<'a>>(body: &'a [u8]) -> Result<T> {
1179 T::decode(body).map_err(malformed)
1180}
1181
1182fn collect<'a, E: GvDecode<'a> + Copy, T>(
1187 items: ArrayIter<'a, E>,
1188 mut f: impl FnMut(E) -> Result<T>,
1189) -> Result<Vec<T>> {
1190 let mut out = Vec::with_capacity(items.count());
1191 for e in items {
1192 out.push(f(e.map_err(malformed)?)?);
1193 }
1194 Ok(out)
1195}
1196
1197fn maybe_checksum(m: MaybeBytes) -> Result<Option<Checksum>> {
1198 m.0.map(checksum).transpose()
1199}
1200
1201#[derive(Clone, Copy)]
1204struct MaybeBytes<'a>(Option<&'a [u8]>);
1205
1206impl GvType for MaybeBytes<'_> {
1207 const ALIGNMENT: usize = 1;
1208 const FIXED_SIZE: Option<usize> = None;
1209}
1210
1211impl<'a> GvDecode<'a> for MaybeBytes<'a> {
1212 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1213 match data.split_last() {
1214 None => Ok(MaybeBytes(None)),
1215 Some((0, rest)) => Ok(MaybeBytes(Some(rest))),
1216 Some(_) => Err(ostrya_gvariant::Error::NotNormal(
1217 "maybe lacks its terminating zero byte",
1218 )),
1219 }
1220 }
1221}
1222
1223struct MaybeU64(Option<u64>);
1227
1228impl GvType for MaybeU64 {
1229 const ALIGNMENT: usize = 8;
1230 const FIXED_SIZE: Option<usize> = None;
1231}
1232
1233impl<'a> GvDecode<'a> for MaybeU64 {
1234 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1235 match data.len() {
1236 0 => Ok(MaybeU64(None)),
1237 8 => u64::decode(data).map(|n| MaybeU64(Some(n))),
1238 _ => Err(ostrya_gvariant::Error::NotNormal(
1239 "maybe of a u64 is not 0 or 8 bytes",
1240 )),
1241 }
1242 }
1243}
1244
1245struct RawVariant<'a> {
1248 ty: Type,
1249 child: &'a [u8],
1250}
1251
1252impl GvType for RawVariant<'_> {
1253 const ALIGNMENT: usize = 8;
1254 const FIXED_SIZE: Option<usize> = None;
1255}
1256
1257impl<'a> GvDecode<'a> for RawVariant<'a> {
1258 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1259 let not_normal = ostrya_gvariant::Error::NotNormal;
1260 let sep = data
1261 .iter()
1262 .rposition(|&b| b == 0)
1263 .ok_or(not_normal("variant lacks a type separator"))?;
1264 let signature = std::str::from_utf8(&data[sep + 1..])
1265 .map_err(|_| not_normal("variant type signature is not UTF-8"))?;
1266 let ty =
1267 Type::parse(signature).map_err(|_| not_normal("variant type signature is invalid"))?;
1268 Ok(RawVariant {
1269 ty,
1270 child: &data[..sep],
1271 })
1272 }
1273}
1274
1275type Dict<'a> = ArrayIter<'a, (&'a str, RawVariant<'a>)>;
1277
1278#[derive(Clone, Copy)]
1280struct VariantSlice<'a> {
1281 inner: &'a [u8],
1282}
1283
1284impl GvType for VariantSlice<'_> {
1285 const ALIGNMENT: usize = 8;
1286 const FIXED_SIZE: Option<usize> = None;
1287}
1288
1289impl<'a> GvDecode<'a> for VariantSlice<'a> {
1290 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1291 Ok(VariantSlice { inner: data })
1292 }
1293}
1294
1295impl GvEncode for VariantSlice<'_> {
1296 fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
1297 out.extend_from_slice(self.inner);
1298 Ok(())
1299 }
1300}
1301
1302fn dict<'a, const N: usize>(
1307 entries: Dict<'a>,
1308 keys: [&str; N],
1309) -> Result<[Option<RawVariant<'a>>; N]> {
1310 let mut found = [const { None }; N];
1311 for entry in entries {
1312 let (key, value) = entry.map_err(malformed)?;
1313 match keys.iter().position(|k| *k == key) {
1314 Some(i) if found[i].is_none() => found[i] = Some(value),
1315 _ => {
1316 ostrya_gvariant::validate(&value.ty, value.child).map_err(malformed)?;
1317 }
1318 }
1319 }
1320 Ok(found)
1321}
1322
1323fn field<'a, T: GvDecode<'a>>(
1328 entry: Option<RawVariant<'a>>,
1329 key: &str,
1330 ty: &Type,
1331) -> Result<Option<T>> {
1332 let Some(v) = entry else {
1333 return Ok(None);
1334 };
1335 if v.ty != *ty {
1336 return Err(protocol(format!("key {key} has the wrong type")));
1337 }
1338 T::decode(v.child).map(Some).map_err(malformed)
1339}
1340
1341fn required<'a, T: GvDecode<'a>>(entry: Option<RawVariant<'a>>, key: &str, ty: &Type) -> Result<T> {
1345 field(entry, key, ty)?.ok_or_else(|| protocol(format!("HelloReply lacks {key}")))
1346}