Skip to content

Commit

Permalink
Introduce config for default mx lock duration; re-export some type al…
Browse files Browse the repository at this point in the history
…iases
  • Loading branch information
Dennis Diatlov committed Jul 20, 2023
1 parent 0ec7e5b commit 31e9712
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 27 deletions.
2 changes: 2 additions & 0 deletions gcore/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ pub use general::*;
mod utils;
pub use utils::ext;

pub use gsys::{BlockCount, BlockNumber};

use core::mem::size_of;
use static_assertions::const_assert;

Expand Down
3 changes: 3 additions & 0 deletions gstd/src/common/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ pub enum Error {
/// function (see
/// [Config::set_system_reserve](crate::Config::set_system_reserve)).
ZeroSystemReservationAmount,
/// This error occurs when providing zero duration to mutex lock function
ZeroMxLockDuration,
}

impl Error {
Expand All @@ -74,6 +76,7 @@ impl fmt::Display for Error {
Error::ZeroSystemReservationAmount => {
write!(f, "System reservation amount can not be zero in config.")
}
Error::ZeroMxLockDuration => write!(f, "Mutex lock duration can not be zero."),
}
}
}
Expand Down
42 changes: 33 additions & 9 deletions gstd/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@
//! Gear libs are `#![no_std]`, which makes them lightweight.

//! This module is for configuring `gstd` inside gear programs.
use crate::errors::{Error, Result};
use crate::{
errors::{Error, Result},
BlockCount,
};

