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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use anyhow::Result;
use cid::Cid;
use noosphere_core::data::{AddressIpld, MapOperation};
use std::{collections::BTreeSet, marker::PhantomData};
use async_stream::try_stream;
use noosphere_storage::Storage;
use tokio::io::AsyncRead;
use tokio_stream::{Stream, StreamExt};
use ucan::crypto::KeyMaterial;
use crate::{
content::{SphereContentRead, SphereFile},
internal::SphereContextInternal,
HasSphereContext, SpherePetnameRead,
};
pub struct SphereWalker<H, K, S>
where
H: HasSphereContext<K, S>,
K: KeyMaterial + Clone + 'static,
S: Storage + 'static,
{
has_sphere_context: H,
key: PhantomData<K>,
storage: PhantomData<S>,
}
impl<H, K, S> From<H> for SphereWalker<H, K, S>
where
H: HasSphereContext<K, S>,
K: KeyMaterial + Clone + 'static,
S: Storage + 'static,
{
fn from(has_sphere_context: H) -> Self {
SphereWalker {
has_sphere_context,
key: Default::default(),
storage: Default::default(),
}
}
}
impl<H, K, S> SphereWalker<H, K, S>
where
H: SpherePetnameRead<K, S> + HasSphereContext<K, S>,
K: KeyMaterial + Clone + 'static,
S: Storage + 'static,
{
pub fn petname_stream<'a>(&'a self) -> impl Stream<Item = Result<(String, AddressIpld)>> + 'a {
try_stream! {
let sphere = self.has_sphere_context.to_sphere().await?;
let petnames = sphere.get_names().await?;
let stream = petnames.stream().await?;
for await entry in stream {
let (petname, address) = entry?;
yield (petname.clone(), address.clone());
}
}
}
pub fn petname_change_stream<'a>(
&'a self,
since: Option<&'a Cid>,
) -> impl Stream<Item = Result<(Cid, BTreeSet<String>)>> + 'a {
try_stream! {
let sphere = self.has_sphere_context.to_sphere().await?;
let since = since.cloned();
let stream = sphere.into_name_changelog_stream(since.as_ref());
for await change in stream {
let (cid, changelog) = change?;
let mut changed_petnames = BTreeSet::new();
for operation in changelog.changes {
let petname = match operation {
MapOperation::Add { key, .. } => key,
MapOperation::Remove { key } => key,
};
changed_petnames.insert(petname);
}
yield (cid, changed_petnames);
}
}
}
pub async fn list_petnames(&self) -> Result<BTreeSet<String>> {
let sphere_identity = self.has_sphere_context.identity().await?;
let petname_stream = self.petname_stream();
tokio::pin!(petname_stream);
Ok(petname_stream
.fold(BTreeSet::new(), |mut petnames, another_petname| {
match another_petname {
Ok((petname, _)) => {
petnames.insert(petname);
}
Err(error) => {
warn!(
"Could not read a petname from {}: {}",
sphere_identity, error
)
}
};
petnames
})
.await)
}
pub async fn petname_changes(&self, since: Option<&Cid>) -> Result<BTreeSet<String>> {
let sphere_identity = self.has_sphere_context.identity().await?;
let change_stream = self.petname_change_stream(since);
tokio::pin!(change_stream);
Ok(change_stream
.fold(BTreeSet::new(), |mut all, some| {
match some {
Ok((_, mut changes)) => all.append(&mut changes),
Err(error) => warn!(
"Could not read some changes from {}: {}",
sphere_identity, error
),
};
all
})
.await)
}
}
impl<H, K, S> SphereWalker<H, K, S>
where
H: SphereContentRead<K, S> + HasSphereContext<K, S>,
K: KeyMaterial + Clone + 'static,
S: Storage + 'static,
{
pub fn into_content_stream(
self,
) -> impl Stream<Item = Result<(String, SphereFile<impl AsyncRead>)>> {
try_stream! {
let sphere = self.has_sphere_context.to_sphere().await?;
let links = sphere.get_links().await?;
let stream = links.stream().await?;
for await entry in stream {
let (key, memo_revision) = entry?;
let file = self.has_sphere_context.get_file(sphere.cid(), memo_revision).await?;
yield (key.clone(), file);
}
}
}
pub fn content_stream<'a>(
&'a self,
) -> impl Stream<Item = Result<(String, SphereFile<impl AsyncRead + 'a>)>> {
try_stream! {
let sphere = self.has_sphere_context.to_sphere().await?;
let links = sphere.get_links().await?;
let stream = links.stream().await?;
for await entry in stream {
let (key, memo_revision) = entry?;
let file = self.has_sphere_context.get_file(sphere.cid(), memo_revision).await?;
yield (key.clone(), file);
}
}
}
pub fn content_change_stream<'a>(
&'a self,
since: Option<&'a Cid>,
) -> impl Stream<Item = Result<(Cid, BTreeSet<String>)>> + 'a {
try_stream! {
let sphere = self.has_sphere_context.to_sphere().await?;
let since = since.cloned();
let stream = sphere.into_link_changelog_stream(since.as_ref());
for await change in stream {
let (cid, changelog) = change?;
let mut changed_slugs = BTreeSet::new();
for operation in changelog.changes {
let slug = match operation {
MapOperation::Add { key, .. } => key,
MapOperation::Remove { key } => key,
};
changed_slugs.insert(slug);
}
yield (cid, changed_slugs);
}
}
}
pub async fn list_slugs(&self) -> Result<BTreeSet<String>> {
let sphere_identity = self.has_sphere_context.identity().await?;
let link_stream = self.content_stream();
tokio::pin!(link_stream);
Ok(link_stream
.fold(BTreeSet::new(), |mut links, another_link| {
match another_link {
Ok((slug, _)) => {
links.insert(slug);
}
Err(error) => {
warn!("Could not read a link from {}: {}", sphere_identity, error)
}
};
links
})
.await)
}
pub async fn content_changes(&self, since: Option<&Cid>) -> Result<BTreeSet<String>> {
let sphere_identity = self.has_sphere_context.identity().await?;
let change_stream = self.content_change_stream(since);
tokio::pin!(change_stream);
Ok(change_stream
.fold(BTreeSet::new(), |mut all, some| {
match some {
Ok((_, mut changes)) => all.append(&mut changes),
Err(error) => warn!(
"Could not read some changes from {}: {}",
sphere_identity, error
),
};
all
})
.await)
}
}
#[cfg(test)]
pub mod tests {
use std::collections::BTreeSet;
use noosphere_core::data::ContentType;
use tokio::io::AsyncReadExt;
use tokio_stream::StreamExt;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test;
#[cfg(target_arch = "wasm32")]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
use super::SphereWalker;
use crate::helpers::{simulated_sphere_context, SimulationAccess};
use crate::{HasMutableSphereContext, SphereContentWrite, SphereCursor};
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
async fn it_can_be_initialized_with_a_context_or_a_cursor() {
let sphere_context = simulated_sphere_context(SimulationAccess::ReadWrite)
.await
.unwrap();
let mut cursor = SphereCursor::latest(sphere_context.clone());
let changes = vec![
vec!["dogs", "birds"],
vec!["cats", "dogs"],
vec!["birds"],
vec!["cows", "beetles"],
];
for change in changes {
for slug in change {
cursor
.write(
slug,
&ContentType::Subtext.to_string(),
b"are cool".as_ref(),
None,
)
.await
.unwrap();
}
cursor.save(None).await.unwrap();
}
let walker_cursor = SphereWalker::from(cursor);
let walker_context = SphereWalker::from(sphere_context);
let slugs_cursor = walker_cursor.list_slugs().await.unwrap();
let slugs_context = walker_context.list_slugs().await.unwrap();
assert_eq!(slugs_cursor.len(), 5);
assert_eq!(slugs_cursor, slugs_context);
}
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
async fn it_can_list_all_slugs_currently_in_a_sphere() {
let sphere_context = simulated_sphere_context(SimulationAccess::ReadWrite)
.await
.unwrap();
let mut cursor = SphereCursor::latest(sphere_context);
let changes = vec![
vec!["dogs", "birds"],
vec!["cats", "dogs"],
vec!["birds"],
vec!["cows", "beetles"],
];
for change in changes {
for slug in change {
cursor
.write(
slug,
&ContentType::Subtext.to_string(),
b"are cool".as_ref(),
None,
)
.await
.unwrap();
}
cursor.save(None).await.unwrap();
}
let walker = SphereWalker::from(cursor.clone());
let slugs = walker.list_slugs().await.unwrap();
assert_eq!(slugs.len(), 5);
cursor.remove("dogs").await.unwrap();
cursor.save(None).await.unwrap();
let slugs = walker.list_slugs().await.unwrap();
assert_eq!(slugs.len(), 4);
}
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
async fn it_can_stream_the_whole_index() {
let sphere_context = simulated_sphere_context(SimulationAccess::ReadWrite)
.await
.unwrap();
let mut cursor = SphereCursor::latest(sphere_context);
let expected = BTreeSet::<(String, String)>::from([
("cats".into(), "Cats are awesome".into()),
("dogs".into(), "Dogs are pretty cool".into()),
("birds".into(), "Birds rights".into()),
("mice".into(), "Mice like cookies".into()),
]);
for (slug, content) in &expected {
cursor
.write(
slug.as_str(),
&ContentType::Subtext.to_string(),
content.as_ref(),
None,
)
.await
.unwrap();
cursor.save(None).await.unwrap();
}
let mut actual = BTreeSet::new();
let walker = SphereWalker::from(cursor);
let stream = walker.content_stream();
tokio::pin!(stream);
while let Some(Ok((slug, mut file))) = stream.next().await {
let mut contents = String::new();
file.contents.read_to_string(&mut contents).await.unwrap();
actual.insert((slug, contents));
}
assert_eq!(expected, actual);
}
}