forked from paritytech/substrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipfs.rs
672 lines (610 loc) · 25.8 KB
/
ipfs.rs
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! This module is composed of two structs: [`IpfsApi`] and [`IpfsWorker`]. Calling the [`ipfs`]
//! function returns a pair of [`IpfsApi`] and [`IpfsWorker`] that share some state.
//!
//! The [`IpfsApi`] is (indirectly) passed to the runtime when calling an offchain worker, while
//! the [`IpfsWorker`] must be processed in the background. The [`IpfsApi`] mimics the API of the
//! IPFS-related methods available to offchain workers.
//!
//! The reason for this design is driven by the fact that IPFS requests should continue running
//! in the background even if the runtime isn't actively calling any function.
use crate::api::timestamp;
use fnv::FnvHashMap;
use futures::{future, prelude::*};
use libipld::{cid, Cid};
use log::error;
use rust_ipfs::{
unixfs::{UnixfsStatus, AddOpt},
Block, Ipfs, IpfsPath, Multiaddr, PeerId, PublicKey, SubscriptionStream, MessageId
};
use sp_core::offchain::{IpfsRequest, IpfsRequestId, IpfsRequestStatus, IpfsResponse, OpaqueMultiaddr, Timestamp};
use std::{convert::TryInto, fmt, mem, pin::Pin, str, task::{Context, Poll}};
use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedSender, TracingUnboundedReceiver};
// wasm-friendly implementations of Ipfs::{add, get}
async fn ipfs_add(ipfs: &Ipfs, data: Vec<u8>) -> Result<Cid, rust_ipfs::Error> {
// let cid_version = cid_version_from_raw(version);
// let data_packed = tokio_stream::once(data).boxed();
let mut data_stream = ipfs.add_unixfs(AddOpt::Stream(
stream::once(
async { Ok::<_, std::io::Error>(bytes::Bytes::from(data)) }
).boxed()
));
let mut result: Result<Cid, rust_ipfs::Error> = Result::Err(rust_ipfs::Error::msg("Unknown error"));
while let Some(status) = data_stream.next().await {
match status {
UnixfsStatus::ProgressStatus {
written,
total_size,
} => match total_size {
Some(size) => log::info!("{written} out of {size} stored"),
None => tracing::debug!("{written} been stored"),
},
UnixfsStatus::FailedStatus {
written: _,
total_size: _,
error: _,
} => {
result = Result::Err(rust_ipfs::Error::msg("Error adding file"))
}
UnixfsStatus::CompletedStatus { path, written, total_size } => {
tracing::info!("{written} been stored with path {path} and total size {:?}", total_size);
let cid_str = path.to_string().replace("/ipfs/", "");
match Cid::try_from(cid_str) {
Ok(cid) => result = Ok(cid),
Err(_) => result = Err(rust_ipfs::Error::msg("Unable to upload file")),
}
}
}
}
tracing::info!("IPFS add file result: {:?}", result);
result
}
async fn ipfs_ipns(ipfs: &Ipfs, path: IpfsPath) -> Result<IpfsPath, rust_ipfs::Error> {
// let cid_version = cid_version_from_raw(version);
// let data_packed = tokio_stream::once(data).boxed();
//let ipfs_path = IpfsPath::from(cid);
let result = ipfs.publish_ipns(&path).await?;
tracing::info!("IPFS been published to: {:?}", result);
Ok(result)
}
async fn ipfs_get(ipfs: &Ipfs, path: IpfsPath) -> Result<Vec<u8>, rust_ipfs::Error> {
let path_copy = path.clone();
let stream_result = ipfs.cat_unixfs(path).await;
let default_error_msg = "Unable to cat file: ".to_string() + &path_copy.to_string();
let _default_error = rust_ipfs::Error::msg(default_error_msg);
if let Ok(stream) = stream_result {
// futures::pin_mut!(stream);
// let pin_stream: Pin<&mut bytes::Bytes> = stream;
//
// loop {
// match pin_stream.next().await {
// Some(Ok(bytes)) => {
// data.append(&mut bytes.clone());
// }
// Some(Err( _ )) => {
// return Err(default_error);
// }
// None => {
// break
// }
// }
// }
let mut data = Vec::<u8>::new();
data.append(&mut stream.to_vec());
Ok(data)
}
else {
Err(rust_ipfs::Error::msg("Unable to upload file"))
}
}
#[allow(dead_code)]
fn cid_version_from_raw(raw_version: u8) -> cid::Version {
if raw_version <= 0 {
cid::Version::V0
} else {
cid::Version::V1
}
}
/// Creates a pair of [`IpfsApi`] and [`IpfsWorker`].
pub fn ipfs(ipfs_node: rust_ipfs::Ipfs) -> (IpfsApi, IpfsWorker) {
let (to_worker, from_api) = tracing_unbounded("mpsc_ocw_to_ipfs_worker", 1_000_000);
let (to_api, from_worker) = tracing_unbounded("mpsc_ocw_to_ipfs_api", 1_000_000);
let api = IpfsApi {
to_worker,
from_worker: from_worker.fuse(),
// We start with a random ID for the first IPFS request, to prevent mischievous people from
// writing runtime code with hardcoded IDs.
next_id: IpfsRequestId(rand::random::<u16>() % 2000),
requests: FnvHashMap::default(),
};
let worker = IpfsWorker {
to_api,
from_api,
ipfs_node,
requests: Vec::new(),
};
(api, worker)
}
/// Provides IPFS capabilities.
///
/// Since this struct is a helper for offchain workers, its API is mimicking the API provided
/// to offchain workers.
pub struct IpfsApi {
/// Used to send messages to the worker.
to_worker: TracingUnboundedSender<ApiToWorker>,
/// Used to receive messages from the worker.
/// We use a `Fuse` to have extra protection against panicking.
from_worker: stream::Fuse<TracingUnboundedReceiver<WorkerToApi>>,
/// I'd to assign to the next IPFS request that is started.
next_id: IpfsRequestId,
/// List of IPFS requests in preparation or in progress.
requests: FnvHashMap<IpfsRequestId, IpfsApiRequest>,
}
/// One active request within `IpfsApi`.
enum IpfsApiRequest {
Dispatched,
Response(IpfsNativeResponse),
Fail(rust_ipfs::Error),
}
impl IpfsApi {
/// Mimics the corresponding method in the offchain API.
pub fn request_start(&mut self, request: IpfsRequest) -> Result<IpfsRequestId, ()> {
let id = self.next_id;
debug_assert!(!self.requests.contains_key(&id));
match self.next_id.0.checked_add(1) {
Some(id) => self.next_id.0 = id,
None => {
error!("Overflow in offchain worker IPFS request ID assignment");
return Err(());
}
};
let _ = self.to_worker.unbounded_send(ApiToWorker {
id,
request
});
self.requests.insert(id, IpfsApiRequest::Dispatched);
Ok(id)
}
/// Mimics the corresponding method in the offchain API.
pub fn response_wait(
&mut self,
ids: &[IpfsRequestId],
deadline: Option<Timestamp>
) -> Vec<IpfsRequestStatus> {
let mut deadline = timestamp::deadline_to_future(deadline);
let mut output = vec![IpfsRequestStatus::DeadlineReached; ids.len()];
loop {
{
let mut must_wait_more = false;
let mut out_idx = 0;
for id in ids {
match self.requests.get_mut(id) {
None => output[out_idx] = IpfsRequestStatus::Invalid,
Some(IpfsApiRequest::Dispatched) => must_wait_more = true,
Some(IpfsApiRequest::Fail(e)) => {
output[out_idx] = IpfsRequestStatus::IoError(e.to_string().into_bytes())
},
Some(IpfsApiRequest::Response(IpfsNativeResponse::Success)) => {},
Some(IpfsApiRequest::Response(ref mut resp)) => {
output[out_idx] = IpfsRequestStatus::Finished(IpfsResponse::from(
mem::replace(resp, IpfsNativeResponse::Success)
));
},
};
out_idx += 1;
}
debug_assert_eq!(output.len(), ids.len());
// Are we ready to call `return`?
let is_done = if let future::MaybeDone::Done(_) = deadline {
true
} else {
!must_wait_more
};
if is_done {
// Requests in "fail" mode are purged before returning.
debug_assert_eq!(output.len(), ids.len());
for n in (0..ids.len()).rev() {
if let IpfsRequestStatus::IoError(_) = output[n] {
self.requests.remove(&ids[n]);
}
}
return output
}
}
// Grab the next message from the worker. We call `continue` if deadline is reached so that
// we loop back and `return`.
let next_message = {
let mut next_msg = future::maybe_done(self.from_worker.next());
futures::executor::block_on(future::select(&mut next_msg, &mut deadline));
if let future::MaybeDone::Done(msg) = next_msg {
msg
} else {
debug_assert!(matches!(deadline, future::MaybeDone::Done(..)));
continue
}
};
// Update internal state based on a received message.
match next_message {
Some(WorkerToApi::Response { id, value }) =>
match self.requests.remove(&id) {
Some(IpfsApiRequest::Dispatched) => {
self.requests.insert(id, IpfsApiRequest::Response(value));
}
_ => error!("State mismatch between the API and worker"),
}
Some(WorkerToApi::Fail { id, error }) =>
match self.requests.remove(&id) {
Some(IpfsApiRequest::Dispatched) => {
self.requests.insert(id, IpfsApiRequest::Fail(error));
}
_ => error!("State mismatch between the API and worker"),
}
None => {
error!("Worker has crashed");
return ids.iter().map(|_| IpfsRequestStatus::IoError(b"The IPFS worker has crashed!".to_vec())).collect()
}
}
}
}
}
impl fmt::Debug for IpfsApi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list()
.entries(self.requests.iter())
.finish()
}
}
impl fmt::Debug for IpfsApiRequest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
IpfsApiRequest::Dispatched =>
f.debug_tuple("IpfsApiRequest::Dispatched").finish(),
IpfsApiRequest::Response(_) =>
f.debug_tuple("IpfsApiRequest::Response").finish(),
IpfsApiRequest::Fail(err) =>
f.debug_tuple("IpfsApiRequest::Fail").field(err).finish(),
}
}
}
/// Message sends from the API to the worker.
struct ApiToWorker {
/// ID to send back when the response comes back.
id: IpfsRequestId,
/// Request to start executing.
request: IpfsRequest,
}
/// Message sends from the API to the worker.
enum WorkerToApi {
/// A request has succeeded.
Response {
/// The ID that was passed to the worker.
id: IpfsRequestId,
/// Status code of the response.
value: IpfsNativeResponse,
},
/// A request has failed because of an error. The request is then no longer valid.
Fail {
/// The ID that was passed to the worker.
id: IpfsRequestId,
/// Error that happened.
error: rust_ipfs::Error,
},
}
/// Must be continuously polled for the [`IpfsApi`] to properly work.
pub struct IpfsWorker {
/// Used to send messages to the `IpfsApi`.
to_api: TracingUnboundedSender<WorkerToApi>,
/// Used to receive messages from the `IpfsApi`.
from_api: TracingUnboundedReceiver<ApiToWorker>,
/// The engine that runs IPFS requests.
ipfs_node: rust_ipfs::Ipfs,
/// IPFS requests that are being worked on by the engine.
requests: Vec<(IpfsRequestId, IpfsWorkerRequest)>,
}
/// IPFS request being processed by the worker.
struct IpfsWorkerRequest(
Pin<Box<dyn Future<Output = Result<IpfsNativeResponse, rust_ipfs::Error>> + Send>>
);
pub enum IpfsNativeResponse {
Addrs(Vec<(PeerId, Vec<Multiaddr>)>),
AddBytes(Cid),
AddListeningAddr(Multiaddr),
// BitswapStats(BitswapStats),
CatBytes(Vec<u8>),
PublishIpns(IpfsPath),
Connect(()),
Disconnect(()),
FindPeer(Vec<Multiaddr>),
GetBlock(Block),
GetClosestPeers(Vec<PeerId>),
GetProviders(Vec<PeerId>),
Identity(PublicKey, Vec<Multiaddr>),
InsertPin(()),
LocalAddrs(Vec<Multiaddr>),
LocalRefs(Vec<Cid>),
Peers(Vec<PeerId>),
Publish(MessageId),
RemoveListeningAddr(()),
RemoveBlock(Vec<Cid>),
RemovePin(()),
Subscribe(SubscriptionStream), // TODO: actually using the SubscriptionStream would require it to be stored within the node.
SubscriptionList(Vec<Vec<u8>>),
Unsubscribe(bool),
// a technical placeholder replacing the actual response owned for conversion purposes.
Success,
}
impl From<IpfsNativeResponse> for IpfsResponse {
fn from(resp: IpfsNativeResponse) -> Self {
match resp {
IpfsNativeResponse::Addrs(resp) => {
let mut ret = Vec::with_capacity(resp.len());
for (peer_id, addrs) in resp {
let peer = peer_id.as_ref().to_bytes();
let mut converted_addrs = Vec::with_capacity(addrs.len());
for addr in addrs {
converted_addrs.push(OpaqueMultiaddr(addr.to_string().into_bytes()));
}
ret.push((peer, converted_addrs));
}
IpfsResponse::Addrs(ret)
}
IpfsNativeResponse::AddBytes(cid) => {
IpfsResponse::AddBytes(cid.to_string().into_bytes())
},
// IpfsNativeResponse::BitswapStats(BitswapStats {
// blocks_sent,
// data_sent,
// blocks_received,
// data_received,
// dup_blks_received,
// dup_data_received,
// peers,
// wantlist,
// }) => {
// IpfsResponse::BitswapStats {
// blocks_sent,
// data_sent,
// blocks_received,
// data_received,
// dup_blks_received,
// dup_data_received,
// peers: peers.into_iter().map(|peer_id| peer_id.as_ref().to_bytes()).collect(),
// wantlist: wantlist.into_iter().map(|(cid, prio)| (cid.to_bytes(), prio)).collect(),
// }
// }
IpfsNativeResponse::CatBytes(data) => {
IpfsResponse::CatBytes(data)
},
IpfsNativeResponse::GetClosestPeers(peer_ids) => {
let ids = peer_ids.into_iter()
.map(|peer_id| peer_id.to_string().into_bytes())
.collect();
IpfsResponse::GetClosestPeers(ids)
},
IpfsNativeResponse::GetProviders(peer_ids) => {
let ids = peer_ids.into_iter()
.map(|peer_id| peer_id.to_string().into_bytes())
.collect();
IpfsResponse::GetProviders(ids)
},
IpfsNativeResponse::FindPeer(addrs) => {
let addrs = addrs.into_iter()
.map(|addr| OpaqueMultiaddr(addr.to_string().into_bytes()))
.collect();
IpfsResponse::FindPeer(addrs)
},
IpfsNativeResponse::Identity(pk, addrs) => {
let pk = pk.to_peer_id().as_ref().to_bytes();
let addrs = addrs.into_iter().map(|addr|
OpaqueMultiaddr(addr.to_string().into_bytes())
).collect();
IpfsResponse::Identity(pk, addrs)
}
IpfsNativeResponse::LocalAddrs(addrs) => {
let addrs = addrs.into_iter().map(|addr|
OpaqueMultiaddr(addr.to_string().into_bytes())
).collect();
IpfsResponse::LocalAddrs(addrs)
}
IpfsNativeResponse::LocalRefs(cids) => {
let cids = cids.into_iter().map(|cid|
cid.to_bytes()
).collect();
IpfsResponse::LocalRefs(cids)
}
IpfsNativeResponse::Peers(conns) => {
let addrs = conns.into_iter().map(|conn|
OpaqueMultiaddr(conn.to_string().into_bytes())
).collect();
IpfsResponse::Peers(addrs)
},
IpfsNativeResponse::RemoveBlock(cid) => {
IpfsResponse::RemoveBlock(cid.into_iter().map(|cid| cid.codec() as u8).collect())
}
_ => IpfsResponse::Success,
}
}
}
async fn ipfs_request(ipfs: rust_ipfs::Ipfs, request: IpfsRequest) -> Result<IpfsNativeResponse, rust_ipfs::Error> {
match request {
IpfsRequest::Addrs => {
Ok(IpfsNativeResponse::Addrs(ipfs.addrs().await?))
},
IpfsRequest::AddBytes(data, _version) => {
Ok(IpfsNativeResponse::AddBytes(ipfs_add(&ipfs, data).await?))
},
IpfsRequest::AddListeningAddr(addr) => {
let ret = ipfs.add_listening_address(str::from_utf8(&addr.0)?.parse()?).await?;
Ok(IpfsNativeResponse::AddListeningAddr(ret))
},
// IpfsRequest::BitswapStats => {
// Ok(IpfsNativeResponse::BitswapStats(ipfs.bitswap_stats().await?))
// },
IpfsRequest::CatBytes(cid) => {
let data = ipfs_get(&ipfs, str::from_utf8(&cid)?.parse::<IpfsPath>()?).await?;
Ok(IpfsNativeResponse::CatBytes(data))
},
IpfsRequest::PublishIpns(cid) => {
let data = ipfs_ipns(&ipfs, str::from_utf8(&cid)?.parse::<IpfsPath>()?).await?;
Ok(IpfsNativeResponse::PublishIpns(data))
},
IpfsRequest::Connect(addr) => {
let peer_id = str::from_utf8(&addr)?.parse::<PeerId>()?;
Ok(IpfsNativeResponse::Connect(ipfs.connect(peer_id).await?))
},
IpfsRequest::Disconnect(addr) => {
let peer_id = str::from_utf8(&addr)?.parse::<PeerId>()?;
Ok(IpfsNativeResponse::Disconnect(ipfs.disconnect(peer_id).await?))
},
IpfsRequest::FindPeer(peer_id) => {
let peer_id = str::from_utf8(&peer_id)?.parse::<PeerId>()?;
Ok(IpfsNativeResponse::FindPeer(ipfs.find_peer(peer_id).await?))
},
IpfsRequest::GetBlock(cid) => {
Ok(IpfsNativeResponse::GetBlock(ipfs.get_block(&cid.try_into()?).await?))
},
IpfsRequest::GetClosestPeers(peer_id) => {
let peer_id = str::from_utf8(&peer_id)?.parse::<PeerId>()?;
Ok(IpfsNativeResponse::GetClosestPeers(ipfs.get_closest_peers(peer_id).await?))
},
IpfsRequest::GetProviders(cid) => {
let cid = str::from_utf8(&cid)?.parse()?;
let mut stream = ipfs.get_providers(cid).await?;
let mut peer_ids = Vec::<PeerId>::new();
while let Some(provider) = stream.next().await {
peer_ids.push(provider);
}
Ok(IpfsNativeResponse::GetProviders(peer_ids))
}
IpfsRequest::Identity => {
let peer_info = ipfs.identity(None).await?;
let (pk, addrs) = (peer_info.public_key, peer_info.listen_addrs);
Ok(IpfsNativeResponse::Identity(pk, addrs))
},
IpfsRequest::InsertPin(cid, _recursive) => {
let cid = str::from_utf8(&cid)?.parse()?;
Ok(IpfsNativeResponse::InsertPin(ipfs.insert_pin(&cid).await?))
},
IpfsRequest::LocalAddrs => {
Ok(IpfsNativeResponse::LocalAddrs(ipfs.listening_addresses().await?))
},
IpfsRequest::LocalRefs => {
Ok(IpfsNativeResponse::LocalRefs(ipfs.refs_local().await))
},
IpfsRequest::Peers => {
Ok(IpfsNativeResponse::Peers(ipfs.connected().await?))
},
IpfsRequest::Publish { topic, message } => {
let ret = ipfs.pubsub_publish(String::from_utf8(topic)?, message).await?;
Ok(IpfsNativeResponse::Publish(ret))
},
IpfsRequest::RemoveListeningAddr(addr) => {
let ret = ipfs.remove_listening_address(str::from_utf8(&addr.0)?.parse()?).await?;
Ok(IpfsNativeResponse::RemoveListeningAddr(ret))
},
IpfsRequest::RemoveBlock(cid, recursive) => {
let cid = str::from_utf8(&cid)?.parse()?;
Ok(IpfsNativeResponse::RemoveBlock(ipfs.remove_block(cid, recursive).await?))
},
IpfsRequest::RemovePin(cid, _recursive) => {
let cid = str::from_utf8(&cid)?.parse()?;
Ok(IpfsNativeResponse::RemovePin(ipfs.remove_pin(&cid).await?))
},
IpfsRequest::Subscribe(topic) => {
let ret = ipfs.pubsub_subscribe(String::from_utf8(topic)?).await?;
Ok(IpfsNativeResponse::Subscribe(ret))
},
IpfsRequest::SubscriptionList => {
let list = ipfs.pubsub_subscribed().await?.into_iter().map(|s| s.into_bytes()).collect();
Ok(IpfsNativeResponse::SubscriptionList(list))
},
IpfsRequest::Unsubscribe(topic) => {
let ret = ipfs.pubsub_unsubscribe(str::from_utf8(&topic)?).await?;
Ok(IpfsNativeResponse::Unsubscribe(ret))
},
}
}
impl Future for IpfsWorker {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
// We use a `me` variable because the compiler isn't smart enough to allow borrowing
// multiple fields at once through a `Deref`.
let me = &mut *self;
// We remove each element from `requests` one by one and add them back only if necessary.
for n in (0..me.requests.len()).rev() {
let (id, mut request) = me.requests.swap_remove(n);
match Future::poll(Pin::new(&mut request.0), cx) {
Poll::Pending => me.requests.push((id, request)),
Poll::Ready(Ok(value)) => {
let _ = me.to_api.unbounded_send(WorkerToApi::Response { id, value });
cx.waker().wake_by_ref(); // reschedule to poll the new future
},
Poll::Ready(Err(error)) => {
let _ = me.to_api.unbounded_send(WorkerToApi::Fail { id, error });
}
};
}
// Check for messages coming from the [`IpfsApi`].
match Stream::poll_next(Pin::new(&mut me.from_api), cx) {
Poll::Pending => {},
Poll::Ready(None) => return Poll::Ready(()), // stops the worker
Poll::Ready(Some(ApiToWorker { id, request })) => {
let ipfs_node = me.ipfs_node.clone();
let future = Box::pin(ipfs_request(ipfs_node, request));
debug_assert!(me.requests.iter().all(|(i, _)| *i != id));
me.requests.push((id, IpfsWorkerRequest(future)));
cx.waker().wake_by_ref(); // reschedule the task to poll the request
}
}
Poll::Pending
}
}
impl fmt::Debug for IpfsWorker {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list()
.entries(self.requests.iter())
.finish()
}
}
impl fmt::Debug for IpfsWorkerRequest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("IpfsWorkerRequest").finish()
}
}
#[cfg(test)]
mod tests {
use crate::api::timestamp;
use super::*;
use sp_core::offchain::{IpfsRequest, IpfsRequestStatus, IpfsResponse, Duration};
#[test]
fn metadata_calls() {
let options = rust_ipfs::IpfsOptions::default();
let mut rt = tokio::runtime::Runtime::new().unwrap();
let ipfs_node = rt.block_on(async move {
let (ipfs, fut): (Ipfs, _) =
rust_ipfs::UninitializedIpfs::new().await.start().await.unwrap();
tokio::task::spawn(fut);
ipfs
});
let (mut api, worker) = ipfs(ipfs_node);
std::thread::spawn(move || {
let worker = rt.spawn(worker);
rt.block_on(worker).unwrap();
});
let deadline = timestamp::now().add(Duration::from_millis(10_000));
let id1 = api.request_start(IpfsRequest::Addrs).unwrap();
let id2 = api.request_start(IpfsRequest::BitswapStats).unwrap();
let id3 = api.request_start(IpfsRequest::Identity).unwrap();
let id4 = api.request_start(IpfsRequest::LocalAddrs).unwrap();
let id5 = api.request_start(IpfsRequest::Peers).unwrap();
match api.response_wait(&[id1, id2, id3, id4, id5], Some(deadline)).as_slice() {
[
IpfsRequestStatus::Finished(IpfsResponse::Addrs(..)),
IpfsRequestStatus::Finished(IpfsResponse::BitswapStats { .. }),
IpfsRequestStatus::Finished(IpfsResponse::Identity(..)),
IpfsRequestStatus::Finished(IpfsResponse::LocalAddrs(..)),
IpfsRequestStatus::Finished(IpfsResponse::Peers(..)),
] => {},
x => panic!("Connecting to the IPFS node failed: {:?}", x),
}
}
}