/// Wait types.
#[derive(Clone, Copy, Default)]
Expand All @@ -39,12 +42,17 @@ pub struct Config {
/// count.
///
/// Initial value: **100 blocks**
pub wait_up_to: u32,
pub wait_up_to: BlockCount,

/// Default wait duration for `wait_for` messages expressed in block count.
///
/// Initial value: **100 blocks**
pub wait_for: u32,
pub wait_for: BlockCount,

/// Default amount of blocks a mutex lock can be owned for by a message.
///
/// Initial value: **100 blocks**
pub mx_lock_duration: BlockCount,

/// Default gas amount reserved for system purposes.
///
Expand All @@ -59,6 +67,7 @@ impl Config {
Self {
wait_up_to: 100,
wait_for: 100,
mx_lock_duration: 100,
system_reserve: 1_000_000_000,
wait_type: WaitType::WaitUpTo,
}
Expand All @@ -69,22 +78,27 @@ impl Config {
}

/// Get the `wait_for` duration (in blocks).
pub fn wait_for() -> u32 {
pub fn wait_for() -> BlockCount {
unsafe { CONFIG.wait_for }
}

/// Get the `wait_up_to` duration (in blocks).
pub fn wait_up_to() -> u32 {
pub fn wait_up_to() -> BlockCount {
unsafe { CONFIG.wait_up_to }
}

/// Get the `mx_lock_duration` duration (in blocks).
pub fn mx_lock_duration() -> BlockCount {
unsafe { CONFIG.mx_lock_duration }
}

/// Get the `system_reserve` gas amount.
pub fn system_reserve() -> u64 {
unsafe { CONFIG.system_reserve }
}

/// Set `wait_for` duration (in blocks).
pub fn set_wait_for(duration: u32) -> Result<()> {
pub fn set_wait_for(duration: BlockCount) -> Result<()> {
if duration == 0 {
return Err(Error::EmptyWaitDuration);
}
Expand All @@ -97,15 +111,15 @@ impl Config {
///
/// Calling this function forces all async functions that wait for some
/// condition to wait exactly for `duration` blocks.
pub fn set_default_wait_for(duration: u32) -> Result<()> {
pub fn set_default_wait_for(duration: BlockCount) -> Result<()> {
Self::set_wait_for(duration)?;
unsafe { CONFIG.wait_type = WaitType::WaitFor };

Ok(())
}

/// Set the `wait_up_to` duration (in blocks).
pub fn set_wait_up_to(duration: u32) -> Result<()> {
pub fn set_wait_up_to(duration: BlockCount) -> Result<()> {
if duration == 0 {
return Err(Error::EmptyWaitDuration);
}
Expand All @@ -118,13 +132,23 @@ impl Config {
///
/// Calling this function forces all async functions that wait for some
/// condition to wait not more than `duration` blocks.
pub fn set_default_wait_up_to(duration: u32) -> Result<()> {
pub fn set_default_wait_up_to(duration: BlockCount) -> Result<()> {
Self::set_wait_up_to(duration)?;
unsafe { CONFIG.wait_type = WaitType::WaitUpTo };

Ok(())
}

/// Set `mx_lock_duration_max` duration (in blocks).
pub fn set_mx_lock_duration(duration: BlockCount) -> Result<()> {
if duration == 0 {
return Err(Error::ZeroMxLockDuration);
}

unsafe { CONFIG.mx_lock_duration = duration };
Ok(())
}

/// Set `system_reserve` gas amount.
pub fn set_system_reserve(amount: u64) -> Result<()> {
if amount == 0 {
Expand Down
2 changes: 1 addition & 1 deletion gstd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ pub mod util;
pub use async_runtime::{handle_signal, message_loop, record_reply};
pub use common::{errors, primitives::*};
pub use config::Config;
pub use gcore::ext;
pub use gcore::{ext, BlockCount, BlockNumber};
pub use gstd_codegen::{async_init, async_main};
pub use prelude::*;
pub use reservations::*;
Expand Down
30 changes: 13 additions & 17 deletions gstd/src/lock/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use super::access::AccessQueue;
use crate::{async_runtime, exec, msg, MessageId};
use crate::{async_runtime, exec, msg, BlockCount, BlockNumber, Config, MessageId};
use core::{
cell::UnsafeCell,
future::Future,
Expand Down Expand Up @@ -77,7 +77,7 @@ use core::{
/// # fn main() {}
/// ```
pub struct Mutex<T> {
locked: UnsafeCell<Option<(MessageId, u32)>>,
locked: UnsafeCell<Option<(MessageId, BlockNumber)>>,
value: UnsafeCell<T>,
queue: AccessQueue,
}
Expand All @@ -104,7 +104,7 @@ impl<T> Mutex<T> {
pub fn lock(&self) -> MutexLockFuture<'_, T> {
MutexLockFuture {
mutex: self,
own_up_for_block_count: None,
own_up_for: Config::mx_lock_duration(),
}
}
}
Expand Down Expand Up @@ -227,30 +227,26 @@ unsafe impl<T> Sync for Mutex<T> {}
/// ```
pub struct MutexLockFuture<'a, T> {
mutex: &'a Mutex<T>,
own_up_for_block_count: Option<u32>,
own_up_for: BlockCount,
}

impl<'a, T> MutexLockFuture<'a, T> {
/// Sets the maximum number of blocks the mutex lock can be owned by
/// some message before the ownership can be seized by another rival
pub fn own_up_for(self, block_count: u32) -> Self {
pub fn own_up_for(self, block_count: BlockCount) -> Self {
MutexLockFuture {
mutex: self.mutex,
own_up_for_block_count: Some(block_count),
own_up_for: block_count,
}
}

fn acquire_lock_ownership(
&mut self,
owner_msg_id: MessageId,
current_block_number: u32,
current_block: BlockNumber,
) -> Poll<MutexGuard<'a, T>> {
let locked_by = unsafe { &mut *self.mutex.locked.get() };
*locked_by = Some((
owner_msg_id,
self.own_up_for_block_count
.map_or(u32::MAX, |v| current_block_number.saturating_add(v)),
));
*locked_by = Some((owner_msg_id, current_block.saturating_add(self.own_up_for)));
Poll::Ready(MutexGuard {
mutex: self.mutex,
holder_msg_id: owner_msg_id,
Expand All @@ -276,10 +272,10 @@ impl<'a, T> Future for MutexLockFuture<'a, T> {
// mutex can be taken, else it waits (goes into *waiting queue*).
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
let current_msg_id = msg::id();
let current_block_number = exec::block_height();
let current_block = exec::block_height();
let locked_by = unsafe { &mut *self.mutex.locked.get() };
if let Some((lock_owner_msg_id, deadline_block_number)) = *locked_by {
if current_block_number > deadline_block_number {
if let Some((lock_owner_msg_id, deadline_block)) = *locked_by {
if current_block > deadline_block {
if let Some(msg_future_task) = async_runtime::futures().get_mut(&lock_owner_msg_id)
{
msg_future_task.set_lock_exceeded();
Expand All @@ -300,12 +296,12 @@ impl<'a, T> Future for MutexLockFuture<'a, T> {

return self
.get_mut()
.acquire_lock_ownership(current_msg_id, current_block_number);
.acquire_lock_ownership(current_msg_id, current_block);
}
return self.get_mut().queue_for_lock_ownership(current_msg_id);
}

self.get_mut()
.acquire_lock_ownership(current_msg_id, current_block_number)
.acquire_lock_ownership(current_msg_id, current_block)
}
}
3 changes: 3 additions & 0 deletions gsys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ pub type ErrorCode = u32;
/// Represents block number type.
pub type BlockNumber = u32;

/// Represents block count type.
pub type BlockCount = u32;

/// Represents block number type.
pub type BlockTimestamp = u64;

Expand Down

0 comments on commit 31e9712

Please sign in to comment.