1use std::collections::{BTreeMap, HashMap};
10
11use anyhow::{Result, anyhow, bail};
12
13use super::archive::{self, Ka};
14
15pub mod request {
17 pub const GLOBAL: i64 = 2;
19 pub const SINGLE: i64 = 3;
21 pub const APPLICATION: i64 = 4;
23 pub const BATCH: i64 = 5;
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
28pub struct ObjKey {
29 pub pid: i64,
30 pub object_id: u64,
31}
32
33impl ObjKey {
34 pub fn from_ka(v: &Ka) -> Option<Self> {
35 if v.class() != Some("AXPTranslationObject") {
36 return None;
37 }
38 Some(Self {
39 pid: v.get("pid")?.as_i64()?,
40 object_id: v.get("objectID")?.as_u64()?,
41 })
42 }
43}
44
45#[derive(Debug, Clone, Default)]
46pub struct RawElement {
47 pub is_application: bool,
48 pub attrs: BTreeMap<i64, Ka>,
50 pub singles: BTreeMap<i64, Ka>,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum DumpKind {
57 Initial,
59 Additional,
61 Other(String),
62}
63
64#[derive(Debug, Clone)]
66pub enum Payload {
67 Dump(Dump),
68 Notification(i64),
71 Answer(Answer),
73}
74
75#[derive(Debug, Clone)]
77pub struct Answer {
78 pub key: Option<ObjKey>,
79 pub attribute: i64,
80 pub value: Ka,
82}
83
84#[derive(Debug, Clone)]
85pub struct Dump {
86 pub kind: DumpKind,
87 pub applications: Vec<ObjKey>,
89 pub elements: HashMap<ObjKey, RawElement>,
90 pub order: Vec<ObjKey>,
92}
93
94fn unwrap_layers(bytes: &[u8]) -> Result<Ka> {
97 let mut current = archive::decode(bytes)?;
98 for _ in 0..4 {
99 match current {
100 Ka::Data(ref inner) if archive::looks_like_archive(inner) => {
101 current = archive::decode(inner)?;
102 }
103 _ => return Ok(current),
104 }
105 }
106 bail!("too many nested archive layers")
107}
108
109impl Payload {
110 pub fn parse(bytes: &[u8]) -> Result<Self> {
111 let root = unwrap_layers(bytes)?;
112 let result = root
113 .get("resultData")
114 .ok_or_else(|| anyhow!("payload is not a translator response"))?;
115 if result.get("treeDump").is_none() {
116 let notification = root.get("notification").and_then(|n| n.as_i64()).unwrap_or(0);
117 if notification != 0 {
118 return Ok(Payload::Notification(notification));
119 }
120 return Ok(Payload::Answer(Answer {
121 key: root.get("associatedTranslationObject").and_then(ObjKey::from_ka),
122 attribute: root.get("attribute").and_then(|a| a.as_i64()).unwrap_or(0),
123 value: result.clone(),
124 }));
125 }
126 Dump::from_response(result).map(Payload::Dump)
127 }
128}
129
130impl Dump {
131 pub fn parse(bytes: &[u8]) -> Result<Self> {
132 match Payload::parse(bytes)? {
133 Payload::Dump(d) => Ok(d),
134 Payload::Notification(n) => bail!("payload is notification {n}, not a tree dump"),
135 Payload::Answer(_) => bail!("payload is a translator answer, not a tree dump"),
136 }
137 }
138
139 fn from_response(result: &Ka) -> Result<Self> {
140 let entries = result
141 .get("treeDump")
142 .and_then(|t| t.as_array())
143 .ok_or_else(|| anyhow!("payload has no treeDump"))?;
144 let kind = match result.get("treeDumpType").and_then(|t| t.as_str()) {
145 Some("AXPTreeDumpTypeInitialDump") => DumpKind::Initial,
146 Some("AXPTreeDumpTypeAdditionalData") => DumpKind::Additional,
147 Some(other) => DumpKind::Other(other.to_string()),
148 None => DumpKind::Other(String::new()),
149 };
150
151 let mut dump = Dump {
152 kind,
153 applications: Vec::new(),
154 elements: HashMap::new(),
155 order: Vec::new(),
156 };
157 for entry in entries {
158 let request = entry
159 .get("associatedRequestType")
160 .and_then(|v| v.as_i64())
161 .unwrap_or(-1);
162 let attribute = entry.get("attribute").and_then(|v| v.as_i64()).unwrap_or(0);
163 let data = entry.get("resultData").unwrap_or(&Ka::Null);
164 let subject = entry
165 .get("associatedTranslationObject")
166 .and_then(ObjKey::from_ka);
167 match request {
168 request::APPLICATION => {
169 if let Some(key) = ObjKey::from_ka(data) {
170 dump.touch(key).is_application = true;
171 if !dump.applications.contains(&key) {
172 dump.applications.push(key);
173 }
174 }
175 }
176 request::BATCH => {
177 let (Some(key), Ka::Dict(pairs)) = (subject, data) else {
178 continue;
179 };
180 let el = dump.touch(key);
181 for (k, v) in pairs {
182 if let Some(n) = k.as_i64() {
183 el.attrs.insert(n, v.clone());
184 }
185 }
186 }
187 request::SINGLE => {
188 if let Some(key) = subject {
189 dump.touch(key).singles.insert(attribute, data.clone());
190 }
191 }
192 _ => {}
193 }
194 }
195 Ok(dump)
196 }
197
198 fn touch(&mut self, key: ObjKey) -> &mut RawElement {
199 if !self.elements.contains_key(&key) {
200 self.order.push(key);
201 }
202 self.elements.entry(key).or_default()
203 }
204
205 pub fn absorb(&mut self, extra: &Dump) {
208 for (key, more) in &extra.elements {
209 if let Some(el) = self.elements.get_mut(key) {
210 for (n, v) in &more.attrs {
211 el.attrs.entry(*n).or_insert_with(|| v.clone());
212 }
213 for (n, v) in &more.singles {
214 el.singles.entry(*n).or_insert_with(|| v.clone());
215 }
216 }
217 }
218 }
219
220 pub fn same_elements(&self, other: &Dump) -> bool {
222 self.elements.len() == other.elements.len()
223 && self.elements.keys().all(|k| other.elements.contains_key(k))
224 }
225}