1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    crate::CachePackagesInitError,
    fuchsia_hash::Hash,
    fuchsia_inspect::{self as finspect, ArrayProperty as _},
    fuchsia_url::{AbsolutePackageUrl, PinnedAbsolutePackageUrl, UnpinnedAbsolutePackageUrl},
    futures::{future::BoxFuture, FutureExt as _},
    serde::{Deserialize, Serialize},
    std::sync::Arc,
};

#[derive(Debug, PartialEq, Eq)]
pub struct CachePackages {
    contents: Vec<PinnedAbsolutePackageUrl>,
}

impl CachePackages {
    /// Create a new instance of `CachePackages` containing entries provided.
    pub fn from_entries(entries: Vec<PinnedAbsolutePackageUrl>) -> Self {
        CachePackages { contents: entries }
    }

    /// Create a new instance of `CachePackages` from parsing a json.
    /// If there are no cache packages, `file_contents` must be empty.
    pub(crate) fn from_json(file_contents: &[u8]) -> Result<Self, CachePackagesInitError> {
        if file_contents.is_empty() {
            return Ok(CachePackages { contents: vec![] });
        }
        let contents = parse_json(file_contents)?;
        if contents.is_empty() {
            return Err(CachePackagesInitError::NoCachePackages);
        }
        Ok(CachePackages { contents })
    }

    /// Iterator over the contents of the mapping.
    pub fn contents(&self) -> impl Iterator<Item = &PinnedAbsolutePackageUrl> + ExactSizeIterator {
        self.contents.iter()
    }

    /// Iterator over the contents of the mapping, consuming self.
    pub fn into_contents(
        self,
    ) -> impl Iterator<Item = PinnedAbsolutePackageUrl> + ExactSizeIterator {
        self.contents.into_iter()
    }

    /// Get the hash for a package.
    pub fn hash_for_package(&self, pkg: &AbsolutePackageUrl) -> Option<Hash> {
        self.contents.iter().find_map(|candidate| {
            if pkg.as_unpinned() == candidate.as_unpinned() {
                match pkg.hash() {
                    None => Some(candidate.hash()),
                    Some(hash) if hash == candidate.hash() => Some(hash),
                    _ => None,
                }
            } else {
                None
            }
        })
    }

    pub fn serialize(&self, writer: impl std::io::Write) -> Result<(), serde_json::Error> {
        if self.contents.is_empty() {
            return Ok(());
        }
        let content = Packages { version: "1".to_string(), content: self.contents.clone() };
        serde_json::to_writer(writer, &content)
    }

    pub fn find_unpinned_url(
        &self,
        url: &UnpinnedAbsolutePackageUrl,
    ) -> Option<&PinnedAbsolutePackageUrl> {
        self.contents().find(|pinned_url| pinned_url.as_unpinned() == url)
    }

