Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(gtest): make gtest thread safe #4032

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/waiter/tests/mx_lock_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ fn access_mx_lock_guard_from_different_msg_fails(
));
}

fn init_fixture(system: &System) -> (Program<'_>, MessageId) {
fn init_fixture(system: &System) -> (Program, MessageId) {
system.init_logger_with_default_filter("");
let program = Program::current(system);
program.send_bytes(USER_ID, []);
Expand Down
2 changes: 1 addition & 1 deletion examples/waiter/tests/rw_lock_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ fn access_rw_lock_guard_from_different_msg_fails(
));
}

fn init_fixture(system: &System, lock_type: RwLockType) -> (Program<'_>, MessageId) {
fn init_fixture(system: &System, lock_type: RwLockType) -> (Program, MessageId) {
system.init_logger_with_default_filter("");
let program = Program::current(system);
program.send_bytes(USER_ID, []);
Expand Down
1 change: 1 addition & 0 deletions gtest/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ log.workspace = true
indexmap.workspace = true
cargo_toml.workspace = true
etc.workspace = true
parking_lot.workspace = true

[dev-dependencies]
demo-custom.workspace = true
Expand Down
43 changes: 22 additions & 21 deletions gtest/src/mailbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,40 +16,44 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::{manager::ExtManager, CoreLog, Log, RunResult};
use crate::{
manager::{ExtManager, ExtManagerPointer},
CoreLog, Log, RunResult,
};
use codec::Encode;
use core_processor::common::JournalHandler;
use gear_core::{
ids::{MessageId, ProgramId},
message::{Dispatch, DispatchKind, Message, ReplyDetails, StoredMessage},
};
use gear_core_errors::{ReplyCode, SuccessReplyReason};
use std::{cell::RefCell, convert::TryInto};
use parking_lot::RwLock;
use std::{convert::TryInto, sync::Arc};

pub struct Mailbox<'a> {
manager: &'a RefCell<ExtManager>,
pub struct Mailbox {
manager: Arc<RwLock<ExtManager>>,
user_id: ProgramId,
}

impl<'a> Mailbox<'a> {
pub(crate) fn new(user_id: ProgramId, manager: &'a RefCell<ExtManager>) -> Mailbox<'a> {
impl Mailbox {
pub(crate) fn new(user_id: ProgramId, manager: Arc<RwLock<ExtManager>>) -> Mailbox {
Mailbox { user_id, manager }
}

pub fn contains<T: Into<Log> + Clone>(&self, log: &T) -> bool {
let log: Log = log.clone().into();
if let Some(mailbox) = self.manager.borrow().mailbox.get(&self.user_id) {
if let Some(mailbox) = self.manager.read().mailbox.get(&self.user_id) {
return mailbox.iter().any(|message| log.eq(message));
}
self.manager
.borrow_mut()
.write()
.mailbox
.insert(self.user_id, Vec::default());
false
}

pub fn take_message<T: Into<Log>>(&self, log: T) -> MessageReplier {
MessageReplier::new(self.remove_message(log), self.manager)
MessageReplier::new(self.remove_message(log), self.manager.clone())
}

pub fn reply(&self, log: Log, payload: impl Encode, value: u128) -> RunResult {
Expand All @@ -62,7 +66,7 @@ impl<'a> Mailbox<'a> {

pub fn claim_value<T: Into<Log>>(&self, log: T) {
let message = self.remove_message(log);
self.manager.borrow_mut().send_value(
self.manager.write().send_value(
message.source(),
Some(message.destination()),
message.value(),
Expand All @@ -72,7 +76,7 @@ impl<'a> Mailbox<'a> {
#[track_caller]
fn remove_message<T: Into<Log>>(&self, log: T) -> StoredMessage {
let log = log.into();
let mut manager = self.manager.borrow_mut();
let mut manager = self.manager.write();
let messages = manager
.mailbox
.get_mut(&self.user_id)
Expand All @@ -85,16 +89,13 @@ impl<'a> Mailbox<'a> {
}
}

pub struct MessageReplier<'a> {
pub struct MessageReplier {
log: CoreLog,
manager: &'a RefCell<ExtManager>,
manager: ExtManagerPointer,
}

impl<'a> MessageReplier<'a> {
pub(crate) fn new(
message: StoredMessage,
manager: &'a RefCell<ExtManager>,
) -> MessageReplier<'a> {
impl MessageReplier {
pub(crate) fn new(message: StoredMessage, manager: ExtManagerPointer) -> MessageReplier {
MessageReplier {
log: message.into(),
manager,
Expand All @@ -107,7 +108,7 @@ impl<'a> MessageReplier<'a> {

pub fn reply_bytes(&self, raw_payload: impl AsRef<[u8]>, value: u128) -> RunResult {
let message = Message::new(
MessageId::from(self.manager.borrow_mut().fetch_inc_message_nonce()),
MessageId::from(self.manager.write().fetch_inc_message_nonce()),
self.log.destination(),
self.log.source(),
raw_payload.as_ref().to_vec().try_into().unwrap(),
Expand All @@ -123,7 +124,7 @@ impl<'a> MessageReplier<'a> {
);

self.manager
.borrow_mut()
.write()
.validate_and_run_dispatch(Dispatch::new(DispatchKind::Reply, message))
}
}
Expand Down Expand Up @@ -395,7 +396,7 @@ mod tests {

let bn_before_schedule = 5;
let scheduled_delay = 10;
system.0.borrow_mut().send_delayed_dispatch(
system.0.write().send_delayed_dispatch(
Dispatch::new(DispatchKind::Handle, message),
scheduled_delay,
);
Expand Down
24 changes: 14 additions & 10 deletions gtest/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,19 @@ use gear_core_errors::{ErrorReplyReason, SignalCode, SimpleExecutionError};
use gear_lazy_pages_common::LazyPagesCosts;
use gear_lazy_pages_native_interface::LazyPagesNative;
use gear_wasm_instrument::gas_metering::Schedule;
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use rand::{rngs::StdRng, RngCore, SeedableRng};
use std::{
cell::{Ref, RefCell, RefMut},
collections::{BTreeMap, HashMap, VecDeque},
convert::TryInto,
rc::Rc,
sync::Arc,
};

const OUTGOING_LIMIT: u32 = 1024;
const OUTGOING_BYTES_LIMIT: u32 = 64 * 1024 * 1024;

pub(crate) type ExtManagerPointer = Arc<RwLock<ExtManager>>;

pub(crate) type Balance = u128;

#[derive(Debug)]
Expand Down Expand Up @@ -178,31 +180,33 @@ impl Program {
}

#[derive(Default, Debug, Clone)]
pub(crate) struct Actors(Rc<RefCell<BTreeMap<ProgramId, (TestActor, Balance)>>>);
pub(crate) struct Actors(Arc<RwLock<BTreeMap<ProgramId, (TestActor, Balance)>>>);

impl Actors {
pub fn borrow(&self) -> Ref<'_, BTreeMap<ProgramId, (TestActor, Balance)>> {
self.0.borrow()
pub fn borrow(&self) -> RwLockReadGuard<'_, BTreeMap<ProgramId, (TestActor, Balance)>> {
self.0.read()
}

pub fn borrow_mut(&mut self) -> RefMut<'_, BTreeMap<ProgramId, (TestActor, Balance)>> {
self.0.borrow_mut()
pub fn borrow_mut(
&mut self,
) -> RwLockWriteGuard<'_, BTreeMap<ProgramId, (TestActor, Balance)>> {
self.0.write()
}

fn insert(
&mut self,
program_id: ProgramId,
actor_and_balance: (TestActor, Balance),
) -> Option<(TestActor, Balance)> {
self.0.borrow_mut().insert(program_id, actor_and_balance)
self.0.write().insert(program_id, actor_and_balance)
}

pub fn contains_key(&self, program_id: &ProgramId) -> bool {
self.0.borrow().contains_key(program_id)
self.0.write().contains_key(program_id)
}

fn remove(&mut self, program_id: &ProgramId) -> Option<(TestActor, Balance)> {
self.0.borrow_mut().remove(program_id)
self.0.write().remove(program_id)
}
}

Expand Down
Loading
Loading