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
use crate::config::{Config, HashFor, RpcConfigFor};
use crate::error::BackendError;
use futures::{FutureExt, Stream, StreamExt};
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use subxt_rpcs::Error as RpcError;
use subxt_rpcs::methods::ChainHeadRpcMethods;
use subxt_rpcs::methods::chain_head::{
ArchiveStorageEvent, ArchiveStorageEventItem, ArchiveStorageQuery, ArchiveStorageSubscription,
};
pub struct ArchiveStorageStream<T: Config> {
at: HashFor<T>,
methods: ChainHeadRpcMethods<RpcConfigFor<T>>,
query_queue: VecDeque<ArchiveStorageQuery<Vec<u8>>>,
state: Option<StreamState<T>>,
}
enum StreamState<T: Config> {
GetSubscription {
current_query: ArchiveStorageQuery<Vec<u8>>,
sub_fut: Pin<
Box<
dyn Future<Output = Result<ArchiveStorageSubscription<HashFor<T>>, RpcError>>
+ Send
+ 'static,
>,
>,
},
RunSubscription {
current_query: ArchiveStorageQuery<Vec<u8>>,
sub: ArchiveStorageSubscription<HashFor<T>>,
},
}
impl<T: Config> ArchiveStorageStream<T> {
/// Fetch descendant keys.
pub fn new(
at: HashFor<T>,
methods: ChainHeadRpcMethods<RpcConfigFor<T>>,
query_queue: VecDeque<ArchiveStorageQuery<Vec<u8>>>,
) -> Self {
Self {
at,
methods,
query_queue,
state: None,
}
}
}
impl<T: Config> std::marker::Unpin for ArchiveStorageStream<T> {}
impl<T: Config> Stream for ArchiveStorageStream<T> {
type Item = Result<ArchiveStorageEventItem<HashFor<T>>, BackendError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.as_mut();
loop {
match this.state.take() {
// No state yet so initialise!
None => {
// Nothing left; we're done.
let Some(query) = this.query_queue.pop_front() else {
return Poll::Ready(None);
};
let at = this.at;
let methods = this.methods.clone();
let current_query = query.clone();
let sub_fut = async move {
let query = std::iter::once(ArchiveStorageQuery {
key: query.key.as_ref(),
query_type: query.query_type,
pagination_start_key: query.pagination_start_key.as_deref(),
});
methods.archive_v1_storage(at, query, None).await
};
this.state = Some(StreamState::GetSubscription {
current_query,
sub_fut: Box::pin(sub_fut),
});
}
// We're getting our subscription stream for the current query.
Some(StreamState::GetSubscription {
current_query,
mut sub_fut,
}) => {
match sub_fut.poll_unpin(cx) {
Poll::Ready(Ok(sub)) => {
this.state = Some(StreamState::RunSubscription { current_query, sub });
}
Poll::Ready(Err(e)) => {
if e.is_disconnected_will_reconnect() {
// Push the query back onto the queue to try again
this.query_queue.push_front(current_query);
continue;
}
this.state = None;
return Poll::Ready(Some(Err(e.into())));
}
Poll::Pending => {
this.state = Some(StreamState::GetSubscription {
current_query,
sub_fut,
});
return Poll::Pending;
}
}
}
// Running the subscription and returning results.
Some(StreamState::RunSubscription {
current_query,
mut sub,
}) => {
match sub.poll_next_unpin(cx) {
Poll::Ready(Some(Ok(val))) => {
match val {
ArchiveStorageEvent::Item(item) => {
this.state = Some(StreamState::RunSubscription {
current_query: ArchiveStorageQuery {
key: current_query.key,
query_type: current_query.query_type,
// In the event of error, we resume from the last seen value.
// At the time of writing, it's not clear if paginationStartKey
// starts from the key itself or the first key after it:
// https://github.com/paritytech/json-rpc-interface-spec/issues/176
pagination_start_key: Some(item.key.0.clone()),
},
sub,
});
// We treat `paginationStartKey` as being the key we want results to begin _after_.
// So, if we see a value that's <= it, ignore the value.
let ignore_this_value = current_query
.pagination_start_key
.as_ref()
.is_some_and(|k| item.key.0.cmp(k).is_le());
if ignore_this_value {
continue;
}
return Poll::Ready(Some(Ok(item)));
}
ArchiveStorageEvent::Error(e) => {
this.state = None;
return Poll::Ready(Some(Err(BackendError::other(e.error))));
}
ArchiveStorageEvent::Done => {
this.state = None;
continue;
}
}
}
Poll::Ready(Some(Err(e))) => {
if e.is_disconnected_will_reconnect() {
// Put the current query back into the queue and retry.
// We've been keeping it uptodate as needed.
this.query_queue.push_front(current_query);
this.state = None;
continue;
}
this.state = None;
return Poll::Ready(Some(Err(e.into())));
}
Poll::Ready(None) => {
this.state = None;
continue;
}
Poll::Pending => {
this.state = Some(StreamState::RunSubscription { current_query, sub });
return Poll::Pending;
}
}
}
}
}
}
}