    /// Returns a callback to be given to `finspect::Node::record_lazy_values`.
    /// Creates an array named `array_name`.
    pub fn record_lazy_inspect(
        self: &Arc<Self>,
        array_name: &'static str,
    ) -> impl Fn() -> BoxFuture<'static, Result<finspect::Inspector, anyhow::Error>>
           + Send
           + Sync
           + 'static {
        let this = Arc::downgrade(self);
        move || {
            let this = this.clone();
            async move {
                let inspector = finspect::Inspector::default();
                if let Some(this) = this.upgrade() {
                    let root = inspector.root();
                    let array = root.create_string_array(array_name, this.contents.len());
                    let () = this
                        .contents
                        .iter()
                        .enumerate()
                        .for_each(|(i, url)| array.set(i, url.to_string()));
                    root.record(array);
                }
                Ok(inspector)
            }
            .boxed()
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct Packages {
    version: String,
    content: Vec<PinnedAbsolutePackageUrl>,
}

fn parse_json(contents: &[u8]) -> Result<Vec<PinnedAbsolutePackageUrl>, CachePackagesInitError> {
    match serde_json::from_slice(contents).map_err(CachePackagesInitError::JsonError)? {
        Packages { ref version, content } if version == "1" => Ok(content),
        Packages { version, .. } => Err(CachePackagesInitError::VersionNotSupported(version)),
    }
}

#[cfg(test)]
mod tests {
    use {super::*, assert_matches::assert_matches, diagnostics_assertions::assert_data_tree};

    #[test]
    fn populate_from_valid_json() {
        let file_contents = br#"
        {
            "version": "1",
            "content": [
                "fuchsia-pkg://foo.bar/qwe/0?hash=0000000000000000000000000000000000000000000000000000000000000000",
                "fuchsia-pkg://foo.bar/rty/0?hash=1111111111111111111111111111111111111111111111111111111111111111"
            ]
        }"#;

        let packages = CachePackages::from_json(file_contents).unwrap();
        let expected = vec![
            "fuchsia-pkg://foo.bar/qwe/0?hash=0000000000000000000000000000000000000000000000000000000000000000",
            "fuchsia-pkg://foo.bar/rty/0?hash=1111111111111111111111111111111111111111111111111111111111111111"
        ];
        assert!(packages.into_contents().map(|u| u.to_string()).eq(expected));
    }

    #[test]
    fn populate_from_empty_json() {
        let packages = CachePackages::from_json(b"").unwrap();
        assert_eq!(packages.into_contents().count(), 0);
    }

    #[test]
    fn reject_non_empty_json_with_no_cache_packages() {
        let file_contents = br#"
        {
            "version": "1",
            "content": []
        }"#;

        assert_matches!(
            CachePackages::from_json(file_contents),
            Err(CachePackagesInitError::NoCachePackages)
        );
    }

    #[test]
    fn test_hash_for_package_returns_none() {
        let correct_hash = fuchsia_hash::Hash::from([0; 32]);
        let packages = CachePackages::from_entries(vec![PinnedAbsolutePackageUrl::parse(
            &format!("fuchsia-pkg://fuchsia.com/name?hash={correct_hash}"),
        )
        .unwrap()]);
        let wrong_hash = fuchsia_hash::Hash::from([1; 32]);
        assert_eq!(
            None,
            packages.hash_for_package(
                &AbsolutePackageUrl::parse("fuchsia-pkg://fuchsia.com/wrong-name").unwrap()
            )
        );
        assert_eq!(
            None,
            packages.hash_for_package(
                &AbsolutePackageUrl::parse(&format!(
                    "fuchsia-pkg://fuchsia.com/name?hash={wrong_hash}"
                ))
                .unwrap()
            )
        );
    }

    #[test]
    fn test_hash_for_package_returns_hashes() {
        let hash = fuchsia_hash::Hash::from([0; 32]);
        let packages = CachePackages::from_entries(vec![PinnedAbsolutePackageUrl::parse(
            &format!("fuchsia-pkg://fuchsia.com/name?hash={hash}"),
        )
        .unwrap()]);
        assert_eq!(
            Some(hash),
            packages.hash_for_package(
                &AbsolutePackageUrl::parse(&format!("fuchsia-pkg://fuchsia.com/name?hash={hash}"))
                    .unwrap()
            )
        );
        assert_eq!(
            Some(hash),
            packages.hash_for_package(
                &AbsolutePackageUrl::parse("fuchsia-pkg://fuchsia.com/name").unwrap()
            )
        );
    }

    #[test]
    fn test_serialize() {
        let hash = fuchsia_hash::Hash::from([0; 32]);
        let packages = CachePackages::from_entries(vec![PinnedAbsolutePackageUrl::parse(
            &format!("fuchsia-pkg://foo.bar/qwe/0?hash={hash}"),
        )
        .unwrap()]);
        let mut bytes = vec![];

        let () = packages.serialize(&mut bytes).unwrap();

        assert_eq!(
            serde_json::from_slice::<serde_json::Value>(bytes.as_slice()).unwrap(),
            serde_json::json!({
                "version": "1",
                "content": vec![
                    "fuchsia-pkg://foo.bar/qwe/0?hash=0000000000000000000000000000000000000000000000000000000000000000"
                    ],
            })
        );
    }

    #[test]
    fn test_serialize_deserialize_round_trip() {
        let hash = fuchsia_hash::Hash::from([0; 32]);
        let packages = CachePackages::from_entries(vec![PinnedAbsolutePackageUrl::parse(
            &format!("fuchsia-pkg://foo.bar/qwe/0?hash={hash}"),
        )
        .unwrap()]);
        let mut bytes = vec![];

        packages.serialize(&mut bytes).unwrap();

        assert_eq!(CachePackages::from_json(&bytes).unwrap(), packages);
    }

    #[fuchsia::test]
    async fn test_inspect() {
        let hash = fuchsia_hash::Hash::from([0; 32]);
        let packages = Arc::new(CachePackages::from_entries(vec![
            PinnedAbsolutePackageUrl::parse(&format!("fuchsia-pkg://foo.bar/qwe/0?hash={hash}"))
                .unwrap(),
            PinnedAbsolutePackageUrl::parse(&format!("fuchsia-pkg://foo.bar/other/0?hash={hash}"))
                .unwrap(),
        ]));
        let inspector = finspect::Inspector::default();

        inspector
            .root()
            .record_lazy_values("unused", packages.record_lazy_inspect("cache-packages"));

        assert_data_tree!(inspector, root: {
            "cache-packages": vec![
                "fuchsia-pkg://foo.bar/qwe/0?hash=\
                0000000000000000000000000000000000000000000000000000000000000000",
                "fuchsia-pkg://foo.bar/other/0?hash=\
                0000000000000000000000000000000000000000000000000000000000000000",
            ],
        });
    }
}