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
// This file is part of Gear.

// Copyright (C) 2021-2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! # Gear Scheduler Pallet

#![cfg_attr(not(feature = "std"), no_std)]
#![doc(html_logo_url = "https://docs.gear.rs/logo.svg")]
#![doc(html_favicon_url = "https://gear-tech.io/favicons/favicon.ico")]

// Runtime mock for running tests.
#[cfg(test)]
mod mock;

// Unit tests module.
#[cfg(test)]
mod tests;

#[macro_export]
macro_rules! impl_config {
    ($runtime:ty) => {
        impl pallet_gear_scheduler::Config for $runtime {
            type BlockLimiter = GearGas;
            type ReserveThreshold = ReserveThreshold;
            type WaitlistCost = ConstU64<100>;
            type MailboxCost = ConstU64<100>;
            type ReservationCost = ConstU64<100>;
            type DispatchHoldCost = ConstU64<100>;
        }
    };
}

// Public exports from pallet.
pub use pallet::*;

// Gear Scheduler Pallet module.
#[frame_support::pallet]
pub mod pallet {
    pub use frame_support::weights::Weight;

    use common::{
        scheduler::{SchedulingCostsPerBlock, TaskPoolImpl, *},
        storage::*,
        BlockLimiter, Origin,
    };
    use frame_support::{
        pallet_prelude::*,
        storage::PrefixIterator,
        traits::{Get, StorageVersion},
    };
    use frame_system::pallet_prelude::*;
    use sp_runtime::DispatchError;
    use sp_std::{convert::TryInto, marker::PhantomData};

    pub type Cost = u64;

    pub(crate) type GasAllowanceOf<T> = <<T as Config>::BlockLimiter as BlockLimiter>::GasAllowance;

    /// The current storage version.
    const SCHEDULER_STORAGE_VERSION: StorageVersion = StorageVersion::new(2);

    // Gear Scheduler Pallet's `Config`.
    #[pallet::config]
    pub trait Config: frame_system::Config {
        /// Block limits.
        type BlockLimiter: BlockLimiter<Balance = u64>;

        /// Amount of blocks for extra delay used to secure from outdated tasks.
        #[pallet::constant]
        type ReserveThreshold: Get<BlockNumberFor<Self>>;

        /// Cost for storing in waitlist per block.
        #[pallet::constant]
        type WaitlistCost: Get<Cost>;

        /// Cost for storing in mailbox per block.
        #[pallet::constant]
        type MailboxCost: Get<Cost>;

        /// Cost for reservation holding.
        #[pallet::constant]
        type ReservationCost: Get<Cost>;

        /// Cost for reservation holding.
        #[pallet::constant]
        type DispatchHoldCost: Get<Cost>;
    }

    // Gear Scheduler Pallet itself.
    //
    // Uses without storage info to avoid direct access to pallet's
    // storage from outside.
    //
    // Uses `SCHEDULER_STORAGE_VERSION` as current storage version.
    #[pallet::pallet]
    #[pallet::without_storage_info]
    #[pallet::storage_version(SCHEDULER_STORAGE_VERSION)]
    pub struct Pallet<T>(_);

    // Gear Scheduler Pallet error type.
    //
    // Used as inner error type for `Scheduler` implementation.
    #[pallet::error]
    pub enum Error<T> {
        /// Occurs when given task already exists in task pool.
        DuplicateTask,
        /// Occurs when task wasn't found in storage.
        TaskNotFound,
    }

    // Implementation of `DequeueError` for `Error<T>`
    // usage as `Queue::Error`.
    impl<T: crate::Config> TaskPoolError for Error<T> {
        fn duplicate_task() -> Self {
            Self::DuplicateTask
        }

        fn task_not_found() -> Self {
            Self::TaskNotFound
        }
    }

    /// Account Id type of the task.
    type AccountId<T> = <T as frame_system::Config>::AccountId;

    /// Task type of the scheduler.
    type Task<T> = ScheduledTask<AccountId<T>>;

    // Below goes storages and their gear's wrapper implementations.
    //
    // Note, that we declare storages private to avoid outside
    // interaction with them, but wrappers - public to be able
    // use them as generic parameters in public `Scheduler`
    // implementation.

    // ----

    // Private storage for the first block of incomplete tasks.
    #[pallet::storage]
    pub(crate) type FirstIncompleteTasksBlock<T> = StorageValue<_, BlockNumberFor<T>>;

