Skip to content

Commit add37ea

Browse files
committed
Revert "chore(ctx): replace gstuff constructible with oncelock (#2267)"
This reverts commit ac926dd
1 parent cb3fddc commit add37ea

File tree

21 files changed

+53
-87
lines changed

21 files changed

+53
-87
lines changed

mm2src/coins/eth/eth_tests.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
use super::*;
22
use crate::IguanaPrivKey;
3-
use common::block_on;
3+
use common::{block_on, block_on_f01};
44
use mm2_core::mm_ctx::MmCtxBuilder;
55

66
cfg_native!(
77
use crate::eth::for_tests::{eth_coin_for_test, eth_coin_from_keypair};
88
use crate::DexFee;
99

10-
use common::{now_sec, block_on_f01};
10+
use common::now_sec;
1111
use ethkey::{Generator, Random};
1212
use mm2_test_helpers::for_tests::{ETH_MAINNET_CHAIN_ID, ETH_MAINNET_NODE, ETH_SEPOLIA_CHAIN_ID, ETH_SEPOLIA_NODES,
1313
ETH_SEPOLIA_TOKEN_CONTRACT};

mm2src/coins/hd_wallet/storage/sqlite_storage.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ impl HDWalletStorageInternalOps for HDWalletSqliteStorage {
101101
where
102102
Self: Sized,
103103
{
104-
let shared = ctx.shared_sqlite_conn.get().or_mm_err(|| {
104+
let shared = ctx.shared_sqlite_conn.as_option().or_mm_err(|| {
105105
HDWalletStorageError::Internal("'MmCtx::shared_sqlite_conn' is not initialized".to_owned())
106106
})?;
107107
let storage = HDWalletSqliteStorage {

mm2src/coins/lightning/ln_utils.rs

-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ pub async fn init_db(ctx: &MmArc, ticker: String) -> EnableLightningResult<Sqlit
8787
let db = SqliteLightningDB::new(
8888
ticker,
8989
ctx.sqlite_connection
90-
.get()
9190
.ok_or(MmError::new(EnableLightningError::DbError(
9291
"sqlite_connection is not initialized".into(),
9392
)))?

mm2src/coins/nft/nft_structs.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -734,15 +734,14 @@ impl NftCtx {
734734
/// If an `NftCtx` instance doesn't already exist in the MM context, it gets created and cached for subsequent use.
735735
#[cfg(not(target_arch = "wasm32"))]
736736
pub(crate) fn from_ctx(ctx: &MmArc) -> Result<Arc<NftCtx>, String> {
737-
from_ctx(&ctx.nft_ctx, move || {
737+
Ok(try_s!(from_ctx(&ctx.nft_ctx, move || {
738738
let async_sqlite_connection = ctx
739739
.async_sqlite_connection
740-
.get()
741740
.ok_or("async_sqlite_connection is not initialized".to_owned())?;
742741
Ok(NftCtx {
743742
nft_cache_db: async_sqlite_connection.clone(),
744743
})
745-
})
744+
})))
746745
}
747746

748747
#[cfg(target_arch = "wasm32")]

mm2src/coins/tx_history_storage/sql_tx_history_storage_v2.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -376,12 +376,11 @@ pub struct SqliteTxHistoryStorage(Arc<Mutex<Connection>>);
376376

377377
impl SqliteTxHistoryStorage {
378378
pub fn new(ctx: &MmArc) -> Result<Self, MmError<CreateTxHistoryStorageError>> {
379-
let sqlite_connection =
380-
ctx.sqlite_connection
381-
.get()
382-
.ok_or(MmError::new(CreateTxHistoryStorageError::Internal(
383-
"sqlite_connection is not initialized".to_owned(),
384-
)))?;
379+
let sqlite_connection = ctx
380+
.sqlite_connection
381+
.ok_or(MmError::new(CreateTxHistoryStorageError::Internal(
382+
"sqlite_connection is not initialized".to_owned(),
383+
)))?;
385384
Ok(SqliteTxHistoryStorage(sqlite_connection.clone()))
386385
}
387386
}

mm2src/coins/utxo/utxo_block_header_storage/mod.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ impl Debug for BlockHeaderStorage {
2727
impl BlockHeaderStorage {
2828
#[cfg(all(not(test), not(target_arch = "wasm32")))]
2929
pub(crate) fn new_from_ctx(ctx: MmArc, ticker: String) -> Result<Self, BlockHeaderStorageError> {
30-
let sqlite_connection = ctx.sqlite_connection.get().ok_or(BlockHeaderStorageError::Internal(
30+
let sqlite_connection = ctx.sqlite_connection.ok_or(BlockHeaderStorageError::Internal(
3131
"sqlite_connection is not initialized".to_owned(),
3232
))?;
3333
Ok(BlockHeaderStorage {
@@ -50,11 +50,8 @@ impl BlockHeaderStorage {
5050
use db_common::sqlite::rusqlite::Connection;
5151
use std::sync::{Arc, Mutex};
5252

53-
let conn = ctx
54-
.sqlite_connection
55-
.get()
56-
.cloned()
57-
.unwrap_or_else(|| Arc::new(Mutex::new(Connection::open_in_memory().unwrap())));
53+
let conn = Arc::new(Mutex::new(Connection::open_in_memory().unwrap()));
54+
let conn = ctx.sqlite_connection.clone_or(conn);
5855

5956
Ok(BlockHeaderStorage {
6057
inner: Box::new(SqliteBlockHeadersStorage { ticker, conn }),

mm2src/coins/z_coin/storage/blockdb/blockdb_sql_storage.rs

+9-11
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,10 @@ impl BlockDbImpl {
4949
async_blocking(move || {
5050
let conn = Connection::open(path).map_to_mm(|err| ZcoinStorageError::DbError(err.to_string()))?;
5151
let conn = Arc::new(Mutex::new(conn));
52-
let conn_lock = conn.lock().unwrap();
53-
run_optimization_pragmas(&conn_lock).map_to_mm(|err| ZcoinStorageError::DbError(err.to_string()))?;
54-
conn_lock
52+
let conn_clone = conn.clone();
53+
let conn_clone = conn_clone.lock().unwrap();
54+
run_optimization_pragmas(&conn_clone).map_to_mm(|err| ZcoinStorageError::DbError(err.to_string()))?;
55+
conn_clone
5556
.execute(
5657
"CREATE TABLE IF NOT EXISTS compactblocks (
5758
height INTEGER PRIMARY KEY,
@@ -60,7 +61,6 @@ impl BlockDbImpl {
6061
[],
6162
)
6263
.map_to_mm(|err| ZcoinStorageError::DbError(err.to_string()))?;
63-
drop(conn_lock);
6464

6565
Ok(Self { db: conn, ticker })
6666
})
@@ -73,12 +73,11 @@ impl BlockDbImpl {
7373
async_blocking(move || {
7474
let conn = ctx
7575
.sqlite_connection
76-
.get()
77-
.cloned()
78-
.unwrap_or_else(|| Arc::new(Mutex::new(Connection::open_in_memory().unwrap())));
79-
let conn_lock = conn.lock().unwrap();
80-
run_optimization_pragmas(&conn_lock).map_err(|err| ZcoinStorageError::DbError(err.to_string()))?;
81-
conn_lock
76+
.clone_or(Arc::new(Mutex::new(Connection::open_in_memory().unwrap())));
77+
let conn_clone = conn.clone();
78+
let conn_clone = conn_clone.lock().unwrap();
79+
run_optimization_pragmas(&conn_clone).map_err(|err| ZcoinStorageError::DbError(err.to_string()))?;
80+
conn_clone
8281
.execute(
8382
"CREATE TABLE IF NOT EXISTS compactblocks (
8483
height INTEGER PRIMARY KEY,
@@ -87,7 +86,6 @@ impl BlockDbImpl {
8786
[],
8887
)
8988
.map_to_mm(|err| ZcoinStorageError::DbError(err.to_string()))?;
90-
drop(conn_lock);
9189

9290
Ok(BlockDbImpl { db: conn, ticker })
9391
})

mm2src/crypto/src/crypto_ctx.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -316,12 +316,10 @@ impl CryptoCtx {
316316
*ctx_field = Some(result.clone());
317317
drop(ctx_field);
318318

319-
ctx.rmd160
320-
.set(rmd160)
321-
.map_to_mm(|_| CryptoInitError::Internal("Already Initialized".to_string()))?;
319+
ctx.rmd160.pin(rmd160).map_to_mm(CryptoInitError::Internal)?;
322320
ctx.shared_db_id
323-
.set(shared_db_id)
324-
.map_to_mm(|_| CryptoInitError::Internal("Already Initialized".to_string()))?;
321+
.pin(shared_db_id)
322+
.map_to_mm(CryptoInitError::Internal)?;
325323

326324
info!("Public key hash: {rmd160}");
327325
info!("Shared Database ID: {shared_db_id}");

mm2src/mm2_bin_lib/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ fn mm2_status() -> MainStatus {
4141
Err(_) => return MainStatus::NoRpc,
4242
};
4343

44-
if *ctx.rpc_started.get().unwrap_or(&false) {
44+
if ctx.rpc_started.copy_or(false) {
4545
MainStatus::RpcIsUp
4646
} else {
4747
MainStatus::NoRpc

mm2src/mm2_bin_lib/src/mm2_wasm_lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ pub async fn mm2_rpc(payload: JsValue) -> Result<JsValue, JsValue> {
216216
Err(_) => return Err(Mm2RpcErr::NotRunning.into()),
217217
};
218218

219-
let wasm_rpc = ctx.wasm_rpc.get().ok_or(JsValue::from(Mm2RpcErr::NotRunning))?;
219+
let wasm_rpc = ctx.wasm_rpc.ok_or(JsValue::from(Mm2RpcErr::NotRunning))?;
220220
let response: Mm2RpcResponse = wasm_rpc.request(request_json).await.into();
221221

222222
serialize_to_js(&response).map_err(|e| {

mm2src/mm2_core/Cargo.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ common = { path = "../common" }
1515
db_common = { path = "../db_common" }
1616
derive_more = "0.99"
1717
futures = { version = "0.3", package = "futures", features = ["compat", "async-await", "thread-pool"] }
18-
gstuff = { version = "0.7", features = ["nightly"] }
1918
hex = "0.4.2"
2019
lazy_static = "1.4"
2120
libp2p = { git = "https://github.com/KomodoPlatform/rust-libp2p.git", tag = "k-0.52.12", default-features = false, features = ["identify"] }
@@ -32,13 +31,15 @@ shared_ref_counter = { path = "../common/shared_ref_counter" }
3231
uuid = { version = "1.2.2", features = ["fast-rng", "serde", "v4"] }
3332

3433
[target.'cfg(target_arch = "wasm32")'.dependencies]
34+
gstuff = { version = "0.7", features = ["nightly"] }
3535
instant = { version = "0.1.12", features = ["wasm-bindgen"] }
3636
mm2_rpc = { path = "../mm2_rpc", features = [ "rpc_facilities" ] }
3737
timed-map = { version = "1.3", features = ["rustc-hash", "wasm"] }
3838
wasm-bindgen-test = { version = "0.3.2" }
3939

4040
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
4141
rustls = { version = "0.21", default-features = false }
42+
gstuff = { version = "0.7", features = ["nightly"] }
4243
instant = "0.1.12"
4344
tokio = { version = "1.20", features = ["io-util", "rt-multi-thread", "net"] }
4445
timed-map = { version = "1.3", features = ["rustc-hash"] }

mm2src/mm2_gui_storage/src/account/storage/sqlite_storage.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ impl SqliteAccountStorage {
118118
pub(crate) fn new(ctx: &MmArc) -> AccountStorageResult<SqliteAccountStorage> {
119119
let shared = ctx
120120
.sqlite_connection
121-
.get()
121+
.as_option()
122122
.or_mm_err(|| AccountStorageError::Internal("'MmCtx::sqlite_connection' is not initialized".to_owned()))?;
123123
Ok(SqliteAccountStorage {
124124
conn: Arc::clone(shared),

mm2src/mm2_main/src/lp_native_dex.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -477,9 +477,7 @@ pub async fn lp_init_continue(ctx: MmArc) -> MmInitResult<()> {
477477
let balance_update_ordermatch_handler = BalanceUpdateOrdermatchHandler::new(ctx.clone());
478478
register_balance_update_handler(ctx.clone(), Box::new(balance_update_ordermatch_handler)).await;
479479

480-
ctx.initialized
481-
.set(true)
482-
.map_to_mm(|_| MmInitError::Internal("Already Initialized".to_string()))?;
480+
ctx.initialized.pin(true).map_to_mm(MmInitError::Internal)?;
483481

484482
// launch kickstart threads before RPC is available, this will prevent the API user to place
485483
// an order and start new swap that might get started 2 times because of kick-start

mm2src/mm2_main/src/lp_wallet.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -305,8 +305,8 @@ fn initialize_crypto_context(ctx: &MmArc, passphrase: &str) -> WalletInitResult<
305305
pub(crate) async fn initialize_wallet_passphrase(ctx: &MmArc) -> WalletInitResult<()> {
306306
let (wallet_name, passphrase) = deserialize_wallet_config(ctx)?;
307307
ctx.wallet_name
308-
.set(wallet_name.clone())
309-
.map_to_mm(|_| WalletInitError::InternalError("Already Initialized".to_string()))?;
308+
.pin(wallet_name.clone())
309+
.map_to_mm(WalletInitError::InternalError)?;
310310
let passphrase = process_passphrase_logic(ctx, wallet_name, passphrase).await?;
311311

312312
if let Some(passphrase) = passphrase {
@@ -541,7 +541,7 @@ pub async fn get_wallet_names_rpc(ctx: MmArc, _req: Json) -> MmResult<GetWalletN
541541
let wallets = read_all_wallet_names(&ctx).await?.sorted().collect();
542542
// Note: `ok_or` is used here on `Constructible<Option<String>>` to handle the case where the wallet name is not set.
543543
// `wallet_name` can be `None` in the case of no-login mode.
544-
let activated_wallet = ctx.wallet_name.get().ok_or(GetWalletsError::Internal(
544+
let activated_wallet = ctx.wallet_name.ok_or(GetWalletsError::Internal(
545545
"`wallet_name` not initialized yet!".to_string(),
546546
))?;
547547

mm2src/mm2_main/src/lp_wallet/mnemonics_storage.rs

-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ pub(super) async fn save_encrypted_passphrase(
4747
pub(super) async fn read_encrypted_passphrase_if_available(ctx: &MmArc) -> WalletsStorageResult<Option<EncryptedData>> {
4848
let wallet_name = ctx
4949
.wallet_name
50-
.get()
5150
.ok_or(WalletsStorageError::Internal(
5251
"`wallet_name` not initialized yet!".to_string(),
5352
))?

mm2src/mm2_main/src/lp_wallet/mnemonics_wasm_db.rs

-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,6 @@ pub(super) async fn read_encrypted_passphrase_if_available(ctx: &MmArc) -> Walle
126126

127127
let wallet_name = ctx
128128
.wallet_name
129-
.get()
130129
.ok_or(WalletsDBError::Internal(
131130
"`wallet_name` not initialized yet!".to_string(),
132131
))?

mm2src/mm2_main/src/mm2.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ pub fn mm2_main(version: String, datetime: String) {
278278
}
279279

280280
if first_arg == Some("--version") || first_arg == Some("-v") || first_arg == Some("version") {
281-
println!("Komodo DeFi Framework: {version}");
281+
println!("AtomicDEX API: {version}");
282282
return;
283283
}
284284

@@ -292,7 +292,7 @@ pub fn mm2_main(version: String, datetime: String) {
292292
return;
293293
}
294294

295-
log!("Komodo DeFi Framework {} DT {}", version, datetime);
295+
log!("AtomicDEX API {} DT {}", version, datetime);
296296

297297
if let Err(err) = run_lp_main(first_arg, &|_| (), version, datetime) {
298298
log!("{}", err);

mm2src/mm2_main/src/ordermatch_tests.rs

+3-12
Original file line numberDiff line numberDiff line change
@@ -1055,10 +1055,7 @@ fn test_cancel_by_single_coin() {
10551055
let rx = prepare_for_cancel_by(&ctx);
10561056

10571057
let connection = Connection::open_in_memory().unwrap();
1058-
let _ = ctx
1059-
.sqlite_connection
1060-
.set(Arc::new(Mutex::new(connection)))
1061-
.map_err(|_| "Already Initialized".to_string());
1058+
let _ = ctx.sqlite_connection.pin(Arc::new(Mutex::new(connection)));
10621059

10631060
delete_my_maker_order.mock_safe(|_, _, _| MockResult::Return(Box::new(futures01::future::ok(()))));
10641061
delete_my_taker_order.mock_safe(|_, _, _| MockResult::Return(Box::new(futures01::future::ok(()))));
@@ -1077,10 +1074,7 @@ fn test_cancel_by_pair() {
10771074
let rx = prepare_for_cancel_by(&ctx);
10781075

10791076
let connection = Connection::open_in_memory().unwrap();
1080-
let _ = ctx
1081-
.sqlite_connection
1082-
.set(Arc::new(Mutex::new(connection)))
1083-
.map_err(|_| "Already Initialized".to_string());
1077+
let _ = ctx.sqlite_connection.pin(Arc::new(Mutex::new(connection)));
10841078

10851079
delete_my_maker_order.mock_safe(|_, _, _| MockResult::Return(Box::new(futures01::future::ok(()))));
10861080
delete_my_taker_order.mock_safe(|_, _, _| MockResult::Return(Box::new(futures01::future::ok(()))));
@@ -1103,10 +1097,7 @@ fn test_cancel_by_all() {
11031097
let rx = prepare_for_cancel_by(&ctx);
11041098

11051099
let connection = Connection::open_in_memory().unwrap();
1106-
let _ = ctx
1107-
.sqlite_connection
1108-
.set(Arc::new(Mutex::new(connection)))
1109-
.map_err(|_| "Already Initialized".to_string());
1100+
let _ = ctx.sqlite_connection.pin(Arc::new(Mutex::new(connection)));
11101101

11111102
delete_my_maker_order.mock_safe(|_, _, _| MockResult::Return(Box::new(futures01::future::ok(()))));
11121103
delete_my_taker_order.mock_safe(|_, _, _| MockResult::Return(Box::new(futures01::future::ok(()))));

mm2src/mm2_main/src/rpc.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,7 @@ pub extern "C" fn spawn_rpc(ctx_h: u32) {
410410
$port,
411411
now_sec()
412412
);
413-
let _ = $ctx.rpc_started.set(true);
413+
let _ = $ctx.rpc_started.pin(true);
414414
server
415415
});
416416
}
@@ -479,7 +479,7 @@ pub fn spawn_rpc(ctx_h: u32) {
479479
use std::sync::Mutex;
480480

481481
let ctx = MmArc::from_ffi_handle(ctx_h).expect("No context");
482-
if ctx.wasm_rpc.get().is_some() {
482+
if ctx.wasm_rpc.is_some() {
483483
error!("RPC is initialized already");
484484
return;
485485
}
@@ -512,12 +512,12 @@ pub fn spawn_rpc(ctx_h: u32) {
512512
ctx.spawner().spawn(fut);
513513

514514
// even if the [`MmCtx::wasm_rpc`] is initialized already, the spawned future above will be shutdown
515-
if ctx.wasm_rpc.set(request_tx).is_err() {
516-
error!("'MmCtx::wasm_rpc' is initialized already");
515+
if let Err(e) = ctx.wasm_rpc.pin(request_tx) {
516+
error!("'MmCtx::wasm_rpc' is initialized already: {}", e);
517517
return;
518518
};
519-
if ctx.rpc_started.set(true).is_err() {
520-
error!("'MmCtx::rpc_started' is set already");
519+
if let Err(e) = ctx.rpc_started.pin(true) {
520+
error!("'MmCtx::rpc_started' is set already: {}", e);
521521
return;
522522
}
523523

mm2src/mm2_main/tests/docker_tests/swap_watcher_tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3320,5 +3320,5 @@ fn test_watcher_reward() {
33203320

33213321
let watcher_reward =
33223322
block_on(utxo_coin.get_maker_watcher_reward(&MmCoinEnum::UtxoCoin(utxo_coin.clone()), None, timeout)).unwrap();
3323-
assert!(watcher_reward.is_none());
3323+
assert!(matches!(watcher_reward, None));
33243324
}

0 commit comments

Comments
 (0)