Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ mod args;
mod catalog;
mod suite;

use std::{num::NonZeroUsize, process::ExitCode, rc::Rc};
use std::{
num::NonZeroUsize,
process::ExitCode,
rc::Rc,
sync::{Arc, OnceLock},
time::Instant,
};

use anyhow::Context;
use args::{Benchmarks, Checks, Cli, Command};
Expand Down Expand Up @@ -60,15 +66,18 @@ fn run_seed(seed: Option<u64>) -> u64 {
}

async fn interruptible(
run: impl AsyncFnOnce(watch::Receiver<bool>) -> Result<()>,
run: impl AsyncFnOnce(watch::Receiver<bool>, Arc<OnceLock<Instant>>) -> Result<()>,
) -> Result<ExitCode> {
let (stop, receiver) = watch::channel(false);
let stop_requested_at = Arc::new(OnceLock::new());
let interrupted_at = stop_requested_at.clone();
let interrupt = tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
interrupted_at.get_or_init(Instant::now);
stop.send_replace(true);
}
});
let outcome = run(receiver.clone()).await;
let outcome = run(receiver.clone(), stop_requested_at).await;
interrupt.abort();
if *receiver.borrow() {
if let Err(error) = outcome {
Expand Down Expand Up @@ -129,10 +138,11 @@ async fn dispatch(command: Command) -> Result<ExitCode> {
} else {
None
};
return interruptible(async move |stop| {
return interruptible(async move |stop, stop_requested_at| {
let config = ExecutionConfig {
duration: Some(args.duration),
stop: Some(stop),
stop_requested_at: Some(stop_requested_at),
environment,
profile: args.profile,
loop_mode: args.loop_mode,
Expand All @@ -154,11 +164,12 @@ async fn dispatch(command: Command) -> Result<ExitCode> {
},
Command::Continuous(args) => {
let seed = run_seed(args.seed);
return interruptible(async move |stop| {
return interruptible(async move |stop, stop_requested_at| {
let config = ExecutionConfig {
seed,
duration: Some(args.duration),
stop: Some(stop),
stop_requested_at: Some(stop_requested_at),
profile: args.profile,
continuous: true,
..ExecutionConfig::default()
Expand Down
28 changes: 26 additions & 2 deletions core/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ use solana_instruction_error::InstructionError;
use solana_rpc_client_types::{
config::{
RpcBlockConfig, RpcProgramAccountsConfig, RpcSendTransactionConfig,
RpcSignaturesForAddressConfig, RpcSimulateTransactionConfig, RpcTransactionConfig,
RpcSignatureStatusConfig, RpcSignaturesForAddressConfig, RpcSimulateTransactionConfig,
RpcTransactionConfig,
},
request::RpcRequest,
response::{
Expand Down Expand Up @@ -332,9 +333,32 @@ impl Api {
pub async fn get_signature_statuses(
&self,
signatures: &[Signature],
) -> Result<Vec<Option<TransactionStatus>>> {
self.signature_statuses(signatures, None).await
}

pub async fn get_signature_statuses_with_history(
&self,
signatures: &[Signature],
) -> Result<Vec<Option<TransactionStatus>>> {
self.signature_statuses(
signatures,
Some(RpcSignatureStatusConfig { search_transaction_history: true }),
)
.await
}

async fn signature_statuses(
&self,
signatures: &[Signature],
config: Option<RpcSignatureStatusConfig>,
) -> Result<Vec<Option<TransactionStatus>>> {
let signatures: Vec<_> = signatures.iter().map(ToString::to_string).collect();
self.call_value(RpcRequest::GetSignatureStatuses, &(signatures,)).await
let method = RpcRequest::GetSignatureStatuses;
match config {
Some(config) => self.call_value(method, &(signatures, config)).await,
None => self.call_value(method, &(signatures,)).await,
}
}

/// Reads receipts without JSON's per-instruction base58 encoding, which is
Expand Down
8 changes: 7 additions & 1 deletion core/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use clap::ValueEnum;
use std::{path::PathBuf, rc::Rc, time::Duration};
use std::{
path::PathBuf,
rc::Rc,
sync::{Arc, OnceLock},
time::{Duration, Instant},
};
use url::Url;

/// An existing devnet-backed environment whose processes are not owned by RedSuite.
Expand Down Expand Up @@ -57,6 +62,7 @@ pub struct ExecutionConfig {
pub seed: u64,
pub duration: Option<Duration>,
pub stop: Option<tokio::sync::watch::Receiver<bool>>,
pub stop_requested_at: Option<Arc<OnceLock<Instant>>>,
pub environment: Option<Rc<Environment>>,
pub continuous: bool,
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/report/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ pub fn run_id() -> &'static str {
RUN_ID.get_or_init(|| format!("{}-{}", utc_stamp(), std::process::id()))
}

fn campaign_dir() -> PathBuf {
pub fn campaign_dir() -> PathBuf {
reports_dir().join(run_id())
}

Expand Down
3 changes: 1 addition & 2 deletions core/src/transport/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,7 @@ impl EventSubscriptions {
topic,
payload: PhantomData,
};
self.connection.subscribe(topic, params, (key, topic)).await?;
self.connection.await_ack((key, topic)).await?;
self.connection.subscribe_and_wait(topic, params, (key, topic)).await?;
Ok(subscription)
}

Expand Down
1 change: 1 addition & 0 deletions core/src/transport/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub const NETWORK_TIMEOUT: Duration = Duration::from_secs(60);
pub mod clock;
pub mod events;
pub mod http;
pub mod observations;
pub mod rate;
pub(crate) mod rpc;
mod socket;
Expand Down
126 changes: 126 additions & 0 deletions core/src/transport/observations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
use std::{
ops::ControlFlow::{Break, Continue},
rc::Rc,
};

use pubkey::Pubkey;
use signature::Signature;
use tokio::sync::Notify;
use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
use url::Url;

use super::{
socket::CloseReason,
subscription::{self, Connection, SubscriptionState, Topic},
};
use crate::Result;

#[derive(Clone, Copy, PartialEq)]
enum Key {
Account(usize),
Signature(u64),
}

#[derive(Clone, Copy)]
pub enum ObservationClose {
GoingAway,
Transport,
Other,
}

#[derive(Default)]
struct Observer {
close_reason: Option<ObservationClose>,
closed: Rc<Notify>,
}

impl SubscriptionState for Observer {
type Key = Key;

fn on_close(&mut self, reason: &CloseReason) {
self.close_reason = Some(match reason {
CloseReason::ServerClose(Some(frame)) if frame.code == CloseCode::Away => {
ObservationClose::GoingAway
}
CloseReason::Transport(_) => ObservationClose::Transport,
_ => ObservationClose::Other,
});
self.closed.notify_waiters();
}
}

pub enum Notification {
Account { index: usize, data: Vec<u8> },
Signature { id: u64, succeeded: bool },
}

pub struct ObservationSocket {
connection: Connection<Observer>,
}

impl ObservationSocket {
pub async fn connect(
url: &Url,
mut observe: impl FnMut(Notification) + 'static,
) -> Result<Self> {
let connection =
Connection::connect(url, Observer::default(), move |_, key, payload| match key {
Key::Account(index) => {
if let Some(data) = subscription::account_data(payload) {
observe(Notification::Account { index, data });
}
Continue(())
}
Key::Signature(id) => {
let Some(result) = subscription::processed_signature(payload) else {
return Continue(());
};
observe(Notification::Signature {
id,
succeeded: result.err.is_none(),
});
Break(())
}
})
.await?;
Ok(Self { connection })
}

pub async fn account(&self, index: usize, address: &Pubkey) -> Result<()> {
self.connection
.subscribe_and_wait(
Topic::Account,
&subscription::account_params(address),
Key::Account(index),
)
.await
}

pub async fn signature(&self, id: u64, signature: &Signature) -> Result<()> {
self.connection
.subscribe_and_wait(
Topic::Signature,
&subscription::signature_params(signature),
Key::Signature(id),
)
.await
}

pub async fn unsubscribe_signature(&self, id: u64) -> Result<()> {
self.connection.unsubscribe(Key::Signature(id), Topic::Signature).await
}

pub fn is_open(&self) -> bool {
self.connection.check_error().is_ok()
}

pub async fn closed(&self) -> ObservationClose {
let closed = self.connection.state().closed.clone();
let notification = closed.notified();
if let Some(reason) = self.connection.state().close_reason {
return reason;
}
notification.await;
self.connection.state().close_reason.expect("close notification has a reason")
}
}
25 changes: 23 additions & 2 deletions core/src/transport/subscription.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use solana_rpc_client_types::{
RpcTransactionLogsConfig, RpcTransactionLogsFilter,
},
request::RpcRequest,
response::Response,
response::{ProcessedSignatureResult, Response, RpcSignatureResult},
};
use tokio::{
sync::{Mutex, Notify},
Expand Down Expand Up @@ -221,6 +221,19 @@ impl<S: SubscriptionState + 'static> Connection<S> {
Ok(())
}

pub(super) async fn subscribe_and_wait(
&self,
topic: Topic,
params: &impl Serialize,
key: S::Key,
) -> Result<()>
where
S::Key: PartialEq,
{
self.subscribe(topic, params, key).await?;
self.await_ack(key).await
}

pub(super) fn state(&self) -> Ref<'_, S> {
Ref::map(self.router.borrow(), |router| &router.state)
}
Expand Down Expand Up @@ -282,7 +295,7 @@ impl<S: SubscriptionState + 'static> Connection<S> {
)
}

pub(super) async fn await_ack(&self, key: S::Key) -> Result<()>
async fn await_ack(&self, key: S::Key) -> Result<()>
where
S::Key: PartialEq,
{
Expand Down Expand Up @@ -339,6 +352,14 @@ impl<S: SubscriptionState> Drop for Connection<S> {
}
}

pub(super) fn processed_signature(payload: &LazyValue<'_>) -> Option<ProcessedSignatureResult> {
let response: Response<RpcSignatureResult> = json::from_str(payload.as_raw_str()).ok()?;
match response.value {
RpcSignatureResult::ProcessedSignature(result) => Some(result),
RpcSignatureResult::ReceivedSignature(_) => None,
}
}

pub(super) fn account_data(payload: &LazyValue<'_>) -> Option<Vec<u8>> {
let payload: Response<UiAccount> = json::from_str(payload.as_raw_str()).ok()?;
payload.value.data.decode()
Expand Down
12 changes: 3 additions & 9 deletions core/src/transport/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use anyhow::Context;
use json::LazyValue;
use pubkey::Pubkey;
use signature::Signature;
use solana_rpc_client_types::response::{Response, RpcSignatureResult};
use tokio::{sync::oneshot, time};
use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
use url::Url;
Expand Down Expand Up @@ -224,11 +223,7 @@ impl SubscriptionState for SignatureState {

impl SignatureState {
fn observe(&mut self, id: u64, payload: &LazyValue<'_>, clock: &SendClock) -> ControlFlow<()> {
let Ok(Response {
value: RpcSignatureResult::ProcessedSignature(result),
..
}) = json::from_str::<Response<RpcSignatureResult>>(payload.as_raw_str())
else {
let Some(result) = subscription::processed_signature(payload) else {
return Continue(());
};
if !self.pending.remove(&id) {
Expand Down Expand Up @@ -273,13 +268,12 @@ impl SignatureConfirmations {
self.connection.check_error()?;
self.connection.state_mut().pending.insert(id);
self.connection
.subscribe(
.subscribe_and_wait(
Topic::Signature,
&subscription::signature_params(signature),
id,
)
.await?;
self.connection.await_ack(id).await
.await
}

pub async fn await_id(&self, id: u64) -> Result<()> {
Expand Down
Loading
Loading