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
#![deny(
clippy::disallowed_methods,
clippy::suspicious,
clippy::style,
clippy::clone_on_ref_ptr,
missing_debug_implementations,
missing_copy_implementations
)]
#![warn(clippy::pedantic, missing_docs)]
#![allow(clippy::module_name_repetitions)]
//! Vixen provides a simple API for requesting, parsing, and consuming data
//! from Yellowstone.
use std::marker::PhantomData;
use config::BufferConfig;
use tokio::sync::{mpsc, oneshot};
use yellowstone_grpc_proto::tonic::Status;
use crate::sources::SourceExitStatus;
#[cfg(feature = "prometheus")]
pub extern crate prometheus;
#[cfg(feature = "prometheus")]
pub mod metrics;
pub extern crate thiserror;
pub extern crate yellowstone_vixen_core as vixen_core;
pub use vixen_core::bs58;
mod buffer;
pub mod builder;
pub mod config;
pub mod handler;
pub mod instruction;
pub mod sources;
/// Utility functions for the Vixen runtime.
pub mod util;
pub mod filter_pipeline;
pub use handler::{Handler, HandlerResult, Pipeline};
pub use util::*;
use yellowstone_grpc_proto::geyser::SubscribeUpdate;
pub use yellowstone_vixen_core::CommitmentLevel;
use crate::{builder::RuntimeBuilder, sources::SourceTrait};
/// An error thrown by the Vixen runtime.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// A system I/O error.
#[error("I/O error")]
Io(#[from] std::io::Error),
/// An error returned by a Yellowstone server.
#[error("Yellowstone client builder error")]
YellowstoneBuilder(#[from] yellowstone_grpc_client::GeyserGrpcBuilderError),
/// An error returned by a Yellowstone client.
#[error("Yellowstone client error")]
YellowstoneClient(#[from] yellowstone_grpc_client::GeyserGrpcClientError),
/// An error occurring when the Yellowstone client stops early.
#[error("Yellowstone client crashed")]
ClientHangup,
/// An error occurring when the Yellowstone server closes the connection.
#[error("Yellowstone stream hung up unexpectedly")]
ServerHangup,
/// A gRPC error returned by the Yellowstone server.
#[error("Yellowstone stream returned an error")]
YellowstoneStatus(#[from] yellowstone_grpc_proto::tonic::Status),
/// An error occurring when a datasource is not configured correctly.
#[error("Yellowstone stream config error")]
ConfigError,
/// An error occurring when a runtime error occurs.
#[error("Other error")]
Other(#[from] Box<dyn std::error::Error + Send + Sync>),
}
/// The main runtime for Vixen.
#[derive(Debug)]
pub struct Runtime<S: SourceTrait> {
buffer: BufferConfig,
source: S::Config,
pipelines: handler::PipelineSets,
#[cfg(feature = "prometheus")]
metrics_registry: prometheus::Registry,
_source: PhantomData<S>,
}
impl<S: SourceTrait> Runtime<S> {
/// Create a new runtime builder.
pub fn builder() -> RuntimeBuilder<S> { RuntimeBuilder::<S>::default() }
}
impl<S: SourceTrait> Runtime<S> {
/// Create a new Tokio runtime and run the Vixen runtime within it,
/// terminating the current process if the runtime crashes.
///
/// For error handling, use the recoverable variant [`Self::try_run`].
///
/// If you want to provide your own tokio Runtime because you need to run
/// async code outside of the Vixen runtime, use the [`Self::run_async`]
/// method.
///
/// # Example
///
/// ```ignore
/// use yellowstone_vixen::Pipeline;
/// use yellowstone_vixen_spl_token_parser::{AccountParser, InstructionParser};
///
/// // MyHandler is a handler that implements the Handler trait
/// // NOTE: The main function is not async
/// fn main() {
/// Runtime::builder::<YellowstoneGrpcSource>()
/// .account(Pipeline::new(AccountParser, [MyHandler]))
/// .instruction(Pipeline::new(InstructionParser, [MyHandler]))
/// .build(config)
/// .run(); // Process will exit if an error occurs
/// }
/// ```
#[inline]
pub fn run(self) { util::handle_fatal(self.try_run()); }
/// Error returning variant of [`Self::run`].
///
/// # Errors
/// This function returns an error if the runtime crashes.
#[inline]
pub fn try_run(self) -> Result<(), Box<Error>> {
tokio::runtime::Runtime::new()
.map_err(|e| Box::new(e.into()))?
.block_on(self.try_run_async())
}
/// Run the Vixen runtime asynchronously, terminating the current process
/// if the runtime crashes.
///
/// For error handling, use the recoverable variant [`Self::try_run_async`].
///
/// If you don't need to run any async code outside the Vixen runtime, you
/// can use the [`Self::run`] method instead, which takes care of creating
/// a tokio Runtime for you.
///
/// # Example
///
/// ```ignore
/// use yellowstone_vixen_parser::{
/// token_extension_program::{
/// AccountParser as TokenExtensionProgramAccParser,
/// InstructionParser as TokenExtensionProgramIxParser,
/// },
/// token_program::{
/// AccountParser as TokenProgramAccParser, InstructionParser as TokenProgramIxParser,
/// },
/// };
///
/// // MyHandler is a handler that implements the Handler trait
///
/// #[tokio::main]
/// async fn main() {
/// Runtime::builder::<YellowstoneGrpcSource>()
/// .account(Pipeline::new(TokenProgramAccParser, [MyHandler]))
/// .account(Pipeline::new(TokenExtensionProgramAccParser, [MyHandler]))
/// .instruction(Pipeline::new(TokenExtensionProgramIxParser, [MyHandler]))
/// .instruction(Pipeline::new(TokenProgramIxParser, [MyHandler]))
/// .build(config)
/// .run_async()
/// .await;
/// }
/// ```
#[inline]
pub async fn run_async(self) { util::handle_fatal(self.try_run_async().await); }
/// Error returning variant of [`Self::run_async`].
///
/// # Errors
/// This function returns an error if the runtime crashes.
///
/// # Panics
/// Only panics if the rustls crypto provider fails to install.
///
/// # Shutdown Flows
///
/// ```text
/// ┌─────────────────────────────────────────────────────────────────────┐
/// │ RUNTIME SELECT! │
/// │ │
/// │ Signal ─────────────────┐ │
/// │ (Ctrl+C, SIGTERM) │ │
/// │ ▼ │
/// │ ┌─────────────┐ ┌─────────────┐ │
/// │ │Signal wins │────▶│stop_buffer()│ │
/// │ │select! │ │drops rx │ │
/// │ └─────────────┘ └──────┬──────┘ │
/// │ │ │ │
/// │ ▼ ▼ │
/// │ Ok(()) exit Source sees send │
/// │ fail, but select! │
/// │ already done │
/// │ │
/// ├─────────────────────────────────────────────────────────────────────┤
/// │ │
/// │ Buffer ─────────────────┐ │
/// │ (rx recv error/close) │ │
/// │ ▼ │
/// │ ┌─────────────┐ │
/// │ │Buffer wins │────▶ Err(YellowstoneStatus) │
/// │ │select! │ or Ok(StopCode) │
/// │ └─────────────┘ │
/// │ │
/// ├─────────────────────────────────────────────────────────────────────┤
/// │ │
/// │ SourceExit ─────────────┐ │
/// │ (source task ended) │ │
/// │ ▼ │
/// │ ┌─────────────┐ │
/// │ │SourceExit │ │
/// │ │wins select! │ │
/// │ └──────┬──────┘ │
/// │ │ │
/// │ ┌──────────────┬───┴──------───┬──────────────┐ │
/// │ ▼ ▼ ▼ ▼ │
/// │ Completed StreamEnded StreamError Error │
/// │ (finite src) (unexpected) (gRPC) (other) │
/// │ │ │ │ │ │
/// │ ▼ ▼ ▼ ▼ │
/// │ Ok(()) ServerHangup ServerHangup Other │
/// │ │
/// │ ┌──────────────────────────────────────────────────────────┐ │
/// │ │ ReceiverDropped: defensive only - normally unreachable │ │
/// │ │ because Signal/Buffer branch wins first when rx drops │ │
/// │ └──────────────────────────────────────────────────────────┘ │
/// └─────────────────────────────────────────────────────────────────────┘
/// ```
#[tracing::instrument("Runtime::run", skip(self))]
#[allow(clippy::too_many_lines)]
pub async fn try_run_async(self) -> Result<(), Box<Error>> {
enum StopType<S> {
Signal(S),
Buffer(Result<(), Error>),
SourceExit(Result<SourceExitStatus, oneshot::error::RecvError>),
}
let (tx, updates_rx) =
mpsc::channel::<Result<SubscribeUpdate, Status>>(self.buffer.sources_channel_size);
let (status_tx, status_rx) = oneshot::channel::<SourceExitStatus>();
#[cfg(feature = "prometheus")]
metrics::register_metrics(&self.metrics_registry);
let filters = self.pipelines.filters();
let source = S::new(self.source, filters);
tokio::spawn(async move {
let _ = source.connect(tx, status_tx).await;
});
let signal;
#[cfg(unix)]
{
use futures_util::stream::{FuturesUnordered, StreamExt};
use tokio::signal::unix::SignalKind;
let mut stream = [
SignalKind::hangup(),
SignalKind::interrupt(),
SignalKind::quit(),
SignalKind::terminate(),
]
.into_iter()
.map(|k| {
tokio::signal::unix::signal(k).map(|mut s| async move {
s.recv().await;
Ok(k)
})
})
.collect::<Result<FuturesUnordered<_>, _>>()
.map_err(|e| Box::new(e.into()))?;
signal = async move { stream.next().await.transpose() }
}
#[cfg(not(unix))]
{
use std::fmt;
use futures_util::TryFutureExt;
struct CtrlC;
impl fmt::Debug for CtrlC {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("^C") }
}
signal = tokio::signal::ctrl_c()
.map_ok(|()| Some(CtrlC))
.map_err(Into::into);
}
let mut buffer = buffer::Buffer::run_yellowstone(self.buffer, updates_rx, self.pipelines);
let stop_ty = tokio::select! {
s = signal => StopType::Signal(s),
b = buffer.wait_for_stop() => StopType::Buffer(b),
status = status_rx => StopType::SourceExit(status),
};
let should_stop_buffer = !matches!(stop_ty, StopType::Buffer(..));
match stop_ty {
StopType::Signal(Ok(Some(s))) => {
tracing::warn!("{s:?} received, shutting down...");
Ok(())
},
StopType::Signal(Ok(None)) => Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"Signal handler returned None",
)
.into()),
StopType::Buffer(result) => result,
StopType::Signal(Err(e)) => Err(e),
StopType::SourceExit(Ok(status)) => match status {
SourceExitStatus::ReceiverDropped => {
tracing::info!("Source stopped: receiver dropped (shutdown)");
Ok(())
},
SourceExitStatus::Completed => {
tracing::info!("Source completed successfully");
Ok(())
},
SourceExitStatus::StreamEnded => {
tracing::warn!("Source stopped: stream ended unexpectedly");
Err(Error::ServerHangup)
},
SourceExitStatus::StreamError { code, message } => {
tracing::error!(?code, %message, "Source stopped: stream error");
Err(Error::YellowstoneStatus(Status::new(code, message)))
},
SourceExitStatus::Error(msg) => {
tracing::error!(%msg, "Source stopped: error");
Err(Error::Other(msg.into()))
},
},
StopType::SourceExit(Err(_)) => {
tracing::warn!("Source exit status channel closed unexpectedly");
Err(Error::ClientHangup)
},
}?;
if should_stop_buffer {
Self::stop_buffer(buffer).await;
}
Ok(())
}
async fn stop_buffer(buffer: buffer::Buffer) {
match buffer.join().await {
Err(e) => tracing::warn!(err = %Chain(&e), "Error stopping runtime buffer"),
Ok(c) => c.as_unit(),
}
}
}
#[cfg(test)]
mod runtime_tests;