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{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>,
50 pub collection: Option<String>,
57 pub one_way: bool,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct HelloReply {
71 pub version: u32,
73 pub mode: String,
75 pub collection_id: Option<String>,
77 pub collection: Option<String>,
83 pub max_frame: u32,
88 pub max_have: u32,
93 pub encodings: Vec<Encoding>,
98 pub parallel_uploads: u32,
104 pub refs: Vec<RefState>,
106}
107
108#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct HaveReply {
115 pub bitmap: Vec<u8>,
117}
118
119impl HaveReply {
120 pub fn from_missing(missing: impl IntoIterator<Item = bool>) -> HaveReply {
125 let mut bitmap = Vec::new();
126 for (i, set) in missing.into_iter().enumerate() {
127 if i % 8 == 0 {
128 bitmap.push(0);
129 }
130 if set {
131 bitmap[i / 8] |= 1 << (i % 8);
132 }
133 }
134 HaveReply { bitmap }
135 }
136
137 pub fn is_missing(&self, index: usize) -> bool {
141 self.bitmap
142 .get(index / 8)
143 .is_some_and(|b| b & (1 << (index % 8)) != 0)
144 }
145
146 pub fn check_len(&self, entries: usize) -> Result<()> {
156 if self.bitmap.len() != entries.div_ceil(8) {
157 return Err(protocol(format!(
158 "HaveReply of {} bytes for {entries} entries",
159 self.bitmap.len()
160 )));
161 }
162 let tail = entries % 8;
163 if tail != 0 && self.bitmap[entries / 8] >> tail != 0 {
164 return Err(protocol("HaveReply sets a bit after the last entry"));
165 }
166 Ok(())
167 }
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct ObjectHeader {
174 pub name: ObjectName,
178 pub encoding: Encoding,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct ObjectsReply {
192 pub objects: u32,
194 pub payload_bytes: u64,
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct CommitRequest {
201 pub updates: Vec<RefUpdate>,
206 pub force: bool,
211 pub server_commit: Option<Box<ServerCommit>>,
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct ServerCommit {
234 pub branch: String,
236 pub tags: Vec<String>,
238 pub bind_refs: Vec<String>,
243 pub root_dirtree: Checksum,
245 pub root_dirmeta: Checksum,
247 pub subject: String,
249 pub body: String,
251 pub metadata: Vec<(String, Vec<u8>)>,
261 pub timestamp: Option<u64>,
267 pub orphan: bool,
272}
273
274#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct ErrorMessage {
280 pub code: ErrorCode,
282 pub message: String,
284 pub missing: Vec<ObjectName>,
290 pub current: Option<RefState>,
297}
298
299#[derive(Debug, Clone, PartialEq, Eq)]
301pub struct PullHello {
302 pub version: u32,
304 pub agent: Option<String>,
306}
307
308#[derive(Debug, Clone, PartialEq, Eq)]
313pub struct PullHelloReply {
314 pub version: u32,
319}
320
321#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct GetReply {
324 pub found: bool,
329 pub len: Option<u64>,
335}
336
337#[derive(Debug, Clone, PartialEq, Eq, Default)]
349pub struct ListRefsRequest {
350 pub refs: Vec<String>,
353 pub collections: Option<Vec<String>>,
360}
361
362#[derive(Debug, Clone, PartialEq, Eq)]
366#[non_exhaustive]
367pub enum Message {
368 Hello(Hello),
370 HelloReply(HelloReply),
372 Have(Vec<ObjectName>),
376 HaveReply(HaveReply),
378 ObjectHeader(ObjectHeader),
380 ObjectsEnd,
382 ObjectsReply(ObjectsReply),
384 Commit(CommitRequest),
386 CommitReply(Vec<RefOutcome>),
389 Error(ErrorMessage),
391 Abort,
393 PullHello(PullHello),
395 PullHelloReply(PullHelloReply),
397 Get(String),
401 GetReply(GetReply),
403 ListRefs(ListRefsRequest),
405}
406
407impl Message {
408 pub fn kind(&self) -> Kind {
410 match self {
411 Message::Hello(_) => Kind::Hello,
412 Message::HelloReply(_) => Kind::HelloReply,
413 Message::Have(_) => Kind::Have,
414 Message::HaveReply(_) => Kind::HaveReply,
415 Message::ObjectHeader(_) => Kind::ObjectHeader,
416 Message::ObjectsEnd => Kind::ObjectsEnd,
417 Message::ObjectsReply(_) => Kind::ObjectsReply,
418 Message::Commit(_) => Kind::Commit,
419 Message::CommitReply(_) => Kind::CommitReply,
420 Message::Error(_) => Kind::Error,
421 Message::Abort => Kind::Abort,
422 Message::PullHello(_) => Kind::PullHello,
423 Message::PullHelloReply(_) => Kind::PullHelloReply,
424 Message::Get(_) => Kind::Get,
425 Message::GetReply(_) => Kind::GetReply,
426 Message::ListRefs(_) => Kind::ListRefs,
427 }
428 }
429
430 pub fn encode_body(&self) -> Result<Vec<u8>> {
450 let (ty, value): (&Type, Value) = match self {
451 Message::Commit(c) => return encode_commit(c),
452 Message::ObjectsEnd => return Ok(Vec::new()),
453 Message::Abort => return Ok(vec![0]),
454 Message::Hello(h) => {
455 let mut opts = DictBuilder::new();
456 if let Some(agent) = &h.agent {
457 opts.insert_str("agent", agent);
458 }
459 if let Some(collection) = &h.collection {
460 opts.insert_str("collection", collection);
461 }
462 if h.one_way {
463 opts.insert_bool("one-way", true);
464 }
465 let refs = h.refs.iter().cloned().map(Value::Str).collect();
466 let v = Value::Tuple(vec![
467 Value::U32(h.version),
468 opts.build(),
469 Value::Array(refs),
470 ]);
471 (&HELLO, v)
472 }
473 Message::HelloReply(r) => {
474 check_limits(r.max_frame, r.max_have, r.parallel_uploads)?;
475 let mut opts = DictBuilder::new();
476 opts.insert_str("mode", &r.mode);
477 if let Some(id) = &r.collection_id {
478 opts.insert_str("collection-id", id);
479 }
480 if let Some(collection) = &r.collection {
481 opts.insert_str("collection", collection);
482 }
483 let encodings: Vec<String> =
484 r.encodings.iter().map(|e| e.as_str().to_owned()).collect();
485 opts.insert("max-frame", Type::U32, Value::U32(r.max_frame))
486 .insert("max-have", Type::U32, Value::U32(r.max_have))
487 .insert_strv("encodings", &encodings)
488 .insert(
489 "parallel-uploads",
490 Type::U32,
491 Value::U32(r.parallel_uploads),
492 );
493 let refs = r
494 .refs
495 .iter()
496 .map(|s| Value::Tuple(vec![Value::Str(s.name.clone()), maybe_value(s.commit)]))
497 .collect();
498 let v = Value::Tuple(vec![
499 Value::U32(r.version),
500 opts.build(),
501 Value::Array(refs),
502 ]);
503 (&HELLO_REPLY, v)
504 }
505 Message::Have(names) => (&OBJECT_NAMES, object_names_value(names)?),
506 Message::HaveReply(r) => (&BYTES, Value::Bytes(r.bitmap.clone())),
507 Message::ObjectHeader(h) => {
508 check_header(&h.name, h.encoding)?;
509 let v = Value::Tuple(vec![
510 Value::Byte(h.name.ty.as_u32() as u8),
511 Value::Bytes(h.name.checksum.as_bytes().to_vec()),
512 Value::Byte(h.encoding.as_u8()),
513 ]);
514 (&OBJECT_HEADER, v)
515 }
516 Message::ObjectsReply(r) => {
517 let v = Value::Tuple(vec![Value::U32(r.objects), Value::U64(r.payload_bytes)]);
518 (&OBJECTS_REPLY, v)
519 }
520 Message::CommitReply(outcomes) => {
521 let v = outcomes
522 .iter()
523 .map(|o| {
524 Value::Tuple(vec![
525 Value::Str(o.name.clone()),
526 maybe_value(o.old),
527 maybe_value(o.new),
528 ])
529 })
530 .collect();
531 (&COMMIT_REPLY, Value::Array(v))
532 }
533 Message::Error(e) => {
534 check_error(e)?;
535 let mut detail = DictBuilder::new();
536 if !e.missing.is_empty() {
537 detail.insert(
538 "missing",
539 OBJECT_NAMES.clone(),
540 object_names_value(&e.missing)?,
541 );
542 }
543 if let Some(state) = &e.current {
544 detail.insert_str("ref", &state.name).insert(
545 "current",
546 MAYBE_CHECKSUM.clone(),
547 maybe_value(state.commit),
548 );
549 }
550 let v = Value::Tuple(vec![
551 Value::Str(e.code.as_str().to_owned()),
552 Value::Str(e.message.clone()),
553 detail.build(),
554 ]);
555 (&ERROR, v)
556 }
557 Message::PullHello(h) => {
558 let mut opts = DictBuilder::new();
559 if let Some(agent) = &h.agent {
560 opts.insert_str("agent", agent);
561 }
562 let v = Value::Tuple(vec![Value::U32(h.version), opts.build()]);
563 (&PULL_HELLO, v)
564 }
565 Message::PullHelloReply(r) => {
566 let v = Value::Tuple(vec![Value::U32(r.version), DictBuilder::new().build()]);
567 (&PULL_HELLO, v)
568 }
569 Message::Get(path) => (&Type::Str, Value::Str(path.clone())),
570 Message::GetReply(r) => {
571 check_get_reply(r)?;
572 let len = Value::Maybe(r.len.map(|n| Box::new(Value::U64(n))));
573 (&GET_REPLY, Value::Tuple(vec![Value::Bool(r.found), len]))
574 }
575 Message::ListRefs(r) => {
576 let mut opts = DictBuilder::new();
577 if let Some(collections) = &r.collections {
578 opts.insert_strv("collections", collections);
579 }
580 let refs = r.refs.iter().cloned().map(Value::Str).collect();
581 (
582 &LIST_REFS,
583 Value::Tuple(vec![Value::Array(refs), opts.build()]),
584 )
585 }
586 };
587 to_bytes(ty, &value).map_err(encode_error)
588 }
589
590 pub fn decode(kind: Kind, body: &[u8]) -> Result<Message> {
621 Ok(match kind {
622 Kind::ObjectsEnd => {
623 if !body.is_empty() {
624 return Err(protocol("ObjectsEnd body is not empty"));
625 }
626 Message::ObjectsEnd
627 }
628 Kind::Abort => {
629 if body != [0] {
630 return Err(protocol("Abort body is not the unit tuple"));
631 }
632 Message::Abort
633 }
634 Kind::Hello => {
635 let (version, opts, refs): (u32, Dict, ArrayIter<&str>) = parse_body(body)?;
636 let [agent, collection, one_way] = dict(opts, ["agent", "collection", "one-way"])?;
637 let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
638 let collection: Option<&str> = field(collection, "collection", &Type::Str)?;
639 let one_way = field(one_way, "one-way", &Type::Bool)?.unwrap_or(false);
640 Message::Hello(Hello {
641 version,
642 agent: agent.map(str::to_owned),
643 refs: collect(refs, |r| Ok(r.to_owned()))?,
644 collection: collection.map(str::to_owned),
645 one_way,
646 })
647 }
648 Kind::HelloReply => Message::HelloReply(decode_hello_reply(body)?),
649 Kind::Have => Message::Have(object_names(parse_body(body)?)?),
650 Kind::HaveReply => {
651 let bitmap: &[u8] = parse_body(body)?;
652 Message::HaveReply(HaveReply {
653 bitmap: bitmap.to_vec(),
654 })
655 }
656 Kind::ObjectHeader => {
657 let (ty, sum, enc): (u8, &[u8], u8) = parse_body(body)?;
658 let name = object_name((ty, sum), header_type)?;
659 let encoding = Encoding::from_u8(enc)?;
660 check_header(&name, encoding)?;
661 Message::ObjectHeader(ObjectHeader { name, encoding })
662 }
663 Kind::ObjectsReply => {
664 let (objects, payload_bytes) = parse_body(body)?;
665 Message::ObjectsReply(ObjectsReply {
666 objects,
667 payload_bytes,
668 })
669 }
670 Kind::Commit => {
671 let (updates, opts): (ArrayIter<UpdateView>, Dict) = parse_body(body)?;
672 let updates = collect(updates, decode_update)?;
673 let [force, server_commit] = dict(opts, ["force", "server-commit"])?;
674 let force = field(force, "force", &Type::Bool)?.unwrap_or(false);
675 let server_commit = field(server_commit, "server-commit", &SERVER_COMMIT)?
676 .map(decode_server_commit)
677 .transpose()?
678 .map(Box::new);
679 Message::Commit(CommitRequest {
680 updates,
681 force,
682 server_commit,
683 })
684 }
685 Kind::CommitReply => {
686 let outcomes: ArrayIter<(&str, MaybeBytes, MaybeBytes)> = parse_body(body)?;
687 Message::CommitReply(collect(outcomes, |(name, old, new)| {
688 Ok(RefOutcome {
689 name: name.to_owned(),
690 old: maybe_checksum(old)?,
691 new: maybe_checksum(new)?,
692 })
693 })?)
694 }
695 Kind::Error => Message::Error(decode_error(body)?),
696 Kind::PullHello => {
697 let (version, opts): (u32, Dict) = parse_body(body)?;
698 let [agent] = dict(opts, ["agent"])?;
699 let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
700 Message::PullHello(PullHello {
701 version,
702 agent: agent.map(str::to_owned),
703 })
704 }
705 Kind::PullHelloReply => {
706 let (version, opts): (u32, Dict) = parse_body(body)?;
707 let [] = dict(opts, [])?;
708 Message::PullHelloReply(PullHelloReply { version })
709 }
710 Kind::Get => {
711 let path: &str = parse_body(body)?;
712 Message::Get(path.to_owned())
713 }
714 Kind::GetReply => {
715 let (found, len): (bool, MaybeU64) = parse_body(body)?;
716 let r = GetReply { found, len: len.0 };
717 check_get_reply(&r)?;
718 Message::GetReply(r)
719 }
720 Kind::ListRefs => {
721 let (refs, opts): (ArrayIter<&str>, Dict) = parse_body(body)?;
722 let [collections] = dict(opts, ["collections"])?;
723 let collections: Option<ArrayIter<&str>> =
724 field(collections, "collections", &STRV)?;
725 Message::ListRefs(ListRefsRequest {
726 refs: collect(refs, |e| Ok(e.to_owned()))?,
727 collections: collections
728 .map(|entries| collect(entries, |e| Ok(e.to_owned())))
729 .transpose()?,
730 })
731 }
732 })
733 }
734}
735
736fn check_limits(max_frame: u32, max_have: u32, parallel_uploads: u32) -> Result<()> {
742 if !(MIN_FRAME_LIMIT..=MAX_FRAME_LIMIT).contains(&max_frame) {
743 return Err(protocol(format!("max-frame {max_frame} is out of range")));
744 }
745 if max_have == 0 || parallel_uploads == 0 {
746 return Err(protocol("max-have and parallel-uploads must be at least 1"));
747 }
748 Ok(())
749}
750
751fn check_error(e: &ErrorMessage) -> Result<()> {
754 if e.code == ErrorCode::RefMismatch && e.current.is_none() {
755 return Err(protocol("ref-mismatch lacks ref and current"));
756 }
757 Ok(())
758}
759
760fn decode_hello_reply(body: &[u8]) -> Result<HelloReply> {
761 let (version, opts, refs): (u32, Dict, ArrayIter<(&str, MaybeBytes)>) = parse_body(body)?;
762 let [
763 mode,
764 collection_id,
765 collection,
766 max_frame,
767 max_have,
768 encodings,
769 parallel_uploads,
770 ] = dict(
771 opts,
772 [
773 "mode",
774 "collection-id",
775 "collection",
776 "max-frame",
777 "max-have",
778 "encodings",
779 "parallel-uploads",
780 ],
781 )?;
782 let mode: &str = required(mode, "mode", &Type::Str)?;
783 let collection_id: Option<&str> = field(collection_id, "collection-id", &Type::Str)?;
784 let collection: Option<&str> = field(collection, "collection", &Type::Str)?;
785 let max_frame = required(max_frame, "max-frame", &Type::U32)?;
786 let max_have = required(max_have, "max-have", &Type::U32)?;
787 let parallel_uploads = required(parallel_uploads, "parallel-uploads", &Type::U32)?;
788 check_limits(max_frame, max_have, parallel_uploads)?;
789 let names: ArrayIter<&str> = required(encodings, "encodings", &STRV)?;
790 let mut encodings = Vec::new();
791 for name in names {
792 encodings.extend(Encoding::from_name(name.map_err(malformed)?));
793 }
794 let refs = collect(refs, |(name, commit)| {
795 Ok(RefState {
796 name: name.to_owned(),
797 commit: maybe_checksum(commit)?,
798 })
799 })?;
800 Ok(HelloReply {
801 version,
802 mode: mode.to_owned(),
803 collection_id: collection_id.map(str::to_owned),
804 collection: collection.map(str::to_owned),
805 max_frame,
806 max_have,
807 encodings,
808 parallel_uploads,
809 refs,
810 })
811}
812
813type UpdateView<'a> = (&'a str, u8, MaybeBytes<'a>, MaybeBytes<'a>);
815
816fn decode_update((name, state, expected, new): UpdateView) -> Result<RefUpdate> {
817 let expected = match (state, maybe_checksum(expected)?) {
818 (0, None) => Expected::Absent,
819 (1, Some(c)) => Expected::Commit(c),
820 (2, None) => Expected::Any,
821 (s @ 0..=2, _) => {
822 return Err(protocol(format!(
823 "expected state {s} does not match its commit"
824 )));
825 }
826 (s, _) => return Err(protocol(format!("unknown expected state {s}"))),
827 };
828 Ok(RefUpdate {
829 name: name.to_owned(),
830 expected,
831 new: maybe_checksum(new)?,
832 })
833}
834
835fn encode_error(e: ostrya_gvariant::Error) -> Error {
837 protocol(format!("encode: {e}"))
838}
839
840fn variant_bytes(ty: Type, value: Value) -> Result<Vec<u8>> {
842 to_bytes(&Type::Variant, &Value::variant(ty, value)).map_err(encode_error)
843}
844
845fn dict_entries<'a>(
848 entries: &'a [(&'static str, Vec<u8>)],
849) -> Vec<(&'static str, VariantSlice<'a>)> {
850 entries
851 .iter()
852 .map(|(key, value)| (*key, VariantSlice { inner: value }))
853 .collect()
854}
855
856fn encode_commit(c: &CommitRequest) -> Result<Vec<u8>> {
863 encode_commit_parts(&c.updates, c.force, c.server_commit.as_deref())
864}
865
866pub(crate) fn server_commit_frame_len(sc: &ServerCommit) -> Result<u64> {
872 Ok(encode_commit_parts(&[], false, Some(sc))?.len() as u64 + 1)
873}
874
875pub(crate) fn check_server_commit_metadata(sc: &ServerCommit) -> Result<()> {
889 for (key, value) in &sc.metadata {
890 let Err(deep) = ostrya_gvariant::validate(&VALUE_IN_COMMIT, value) else {
891 continue;
892 };
893 if let Err(e) = ostrya_gvariant::validate(&Type::Variant, value) {
894 return Err(protocol(format!("encode: metadata entry '{key}': {e}")));
895 }
896 return Err(Error::InvalidInput(format!(
897 "a commit cannot hold the metadata value under '{key}': {deep}"
898 )));
899 }
900 Ok(())
901}
902
903pub(crate) fn server_commit_reply_frame_len(sc: &ServerCommit) -> Result<u64> {
909 let any_commit = Some(Checksum::from_bytes([0; 32]));
910 let refs = std::iter::once(RefOutcome {
911 name: sc.branch.clone(),
912 old: any_commit,
913 new: any_commit,
914 })
915 .chain(sc.tags.iter().map(|tag| RefOutcome {
916 name: tag.clone(),
917 old: None,
918 new: any_commit,
919 }))
920 .collect();
921 Ok(Message::CommitReply(refs).encode_body()?.len() as u64 + 1)
922}
923
924fn encode_commit_parts(
926 updates: &[RefUpdate],
927 force: bool,
928 server_commit: Option<&ServerCommit>,
929) -> Result<Vec<u8>> {
930 let updates = updates
931 .iter()
932 .map(|u| {
933 let (state, expected) = match u.expected {
934 Expected::Absent => (0, None),
935 Expected::Commit(c) => (1, Some(c)),
936 Expected::Any => (2, None),
937 };
938 Value::Tuple(vec![
939 Value::Str(u.name.clone()),
940 Value::Byte(state),
941 maybe_value(expected),
942 maybe_value(u.new),
943 ])
944 })
945 .collect();
946 let updates = to_bytes(&UPDATES, &Value::Array(updates)).map_err(encode_error)?;
947 let mut opts = Vec::new();
948 if force {
949 opts.push(("force", variant_bytes(Type::Bool, Value::Bool(true))?));
950 }
951 if let Some(sc) = server_commit {
952 let mut value = server_commit_bytes(sc)?;
953 value.push(0);
954 value.extend_from_slice(SERVER_COMMIT_SIGNATURE.as_bytes());
955 opts.push(("server-commit", value));
956 }
957 encode_to_vec(&(updates.as_slice(), Slice(&dict_entries(&opts)))).map_err(encode_error)
958}
959
960fn server_commit_bytes(sc: &ServerCommit) -> Result<Vec<u8>> {
965 let tags: Vec<&str> = sc.tags.iter().map(String::as_str).collect();
966 let bind_refs: Vec<&str> = sc.bind_refs.iter().map(String::as_str).collect();
967 let metadata = sc
968 .metadata
969 .iter()
970 .map(|(key, value)| {
971 ostrya_gvariant::validate(&Type::Variant, value)
972 .map_err(|e| protocol(format!("encode: metadata entry '{key}': {e}")))?;
973 Ok((key.as_str(), VariantSlice { inner: value }))
974 })
975 .collect::<Result<Vec<_>>>()?;
976 let mut opts = Vec::new();
977 if let Some(timestamp) = sc.timestamp {
978 opts.push((
979 "timestamp",
980 variant_bytes(Type::U64, Value::U64(timestamp))?,
981 ));
982 }
983 if sc.orphan {
984 opts.push(("orphan", variant_bytes(Type::Bool, Value::Bool(true))?));
985 }
986 encode_to_vec(&(
987 sc.branch.as_str(),
988 Slice(&tags),
989 Slice(&bind_refs),
990 (sc.root_dirtree, sc.root_dirmeta),
991 sc.subject.as_str(),
992 sc.body.as_str(),
993 Slice(&metadata),
994 Slice(&dict_entries(&opts)),
995 ))
996 .map_err(encode_error)
997}
998
999type ServerCommitView<'a> = (
1001 &'a str,
1002 ArrayIter<'a, &'a str>,
1003 ArrayIter<'a, &'a str>,
1004 (&'a [u8], &'a [u8]),
1005 &'a str,
1006 &'a str,
1007 ArrayIter<'a, (&'a str, VariantSlice<'a>)>,
1008 Dict<'a>,
1009);
1010
1011fn decode_server_commit(
1017 (branch, tags, bind_refs, (dirtree, dirmeta), subject, body, metadata, opts): ServerCommitView,
1018) -> Result<ServerCommit> {
1019 let [timestamp, orphan] = dict(opts, ["timestamp", "orphan"])?;
1020 let timestamp = field(timestamp, "timestamp", &Type::U64)?;
1021 let orphan = field(orphan, "orphan", &Type::Bool)?.unwrap_or(false);
1022 let metadata = collect(metadata, |(key, value)| {
1023 ostrya_gvariant::validate(&Type::Variant, value.inner).map_err(malformed)?;
1024 Ok((key.to_owned(), value.inner.to_vec()))
1025 })?;
1026 Ok(ServerCommit {
1027 branch: branch.to_owned(),
1028 tags: collect(tags, |t| Ok(t.to_owned()))?,
1029 bind_refs: collect(bind_refs, |n| Ok(n.to_owned()))?,
1030 root_dirtree: checksum(dirtree)?,
1031 root_dirmeta: checksum(dirmeta)?,
1032 subject: subject.to_owned(),
1033 body: body.to_owned(),
1034 metadata,
1035 timestamp,
1036 orphan,
1037 })
1038}
1039
1040fn decode_error(body: &[u8]) -> Result<ErrorMessage> {
1041 let (name, message, detail): (&str, &str, Dict) = parse_body(body)?;
1042 let code =
1043 ErrorCode::from_name(name).ok_or_else(|| protocol(format!("unknown error code {name}")))?;
1044 let [missing, ref_name, current] = dict(detail, ["missing", "ref", "current"])?;
1045 let missing = match field(missing, "missing", &OBJECT_NAMES)? {
1046 Some(names) => object_names(names)?,
1047 None => Vec::new(),
1048 };
1049 let ref_name: Option<&str> = field(ref_name, "ref", &Type::Str)?;
1050 let current = match (ref_name, field(current, "current", &MAYBE_CHECKSUM)?) {
1051 (Some(name), Some(commit)) => Some(RefState {
1052 name: name.to_owned(),
1053 commit: maybe_checksum(commit)?,
1054 }),
1055 (None, None) => None,
1056 _ => return Err(protocol("Error carries one of ref and current alone")),
1057 };
1058 let e = ErrorMessage {
1059 code,
1060 message: message.to_owned(),
1061 missing,
1062 current,
1063 };
1064 check_error(&e)?;
1065 Ok(e)
1066}
1067
1068fn check_get_reply(r: &GetReply) -> Result<()> {
1070 if !r.found && r.len.is_some() {
1071 return Err(protocol("GetReply with found false carries a length"));
1072 }
1073 Ok(())
1074}
1075
1076fn check_header(name: &ObjectName, encoding: Encoding) -> Result<()> {
1079 if !header_type(name.ty) {
1080 return Err(protocol(format!(
1081 "object type {} is not allowed in ObjectHeader",
1082 name.ty.as_u32()
1083 )));
1084 }
1085 if encoding == Encoding::Deflate && name.ty != ObjectType::File {
1086 return Err(protocol("deflate is allowed for a file object alone"));
1087 }
1088 Ok(())
1089}
1090
1091pub(super) const OBJECT_HEADER_FRAME: usize = 40;
1094
1095pub(super) fn object_header_frame(h: &ObjectHeader) -> Result<[u8; OBJECT_HEADER_FRAME]> {
1101 check_header(&h.name, h.encoding)?;
1102 let mut frame = [0u8; OBJECT_HEADER_FRAME];
1103 frame[..4].copy_from_slice(&(OBJECT_HEADER_FRAME as u32 - 4).to_be_bytes());
1104 frame[4] = Kind::ObjectHeader.as_u8();
1105 frame[5] = h.name.ty.as_u32() as u8;
1106 frame[6..38].copy_from_slice(h.name.checksum.as_bytes());
1107 frame[38] = h.encoding.as_u8();
1108 frame[39] = 33;
1109 Ok(frame)
1110}
1111
1112pub(super) const GET_REPLY_FRAME: usize = 21;
1115
1116pub(super) fn get_reply_frame(r: &GetReply) -> Result<([u8; GET_REPLY_FRAME], usize)> {
1127 check_get_reply(r)?;
1128 let mut frame = [0u8; GET_REPLY_FRAME];
1129 let used = match r.len {
1130 Some(len) => {
1131 frame[13..].copy_from_slice(&len.to_le_bytes());
1132 GET_REPLY_FRAME
1133 }
1134 None => 13,
1135 };
1136 frame[..4].copy_from_slice(&(used as u32 - 4).to_be_bytes());
1137 frame[4] = Kind::GetReply.as_u8();
1138 frame[5] = u8::from(r.found);
1139 Ok((frame, used))
1140}
1141
1142fn object_names_value(names: &[ObjectName]) -> Result<Value> {
1143 if let Some(bad) = names.iter().find(|n| !have_type(n.ty)) {
1144 return Err(protocol(format!(
1145 "object type {} is not allowed in an object list",
1146 bad.ty.as_u32()
1147 )));
1148 }
1149 Ok(Value::Array(names.iter().map(object_name_value).collect()))
1150}
1151
1152fn object_names(names: ArrayIter<(u8, &[u8])>) -> Result<Vec<ObjectName>> {
1153 collect(names, |e| object_name(e, have_type))
1154}
1155
1156fn malformed(e: ostrya_gvariant::Error) -> Error {
1157 protocol(format!("malformed body: {e}"))
1158}
1159
1160fn parse_body<'a, T: GvDecode<'a>>(body: &'a [u8]) -> Result<T> {
1161 T::decode(body).map_err(malformed)
1162}
1163
1164fn collect<'a, E: GvDecode<'a> + Copy, T>(
1169 items: ArrayIter<'a, E>,
1170 mut f: impl FnMut(E) -> Result<T>,
1171) -> Result<Vec<T>> {
1172 let mut out = Vec::with_capacity(items.count());
1173 for e in items {
1174 out.push(f(e.map_err(malformed)?)?);
1175 }
1176 Ok(out)
1177}
1178
1179fn maybe_checksum(m: MaybeBytes) -> Result<Option<Checksum>> {
1180 m.0.map(checksum).transpose()
1181}
1182
1183#[derive(Clone, Copy)]
1186struct MaybeBytes<'a>(Option<&'a [u8]>);
1187
1188impl GvType for MaybeBytes<'_> {
1189 const ALIGNMENT: usize = 1;
1190 const FIXED_SIZE: Option<usize> = None;
1191}
1192
1193impl<'a> GvDecode<'a> for MaybeBytes<'a> {
1194 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1195 match data.split_last() {
1196 None => Ok(MaybeBytes(None)),
1197 Some((0, rest)) => Ok(MaybeBytes(Some(rest))),
1198 Some(_) => Err(ostrya_gvariant::Error::NotNormal(
1199 "maybe lacks its terminating zero byte",
1200 )),
1201 }
1202 }
1203}
1204
1205struct MaybeU64(Option<u64>);
1209
1210impl GvType for MaybeU64 {
1211 const ALIGNMENT: usize = 8;
1212 const FIXED_SIZE: Option<usize> = None;
1213}
1214
1215impl<'a> GvDecode<'a> for MaybeU64 {
1216 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1217 match data.len() {
1218 0 => Ok(MaybeU64(None)),
1219 8 => u64::decode(data).map(|n| MaybeU64(Some(n))),
1220 _ => Err(ostrya_gvariant::Error::NotNormal(
1221 "maybe of a u64 is not 0 or 8 bytes",
1222 )),
1223 }
1224 }
1225}
1226
1227struct RawVariant<'a> {
1230 ty: Type,
1231 child: &'a [u8],
1232}
1233
1234impl GvType for RawVariant<'_> {
1235 const ALIGNMENT: usize = 8;
1236 const FIXED_SIZE: Option<usize> = None;
1237}
1238
1239impl<'a> GvDecode<'a> for RawVariant<'a> {
1240 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1241 let not_normal = ostrya_gvariant::Error::NotNormal;
1242 let sep = data
1243 .iter()
1244 .rposition(|&b| b == 0)
1245 .ok_or(not_normal("variant lacks a type separator"))?;
1246 let signature = std::str::from_utf8(&data[sep + 1..])
1247 .map_err(|_| not_normal("variant type signature is not UTF-8"))?;
1248 let ty =
1249 Type::parse(signature).map_err(|_| not_normal("variant type signature is invalid"))?;
1250 Ok(RawVariant {
1251 ty,
1252 child: &data[..sep],
1253 })
1254 }
1255}
1256
1257type Dict<'a> = ArrayIter<'a, (&'a str, RawVariant<'a>)>;
1259
1260#[derive(Clone, Copy)]
1262struct VariantSlice<'a> {
1263 inner: &'a [u8],
1264}
1265
1266impl GvType for VariantSlice<'_> {
1267 const ALIGNMENT: usize = 8;
1268 const FIXED_SIZE: Option<usize> = None;
1269}
1270
1271impl<'a> GvDecode<'a> for VariantSlice<'a> {
1272 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1273 Ok(VariantSlice { inner: data })
1274 }
1275}
1276
1277impl GvEncode for VariantSlice<'_> {
1278 fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
1279 out.extend_from_slice(self.inner);
1280 Ok(())
1281 }
1282}
1283
1284fn dict<'a, const N: usize>(
1289 entries: Dict<'a>,
1290 keys: [&str; N],
1291) -> Result<[Option<RawVariant<'a>>; N]> {
1292 let mut found = [const { None }; N];
1293 for entry in entries {
1294 let (key, value) = entry.map_err(malformed)?;
1295 match keys.iter().position(|k| *k == key) {
1296 Some(i) if found[i].is_none() => found[i] = Some(value),
1297 _ => {
1298 ostrya_gvariant::validate(&value.ty, value.child).map_err(malformed)?;
1299 }
1300 }
1301 }
1302 Ok(found)
1303}
1304
1305fn field<'a, T: GvDecode<'a>>(
1310 entry: Option<RawVariant<'a>>,
1311 key: &str,
1312 ty: &Type,
1313) -> Result<Option<T>> {
1314 let Some(v) = entry else {
1315 return Ok(None);
1316 };
1317 if v.ty != *ty {
1318 return Err(protocol(format!("key {key} has the wrong type")));
1319 }
1320 T::decode(v.child).map(Some).map_err(malformed)
1321}
1322
1323fn required<'a, T: GvDecode<'a>>(entry: Option<RawVariant<'a>>, key: &str, ty: &Type) -> Result<T> {
1327 field(entry, key, ty)?.ok_or_else(|| protocol(format!("HelloReply lacks {key}")))
1328}