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
#![forbid(unsafe_code)]
use async_trait::async_trait;
use channel::{diem_channel, message_queues::QueueStyle};
use diem_infallible::RwLock;
use diem_types::{
account_state::AccountState,
contract_event::ContractEvent,
event::EventKey,
move_resource::MoveStorage,
on_chain_config,
on_chain_config::{config_address, OnChainConfigPayload, ON_CHAIN_CONFIG_REGISTRY},
transaction::Version,
};
use futures::{channel::mpsc::SendError, stream::FusedStream, Stream};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::{
collections::{HashMap, HashSet},
convert::TryFrom,
iter::FromIterator,
ops::Deref,
pin::Pin,
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
task::{Context, Poll},
};
use storage_interface::DbReaderWriter;
use thiserror::Error;
#[cfg(test)]
mod tests;
const EVENT_NOTIFICATION_CHANNEL_SIZE: usize = 100;
const RECONFIG_NOTIFICATION_CHANNEL_SIZE: usize = 1;
#[derive(Clone, Debug, Deserialize, Error, PartialEq, Serialize)]
pub enum Error {
#[error("Cannot subscribe to zero event keys!")]
CannotSubscribeToZeroEventKeys,
#[error("Missing event subscription! Subscription ID: {0}")]
MissingEventSubscription(u64),
#[error("Unable to send event notification! Error: {0}")]
UnableToSendEventNotification(String),
#[error("Unexpected error encountered: {0}")]
UnexpectedErrorEncountered(String),
}
impl From<SendError> for Error {
fn from(error: SendError) -> Self {
Error::UnableToSendEventNotification(error.to_string())
}
}
#[async_trait]
pub trait EventNotificationSender: Send {
async fn notify_events(
&mut self,
version: Version,
events: Vec<ContractEvent>,
) -> Result<(), Error>;
async fn notify_initial_configs(&mut self, version: Version) -> Result<(), Error>;
}
pub struct EventSubscriptionService {
event_key_subscriptions: HashMap<EventKey, HashSet<SubscriptionId>>,
subscription_id_to_event_subscription: HashMap<SubscriptionId, EventSubscription>,
reconfig_subscriptions: HashMap<SubscriptionId, ReconfigSubscription>,
storage: Arc<RwLock<DbReaderWriter>>,
next_subscription_id: AtomicU64,
}
impl EventSubscriptionService {
pub fn new(storage: Arc<RwLock<DbReaderWriter>>) -> Self {
Self {
event_key_subscriptions: HashMap::new(),
subscription_id_to_event_subscription: HashMap::new(),
reconfig_subscriptions: HashMap::new(),
storage,
next_subscription_id: AtomicU64::new(0),
}
}
pub fn subscribe_to_events(
&mut self,
event_keys: Vec<EventKey>,
) -> Result<EventNotificationListener, Error> {
if event_keys.is_empty() {
return Err(Error::CannotSubscribeToZeroEventKeys);
}
let (notification_sender, notification_receiver) =
diem_channel::new(QueueStyle::KLAST, EVENT_NOTIFICATION_CHANNEL_SIZE, None);
let subscription_id = self.get_new_subscription_id();
let event_subscription = EventSubscription {
subscription_id,
notification_sender,
event_buffer: vec![],
};
if let Some(old_subscription) = self
.subscription_id_to_event_subscription
.insert(subscription_id, event_subscription)
{
panic!(
"Duplicate event subscription found! This should not occur! ID: {}, subscription: {:?}",
subscription_id, old_subscription
);
}
for event_key in event_keys {
self.event_key_subscriptions
.entry(event_key)
.and_modify(|subscriptions| {
subscriptions.insert(subscription_id);
})
.or_insert_with(|| HashSet::from_iter(vec![subscription_id].iter().cloned()));
}
Ok(EventNotificationListener {
notification_receiver,
})
}
pub fn subscribe_to_reconfigurations(&mut self) -> Result<ReconfigNotificationListener, Error> {
let (notification_sender, notification_receiver) =
diem_channel::new(QueueStyle::KLAST, RECONFIG_NOTIFICATION_CHANNEL_SIZE, None);
let subscription_id = self.get_new_subscription_id();
let reconfig_subscription = ReconfigSubscription {
subscription_id,
notification_sender,
};
if let Some(old_subscription) = self
.reconfig_subscriptions
.insert(subscription_id, reconfig_subscription)
{
panic!(
"Duplicate reconfiguration subscription found! This should not occur! ID: {}, subscription: {:?}",
subscription_id, old_subscription
);
}
Ok(ReconfigNotificationListener {
notification_receiver,
})
}
fn get_new_subscription_id(&mut self) -> u64 {
self.next_subscription_id.fetch_add(1, Ordering::Relaxed)
}
fn notify_event_subscribers(
&mut self,
version: Version,
events: Vec<ContractEvent>,
) -> Result<bool, Error> {
let mut reconfig_event_found = false;
let mut event_subscription_ids_to_notify = HashSet::new();
for event in events.iter() {
let event_key = event.key();
if let Some(subscription_ids) = self.event_key_subscriptions.get(event_key) {
for subscription_id in subscription_ids.iter() {
if let Some(event_subscription) = self
.subscription_id_to_event_subscription
.get_mut(subscription_id)
{
event_subscription.buffer_event(event.clone());
event_subscription_ids_to_notify.insert(*subscription_id);
} else {
return Err(Error::MissingEventSubscription(*subscription_id));
}
}
}
if *event_key == on_chain_config::new_epoch_event_key() {
reconfig_event_found = true;
}
}
for event_subscription_id in event_subscription_ids_to_notify {
if let Some(event_subscription) = self
.subscription_id_to_event_subscription
.get_mut(&event_subscription_id)
{
event_subscription.notify_subscriber_of_events(version)?;
} else {
return Err(Error::MissingEventSubscription(event_subscription_id));
}
}
Ok(reconfig_event_found)
}
fn notify_reconfiguration_subscribers(&mut self, version: Version) -> Result<(), Error> {
if self.reconfig_subscriptions.is_empty() {
return Ok(()); }
let new_configs = self.read_on_chain_configs(version)?;
for (_, reconfig_subscription) in self.reconfig_subscriptions.iter_mut() {
reconfig_subscription.notify_subscriber_of_configs(version, new_configs.clone())?;
}
Ok(())
}
fn read_on_chain_configs(&self, version: Version) -> Result<OnChainConfigPayload, Error> {
let config_access_paths = ON_CHAIN_CONFIG_REGISTRY
.iter()
.map(|config_id| config_id.access_path())
.collect();
let on_chain_configs = self
.storage
.read()
.reader
.deref()
.batch_fetch_resources_by_version(config_access_paths, version)
.map_err(|error| {
Error::UnexpectedErrorEncountered(format!(
"Failed to batch fetch resources at version: {:?}. Error: {:?}",
version, error
))
})?;
let (account_state_blob, _) = self
.storage
.read()
.reader
.get_account_state_with_proof_by_version(config_address(), version)
.map_err(|error| {
Error::UnexpectedErrorEncountered(format!(
"Failed to fetch account state with proof {:?}",
error
))
})?;
let account_state_blob = account_state_blob.ok_or_else(|| {
Error::UnexpectedErrorEncountered("Missing account state blob!".into())
})?;
let epoch = AccountState::try_from(&account_state_blob)
.and_then(|state| {
Ok(state
.get_configuration_resource()?
.ok_or_else(|| {
Error::UnexpectedErrorEncountered(
"Configuration resource does not exist!".into(),
)
})?
.epoch())
})
.map_err(|error| {
Error::UnexpectedErrorEncountered(format!(
"Failed to fetch configuration resource! Error: {:?}",
error
))
})?;
Ok(OnChainConfigPayload::new(
epoch,
Arc::new(
ON_CHAIN_CONFIG_REGISTRY
.iter()
.cloned()
.zip_eq(on_chain_configs)
.collect(),
),
))
}
}
#[async_trait]
impl EventNotificationSender for EventSubscriptionService {
async fn notify_events(
&mut self,
version: Version,
events: Vec<ContractEvent>,
) -> Result<(), Error> {
if events.is_empty() {
return Ok(()); }
let reconfig_event_processed = self.notify_event_subscribers(version, events)?;
if reconfig_event_processed {
self.notify_reconfiguration_subscribers(version)
} else {
Ok(())
}
}
async fn notify_initial_configs(&mut self, version: Version) -> Result<(), Error> {
self.notify_reconfiguration_subscribers(version)
}
}
type SubscriptionId = u64;
#[derive(Debug)]
struct EventSubscription {
pub subscription_id: SubscriptionId,
pub event_buffer: Vec<ContractEvent>,
pub notification_sender: channel::diem_channel::Sender<(), EventNotification>,
}
impl EventSubscription {
fn buffer_event(&mut self, event: ContractEvent) {
self.event_buffer.push(event)
}
fn notify_subscriber_of_events(&mut self, version: Version) -> Result<(), Error> {
let event_notification = EventNotification {
subscribed_events: self.event_buffer.drain(..).collect(),
version,
};
self.notification_sender
.push((), event_notification)
.map_err(|error| Error::UnexpectedErrorEncountered(format!("{:?}", error)))
}
}
#[derive(Debug)]
struct ReconfigSubscription {
pub subscription_id: SubscriptionId,
pub notification_sender: channel::diem_channel::Sender<(), ReconfigNotification>,
}
impl ReconfigSubscription {
fn notify_subscriber_of_configs(
&mut self,
version: Version,
on_chain_configs: OnChainConfigPayload,
) -> Result<(), Error> {
let reconfig_notification = ReconfigNotification {
version,
on_chain_configs,
};
self.notification_sender
.push((), reconfig_notification)
.map_err(|error| Error::UnexpectedErrorEncountered(format!("{:?}", error)))
}
}
#[derive(Debug)]
pub struct EventNotification {
pub version: Version,
pub subscribed_events: Vec<ContractEvent>,
}
#[derive(Debug)]
pub struct ReconfigNotification {
pub version: Version,
pub on_chain_configs: OnChainConfigPayload,
}
pub type EventNotificationListener = NotificationListener<EventNotification>;
pub type ReconfigNotificationListener = NotificationListener<ReconfigNotification>;
pub struct NotificationListener<T> {
pub notification_receiver: channel::diem_channel::Receiver<(), T>,
}
impl<T> Stream for NotificationListener<T> {
type Item = T;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().notification_receiver).poll_next(cx)
}
}
impl<T> FusedStream for NotificationListener<T> {
fn is_terminated(&self) -> bool {
self.notification_receiver.is_terminated()
}
}