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>,
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 timestamp: Option<u64>,
265 pub orphan: bool,
270}
271
272#[derive(Debug, Clone, PartialEq, Eq)]
277pub struct ErrorMessage {
278 pub code: ErrorCode,
280 pub message: String,
282 pub missing: Vec<ObjectName>,
288 pub current: Option<RefState>,
295}
296
297#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct PullHello {
300 pub version: u32,
302 pub agent: Option<String>,
304}
305
306#[derive(Debug, Clone, PartialEq, Eq)]
311pub struct PullHelloReply {
312 pub version: u32,
317}
318
319#[derive(Debug, Clone, PartialEq, Eq)]
321pub struct GetReply {
322 pub found: bool,
327 pub len: Option<u64>,
333}
334
335#[derive(Debug, Clone, PartialEq, Eq, Default)]
347pub struct ListRefsRequest {
348 pub refs: Vec<String>,
351 pub collections: Option<Vec<String>>,
358}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
364#[non_exhaustive]
365pub enum Message {
366 Hello(Hello),
368 HelloReply(HelloReply),
370 Have(Vec<ObjectName>),
374 HaveReply(HaveReply),
376 ObjectHeader(ObjectHeader),
378 ObjectsEnd,
380 ObjectsReply(ObjectsReply),
382 Commit(CommitRequest),
384 CommitReply(Vec<RefOutcome>),
387 Error(ErrorMessage),
389 Abort,
391 PullHello(PullHello),
393 PullHelloReply(PullHelloReply),
395 Get(String),
399 GetReply(GetReply),
401 ListRefs(ListRefsRequest),
403}
404
405impl Message {
406 pub fn kind(&self) -> Kind {
408 match self {
409 Message::Hello(_) => Kind::Hello,
410 Message::HelloReply(_) => Kind::HelloReply,
411 Message::Have(_) => Kind::Have,
412 Message::HaveReply(_) => Kind::HaveReply,
413 Message::ObjectHeader(_) => Kind::ObjectHeader,
414 Message::ObjectsEnd => Kind::ObjectsEnd,
415 Message::ObjectsReply(_) => Kind::ObjectsReply,
416 Message::Commit(_) => Kind::Commit,
417 Message::CommitReply(_) => Kind::CommitReply,
418 Message::Error(_) => Kind::Error,
419 Message::Abort => Kind::Abort,
420 Message::PullHello(_) => Kind::PullHello,
421 Message::PullHelloReply(_) => Kind::PullHelloReply,
422 Message::Get(_) => Kind::Get,
423 Message::GetReply(_) => Kind::GetReply,
424 Message::ListRefs(_) => Kind::ListRefs,
425 }
426 }
427
428 pub fn encode_body(&self) -> Result<Vec<u8>> {
448 let (ty, value): (&Type, Value) = match self {
449 Message::Commit(c) => return encode_commit(c),
450 Message::ObjectsEnd => return Ok(Vec::new()),
451 Message::Abort => return Ok(vec![0]),
452 Message::Hello(h) => {
453 let mut opts = DictBuilder::new();
454 if let Some(agent) = &h.agent {
455 opts.insert_str("agent", agent);
456 }
457 if h.one_way {
458 opts.insert_bool("one-way", true);
459 }
460 let refs = h.refs.iter().cloned().map(Value::Str).collect();
461 let v = Value::Tuple(vec![
462 Value::U32(h.version),
463 opts.build(),
464 Value::Array(refs),
465 ]);
466 (&HELLO, v)
467 }
468 Message::HelloReply(r) => {
469 check_limits(r.max_frame, r.max_have, r.parallel_uploads)?;
470 let mut opts = DictBuilder::new();
471 opts.insert_str("mode", &r.mode);
472 if let Some(id) = &r.collection_id {
473 opts.insert_str("collection-id", id);
474 }
475 let encodings: Vec<String> =
476 r.encodings.iter().map(|e| e.as_str().to_owned()).collect();
477 opts.insert("max-frame", Type::U32, Value::U32(r.max_frame))
478 .insert("max-have", Type::U32, Value::U32(r.max_have))
479 .insert_strv("encodings", &encodings)
480 .insert(
481 "parallel-uploads",
482 Type::U32,
483 Value::U32(r.parallel_uploads),
484 );
485 let refs = r
486 .refs
487 .iter()
488 .map(|s| Value::Tuple(vec![Value::Str(s.name.clone()), maybe_value(s.commit)]))
489 .collect();
490 let v = Value::Tuple(vec![
491 Value::U32(r.version),
492 opts.build(),
493 Value::Array(refs),
494 ]);
495 (&HELLO_REPLY, v)
496 }
497 Message::Have(names) => (&OBJECT_NAMES, object_names_value(names)?),
498 Message::HaveReply(r) => (&BYTES, Value::Bytes(r.bitmap.clone())),
499 Message::ObjectHeader(h) => {
500 check_header(&h.name, h.encoding)?;
501 let v = Value::Tuple(vec![
502 Value::Byte(h.name.ty.as_u32() as u8),
503 Value::Bytes(h.name.checksum.as_bytes().to_vec()),
504 Value::Byte(h.encoding.as_u8()),
505 ]);
506 (&OBJECT_HEADER, v)
507 }
508 Message::ObjectsReply(r) => {
509 let v = Value::Tuple(vec![Value::U32(r.objects), Value::U64(r.payload_bytes)]);
510 (&OBJECTS_REPLY, v)
511 }
512 Message::CommitReply(outcomes) => {
513 let v = outcomes
514 .iter()
515 .map(|o| {
516 Value::Tuple(vec![
517 Value::Str(o.name.clone()),
518 maybe_value(o.old),
519 maybe_value(o.new),
520 ])
521 })
522 .collect();
523 (&COMMIT_REPLY, Value::Array(v))
524 }
525 Message::Error(e) => {
526 check_error(e)?;
527 let mut detail = DictBuilder::new();
528 if !e.missing.is_empty() {
529 detail.insert(
530 "missing",
531 OBJECT_NAMES.clone(),
532 object_names_value(&e.missing)?,
533 );
534 }
535 if let Some(state) = &e.current {
536 detail.insert_str("ref", &state.name).insert(
537 "current",
538 MAYBE_CHECKSUM.clone(),
539 maybe_value(state.commit),
540 );
541 }
542 let v = Value::Tuple(vec![
543 Value::Str(e.code.as_str().to_owned()),
544 Value::Str(e.message.clone()),
545 detail.build(),
546 ]);
547 (&ERROR, v)
548 }
549 Message::PullHello(h) => {
550 let mut opts = DictBuilder::new();
551 if let Some(agent) = &h.agent {
552 opts.insert_str("agent", agent);
553 }
554 let v = Value::Tuple(vec![Value::U32(h.version), opts.build()]);
555 (&PULL_HELLO, v)
556 }
557 Message::PullHelloReply(r) => {
558 let v = Value::Tuple(vec![Value::U32(r.version), DictBuilder::new().build()]);
559 (&PULL_HELLO, v)
560 }
561 Message::Get(path) => (&Type::Str, Value::Str(path.clone())),
562 Message::GetReply(r) => {
563 check_get_reply(r)?;
564 let len = Value::Maybe(r.len.map(|n| Box::new(Value::U64(n))));
565 (&GET_REPLY, Value::Tuple(vec![Value::Bool(r.found), len]))
566 }
567 Message::ListRefs(r) => {
568 let mut opts = DictBuilder::new();
569 if let Some(collections) = &r.collections {
570 opts.insert_strv("collections", collections);
571 }
572 let refs = r.refs.iter().cloned().map(Value::Str).collect();
573 (
574 &LIST_REFS,
575 Value::Tuple(vec![Value::Array(refs), opts.build()]),
576 )
577 }
578 };
579 to_bytes(ty, &value).map_err(encode_error)
580 }
581
582 pub fn decode(kind: Kind, body: &[u8]) -> Result<Message> {
613 Ok(match kind {
614 Kind::ObjectsEnd => {
615 if !body.is_empty() {
616 return Err(protocol("ObjectsEnd body is not empty"));
617 }
618 Message::ObjectsEnd
619 }
620 Kind::Abort => {
621 if body != [0] {
622 return Err(protocol("Abort body is not the unit tuple"));
623 }
624 Message::Abort
625 }
626 Kind::Hello => {
627 let (version, opts, refs): (u32, Dict, ArrayIter<&str>) = parse_body(body)?;
628 let [agent, one_way] = dict(opts, ["agent", "one-way"])?;
629 let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
630 let one_way = field(one_way, "one-way", &Type::Bool)?.unwrap_or(false);
631 Message::Hello(Hello {
632 version,
633 agent: agent.map(str::to_owned),
634 refs: collect(refs, |r| Ok(r.to_owned()))?,
635 one_way,
636 })
637 }
638 Kind::HelloReply => Message::HelloReply(decode_hello_reply(body)?),
639 Kind::Have => Message::Have(object_names(parse_body(body)?)?),
640 Kind::HaveReply => {
641 let bitmap: &[u8] = parse_body(body)?;
642 Message::HaveReply(HaveReply {
643 bitmap: bitmap.to_vec(),
644 })
645 }
646 Kind::ObjectHeader => {
647 let (ty, sum, enc): (u8, &[u8], u8) = parse_body(body)?;
648 let name = object_name((ty, sum), header_type)?;
649 let encoding = Encoding::from_u8(enc)?;
650 check_header(&name, encoding)?;
651 Message::ObjectHeader(ObjectHeader { name, encoding })
652 }
653 Kind::ObjectsReply => {
654 let (objects, payload_bytes) = parse_body(body)?;
655 Message::ObjectsReply(ObjectsReply {
656 objects,
657 payload_bytes,
658 })
659 }
660 Kind::Commit => {
661 let (updates, opts): (ArrayIter<UpdateView>, Dict) = parse_body(body)?;
662 let updates = collect(updates, decode_update)?;
663 let [force, server_commit] = dict(opts, ["force", "server-commit"])?;
664 let force = field(force, "force", &Type::Bool)?.unwrap_or(false);
665 let server_commit = field(server_commit, "server-commit", &SERVER_COMMIT)?
666 .map(decode_server_commit)
667 .transpose()?
668 .map(Box::new);
669 Message::Commit(CommitRequest {
670 updates,
671 force,
672 server_commit,
673 })
674 }
675 Kind::CommitReply => {
676 let outcomes: ArrayIter<(&str, MaybeBytes, MaybeBytes)> = parse_body(body)?;
677 Message::CommitReply(collect(outcomes, |(name, old, new)| {
678 Ok(RefOutcome {
679 name: name.to_owned(),
680 old: maybe_checksum(old)?,
681 new: maybe_checksum(new)?,
682 })
683 })?)
684 }
685 Kind::Error => Message::Error(decode_error(body)?),
686 Kind::PullHello => {
687 let (version, opts): (u32, Dict) = parse_body(body)?;
688 let [agent] = dict(opts, ["agent"])?;
689 let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
690 Message::PullHello(PullHello {
691 version,
692 agent: agent.map(str::to_owned),
693 })
694 }
695 Kind::PullHelloReply => {
696 let (version, opts): (u32, Dict) = parse_body(body)?;
697 let [] = dict(opts, [])?;
698 Message::PullHelloReply(PullHelloReply { version })
699 }
700 Kind::Get => {
701 let path: &str = parse_body(body)?;
702 Message::Get(path.to_owned())
703 }
704 Kind::GetReply => {
705 let (found, len): (bool, MaybeU64) = parse_body(body)?;
706 let r = GetReply { found, len: len.0 };
707 check_get_reply(&r)?;
708 Message::GetReply(r)
709 }
710 Kind::ListRefs => {
711 let (refs, opts): (ArrayIter<&str>, Dict) = parse_body(body)?;
712 let [collections] = dict(opts, ["collections"])?;
713 let collections: Option<ArrayIter<&str>> =
714 field(collections, "collections", &STRV)?;
715 Message::ListRefs(ListRefsRequest {
716 refs: collect(refs, |e| Ok(e.to_owned()))?,
717 collections: collections
718 .map(|entries| collect(entries, |e| Ok(e.to_owned())))
719 .transpose()?,
720 })
721 }
722 })
723 }
724}
725
726fn check_limits(max_frame: u32, max_have: u32, parallel_uploads: u32) -> Result<()> {
732 if !(MIN_FRAME_LIMIT..=MAX_FRAME_LIMIT).contains(&max_frame) {
733 return Err(protocol(format!("max-frame {max_frame} is out of range")));
734 }
735 if max_have == 0 || parallel_uploads == 0 {
736 return Err(protocol("max-have and parallel-uploads must be at least 1"));
737 }
738 Ok(())
739}
740
741fn check_error(e: &ErrorMessage) -> Result<()> {
744 if e.code == ErrorCode::RefMismatch && e.current.is_none() {
745 return Err(protocol("ref-mismatch lacks ref and current"));
746 }
747 Ok(())
748}
749
750fn decode_hello_reply(body: &[u8]) -> Result<HelloReply> {
751 let (version, opts, refs): (u32, Dict, ArrayIter<(&str, MaybeBytes)>) = parse_body(body)?;
752 let [
753 mode,
754 collection_id,
755 max_frame,
756 max_have,
757 encodings,
758 parallel_uploads,
759 ] = dict(
760 opts,
761 [
762 "mode",
763 "collection-id",
764 "max-frame",
765 "max-have",
766 "encodings",
767 "parallel-uploads",
768 ],
769 )?;
770 let mode: &str = required(mode, "mode", &Type::Str)?;
771 let collection_id: Option<&str> = field(collection_id, "collection-id", &Type::Str)?;
772 let max_frame = required(max_frame, "max-frame", &Type::U32)?;
773 let max_have = required(max_have, "max-have", &Type::U32)?;
774 let parallel_uploads = required(parallel_uploads, "parallel-uploads", &Type::U32)?;
775 check_limits(max_frame, max_have, parallel_uploads)?;
776 let names: ArrayIter<&str> = required(encodings, "encodings", &STRV)?;
777 let mut encodings = Vec::new();
778 for name in names {
779 encodings.extend(Encoding::from_name(name.map_err(malformed)?));
780 }
781 let refs = collect(refs, |(name, commit)| {
782 Ok(RefState {
783 name: name.to_owned(),
784 commit: maybe_checksum(commit)?,
785 })
786 })?;
787 Ok(HelloReply {
788 version,
789 mode: mode.to_owned(),
790 collection_id: collection_id.map(str::to_owned),
791 max_frame,
792 max_have,
793 encodings,
794 parallel_uploads,
795 refs,
796 })
797}
798
799type UpdateView<'a> = (&'a str, u8, MaybeBytes<'a>, MaybeBytes<'a>);
801
802fn decode_update((name, state, expected, new): UpdateView) -> Result<RefUpdate> {
803 let expected = match (state, maybe_checksum(expected)?) {
804 (0, None) => Expected::Absent,
805 (1, Some(c)) => Expected::Commit(c),
806 (2, None) => Expected::Any,
807 (s @ 0..=2, _) => {
808 return Err(protocol(format!(
809 "expected state {s} does not match its commit"
810 )));
811 }
812 (s, _) => return Err(protocol(format!("unknown expected state {s}"))),
813 };
814 Ok(RefUpdate {
815 name: name.to_owned(),
816 expected,
817 new: maybe_checksum(new)?,
818 })
819}
820
821fn encode_error(e: ostrya_gvariant::Error) -> Error {
823 protocol(format!("encode: {e}"))
824}
825
826fn variant_bytes(ty: Type, value: Value) -> Result<Vec<u8>> {
828 to_bytes(&Type::Variant, &Value::variant(ty, value)).map_err(encode_error)
829}
830
831fn dict_entries<'a>(
834 entries: &'a [(&'static str, Vec<u8>)],
835) -> Vec<(&'static str, VariantSlice<'a>)> {
836 entries
837 .iter()
838 .map(|(key, value)| (*key, VariantSlice { inner: value }))
839 .collect()
840}
841
842fn encode_commit(c: &CommitRequest) -> Result<Vec<u8>> {
849 encode_commit_parts(&c.updates, c.force, c.server_commit.as_deref())
850}
851
852pub(crate) fn server_commit_frame_len(sc: &ServerCommit) -> Result<u64> {
858 Ok(encode_commit_parts(&[], false, Some(sc))?.len() as u64 + 1)
859}
860
861pub(crate) fn check_server_commit_metadata(sc: &ServerCommit) -> Result<()> {
875 for (key, value) in &sc.metadata {
876 let Err(deep) = ostrya_gvariant::validate(&VALUE_IN_COMMIT, value) else {
877 continue;
878 };
879 if let Err(e) = ostrya_gvariant::validate(&Type::Variant, value) {
880 return Err(protocol(format!("encode: metadata entry '{key}': {e}")));
881 }
882 return Err(Error::InvalidInput(format!(
883 "a commit cannot hold the metadata value under '{key}': {deep}"
884 )));
885 }
886 Ok(())
887}
888
889pub(crate) fn server_commit_reply_frame_len(sc: &ServerCommit) -> Result<u64> {
895 let any_commit = Some(Checksum::from_bytes([0; 32]));
896 let refs = std::iter::once(RefOutcome {
897 name: sc.branch.clone(),
898 old: any_commit,
899 new: any_commit,
900 })
901 .chain(sc.tags.iter().map(|tag| RefOutcome {
902 name: tag.clone(),
903 old: None,
904 new: any_commit,
905 }))
906 .collect();
907 Ok(Message::CommitReply(refs).encode_body()?.len() as u64 + 1)
908}
909
910fn encode_commit_parts(
912 updates: &[RefUpdate],
913 force: bool,
914 server_commit: Option<&ServerCommit>,
915) -> Result<Vec<u8>> {
916 let updates = updates
917 .iter()
918 .map(|u| {
919 let (state, expected) = match u.expected {
920 Expected::Absent => (0, None),
921 Expected::Commit(c) => (1, Some(c)),
922 Expected::Any => (2, None),
923 };
924 Value::Tuple(vec![
925 Value::Str(u.name.clone()),
926 Value::Byte(state),
927 maybe_value(expected),
928 maybe_value(u.new),
929 ])
930 })
931 .collect();
932 let updates = to_bytes(&UPDATES, &Value::Array(updates)).map_err(encode_error)?;
933 let mut opts = Vec::new();
934 if force {
935 opts.push(("force", variant_bytes(Type::Bool, Value::Bool(true))?));
936 }
937 if let Some(sc) = server_commit {
938 let mut value = server_commit_bytes(sc)?;
939 value.push(0);
940 value.extend_from_slice(SERVER_COMMIT_SIGNATURE.as_bytes());
941 opts.push(("server-commit", value));
942 }
943 encode_to_vec(&(updates.as_slice(), Slice(&dict_entries(&opts)))).map_err(encode_error)
944}
945
946fn server_commit_bytes(sc: &ServerCommit) -> Result<Vec<u8>> {
951 let tags: Vec<&str> = sc.tags.iter().map(String::as_str).collect();
952 let bind_refs: Vec<&str> = sc.bind_refs.iter().map(String::as_str).collect();
953 let metadata = sc
954 .metadata
955 .iter()
956 .map(|(key, value)| {
957 ostrya_gvariant::validate(&Type::Variant, value)
958 .map_err(|e| protocol(format!("encode: metadata entry '{key}': {e}")))?;
959 Ok((key.as_str(), VariantSlice { inner: value }))
960 })
961 .collect::<Result<Vec<_>>>()?;
962 let mut opts = Vec::new();
963 if let Some(timestamp) = sc.timestamp {
964 opts.push((
965 "timestamp",
966 variant_bytes(Type::U64, Value::U64(timestamp))?,
967 ));
968 }
969 if sc.orphan {
970 opts.push(("orphan", variant_bytes(Type::Bool, Value::Bool(true))?));
971 }
972 encode_to_vec(&(
973 sc.branch.as_str(),
974 Slice(&tags),
975 Slice(&bind_refs),
976 (sc.root_dirtree, sc.root_dirmeta),
977 sc.subject.as_str(),
978 sc.body.as_str(),
979 Slice(&metadata),
980 Slice(&dict_entries(&opts)),
981 ))
982 .map_err(encode_error)
983}
984
985type ServerCommitView<'a> = (
987 &'a str,
988 ArrayIter<'a, &'a str>,
989 ArrayIter<'a, &'a str>,
990 (&'a [u8], &'a [u8]),
991 &'a str,
992 &'a str,
993 ArrayIter<'a, (&'a str, VariantSlice<'a>)>,
994 Dict<'a>,
995);
996
997fn decode_server_commit(
1003 (branch, tags, bind_refs, (dirtree, dirmeta), subject, body, metadata, opts): ServerCommitView,
1004) -> Result<ServerCommit> {
1005 let [timestamp, orphan] = dict(opts, ["timestamp", "orphan"])?;
1006 let timestamp = field(timestamp, "timestamp", &Type::U64)?;
1007 let orphan = field(orphan, "orphan", &Type::Bool)?.unwrap_or(false);
1008 let metadata = collect(metadata, |(key, value)| {
1009 ostrya_gvariant::validate(&Type::Variant, value.inner).map_err(malformed)?;
1010 Ok((key.to_owned(), value.inner.to_vec()))
1011 })?;
1012 Ok(ServerCommit {
1013 branch: branch.to_owned(),
1014 tags: collect(tags, |t| Ok(t.to_owned()))?,
1015 bind_refs: collect(bind_refs, |n| Ok(n.to_owned()))?,
1016 root_dirtree: checksum(dirtree)?,
1017 root_dirmeta: checksum(dirmeta)?,
1018 subject: subject.to_owned(),
1019 body: body.to_owned(),
1020 metadata,
1021 timestamp,
1022 orphan,
1023 })
1024}
1025
1026fn decode_error(body: &[u8]) -> Result<ErrorMessage> {
1027 let (name, message, detail): (&str, &str, Dict) = parse_body(body)?;
1028 let code =
1029 ErrorCode::from_name(name).ok_or_else(|| protocol(format!("unknown error code {name}")))?;
1030 let [missing, ref_name, current] = dict(detail, ["missing", "ref", "current"])?;
1031 let missing = match field(missing, "missing", &OBJECT_NAMES)? {
1032 Some(names) => object_names(names)?,
1033 None => Vec::new(),
1034 };
1035 let ref_name: Option<&str> = field(ref_name, "ref", &Type::Str)?;
1036 let current = match (ref_name, field(current, "current", &MAYBE_CHECKSUM)?) {
1037 (Some(name), Some(commit)) => Some(RefState {
1038 name: name.to_owned(),
1039 commit: maybe_checksum(commit)?,
1040 }),
1041 (None, None) => None,
1042 _ => return Err(protocol("Error carries one of ref and current alone")),
1043 };
1044 let e = ErrorMessage {
1045 code,
1046 message: message.to_owned(),
1047 missing,
1048 current,
1049 };
1050 check_error(&e)?;
1051 Ok(e)
1052}
1053
1054fn check_get_reply(r: &GetReply) -> Result<()> {
1056 if !r.found && r.len.is_some() {
1057 return Err(protocol("GetReply with found false carries a length"));
1058 }
1059 Ok(())
1060}
1061
1062fn check_header(name: &ObjectName, encoding: Encoding) -> Result<()> {
1065 if !header_type(name.ty) {
1066 return Err(protocol(format!(
1067 "object type {} is not allowed in ObjectHeader",
1068 name.ty.as_u32()
1069 )));
1070 }
1071 if encoding == Encoding::Deflate && name.ty != ObjectType::File {
1072 return Err(protocol("deflate is allowed for a file object alone"));
1073 }
1074 Ok(())
1075}
1076
1077pub(super) const OBJECT_HEADER_FRAME: usize = 40;
1080
1081pub(super) fn object_header_frame(h: &ObjectHeader) -> Result<[u8; OBJECT_HEADER_FRAME]> {
1087 check_header(&h.name, h.encoding)?;
1088 let mut frame = [0u8; OBJECT_HEADER_FRAME];
1089 frame[..4].copy_from_slice(&(OBJECT_HEADER_FRAME as u32 - 4).to_be_bytes());
1090 frame[4] = Kind::ObjectHeader.as_u8();
1091 frame[5] = h.name.ty.as_u32() as u8;
1092 frame[6..38].copy_from_slice(h.name.checksum.as_bytes());
1093 frame[38] = h.encoding.as_u8();
1094 frame[39] = 33;
1095 Ok(frame)
1096}
1097
1098pub(super) const GET_REPLY_FRAME: usize = 21;
1101
1102pub(super) fn get_reply_frame(r: &GetReply) -> Result<([u8; GET_REPLY_FRAME], usize)> {
1113 check_get_reply(r)?;
1114 let mut frame = [0u8; GET_REPLY_FRAME];
1115 let used = match r.len {
1116 Some(len) => {
1117 frame[13..].copy_from_slice(&len.to_le_bytes());
1118 GET_REPLY_FRAME
1119 }
1120 None => 13,
1121 };
1122 frame[..4].copy_from_slice(&(used as u32 - 4).to_be_bytes());
1123 frame[4] = Kind::GetReply.as_u8();
1124 frame[5] = u8::from(r.found);
1125 Ok((frame, used))
1126}
1127
1128fn object_names_value(names: &[ObjectName]) -> Result<Value> {
1129 if let Some(bad) = names.iter().find(|n| !have_type(n.ty)) {
1130 return Err(protocol(format!(
1131 "object type {} is not allowed in an object list",
1132 bad.ty.as_u32()
1133 )));
1134 }
1135 Ok(Value::Array(names.iter().map(object_name_value).collect()))
1136}
1137
1138fn object_names(names: ArrayIter<(u8, &[u8])>) -> Result<Vec<ObjectName>> {
1139 collect(names, |e| object_name(e, have_type))
1140}
1141
1142fn malformed(e: ostrya_gvariant::Error) -> Error {
1143 protocol(format!("malformed body: {e}"))
1144}
1145
1146fn parse_body<'a, T: GvDecode<'a>>(body: &'a [u8]) -> Result<T> {
1147 T::decode(body).map_err(malformed)
1148}
1149
1150fn collect<'a, E: GvDecode<'a> + Copy, T>(
1155 items: ArrayIter<'a, E>,
1156 mut f: impl FnMut(E) -> Result<T>,
1157) -> Result<Vec<T>> {
1158 let mut out = Vec::with_capacity(items.count());
1159 for e in items {
1160 out.push(f(e.map_err(malformed)?)?);
1161 }
1162 Ok(out)
1163}
1164
1165fn maybe_checksum(m: MaybeBytes) -> Result<Option<Checksum>> {
1166 m.0.map(checksum).transpose()
1167}
1168
1169#[derive(Clone, Copy)]
1172struct MaybeBytes<'a>(Option<&'a [u8]>);
1173
1174impl GvType for MaybeBytes<'_> {
1175 const ALIGNMENT: usize = 1;
1176 const FIXED_SIZE: Option<usize> = None;
1177}
1178
1179impl<'a> GvDecode<'a> for MaybeBytes<'a> {
1180 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1181 match data.split_last() {
1182 None => Ok(MaybeBytes(None)),
1183 Some((0, rest)) => Ok(MaybeBytes(Some(rest))),
1184 Some(_) => Err(ostrya_gvariant::Error::NotNormal(
1185 "maybe lacks its terminating zero byte",
1186 )),
1187 }
1188 }
1189}
1190
1191struct MaybeU64(Option<u64>);
1195
1196impl GvType for MaybeU64 {
1197 const ALIGNMENT: usize = 8;
1198 const FIXED_SIZE: Option<usize> = None;
1199}
1200
1201impl<'a> GvDecode<'a> for MaybeU64 {
1202 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1203 match data.len() {
1204 0 => Ok(MaybeU64(None)),
1205 8 => u64::decode(data).map(|n| MaybeU64(Some(n))),
1206 _ => Err(ostrya_gvariant::Error::NotNormal(
1207 "maybe of a u64 is not 0 or 8 bytes",
1208 )),
1209 }
1210 }
1211}
1212
1213struct RawVariant<'a> {
1216 ty: Type,
1217 child: &'a [u8],
1218}
1219
1220impl GvType for RawVariant<'_> {
1221 const ALIGNMENT: usize = 8;
1222 const FIXED_SIZE: Option<usize> = None;
1223}
1224
1225impl<'a> GvDecode<'a> for RawVariant<'a> {
1226 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1227 let not_normal = ostrya_gvariant::Error::NotNormal;
1228 let sep = data
1229 .iter()
1230 .rposition(|&b| b == 0)
1231 .ok_or(not_normal("variant lacks a type separator"))?;
1232 let signature = std::str::from_utf8(&data[sep + 1..])
1233 .map_err(|_| not_normal("variant type signature is not UTF-8"))?;
1234 let ty =
1235 Type::parse(signature).map_err(|_| not_normal("variant type signature is invalid"))?;
1236 Ok(RawVariant {
1237 ty,
1238 child: &data[..sep],
1239 })
1240 }
1241}
1242
1243type Dict<'a> = ArrayIter<'a, (&'a str, RawVariant<'a>)>;
1245
1246#[derive(Clone, Copy)]
1248struct VariantSlice<'a> {
1249 inner: &'a [u8],
1250}
1251
1252impl GvType for VariantSlice<'_> {
1253 const ALIGNMENT: usize = 8;
1254 const FIXED_SIZE: Option<usize> = None;
1255}
1256
1257impl<'a> GvDecode<'a> for VariantSlice<'a> {
1258 fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1259 Ok(VariantSlice { inner: data })
1260 }
1261}
1262
1263impl GvEncode for VariantSlice<'_> {
1264 fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
1265 out.extend_from_slice(self.inner);
1266 Ok(())
1267 }
1268}
1269
1270fn dict<'a, const N: usize>(
1275 entries: Dict<'a>,
1276 keys: [&str; N],
1277) -> Result<[Option<RawVariant<'a>>; N]> {
1278 let mut found = [const { None }; N];
1279 for entry in entries {
1280 let (key, value) = entry.map_err(malformed)?;
1281 match keys.iter().position(|k| *k == key) {
1282 Some(i) if found[i].is_none() => found[i] = Some(value),
1283 _ => {
1284 ostrya_gvariant::validate(&value.ty, value.child).map_err(malformed)?;
1285 }
1286 }
1287 }
1288 Ok(found)
1289}
1290
1291fn field<'a, T: GvDecode<'a>>(
1296 entry: Option<RawVariant<'a>>,
1297 key: &str,
1298 ty: &Type,
1299) -> Result<Option<T>> {
1300 let Some(v) = entry else {
1301 return Ok(None);
1302 };
1303 if v.ty != *ty {
1304 return Err(protocol(format!("key {key} has the wrong type")));
1305 }
1306 T::decode(v.child).map(Some).map_err(malformed)
1307}
1308
1309fn required<'a, T: GvDecode<'a>>(entry: Option<RawVariant<'a>>, key: &str, ty: &Type) -> Result<T> {
1313 field(entry, key, ty)?.ok_or_else(|| protocol(format!("HelloReply lacks {key}")))
1314}