frame_support/traits/schedule.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Traits and associated utilities for scheduling dispatchables in FRAME.
19
20#[allow(deprecated)]
21use super::PreimageProvider;
22use codec::{Codec, Decode, DecodeWithMemTracking, Encode, EncodeLike, MaxEncodedLen};
23use core::{fmt::Debug, result::Result};
24use scale_info::TypeInfo;
25use sp_runtime::{traits::Saturating, DispatchError};
26
27/// Information relating to the period of a scheduled task. First item is the length of the
28/// period and the second is the number of times it should be executed in total before the task
29/// is considered finished and removed.
30pub type Period<BlockNumber> = (BlockNumber, u32);
31
32/// Priority with which a call is scheduled. It's just a linear amount with lowest values meaning
33/// higher priority.
34pub type Priority = u8;
35
36/// The dispatch time of a scheduled task.
37#[derive(
38 Encode,
39 Decode,
40 DecodeWithMemTracking,
41 Copy,
42 Clone,
43 PartialEq,
44 Eq,
45 Debug,
46 TypeInfo,
47 MaxEncodedLen,
48)]
49pub enum DispatchTime<BlockNumber> {
50 /// At specified block.
51 At(BlockNumber),
52 /// After specified number of blocks.
53 After(BlockNumber),
54}
55
56impl<BlockNumber: Saturating + Copy> DispatchTime<BlockNumber> {
57 pub fn evaluate(&self, since: BlockNumber) -> BlockNumber {
58 match &self {
59 Self::At(m) => *m,
60 Self::After(m) => m.saturating_add(since),
61 }
62 }
63}
64
65/// The highest priority. We invert the value so that normal sorting will place the highest
66/// priority at the beginning of the list.
67pub const HIGHEST_PRIORITY: Priority = 0;
68/// Anything of this value or lower will definitely be scheduled on the block that they ask for,
69/// even if it breaches the `MaximumWeight` limitation.
70pub const HARD_DEADLINE: Priority = 63;
71/// The lowest priority. Most stuff should be around here.
72pub const LOWEST_PRIORITY: Priority = 255;
73
74/// Type representing an encodable value or the hash of the encoding of such a value.
75#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
76pub enum MaybeHashed<T, Hash> {
77 /// The value itself.
78 Value(T),
79 /// The hash of the encoded value which this value represents.
80 Hash(Hash),
81}
82
83impl<T, H> From<T> for MaybeHashed<T, H> {
84 fn from(t: T) -> Self {
85 MaybeHashed::Value(t)
86 }
87}
88
89/// Error type for `MaybeHashed::lookup`.
90#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
91pub enum LookupError {
92 /// A call of this hash was not known.
93 Unknown,
94 /// The preimage for this hash was known but could not be decoded into a `Call`.
95 BadFormat,
96}
97
98impl<T: Decode, H> MaybeHashed<T, H> {
99 pub fn as_value(&self) -> Option<&T> {
100 match &self {
101 Self::Value(c) => Some(c),
102 Self::Hash(_) => None,
103 }
104 }
105
106 pub fn as_hash(&self) -> Option<&H> {
107 match &self {
108 Self::Value(_) => None,
109 Self::Hash(h) => Some(h),
110 }
111 }
112
113 pub fn ensure_requested<P: PreimageProvider<H>>(&self) {
114 match &self {
115 Self::Value(_) => (),
116 Self::Hash(hash) => P::request_preimage(hash),
117 }
118 }
119
120 pub fn ensure_unrequested<P: PreimageProvider<H>>(&self) {
121 match &self {
122 Self::Value(_) => (),
123 Self::Hash(hash) => P::unrequest_preimage(hash),
124 }
125 }
126
127 pub fn resolved<P: PreimageProvider<H>>(self) -> (Self, Option<H>) {
128 match self {
129 Self::Value(c) => (Self::Value(c), None),
130 Self::Hash(h) => {
131 let data = match P::get_preimage(&h) {
132 Some(p) => p,
133 None => return (Self::Hash(h), None),
134 };
135 match T::decode(&mut &data[..]) {
136 Ok(c) => (Self::Value(c), Some(h)),
137 Err(_) => (Self::Hash(h), None),
138 }
139 },
140 }
141 }
142}
143
144pub mod v3 {
145 use super::*;
146 use crate::traits::Bounded;
147
148 /// A type that can be used as a scheduler.
149 pub trait Anon<BlockNumber, Call, Origin> {
150 /// An address which can be used for removing a scheduled task.
151 type Address: Codec + MaxEncodedLen + Clone + Eq + EncodeLike + Debug + TypeInfo;
152 /// The hasher used in the runtime.
153 type Hasher: sp_runtime::traits::Hash;
154
155 /// Schedule a dispatch to happen at the beginning of some block in the future.
156 ///
157 /// This is not named.
158 fn schedule(
159 when: DispatchTime<BlockNumber>,
160 maybe_periodic: Option<Period<BlockNumber>>,
161 priority: Priority,
162 origin: Origin,
163 call: Bounded<Call, Self::Hasher>,
164 ) -> Result<Self::Address, DispatchError>;
165
166 /// Cancel a scheduled task. If periodic, then it will cancel all further instances of that,
167 /// also.
168 ///
169 /// Will return an `Unavailable` error if the `address` is invalid.
170 ///
171 /// NOTE: This guaranteed to work only *before* the point that it is due to be executed.
172 /// If it ends up being delayed beyond the point of execution, then it cannot be cancelled.
173 ///
174 /// NOTE2: This will not work to cancel periodic tasks after their initial execution. For
175 /// that, you must name the task explicitly using the `Named` trait.
176 fn cancel(address: Self::Address) -> Result<(), DispatchError>;
177
178 /// Reschedule a task. For one-off tasks, this dispatch is guaranteed to succeed
179 /// only if it is executed *before* the currently scheduled block. For periodic tasks,
180 /// this dispatch is guaranteed to succeed only before the *initial* execution; for
181 /// others, use `reschedule_named`.
182 ///
183 /// Will return an `Unavailable` error if the `address` is invalid.
184 fn reschedule(
185 address: Self::Address,
186 when: DispatchTime<BlockNumber>,
187 ) -> Result<Self::Address, DispatchError>;
188
189 /// Return the next dispatch time for a given task.
190 ///
191 /// Will return an `Unavailable` error if the `address` is invalid.
192 fn next_dispatch_time(address: Self::Address) -> Result<BlockNumber, DispatchError>;
193 }
194
195 pub type TaskName = [u8; 32];
196
197 /// A type that can be used as a scheduler.
198 pub trait Named<BlockNumber, Call, Origin> {
199 /// An address which can be used for removing a scheduled task.
200 type Address: Codec + MaxEncodedLen + Clone + Eq + EncodeLike + core::fmt::Debug;
201 /// The hasher used in the runtime.
202 type Hasher: sp_runtime::traits::Hash;
203
204 /// Schedule a dispatch to happen at the beginning of some block in the future.
205 ///
206 /// - `id`: The identity of the task. This must be unique and will return an error if not.
207 ///
208 /// NOTE: This will request `call` to be made available.
209 fn schedule_named(
210 id: TaskName,
211 when: DispatchTime<BlockNumber>,
212 maybe_periodic: Option<Period<BlockNumber>>,
213 priority: Priority,
214 origin: Origin,
215 call: Bounded<Call, Self::Hasher>,
216 ) -> Result<Self::Address, DispatchError>;
217
218 /// Cancel a scheduled, named task. If periodic, then it will cancel all further instances
219 /// of that, also.
220 ///
221 /// Will return an `Unavailable` error if the `id` is invalid.
222 ///
223 /// NOTE: This guaranteed to work only *before* the point that it is due to be executed.
224 /// If it ends up being delayed beyond the point of execution, then it cannot be cancelled.
225 fn cancel_named(id: TaskName) -> Result<(), DispatchError>;
226
227 /// Reschedule a task. For one-off tasks, this dispatch is guaranteed to succeed
228 /// only if it is executed *before* the currently scheduled block.
229 ///
230 /// Will return an `Unavailable` error if the `id` is invalid.
231 fn reschedule_named(
232 id: TaskName,
233 when: DispatchTime<BlockNumber>,
234 ) -> Result<Self::Address, DispatchError>;
235
236 /// Return the next dispatch time for a given task.
237 ///
238 /// Will return an `Unavailable` error if the `id` is invalid.
239 fn next_dispatch_time(id: TaskName) -> Result<BlockNumber, DispatchError>;
240 }
241}