    // Public wrap for storage of the first block of incomplete tasks.
    common::wrap_storage_value!(
        storage: FirstIncompleteTasksBlock,
        name: FirstIncompleteTasksBlockWrap,
        value: BlockNumberFor<T>
    );

    // ----

    // Private storage for task pool elements.
    // Primary item stored as second key of double map for optimization.
    // Value here is useless, so unit type used as space saver:
    // `assert_eq!(().encode().len(), 0)`
    #[pallet::storage]
    type TaskPool<T: Config> =
        StorageDoubleMap<_, Identity, BlockNumberFor<T>, Identity, Task<T>, ()>;

    // Public wrap of the mailbox elements.
    common::wrap_extended_storage_double_map!(
        storage: TaskPool,
        name: TaskPoolWrap,
        key1: BlockNumberFor<T>,
        key2: Task<T>,
        value: (),
        length: usize
    );

    // ----

    // Below goes callbacks, used for task scope algorithm.
    //
    // Note, that they are public like storage wrappers
    // only to be able to use as public trait's generics.

    // ----

    /// Callback function for success `add` and `delete` actions.
    pub struct OnChange<T: crate::Config>(PhantomData<T>);

    // Callback trait implementation.
    //
    // Addition to or deletion from task scope represented with single DB write.
    // This callback reduces block gas allowance by that value.
    impl<T: crate::Config> EmptyCallback for OnChange<T> {
        fn call() {
            let weight = T::DbWeight::get().writes(1);
            log::debug!(
                "TaskPool::OnChange; weight = {weight}, GasAllowance = {}",
                GasAllowanceOf::<T>::get()
            );
            GasAllowanceOf::<T>::decrease(weight.ref_time());
        }
    }

    // ----

    /// Store of queue action's callbacks.
    pub struct TaskPoolCallbacksImpl<T: crate::Config>(PhantomData<T>);

    // Callbacks store for task pool trait implementation.
    impl<T: crate::Config> TaskPoolCallbacks for TaskPoolCallbacksImpl<T> {
        type OnAdd = OnChange<T>;
        type OnDelete = OnChange<T>;
    }

    // ----

    // Below goes costs implementation.

    impl<T: crate::Config> SchedulingCostsPerBlock for Pallet<T>
    where
        T::AccountId: Origin,
    {
        type BlockNumber = BlockNumberFor<T>;
        type Cost = Cost;

        fn reserve_for() -> Self::BlockNumber {
            T::ReserveThreshold::get()
        }

        fn code() -> Self::Cost {
            todo!("#646");
        }

        fn mailbox() -> Self::Cost {
            T::MailboxCost::get()
        }

        fn program() -> Self::Cost {
            todo!("#646");
        }

        fn waitlist() -> Self::Cost {
            T::WaitlistCost::get()
        }

        fn reservation() -> Self::Cost {
            T::ReservationCost::get()
        }

        fn dispatch_stash() -> Self::Cost {
            T::DispatchHoldCost::get()
        }

        fn by_storage_type(storage: StorageType) -> Self::Cost {
            match storage {
                StorageType::Code => Self::code(),
                StorageType::Mailbox => Self::mailbox(),
                StorageType::Program => Self::program(),
                StorageType::Waitlist => Self::waitlist(),
                StorageType::Reservation => Self::reservation(),
                StorageType::DispatchStash => Self::dispatch_stash(),
            }
        }
    }

    // Below goes final `Scheduler` implementation for
    // Gear Scheduler Pallet based on above generated
    // types and parameters.

    /// Delayed tasks centralized behavior for
    /// Gear Scheduler Pallet.
    ///
    /// See `gear_common::scheduler::Scheduler` for
    /// complete documentation.
    impl<T: crate::Config> Scheduler for Pallet<T>
    where
        T::AccountId: Origin,
    {
        type BlockNumber = BlockNumberFor<T>;
        type Task = Task<T>;
        type Cost = u64;
        type Error = Error<T>;
        type OutputError = DispatchError;

        type CostsPerBlock = Self;

        type FirstIncompleteTasksBlock = FirstIncompleteTasksBlockWrap<T>;

        type TaskPool = TaskPoolImpl<
            TaskPoolWrap<T>,
            Self::Task,
            Self::Error,
            DispatchError,
            TaskPoolCallbacksImpl<T>,
        >;
    }
}