pallet_message_queue/
lib.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//! # Generalized Message Queue Pallet
19//!
20//! Provides generalized message queuing and processing capabilities on a per-queue basis for
21//! arbitrary use-cases.
22//!
23//! # Design Goals
24//!
25//! 1. Minimal assumptions about `Message`s and `MessageOrigin`s. Both should be MEL bounded blobs.
26//!  This ensures the generality and reusability of the pallet.
27//! 2. Well known and tightly limited pre-dispatch PoV weights, especially for message execution.
28//!  This is paramount for the success of the pallet since message execution is done in
29//!  `on_initialize` which must _never_ under-estimate its PoV weight. It also needs a frugal PoV
30//!  footprint since PoV is scarce and this is (possibly) done in every block. This must also hold
31//! in  the presence of unpredictable message size distributions.
32//! 3. Usable as XCMP, DMP and UMP message/dispatch queue - possibly through adapter types.
33//!
34//! # Design
35//!
36//! The pallet has means to enqueue, store and process messages. This is implemented by having
37//! *queues* which store enqueued messages and can be *served* to process said messages. A queue is
38//! identified by its origin in the `BookStateFor`. Each message has an origin which defines into
39//! which queue it will be stored. Messages are stored by being appended to the last [`Page`] of a
40//! book. Each book keeps track of its pages by indexing `Pages`. The `ReadyRing` contains all
41//! queues which hold at least one unprocessed message and are thereby *ready* to be serviced. The
42//! `ServiceHead` indicates which *ready* queue is the next to be serviced.
43//! The pallet implements [`frame_support::traits::EnqueueMessage`],
44//! [`frame_support::traits::ServiceQueues`] and has [`frame_support::traits::ProcessMessage`] and
45//! [`OnQueueChanged`] hooks to communicate with the outside world.
46//!
47//! NOTE: The storage items are not linked since they are not public.
48//!
49//! **Message Execution**
50//!
51//! Executing a message is offloaded to the [`Config::MessageProcessor`] which contains the actual
52//! logic of how to handle the message since they are blobs. Storage changes are not rolled back on
53//! error.
54//!
55//! A failed message can be temporarily or permanently overweight. The pallet will perpetually try
56//! to execute a temporarily overweight message. A permanently overweight message is skipped and
57//! must be executed manually.
58//!
59//! **Reentrancy**
60//!
61//! This pallet has two entry points for executing (possibly recursive) logic;
62//! [`Pallet::service_queues`] and [`Pallet::execute_overweight`]. Both entry points are guarded by
63//! the same mutex to error on reentrancy. The only functions that are explicitly **allowed** to be
64//! called by a message processor are: [`Pallet::enqueue_message`] and
65//! [`Pallet::enqueue_messages`]. All other functions are forbidden and error with
66//! [`Error::RecursiveDisallowed`].
67//!
68//! **Pagination**
69//!
70//! Queues are stored in a *paged* manner by splitting their messages into [`Page`]s. This results
71//! in a lot of complexity when implementing the pallet but is completely necessary to achieve the
72//! second #[Design Goal](design-goals). The problem comes from the fact a message can *possibly* be
73//! quite large, lets say 64KiB. This then results in a *MEL* of at least 64KiB which results in a
74//! PoV of at least 64KiB. Now we have the assumption that most messages are much shorter than their
75//! maximum allowed length. This would result in most messages having a pre-dispatch PoV size which
76//! is much larger than their post-dispatch PoV size, possibly by a factor of thousand. Disregarding
77//! this observation would cripple the processing power of the pallet since it cannot straighten out
78//! this discrepancy at runtime. Conceptually, the implementation is packing as many messages into a
79//! single bounded vec, as actually fit into the bounds. This reduces the wasted PoV.
80//!
81//! **Page Data Layout**
82//!
83//! A Page contains a heap which holds all its messages. The heap is built by concatenating
84//! `(ItemHeader, Message)` pairs. The [`ItemHeader`] contains the length of the message which is
85//! needed for retrieving it. This layout allows for constant access time of the next message and
86//! linear access time for any message in the page. The header must remain minimal to reduce its PoV
87//! impact.
88//!
89//! **Weight Metering**
90//!
91//! The pallet utilizes the [`sp_weights::WeightMeter`] to manually track its consumption to always
92//! stay within the required limit. This implies that the message processor hook can calculate the
93//! weight of a message without executing it. This restricts the possible use-cases but is necessary
94//! since the pallet runs in `on_initialize` which has a hard weight limit. The weight meter is used
95//! in a way that `can_accrue` and `check_accrue` are always used to check the remaining weight of
96//! an operation before committing to it. The process of exiting due to insufficient weight is
97//! termed "bailing".
98//!
99//! # Scenario: Message enqueuing
100//!
101//! A message `m` is enqueued for origin `o` into queue `Q[o]` through
102//! [`frame_support::traits::EnqueueMessage::enqueue_message`]`(m, o)`.
103//!
104//! First the queue is either loaded if it exists or otherwise created with empty default values.
105//! The message is then inserted to the queue by appended it into its last `Page` or by creating a
106//! new `Page` just for `m` if it does not fit in there. The number of messages in the `Book` is
107//! incremented.
108//!
109//! `Q[o]` is now *ready* which will eventually result in `m` being processed.
110//!
111//! # Scenario: Message processing
112//!
113//! The pallet runs each block in `on_initialize` or when being manually called through
114//! [`frame_support::traits::ServiceQueues::service_queues`].
115//!
116//! First it tries to "rotate" the `ReadyRing` by one through advancing the `ServiceHead` to the
117//! next *ready* queue. It then starts to service this queue by servicing as many pages of it as
118//! possible. Servicing a page means to execute as many message of it as possible. Each executed
119//! message is marked as *processed* if the [`Config::MessageProcessor`] return Ok. An event
120//! [`Event::Processed`] is emitted afterwards. It is possible that the weight limit of the pallet
121//! will never allow a specific message to be executed. In this case it remains as unprocessed and
122//! is skipped. This process stops if either there are no more messages in the queue or the
123//! remaining weight became insufficient to service this queue. If there is enough weight it tries
124//! to advance to the next *ready* queue and service it. This continues until there are no more
125//! queues on which it can make progress or not enough weight to check that.
126//!
127//! # Scenario: Overweight execution
128//!
129//! A permanently over-weight message which was skipped by the message processing will never be
130//! executed automatically through `on_initialize` nor by calling
131//! [`frame_support::traits::ServiceQueues::service_queues`].
132//!
133//! Manual intervention in the form of
134//! [`frame_support::traits::ServiceQueues::execute_overweight`] is necessary. Overweight messages
135//! emit an [`Event::OverweightEnqueued`] event which can be used to extract the arguments for
136//! manual execution. This only works on permanently overweight messages. There is no guarantee that
137//! this will work since the message could be part of a stale page and be reaped before execution
138//! commences.
139//!
140//! # Terminology
141//!
142//! - `Message`: A blob of data into which the pallet has no introspection, defined as
143//! [`BoundedSlice<u8, MaxMessageLenOf<T>>`]. The message length is limited by [`MaxMessageLenOf`]
144//! which is calculated from [`Config::HeapSize`] and [`ItemHeader::max_encoded_len()`].
145//! - `MessageOrigin`: A generic *origin* of a message, defined as [`MessageOriginOf`]. The
146//! requirements for it are kept minimal to remain as generic as possible. The type is defined in
147//! [`frame_support::traits::ProcessMessage::Origin`].
148//! - `Page`: An array of `Message`s, see [`Page`]. Can never be empty.
149//! - `Book`: A list of `Page`s, see [`BookState`]. Can be empty.
150//! - `Queue`: A `Book` together with an `MessageOrigin` which can be part of the `ReadyRing`. Can
151//!   be empty.
152//! - `ReadyRing`: A double-linked list which contains all *ready* `Queue`s. It chains together the
153//!   queues via their `ready_neighbours` fields. A `Queue` is *ready* if it contains at least one
154//!   `Message` which can be processed. Can be empty.
155//! - `ServiceHead`: A pointer into the `ReadyRing` to the next `Queue` to be serviced.
156//! - (`un`)`processed`: A message is marked as *processed* after it was executed by the pallet. A
157//!   message which was either: not yet executed or could not be executed remains as `unprocessed`
158//!   which is the default state for a message after being enqueued.
159//! - `knitting`/`unknitting`: The means of adding or removing a `Queue` from the `ReadyRing`.
160//! - `MEL`: The Max Encoded Length of a type, see [`codec::MaxEncodedLen`].
161//! - `Reentrance`: To enter an execution context again before it has completed.
162//!
163//! # Properties
164//!
165//! **Liveness - Enqueueing**
166//!
167//! It is always possible to enqueue any message for any `MessageOrigin`.
168//!
169//! **Liveness - Processing**
170//!
171//! `on_initialize` always respects its finite weight-limit.
172//!
173//! **Progress - Enqueueing**
174//!
175//! An enqueued message immediately becomes *unprocessed* and thereby eligible for execution.
176//!
177//! **Progress - Processing**
178//!
179//! The pallet will execute at least one unprocessed message per block, if there is any. Ensuring
180//! this property needs careful consideration of the concrete weights, since it is possible that the
181//! weight limit of `on_initialize` never allows for the execution of even one message; trivially if
182//! the limit is set to zero. `integrity_test` can be used to ensure that this property holds.
183//!
184//! **Fairness - Enqueuing**
185//!
186//! Enqueueing a message for a specific `MessageOrigin` does not influence the ability to enqueue a
187//! message for the same of any other `MessageOrigin`; guaranteed by **Liveness - Enqueueing**.
188//!
189//! **Fairness - Processing**
190//!
191//! The average amount of weight available for message processing is the same for each queue if the
192//! number of queues is constant. Creating a new queue must therefore be, possibly economically,
193//! expensive. Currently this is archived by having one queue per para-chain/thread, which keeps the
194//! number of queues within `O(n)` and should be "good enough".
195
196#![deny(missing_docs)]
197#![cfg_attr(not(feature = "std"), no_std)]
198
199mod benchmarking;
200mod integration_test;
201mod mock;
202pub mod mock_helpers;
203mod tests;
204pub mod weights;
205
206extern crate alloc;
207
208use alloc::{vec, vec::Vec};
209use codec::{Codec, Decode, Encode, MaxEncodedLen};
210use core::{fmt::Debug, ops::Deref};
211use frame_support::{
212	defensive,
213	pallet_prelude::*,
214	traits::{
215		Defensive, DefensiveSaturating, DefensiveTruncateFrom, EnqueueMessage,
216		ExecuteOverweightError, Footprint, ProcessMessage, ProcessMessageError, QueueFootprint,
217		QueuePausedQuery, ServiceQueues,
218	},
219	BoundedSlice, CloneNoBound, DefaultNoBound,
220};
221use frame_system::pallet_prelude::*;
222pub use pallet::*;
223use scale_info::TypeInfo;
224use sp_arithmetic::traits::{BaseArithmetic, Unsigned};
225use sp_core::{defer, H256};
226use sp_runtime::{
227	traits::{One, Zero},
228	SaturatedConversion, Saturating, TransactionOutcome,
229};
230use sp_weights::WeightMeter;
231pub use weights::WeightInfo;
232
233/// Type for identifying a page.
234type PageIndex = u32;
235
236/// Data encoded and prefixed to the encoded `MessageItem`.
237#[derive(Encode, Decode, PartialEq, MaxEncodedLen, Debug)]
238pub struct ItemHeader<Size> {
239	/// The length of this item, not including the size of this header. The next item of the page
240	/// follows immediately after the payload of this item.
241	payload_len: Size,
242	/// Whether this item has been processed.
243	is_processed: bool,
244}
245
246/// A page of messages. Pages always contain at least one item.
247#[derive(
248	CloneNoBound, Encode, Decode, RuntimeDebugNoBound, DefaultNoBound, TypeInfo, MaxEncodedLen,
249)]
250#[scale_info(skip_type_params(HeapSize))]
251#[codec(mel_bound(Size: MaxEncodedLen))]
252pub struct Page<Size: Into<u32> + Debug + Clone + Default, HeapSize: Get<Size>> {
253	/// Messages remaining to be processed; this includes overweight messages which have been
254	/// skipped.
255	remaining: Size,
256	/// The size of all remaining messages to be processed.
257	///
258	/// Includes overweight messages outside of the `first` to `last` window.
259	remaining_size: Size,
260	/// The number of items before the `first` item in this page.
261	first_index: Size,
262	/// The heap-offset of the header of the first message item in this page which is ready for
263	/// processing.
264	first: Size,
265	/// The heap-offset of the header of the last message item in this page.
266	last: Size,
267	/// The heap. If `self.offset == self.heap.len()` then the page is empty and should be deleted.
268	heap: BoundedVec<u8, IntoU32<HeapSize, Size>>,
269}
270
271impl<
272		Size: BaseArithmetic + Unsigned + Copy + Into<u32> + Codec + MaxEncodedLen + Debug + Default,
273		HeapSize: Get<Size>,
274	> Page<Size, HeapSize>
275{
276	/// Create a [`Page`] from one unprocessed message.
277	fn from_message<T: Config>(message: BoundedSlice<u8, MaxMessageLenOf<T>>) -> Self {
278		let payload_len = message.len();
279		let data_len = ItemHeader::<Size>::max_encoded_len().saturating_add(payload_len);
280		let payload_len = payload_len.saturated_into();
281		let header = ItemHeader::<Size> { payload_len, is_processed: false };
282
283		let mut heap = Vec::with_capacity(data_len);
284		header.using_encoded(|h| heap.extend_from_slice(h));
285		heap.extend_from_slice(message.deref());
286
287		Page {
288			remaining: One::one(),
289			remaining_size: payload_len,
290			first_index: Zero::zero(),
291			first: Zero::zero(),
292			last: Zero::zero(),
293			heap: BoundedVec::defensive_truncate_from(heap),
294		}
295	}
296
297	/// Try to append one message to a page.
298	fn try_append_message<T: Config>(
299		&mut self,
300		message: BoundedSlice<u8, MaxMessageLenOf<T>>,
301	) -> Result<(), ()> {
302		let pos = self.heap.len();
303		let payload_len = message.len();
304		let data_len = ItemHeader::<Size>::max_encoded_len().saturating_add(payload_len);
305		let payload_len = payload_len.saturated_into();
306		let header = ItemHeader::<Size> { payload_len, is_processed: false };
307		let heap_size: u32 = HeapSize::get().into();
308		if (heap_size as usize).saturating_sub(self.heap.len()) < data_len {
309			// Can't fit.
310			return Err(())
311		}
312
313		let mut heap = core::mem::take(&mut self.heap).into_inner();
314		header.using_encoded(|h| heap.extend_from_slice(h));
315		heap.extend_from_slice(message.deref());
316		self.heap = BoundedVec::defensive_truncate_from(heap);
317		self.last = pos.saturated_into();
318		self.remaining.saturating_inc();
319		self.remaining_size.saturating_accrue(payload_len);
320		Ok(())
321	}
322
323	/// Returns the first message in the page without removing it.
324	///
325	/// SAFETY: Does not panic even on corrupted storage.
326	fn peek_first(&self) -> Option<BoundedSlice<u8, IntoU32<HeapSize, Size>>> {
327		if self.first > self.last {
328			return None
329		}
330		let f = (self.first.into() as usize).min(self.heap.len());
331		let mut item_slice = &self.heap[f..];
332		if let Ok(h) = ItemHeader::<Size>::decode(&mut item_slice) {
333			let payload_len = h.payload_len.into() as usize;
334			if payload_len <= item_slice.len() {
335				// impossible to truncate since is sliced up from `self.heap: BoundedVec<u8,
336				// HeapSize>`
337				return Some(BoundedSlice::defensive_truncate_from(&item_slice[..payload_len]))
338			}
339		}
340		defensive!("message-queue: heap corruption");
341		None
342	}
343
344	/// Point `first` at the next message, marking the first as processed if `is_processed` is true.
345	fn skip_first(&mut self, is_processed: bool) {
346		let f = (self.first.into() as usize).min(self.heap.len());
347		if let Ok(mut h) = ItemHeader::decode(&mut &self.heap[f..]) {
348			if is_processed && !h.is_processed {
349				h.is_processed = true;
350				h.using_encoded(|d| self.heap[f..f + d.len()].copy_from_slice(d));
351				self.remaining.saturating_dec();
352				self.remaining_size.saturating_reduce(h.payload_len);
353			}
354			self.first
355				.saturating_accrue(ItemHeader::<Size>::max_encoded_len().saturated_into());
356			self.first.saturating_accrue(h.payload_len);
357			self.first_index.saturating_inc();
358		}
359	}
360
361	/// Return the message with index `index` in the form of `(position, processed, message)`.
362	fn peek_index(&self, index: usize) -> Option<(usize, bool, &[u8])> {
363		let mut pos = 0;
364		let mut item_slice = &self.heap[..];
365		let header_len: usize = ItemHeader::<Size>::max_encoded_len().saturated_into();
366		for _ in 0..index {
367			let h = ItemHeader::<Size>::decode(&mut item_slice).ok()?;
368			let item_len = h.payload_len.into() as usize;
369			if item_slice.len() < item_len {
370				return None
371			}
372			item_slice = &item_slice[item_len..];
373			pos.saturating_accrue(header_len.saturating_add(item_len));
374		}
375		let h = ItemHeader::<Size>::decode(&mut item_slice).ok()?;
376		if item_slice.len() < h.payload_len.into() as usize {
377			return None
378		}
379		item_slice = &item_slice[..h.payload_len.into() as usize];
380		Some((pos, h.is_processed, item_slice))
381	}
382
383	/// Set the `is_processed` flag for the item at `pos` to be `true` if not already and decrement
384	/// the `remaining` counter of the page.
385	///
386	/// Does nothing if no [`ItemHeader`] could be decoded at the given position.
387	fn note_processed_at_pos(&mut self, pos: usize) {
388		if let Ok(mut h) = ItemHeader::<Size>::decode(&mut &self.heap[pos..]) {
389			if !h.is_processed {
390				h.is_processed = true;
391				h.using_encoded(|d| self.heap[pos..pos + d.len()].copy_from_slice(d));
392				self.remaining.saturating_dec();
393				self.remaining_size.saturating_reduce(h.payload_len);
394			}
395		}
396	}
397
398	/// Returns whether the page is *complete* which means that no messages remain.
399	fn is_complete(&self) -> bool {
400		self.remaining.is_zero()
401	}
402}
403
404/// A single link in the double-linked Ready Ring list.
405#[derive(Clone, Encode, Decode, MaxEncodedLen, TypeInfo, RuntimeDebug, PartialEq)]
406pub struct Neighbours<MessageOrigin> {
407	/// The previous queue.
408	prev: MessageOrigin,
409	/// The next queue.
410	next: MessageOrigin,
411}
412
413/// The state of a queue as represented by a book of its pages.
414///
415/// Each queue has exactly one book which holds all of its pages. All pages of a book combined
416/// contain all of the messages of its queue; hence the name *Book*.
417/// Books can be chained together in a double-linked fashion through their `ready_neighbours` field.
418#[derive(Clone, Encode, Decode, MaxEncodedLen, TypeInfo, RuntimeDebug)]
419pub struct BookState<MessageOrigin> {
420	/// The first page with some items to be processed in it. If this is `>= end`, then there are
421	/// no pages with items to be processing in them.
422	begin: PageIndex,
423	/// One more than the last page with some items to be processed in it.
424	end: PageIndex,
425	/// The number of pages stored at present.
426	///
427	/// This might be larger than `end-begin`, because we keep pages with unprocessed overweight
428	/// messages outside of the end/begin window.
429	count: PageIndex,
430	/// If this book has any ready pages, then this will be `Some` with the previous and next
431	/// neighbours. This wraps around.
432	ready_neighbours: Option<Neighbours<MessageOrigin>>,
433	/// The number of unprocessed messages stored at present.
434	message_count: u64,
435	/// The total size of all unprocessed messages stored at present.
436	size: u64,
437}
438
439impl<MessageOrigin> Default for BookState<MessageOrigin> {
440	fn default() -> Self {
441		Self { begin: 0, end: 0, count: 0, ready_neighbours: None, message_count: 0, size: 0 }
442	}
443}
444
445impl<MessageOrigin> From<BookState<MessageOrigin>> for QueueFootprint {
446	fn from(book: BookState<MessageOrigin>) -> Self {
447		QueueFootprint {
448			pages: book.count,
449			ready_pages: book.end.defensive_saturating_sub(book.begin),
450			storage: Footprint { count: book.message_count, size: book.size },
451		}
452	}
453}
454
455/// Handler code for when the items in a queue change.
456pub trait OnQueueChanged<Id> {
457	/// Note that the queue `id` now has `item_count` items in it, taking up `items_size` bytes.
458	fn on_queue_changed(id: Id, fp: QueueFootprint);
459}
460
461impl<Id> OnQueueChanged<Id> for () {
462	fn on_queue_changed(_: Id, _: QueueFootprint) {}
463}
464
465#[frame_support::pallet]
466pub mod pallet {
467	use super::*;
468
469	#[pallet::pallet]
470	pub struct Pallet<T>(_);
471
472	/// The module configuration trait.
473	#[pallet::config]
474	pub trait Config: frame_system::Config {
475		/// The overarching event type.
476		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
477
478		/// Weight information for extrinsics in this pallet.
479		type WeightInfo: WeightInfo;
480
481		/// Processor for a message.
482		///
483		/// Storage changes are not rolled back on error.
484		///
485		/// # Benchmarking
486		///
487		/// Must be set to [`mock_helpers::NoopMessageProcessor`] for benchmarking.
488		/// Other message processors that consumes exactly (1, 1) weight for any give message will
489		/// work as well. Otherwise the benchmarking will also measure the weight of the message
490		/// processor, which is not desired.
491		type MessageProcessor: ProcessMessage;
492
493		/// Page/heap size type.
494		type Size: BaseArithmetic
495			+ Unsigned
496			+ Copy
497			+ Into<u32>
498			+ Member
499			+ Encode
500			+ Decode
501			+ MaxEncodedLen
502			+ TypeInfo
503			+ Default;
504
505		/// Code to be called when a message queue changes - either with items introduced or
506		/// removed.
507		type QueueChangeHandler: OnQueueChanged<<Self::MessageProcessor as ProcessMessage>::Origin>;
508
509		/// Queried by the pallet to check whether a queue can be serviced.
510		///
511		/// This also applies to manual servicing via `execute_overweight` and `service_queues`. The
512		/// value of this is only polled once before servicing the queue. This means that changes to
513		/// it that happen *within* the servicing will not be reflected.
514		type QueuePausedQuery: QueuePausedQuery<<Self::MessageProcessor as ProcessMessage>::Origin>;
515
516		/// The size of the page; this implies the maximum message size which can be sent.
517		///
518		/// A good value depends on the expected message sizes, their weights, the weight that is
519		/// available for processing them and the maximal needed message size. The maximal message
520		/// size is slightly lower than this as defined by [`MaxMessageLenOf`].
521		#[pallet::constant]
522		type HeapSize: Get<Self::Size>;
523
524		/// The maximum number of stale pages (i.e. of overweight messages) allowed before culling
525		/// can happen. Once there are more stale pages than this, then historical pages may be
526		/// dropped, even if they contain unprocessed overweight messages.
527		#[pallet::constant]
528		type MaxStale: Get<u32>;
529
530		/// The amount of weight (if any) which should be provided to the message queue for
531		/// servicing enqueued items `on_initialize`.
532		///
533		/// This may be legitimately `None` in the case that you will call
534		/// `ServiceQueues::service_queues` manually or set [`Self::IdleMaxServiceWeight`] to have
535		/// it run in `on_idle`.
536		#[pallet::constant]
537		type ServiceWeight: Get<Option<Weight>>;
538
539		/// The maximum amount of weight (if any) to be used from remaining weight `on_idle` which
540		/// should be provided to the message queue for servicing enqueued items `on_idle`.
541		/// Useful for parachains to process messages at the same block they are received.
542		///
543		/// If `None`, it will not call `ServiceQueues::service_queues` in `on_idle`.
544		#[pallet::constant]
545		type IdleMaxServiceWeight: Get<Option<Weight>>;
546	}
547
548	#[pallet::event]
549	#[pallet::generate_deposit(pub(super) fn deposit_event)]
550	pub enum Event<T: Config> {
551		/// Message discarded due to an error in the `MessageProcessor` (usually a format error).
552		ProcessingFailed {
553			/// The `blake2_256` hash of the message.
554			id: H256,
555			/// The queue of the message.
556			origin: MessageOriginOf<T>,
557			/// The error that occurred.
558			///
559			/// This error is pretty opaque. More fine-grained errors need to be emitted as events
560			/// by the `MessageProcessor`.
561			error: ProcessMessageError,
562		},
563		/// Message is processed.
564		Processed {
565			/// The `blake2_256` hash of the message.
566			id: H256,
567			/// The queue of the message.
568			origin: MessageOriginOf<T>,
569			/// How much weight was used to process the message.
570			weight_used: Weight,
571			/// Whether the message was processed.
572			///
573			/// Note that this does not mean that the underlying `MessageProcessor` was internally
574			/// successful. It *solely* means that the MQ pallet will treat this as a success
575			/// condition and discard the message. Any internal error needs to be emitted as events
576			/// by the `MessageProcessor`.
577			success: bool,
578		},
579		/// Message placed in overweight queue.
580		OverweightEnqueued {
581			/// The `blake2_256` hash of the message.
582			id: [u8; 32],
583			/// The queue of the message.
584			origin: MessageOriginOf<T>,
585			/// The page of the message.
586			page_index: PageIndex,
587			/// The index of the message within the page.
588			message_index: T::Size,
589		},
590		/// This page was reaped.
591		PageReaped {
592			/// The queue of the page.
593			origin: MessageOriginOf<T>,
594			/// The index of the page.
595			index: PageIndex,
596		},
597	}
598
599	#[pallet::error]
600	pub enum Error<T> {
601		/// Page is not reapable because it has items remaining to be processed and is not old
602		/// enough.
603		NotReapable,
604		/// Page to be reaped does not exist.
605		NoPage,
606		/// The referenced message could not be found.
607		NoMessage,
608		/// The message was already processed and cannot be processed again.
609		AlreadyProcessed,
610		/// The message is queued for future execution.
611		Queued,
612		/// There is temporarily not enough weight to continue servicing messages.
613		InsufficientWeight,
614		/// This message is temporarily unprocessable.
615		///
616		/// Such errors are expected, but not guaranteed, to resolve themselves eventually through
617		/// retrying.
618		TemporarilyUnprocessable,
619		/// The queue is paused and no message can be executed from it.
620		///
621		/// This can change at any time and may resolve in the future by re-trying.
622		QueuePaused,
623		/// Another call is in progress and needs to finish before this call can happen.
624		RecursiveDisallowed,
625	}
626
627	/// The index of the first and last (non-empty) pages.
628	#[pallet::storage]
629	pub(super) type BookStateFor<T: Config> =
630		StorageMap<_, Twox64Concat, MessageOriginOf<T>, BookState<MessageOriginOf<T>>, ValueQuery>;
631
632	/// The origin at which we should begin servicing.
633	#[pallet::storage]
634	pub(super) type ServiceHead<T: Config> = StorageValue<_, MessageOriginOf<T>, OptionQuery>;
635
636	/// The map of page indices to pages.
637	#[pallet::storage]
638	pub(super) type Pages<T: Config> = StorageDoubleMap<
639		_,
640		Twox64Concat,
641		MessageOriginOf<T>,
642		Twox64Concat,
643		PageIndex,
644		Page<T::Size, T::HeapSize>,
645		OptionQuery,
646	>;
647
648	#[pallet::hooks]
649	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
650		fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
651			if let Some(weight_limit) = T::ServiceWeight::get() {
652				Self::service_queues_impl(weight_limit, ServiceQueuesContext::OnInitialize)
653			} else {
654				Weight::zero()
655			}
656		}
657
658		fn on_idle(_n: BlockNumberFor<T>, remaining_weight: Weight) -> Weight {
659			if let Some(weight_limit) = T::IdleMaxServiceWeight::get() {
660				// Make use of the remaining weight to process enqueued messages.
661				Self::service_queues_impl(
662					weight_limit.min(remaining_weight),
663					ServiceQueuesContext::OnIdle,
664				)
665			} else {
666				Weight::zero()
667			}
668		}
669
670		#[cfg(feature = "try-runtime")]
671		fn try_state(_: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
672			Self::do_try_state()
673		}
674
675		/// Check all compile-time assumptions about [`crate::Config`].
676		#[cfg(test)]
677		fn integrity_test() {
678			Self::do_integrity_test().expect("Pallet config is valid; qed")
679		}
680	}
681
682	#[pallet::call]
683	impl<T: Config> Pallet<T> {
684		/// Remove a page which has no more messages remaining to be processed or is stale.
685		#[pallet::call_index(0)]
686		#[pallet::weight(T::WeightInfo::reap_page())]
687		pub fn reap_page(
688			origin: OriginFor<T>,
689			message_origin: MessageOriginOf<T>,
690			page_index: PageIndex,
691		) -> DispatchResult {
692			let _ = ensure_signed(origin)?;
693			Self::do_reap_page(&message_origin, page_index)
694		}
695
696		/// Execute an overweight message.
697		///
698		/// Temporary processing errors will be propagated whereas permanent errors are treated
699		/// as success condition.
700		///
701		/// - `origin`: Must be `Signed`.
702		/// - `message_origin`: The origin from which the message to be executed arrived.
703		/// - `page`: The page in the queue in which the message to be executed is sitting.
704		/// - `index`: The index into the queue of the message to be executed.
705		/// - `weight_limit`: The maximum amount of weight allowed to be consumed in the execution
706		///   of the message.
707		///
708		/// Benchmark complexity considerations: O(index + weight_limit).
709		#[pallet::call_index(1)]
710		#[pallet::weight(
711			T::WeightInfo::execute_overweight_page_updated().max(
712			T::WeightInfo::execute_overweight_page_removed()).saturating_add(*weight_limit)
713		)]
714		pub fn execute_overweight(
715			origin: OriginFor<T>,
716			message_origin: MessageOriginOf<T>,
717			page: PageIndex,
718			index: T::Size,
719			weight_limit: Weight,
720		) -> DispatchResultWithPostInfo {
721			let _ = ensure_signed(origin)?;
722			let actual_weight =
723				Self::do_execute_overweight(message_origin, page, index, weight_limit)?;
724			Ok(Some(actual_weight).into())
725		}
726	}
727}
728
729/// The status of a page after trying to execute its next message.
730#[derive(PartialEq, Debug)]
731enum PageExecutionStatus {
732	/// The execution bailed because there was not enough weight remaining.
733	Bailed,
734	/// The page did not make any progress on its execution.
735	///
736	/// This is a transient condition and can be handled by retrying - exactly like [Bailed].
737	NoProgress,
738	/// No more messages could be loaded. This does _not_ imply `page.is_complete()`.
739	///
740	/// The reasons for this status are:
741	///  - The end of the page is reached but there could still be skipped messages.
742	///  - The storage is corrupted.
743	NoMore,
744}
745
746/// The status after trying to execute the next item of a [`Page`].
747#[derive(PartialEq, Debug)]
748enum ItemExecutionStatus {
749	/// The execution bailed because there was not enough weight remaining.
750	Bailed,
751	/// The item did not make any progress on its execution.
752	///
753	/// This is a transient condition and can be handled by retrying - exactly like [Bailed].
754	NoProgress,
755	/// The item was not found.
756	NoItem,
757	/// Whether the execution of an item resulted in it being processed.
758	///
759	/// One reason for `false` would be permanently overweight.
760	Executed(bool),
761}
762
763/// The status of an attempt to process a message.
764#[derive(PartialEq)]
765enum MessageExecutionStatus {
766	/// There is not enough weight remaining at present.
767	InsufficientWeight,
768	/// There will never be enough weight.
769	Overweight,
770	/// The message was processed successfully.
771	Processed,
772	/// The message was processed and resulted in a, possibly permanent, error.
773	Unprocessable { permanent: bool },
774	/// The stack depth limit was reached.
775	///
776	/// We cannot just return `Unprocessable` in this case, because the processability of the
777	/// message depends on how the function was called. This may be a permanent error if it was
778	/// called by a top-level function, or a transient error if it was already called in a nested
779	/// function.
780	StackLimitReached,
781}
782
783/// The context to pass to [`Pallet::service_queues_impl`] through on_idle and on_initialize hooks
784/// We don't want to throw the defensive message if called from on_idle hook
785#[derive(PartialEq)]
786enum ServiceQueuesContext {
787	/// Context of on_idle hook.
788	OnIdle,
789	/// Context of on_initialize hook.
790	OnInitialize,
791	/// Context `service_queues` trait function.
792	ServiceQueues,
793}
794
795impl<T: Config> Pallet<T> {
796	/// Knit `origin` into the ready ring right at the end.
797	///
798	/// Return the two ready ring neighbours of `origin`.
799	fn ready_ring_knit(origin: &MessageOriginOf<T>) -> Result<Neighbours<MessageOriginOf<T>>, ()> {
800		if let Some(head) = ServiceHead::<T>::get() {
801			let mut head_book_state = BookStateFor::<T>::get(&head);
802			let mut head_neighbours = head_book_state.ready_neighbours.take().ok_or(())?;
803			let tail = head_neighbours.prev;
804			head_neighbours.prev = origin.clone();
805			head_book_state.ready_neighbours = Some(head_neighbours);
806			BookStateFor::<T>::insert(&head, head_book_state);
807
808			let mut tail_book_state = BookStateFor::<T>::get(&tail);
809			let mut tail_neighbours = tail_book_state.ready_neighbours.take().ok_or(())?;
810			tail_neighbours.next = origin.clone();
811			tail_book_state.ready_neighbours = Some(tail_neighbours);
812			BookStateFor::<T>::insert(&tail, tail_book_state);
813
814			Ok(Neighbours { next: head, prev: tail })
815		} else {
816			ServiceHead::<T>::put(origin);
817			Ok(Neighbours { next: origin.clone(), prev: origin.clone() })
818		}
819	}
820
821	fn ready_ring_unknit(origin: &MessageOriginOf<T>, neighbours: Neighbours<MessageOriginOf<T>>) {
822		if origin == &neighbours.next {
823			debug_assert!(
824				origin == &neighbours.prev,
825				"unknitting from single item ring; outgoing must be only item"
826			);
827			// Service queue empty.
828			ServiceHead::<T>::kill();
829		} else {
830			BookStateFor::<T>::mutate(&neighbours.next, |book_state| {
831				if let Some(ref mut n) = book_state.ready_neighbours {
832					n.prev = neighbours.prev.clone()
833				}
834			});
835			BookStateFor::<T>::mutate(&neighbours.prev, |book_state| {
836				if let Some(ref mut n) = book_state.ready_neighbours {
837					n.next = neighbours.next.clone()
838				}
839			});
840			if let Some(head) = ServiceHead::<T>::get() {
841				if &head == origin {
842					ServiceHead::<T>::put(neighbours.next);
843				}
844			} else {
845				defensive!("`ServiceHead` must be some if there was a ready queue");
846			}
847		}
848	}
849
850	/// Tries to bump the current `ServiceHead` to the next ready queue.
851	///
852	/// Returns the current head if it got be bumped and `None` otherwise.
853	fn bump_service_head(weight: &mut WeightMeter) -> Option<MessageOriginOf<T>> {
854		if weight.try_consume(T::WeightInfo::bump_service_head()).is_err() {
855			return None
856		}
857
858		if let Some(head) = ServiceHead::<T>::get() {
859			let mut head_book_state = BookStateFor::<T>::get(&head);
860			if let Some(head_neighbours) = head_book_state.ready_neighbours.take() {
861				ServiceHead::<T>::put(&head_neighbours.next);
862				Some(head)
863			} else {
864				None
865			}
866		} else {
867			None
868		}
869	}
870
871	/// The maximal weight that a single message ever can consume.
872	///
873	/// Any message using more than this will be marked as permanently overweight and not
874	/// automatically re-attempted. Returns `None` if the servicing of a message cannot begin.
875	/// `Some(0)` means that only messages with no weight may be served.
876	fn max_message_weight(limit: Weight) -> Option<Weight> {
877		let service_weight = T::ServiceWeight::get().unwrap_or_default();
878		let on_idle_weight = T::IdleMaxServiceWeight::get().unwrap_or_default();
879
880		// Whatever weight is set, the one with the biggest one is used as the maximum weight. If a
881		// message is tried in one context and fails, it will be retried in the other context later.
882		let max_message_weight =
883			if service_weight.any_gt(on_idle_weight) { service_weight } else { on_idle_weight };
884
885		if max_message_weight.is_zero() {
886			// If no service weight is set, we need to use the given limit as max message weight.
887			limit.checked_sub(&Self::single_msg_overhead())
888		} else {
889			max_message_weight.checked_sub(&Self::single_msg_overhead())
890		}
891	}
892
893	/// The overhead of servicing a single message.
894	fn single_msg_overhead() -> Weight {
895		T::WeightInfo::bump_service_head()
896			.saturating_add(T::WeightInfo::service_queue_base())
897			.saturating_add(
898				T::WeightInfo::service_page_base_completion()
899					.max(T::WeightInfo::service_page_base_no_completion()),
900			)
901			.saturating_add(T::WeightInfo::service_page_item())
902			.saturating_add(T::WeightInfo::ready_ring_unknit())
903	}
904
905	/// Checks invariants of the pallet config.
906	///
907	/// The results of this can only be relied upon if the config values are set to constants.
908	#[cfg(test)]
909	fn do_integrity_test() -> Result<(), String> {
910		ensure!(!MaxMessageLenOf::<T>::get().is_zero(), "HeapSize too low");
911
912		let max_block = T::BlockWeights::get().max_block;
913
914		if let Some(service) = T::ServiceWeight::get() {
915			if Self::max_message_weight(service).is_none() {
916				return Err(format!(
917					"ServiceWeight too low: {}. Must be at least {}",
918					service,
919					Self::single_msg_overhead(),
920				))
921			}
922
923			if service.any_gt(max_block) {
924				return Err(format!(
925					"ServiceWeight {service} is bigger than max block weight {max_block}"
926				))
927			}
928		}
929
930		if let Some(on_idle) = T::IdleMaxServiceWeight::get() {
931			if on_idle.any_gt(max_block) {
932				return Err(format!(
933					"IdleMaxServiceWeight {on_idle} is bigger than max block weight {max_block}"
934				))
935			}
936		}
937
938		if let (Some(service_weight), Some(on_idle)) =
939			(T::ServiceWeight::get(), T::IdleMaxServiceWeight::get())
940		{
941			if !(service_weight.all_gt(on_idle) ||
942				on_idle.all_gt(service_weight) ||
943				service_weight == on_idle)
944			{
945				return Err("One of `ServiceWeight` or `IdleMaxServiceWeight` needs to be `all_gt` or both need to be equal.".into())
946			}
947		}
948
949		Ok(())
950	}
951
952	fn do_enqueue_message(
953		origin: &MessageOriginOf<T>,
954		message: BoundedSlice<u8, MaxMessageLenOf<T>>,
955	) {
956		let mut book_state = BookStateFor::<T>::get(origin);
957		book_state.message_count.saturating_inc();
958		book_state
959			.size
960			// This should be payload size, but here the payload *is* the message.
961			.saturating_accrue(message.len() as u64);
962
963		if book_state.end > book_state.begin {
964			debug_assert!(book_state.ready_neighbours.is_some(), "Must be in ready ring if ready");
965			// Already have a page in progress - attempt to append.
966			let last = book_state.end - 1;
967			let mut page = match Pages::<T>::get(origin, last) {
968				Some(p) => p,
969				None => {
970					defensive!("Corruption: referenced page doesn't exist.");
971					return
972				},
973			};
974			if page.try_append_message::<T>(message).is_ok() {
975				Pages::<T>::insert(origin, last, &page);
976				BookStateFor::<T>::insert(origin, book_state);
977				return
978			}
979		} else {
980			debug_assert!(
981				book_state.ready_neighbours.is_none(),
982				"Must not be in ready ring if not ready"
983			);
984			// insert into ready queue.
985			match Self::ready_ring_knit(origin) {
986				Ok(neighbours) => book_state.ready_neighbours = Some(neighbours),
987				Err(()) => {
988					defensive!("Ring state invalid when knitting");
989				},
990			}
991		}
992		// No room on the page or no page - link in a new page.
993		book_state.end.saturating_inc();
994		book_state.count.saturating_inc();
995		let page = Page::from_message::<T>(message);
996		Pages::<T>::insert(origin, book_state.end - 1, page);
997		// NOTE: `T::QueueChangeHandler` is called by the caller.
998		BookStateFor::<T>::insert(origin, book_state);
999	}
1000
1001	/// Try to execute a single message that was marked as overweight.
1002	///
1003	/// The `weight_limit` is the weight that can be consumed to execute the message. The base
1004	/// weight of the function it self must be measured by the caller.
1005	pub fn do_execute_overweight(
1006		origin: MessageOriginOf<T>,
1007		page_index: PageIndex,
1008		index: T::Size,
1009		weight_limit: Weight,
1010	) -> Result<Weight, Error<T>> {
1011		match with_service_mutex(|| {
1012			Self::do_execute_overweight_inner(origin, page_index, index, weight_limit)
1013		}) {
1014			Err(()) => Err(Error::<T>::RecursiveDisallowed),
1015			Ok(x) => x,
1016		}
1017	}
1018
1019	/// Same as `do_execute_overweight` but must be called while holding the `service_mutex`.
1020	fn do_execute_overweight_inner(
1021		origin: MessageOriginOf<T>,
1022		page_index: PageIndex,
1023		index: T::Size,
1024		weight_limit: Weight,
1025	) -> Result<Weight, Error<T>> {
1026		let mut book_state = BookStateFor::<T>::get(&origin);
1027		ensure!(!T::QueuePausedQuery::is_paused(&origin), Error::<T>::QueuePaused);
1028
1029		let mut page = Pages::<T>::get(&origin, page_index).ok_or(Error::<T>::NoPage)?;
1030		let (pos, is_processed, payload) =
1031			page.peek_index(index.into() as usize).ok_or(Error::<T>::NoMessage)?;
1032		let payload_len = payload.len() as u64;
1033		ensure!(
1034			page_index < book_state.begin ||
1035				(page_index == book_state.begin && pos < page.first.into() as usize),
1036			Error::<T>::Queued
1037		);
1038		ensure!(!is_processed, Error::<T>::AlreadyProcessed);
1039		use MessageExecutionStatus::*;
1040		let mut weight_counter = WeightMeter::with_limit(weight_limit);
1041		match Self::process_message_payload(
1042			origin.clone(),
1043			page_index,
1044			index,
1045			payload,
1046			&mut weight_counter,
1047			Weight::MAX,
1048			// ^^^ We never recognise it as permanently overweight, since that would result in an
1049			// additional overweight event being deposited.
1050		) {
1051			Overweight | InsufficientWeight => Err(Error::<T>::InsufficientWeight),
1052			StackLimitReached | Unprocessable { permanent: false } =>
1053				Err(Error::<T>::TemporarilyUnprocessable),
1054			Unprocessable { permanent: true } | Processed => {
1055				page.note_processed_at_pos(pos);
1056				book_state.message_count.saturating_dec();
1057				book_state.size.saturating_reduce(payload_len);
1058				let page_weight = if page.remaining.is_zero() {
1059					debug_assert!(
1060						page.remaining_size.is_zero(),
1061						"no messages remaining; no space taken; qed"
1062					);
1063					Pages::<T>::remove(&origin, page_index);
1064					debug_assert!(book_state.count >= 1, "page exists, so book must have pages");
1065					book_state.count.saturating_dec();
1066					T::WeightInfo::execute_overweight_page_removed()
1067				// no need to consider .first or ready ring since processing an overweight page
1068				// would not alter that state.
1069				} else {
1070					Pages::<T>::insert(&origin, page_index, page);
1071					T::WeightInfo::execute_overweight_page_updated()
1072				};
1073				BookStateFor::<T>::insert(&origin, &book_state);
1074				T::QueueChangeHandler::on_queue_changed(origin, book_state.into());
1075				Ok(weight_counter.consumed().saturating_add(page_weight))
1076			},
1077		}
1078	}
1079
1080	/// Remove a stale page or one which has no more messages remaining to be processed.
1081	fn do_reap_page(origin: &MessageOriginOf<T>, page_index: PageIndex) -> DispatchResult {
1082		match with_service_mutex(|| Self::do_reap_page_inner(origin, page_index)) {
1083			Err(()) => Err(Error::<T>::RecursiveDisallowed.into()),
1084			Ok(x) => x,
1085		}
1086	}
1087
1088	/// Same as `do_reap_page` but must be called while holding the `service_mutex`.
1089	fn do_reap_page_inner(origin: &MessageOriginOf<T>, page_index: PageIndex) -> DispatchResult {
1090		let mut book_state = BookStateFor::<T>::get(origin);
1091		// definitely not reapable if the page's index is no less than the `begin`ning of ready
1092		// pages.
1093		ensure!(page_index < book_state.begin, Error::<T>::NotReapable);
1094
1095		let page = Pages::<T>::get(origin, page_index).ok_or(Error::<T>::NoPage)?;
1096
1097		// definitely reapable if the page has no messages in it.
1098		let reapable = page.remaining.is_zero();
1099
1100		// also reapable if the page index has dropped below our watermark.
1101		let cullable = || {
1102			let total_pages = book_state.count;
1103			let ready_pages = book_state.end.saturating_sub(book_state.begin).min(total_pages);
1104
1105			// The number of stale pages - i.e. pages which contain unprocessed overweight messages.
1106			// We would prefer to keep these around but will restrict how far into history they can
1107			// extend if we notice that there's too many of them.
1108			//
1109			// We don't know *where* in history these pages are so we use a dynamic formula which
1110			// reduces the historical time horizon as the stale pages pile up and increases it as
1111			// they reduce.
1112			let stale_pages = total_pages - ready_pages;
1113
1114			// The maximum number of stale pages (i.e. of overweight messages) allowed before
1115			// culling can happen at all. Once there are more stale pages than this, then historical
1116			// pages may be dropped, even if they contain unprocessed overweight messages.
1117			let max_stale = T::MaxStale::get();
1118
1119			// The amount beyond the maximum which are being used. If it's not beyond the maximum
1120			// then we exit now since no culling is needed.
1121			let overflow = match stale_pages.checked_sub(max_stale + 1) {
1122				Some(x) => x + 1,
1123				None => return false,
1124			};
1125
1126			// The special formula which tells us how deep into index-history we will pages. As
1127			// the overflow is greater (and thus the need to drop items from storage is more urgent)
1128			// this is reduced, allowing a greater range of pages to be culled.
1129			// With a minimum `overflow` (`1`), this returns `max_stale ** 2`, indicating we only
1130			// cull beyond that number of indices deep into history.
1131			// At this overflow increases, our depth reduces down to a limit of `max_stale`. We
1132			// never want to reduce below this since this will certainly allow enough pages to be
1133			// culled in order to bring `overflow` back to zero.
1134			let backlog = (max_stale * max_stale / overflow).max(max_stale);
1135
1136			let watermark = book_state.begin.saturating_sub(backlog);
1137			page_index < watermark
1138		};
1139		ensure!(reapable || cullable(), Error::<T>::NotReapable);
1140
1141		Pages::<T>::remove(origin, page_index);
1142		debug_assert!(book_state.count > 0, "reaping a page implies there are pages");
1143		book_state.count.saturating_dec();
1144		book_state.message_count.saturating_reduce(page.remaining.into() as u64);
1145		book_state.size.saturating_reduce(page.remaining_size.into() as u64);
1146		BookStateFor::<T>::insert(origin, &book_state);
1147		T::QueueChangeHandler::on_queue_changed(origin.clone(), book_state.into());
1148		Self::deposit_event(Event::PageReaped { origin: origin.clone(), index: page_index });
1149
1150		Ok(())
1151	}
1152
1153	/// Execute any messages remaining to be processed in the queue of `origin`, using up to
1154	/// `weight_limit` to do so. Any messages which would take more than `overweight_limit` to
1155	/// execute are deemed overweight and ignored.
1156	fn service_queue(
1157		origin: MessageOriginOf<T>,
1158		weight: &mut WeightMeter,
1159		overweight_limit: Weight,
1160	) -> (bool, Option<MessageOriginOf<T>>) {
1161		use PageExecutionStatus::*;
1162		if weight
1163			.try_consume(
1164				T::WeightInfo::service_queue_base()
1165					.saturating_add(T::WeightInfo::ready_ring_unknit()),
1166			)
1167			.is_err()
1168		{
1169			return (false, None)
1170		}
1171
1172		let mut book_state = BookStateFor::<T>::get(&origin);
1173		let mut total_processed = 0;
1174		if T::QueuePausedQuery::is_paused(&origin) {
1175			let next_ready = book_state.ready_neighbours.as_ref().map(|x| x.next.clone());
1176			return (false, next_ready)
1177		}
1178
1179		while book_state.end > book_state.begin {
1180			let (processed, status) =
1181				Self::service_page(&origin, &mut book_state, weight, overweight_limit);
1182			total_processed.saturating_accrue(processed);
1183			match status {
1184				// Store the page progress and do not go to the next one.
1185				Bailed | NoProgress => break,
1186				// Go to the next page if this one is at the end.
1187				NoMore => (),
1188			};
1189			book_state.begin.saturating_inc();
1190		}
1191		let next_ready = book_state.ready_neighbours.as_ref().map(|x| x.next.clone());
1192		if book_state.begin >= book_state.end {
1193			// No longer ready - unknit.
1194			if let Some(neighbours) = book_state.ready_neighbours.take() {
1195				Self::ready_ring_unknit(&origin, neighbours);
1196			} else if total_processed > 0 {
1197				defensive!("Freshly processed queue must have been ready");
1198			}
1199		}
1200		BookStateFor::<T>::insert(&origin, &book_state);
1201		if total_processed > 0 {
1202			T::QueueChangeHandler::on_queue_changed(origin, book_state.into());
1203		}
1204		(total_processed > 0, next_ready)
1205	}
1206
1207	/// Service as many messages of a page as possible.
1208	///
1209	/// Returns how many messages were processed and the page's status.
1210	fn service_page(
1211		origin: &MessageOriginOf<T>,
1212		book_state: &mut BookStateOf<T>,
1213		weight: &mut WeightMeter,
1214		overweight_limit: Weight,
1215	) -> (u32, PageExecutionStatus) {
1216		use PageExecutionStatus::*;
1217		if weight
1218			.try_consume(
1219				T::WeightInfo::service_page_base_completion()
1220					.max(T::WeightInfo::service_page_base_no_completion()),
1221			)
1222			.is_err()
1223		{
1224			return (0, Bailed)
1225		}
1226
1227		let page_index = book_state.begin;
1228		let mut page = match Pages::<T>::get(origin, page_index) {
1229			Some(p) => p,
1230			None => {
1231				defensive!("message-queue: referenced page not found");
1232				return (0, NoMore)
1233			},
1234		};
1235
1236		let mut total_processed = 0;
1237
1238		// Execute as many messages as possible.
1239		let status = loop {
1240			use ItemExecutionStatus::*;
1241			match Self::service_page_item(
1242				origin,
1243				page_index,
1244				book_state,
1245				&mut page,
1246				weight,
1247				overweight_limit,
1248			) {
1249				Bailed => break PageExecutionStatus::Bailed,
1250				NoItem => break PageExecutionStatus::NoMore,
1251				NoProgress => break PageExecutionStatus::NoProgress,
1252				// Keep going as long as we make progress...
1253				Executed(true) => total_processed.saturating_inc(),
1254				Executed(false) => (),
1255			}
1256		};
1257
1258		if page.is_complete() {
1259			debug_assert!(status != Bailed, "we never bail if a page became complete");
1260			Pages::<T>::remove(origin, page_index);
1261			debug_assert!(book_state.count > 0, "completing a page implies there are pages");
1262			book_state.count.saturating_dec();
1263		} else {
1264			Pages::<T>::insert(origin, page_index, page);
1265		}
1266		(total_processed, status)
1267	}
1268
1269	/// Execute the next message of a page.
1270	pub(crate) fn service_page_item(
1271		origin: &MessageOriginOf<T>,
1272		page_index: PageIndex,
1273		book_state: &mut BookStateOf<T>,
1274		page: &mut PageOf<T>,
1275		weight: &mut WeightMeter,
1276		overweight_limit: Weight,
1277	) -> ItemExecutionStatus {
1278		use MessageExecutionStatus::*;
1279		// This ugly pre-checking is needed for the invariant
1280		// "we never bail if a page became complete".
1281		if page.is_complete() {
1282			return ItemExecutionStatus::NoItem
1283		}
1284		if weight.try_consume(T::WeightInfo::service_page_item()).is_err() {
1285			return ItemExecutionStatus::Bailed
1286		}
1287
1288		let payload = &match page.peek_first() {
1289			Some(m) => m,
1290			None => return ItemExecutionStatus::NoItem,
1291		}[..];
1292		let payload_len = payload.len() as u64;
1293
1294		// Store these for the case that `process_message_payload` is recursive.
1295		Pages::<T>::insert(origin, page_index, &*page);
1296		BookStateFor::<T>::insert(origin, &*book_state);
1297
1298		let res = Self::process_message_payload(
1299			origin.clone(),
1300			page_index,
1301			page.first_index,
1302			payload,
1303			weight,
1304			overweight_limit,
1305		);
1306
1307		// And restore them afterwards to see the changes of a recursive call.
1308		*book_state = BookStateFor::<T>::get(origin);
1309		if let Some(new_page) = Pages::<T>::get(origin, page_index) {
1310			*page = new_page;
1311		} else {
1312			defensive!("page must exist since we just inserted it and recursive calls are not allowed to remove anything");
1313			return ItemExecutionStatus::NoItem
1314		};
1315
1316		let is_processed = match res {
1317			InsufficientWeight => return ItemExecutionStatus::Bailed,
1318			Unprocessable { permanent: false } => return ItemExecutionStatus::NoProgress,
1319			Processed | Unprocessable { permanent: true } | StackLimitReached => true,
1320			Overweight => false,
1321		};
1322
1323		if is_processed {
1324			book_state.message_count.saturating_dec();
1325			book_state.size.saturating_reduce(payload_len as u64);
1326		}
1327		page.skip_first(is_processed);
1328		ItemExecutionStatus::Executed(is_processed)
1329	}
1330
1331	/// Ensure the correctness of state of this pallet.
1332	///
1333	/// # Assumptions-
1334	///
1335	/// If `serviceHead` points to a ready Queue, then BookState of that Queue has:
1336	///
1337	/// * `message_count` > 0
1338	/// * `size` > 0
1339	/// * `end` > `begin`
1340	/// * Some(ready_neighbours)
1341	/// * If `ready_neighbours.next` == self.origin, then `ready_neighbours.prev` == self.origin
1342	///   (only queue in ring)
1343	///
1344	/// For Pages(begin to end-1) in BookState:
1345	///
1346	/// * `remaining` > 0
1347	/// * `remaining_size` > 0
1348	/// * `first` <= `last`
1349	/// * Every page can be decoded into peek_* functions
1350	#[cfg(any(test, feature = "try-runtime", feature = "std"))]
1351	pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
1352		// Checking memory corruption for BookStateFor
1353		ensure!(
1354			BookStateFor::<T>::iter_keys().count() == BookStateFor::<T>::iter_values().count(),
1355			"Memory Corruption in BookStateFor"
1356		);
1357		// Checking memory corruption for Pages
1358		ensure!(
1359			Pages::<T>::iter_keys().count() == Pages::<T>::iter_values().count(),
1360			"Memory Corruption in Pages"
1361		);
1362
1363		// Basic checks for each book
1364		for book in BookStateFor::<T>::iter_values() {
1365			ensure!(book.end >= book.begin, "Invariant");
1366			ensure!(book.end < 1 << 30, "Likely overflow or corruption");
1367			ensure!(book.message_count < 1 << 30, "Likely overflow or corruption");
1368			ensure!(book.size < 1 << 30, "Likely overflow or corruption");
1369			ensure!(book.count < 1 << 30, "Likely overflow or corruption");
1370
1371			let fp: QueueFootprint = book.into();
1372			ensure!(fp.ready_pages <= fp.pages, "There cannot be more ready than total pages");
1373		}
1374
1375		//loop around this origin
1376		let Some(starting_origin) = ServiceHead::<T>::get() else { return Ok(()) };
1377
1378		while let Some(head) = Self::bump_service_head(&mut WeightMeter::new()) {
1379			ensure!(
1380				BookStateFor::<T>::contains_key(&head),
1381				"Service head must point to an existing book"
1382			);
1383
1384			let head_book_state = BookStateFor::<T>::get(&head);
1385			ensure!(
1386				head_book_state.message_count > 0,
1387				"There must be some messages if in ReadyRing"
1388			);
1389			ensure!(head_book_state.size > 0, "There must be some message size if in ReadyRing");
1390			ensure!(
1391				head_book_state.end > head_book_state.begin,
1392				"End > Begin if unprocessed messages exists"
1393			);
1394			ensure!(
1395				head_book_state.ready_neighbours.is_some(),
1396				"There must be neighbours if in ReadyRing"
1397			);
1398
1399			if head_book_state.ready_neighbours.as_ref().unwrap().next == head {
1400				ensure!(
1401					head_book_state.ready_neighbours.as_ref().unwrap().prev == head,
1402					"Can only happen if only queue in ReadyRing"
1403				);
1404			}
1405
1406			for page_index in head_book_state.begin..head_book_state.end {
1407				let page = Pages::<T>::get(&head, page_index).unwrap();
1408				let remaining_messages = page.remaining;
1409				let mut counted_remaining_messages: u32 = 0;
1410				ensure!(
1411					remaining_messages > 0.into(),
1412					"These must be some messages that have not been processed yet!"
1413				);
1414
1415				for i in 0..u32::MAX {
1416					if let Some((_, processed, _)) = page.peek_index(i as usize) {
1417						if !processed {
1418							counted_remaining_messages += 1;
1419						}
1420					} else {
1421						break
1422					}
1423				}
1424
1425				ensure!(
1426					remaining_messages.into() == counted_remaining_messages,
1427					"Memory Corruption"
1428				);
1429			}
1430
1431			if head_book_state.ready_neighbours.as_ref().unwrap().next == starting_origin {
1432				break
1433			}
1434		}
1435		Ok(())
1436	}
1437
1438	/// Print the pages in each queue and the messages in each page.
1439	///
1440	/// Processed messages are prefixed with a `*` and the current `begin`ning page with a `>`.
1441	///
1442	/// # Example output
1443	///
1444	/// ```text
1445	/// queue Here:
1446	///   page 0: []
1447	/// > page 1: []
1448	///   page 2: ["\0weight=4", "\0c", ]
1449	///   page 3: ["\0bigbig 1", ]
1450	///   page 4: ["\0bigbig 2", ]
1451	///   page 5: ["\0bigbig 3", ]
1452	/// ```
1453	#[cfg(feature = "std")]
1454	pub fn debug_info() -> String {
1455		let mut info = String::new();
1456		for (origin, book_state) in BookStateFor::<T>::iter() {
1457			let mut queue = format!("queue {:?}:\n", &origin);
1458			let mut pages = Pages::<T>::iter_prefix(&origin).collect::<Vec<_>>();
1459			pages.sort_by(|(a, _), (b, _)| a.cmp(b));
1460			for (page_index, mut page) in pages.into_iter() {
1461				let page_info = if book_state.begin == page_index { ">" } else { " " };
1462				let mut page_info = format!(
1463					"{} page {} ({:?} first, {:?} last, {:?} remain): [ ",
1464					page_info, page_index, page.first, page.last, page.remaining
1465				);
1466				for i in 0..u32::MAX {
1467					if let Some((_, processed, message)) =
1468						page.peek_index(i.try_into().expect("std-only code"))
1469					{
1470						let msg = String::from_utf8_lossy(message);
1471						if processed {
1472							page_info.push('*');
1473						}
1474						page_info.push_str(&format!("{:?}, ", msg));
1475						page.skip_first(true);
1476					} else {
1477						break
1478					}
1479				}
1480				page_info.push_str("]\n");
1481				queue.push_str(&page_info);
1482			}
1483			info.push_str(&queue);
1484		}
1485		info
1486	}
1487
1488	/// Process a single message.
1489	///
1490	/// The base weight of this function needs to be accounted for by the caller. `weight` is the
1491	/// remaining weight to process the message. `overweight_limit` is the maximum weight that a
1492	/// message can ever consume. Messages above this limit are marked as permanently overweight.
1493	/// This process is also transactional, any form of error that occurs in processing a message
1494	/// causes storage changes to be rolled back.
1495	fn process_message_payload(
1496		origin: MessageOriginOf<T>,
1497		page_index: PageIndex,
1498		message_index: T::Size,
1499		message: &[u8],
1500		meter: &mut WeightMeter,
1501		overweight_limit: Weight,
1502	) -> MessageExecutionStatus {
1503		let mut id = sp_io::hashing::blake2_256(message);
1504		use ProcessMessageError::*;
1505		let prev_consumed = meter.consumed();
1506
1507		let transaction =
1508			storage::with_transaction(|| -> TransactionOutcome<Result<_, DispatchError>> {
1509				let res =
1510					T::MessageProcessor::process_message(message, origin.clone(), meter, &mut id);
1511				match &res {
1512					Ok(_) => TransactionOutcome::Commit(Ok(res)),
1513					Err(_) => TransactionOutcome::Rollback(Ok(res)),
1514				}
1515			});
1516
1517		let transaction = match transaction {
1518			Ok(result) => result,
1519			_ => {
1520				defensive!(
1521					"Error occurred processing message, storage changes will be rolled back"
1522				);
1523				return MessageExecutionStatus::Unprocessable { permanent: true }
1524			},
1525		};
1526
1527		match transaction {
1528			Err(Overweight(w)) if w.any_gt(overweight_limit) => {
1529				// Permanently overweight.
1530				Self::deposit_event(Event::<T>::OverweightEnqueued {
1531					id,
1532					origin,
1533					page_index,
1534					message_index,
1535				});
1536				MessageExecutionStatus::Overweight
1537			},
1538			Err(Overweight(_)) => {
1539				// Temporarily overweight - save progress and stop processing this
1540				// queue.
1541				MessageExecutionStatus::InsufficientWeight
1542			},
1543			Err(Yield) => {
1544				// Processing should be reattempted later.
1545				MessageExecutionStatus::Unprocessable { permanent: false }
1546			},
1547			Err(error @ BadFormat | error @ Corrupt | error @ Unsupported) => {
1548				// Permanent error - drop
1549				Self::deposit_event(Event::<T>::ProcessingFailed { id: id.into(), origin, error });
1550				MessageExecutionStatus::Unprocessable { permanent: true }
1551			},
1552			Err(error @ StackLimitReached) => {
1553				Self::deposit_event(Event::<T>::ProcessingFailed { id: id.into(), origin, error });
1554				MessageExecutionStatus::StackLimitReached
1555			},
1556			Ok(success) => {
1557				// Success
1558				let weight_used = meter.consumed().saturating_sub(prev_consumed);
1559				Self::deposit_event(Event::<T>::Processed {
1560					id: id.into(),
1561					origin,
1562					weight_used,
1563					success,
1564				});
1565				MessageExecutionStatus::Processed
1566			},
1567		}
1568	}
1569
1570	fn service_queues_impl(weight_limit: Weight, context: ServiceQueuesContext) -> Weight {
1571		let mut weight = WeightMeter::with_limit(weight_limit);
1572
1573		// Get the maximum weight that processing a single message may take:
1574		let overweight_limit = Self::max_message_weight(weight_limit).unwrap_or_else(|| {
1575			if matches!(context, ServiceQueuesContext::OnInitialize) {
1576				defensive!("Not enough weight to service a single message.");
1577			}
1578			Weight::zero()
1579		});
1580
1581		match with_service_mutex(|| {
1582			let mut next = match Self::bump_service_head(&mut weight) {
1583				Some(h) => h,
1584				None => return weight.consumed(),
1585			};
1586			// The last queue that did not make any progress.
1587			// The loop aborts as soon as it arrives at this queue again without making any progress
1588			// on other queues in between.
1589			let mut last_no_progress = None;
1590
1591			loop {
1592				let (progressed, n) =
1593					Self::service_queue(next.clone(), &mut weight, overweight_limit);
1594				next = match n {
1595					Some(n) =>
1596						if !progressed {
1597							if last_no_progress == Some(n.clone()) {
1598								break
1599							}
1600							if last_no_progress.is_none() {
1601								last_no_progress = Some(next.clone())
1602							}
1603							n
1604						} else {
1605							last_no_progress = None;
1606							n
1607						},
1608					None => break,
1609				}
1610			}
1611			weight.consumed()
1612		}) {
1613			Err(()) => weight.consumed(),
1614			Ok(w) => w,
1615		}
1616	}
1617}
1618
1619/// Run a closure that errors on re-entrance. Meant to be used by anything that services queues.
1620pub(crate) fn with_service_mutex<F: FnOnce() -> R, R>(f: F) -> Result<R, ()> {
1621	// Holds the singleton token instance.
1622	environmental::environmental!(token: Option<()>);
1623
1624	token::using_once(&mut Some(()), || {
1625		// The first `ok_or` should always be `Ok` since we are inside a `using_once`.
1626		let hold = token::with(|t| t.take()).ok_or(()).defensive()?.ok_or(())?;
1627
1628		// Put the token back when we're done.
1629		defer! {
1630			token::with(|t| {
1631				*t = Some(hold);
1632			});
1633		}
1634
1635		Ok(f())
1636	})
1637}
1638
1639/// Provides a [`sp_core::Get`] to access the `MEL` of a [`codec::MaxEncodedLen`] type.
1640pub struct MaxEncodedLenOf<T>(core::marker::PhantomData<T>);
1641impl<T: MaxEncodedLen> Get<u32> for MaxEncodedLenOf<T> {
1642	fn get() -> u32 {
1643		T::max_encoded_len() as u32
1644	}
1645}
1646
1647/// Calculates the maximum message length and exposed it through the [`codec::MaxEncodedLen`] trait.
1648pub struct MaxMessageLen<Origin, Size, HeapSize>(
1649	core::marker::PhantomData<(Origin, Size, HeapSize)>,
1650);
1651impl<Origin: MaxEncodedLen, Size: MaxEncodedLen + Into<u32>, HeapSize: Get<Size>> Get<u32>
1652	for MaxMessageLen<Origin, Size, HeapSize>
1653{
1654	fn get() -> u32 {
1655		(HeapSize::get().into()).saturating_sub(ItemHeader::<Size>::max_encoded_len() as u32)
1656	}
1657}
1658
1659/// The maximal message length.
1660pub type MaxMessageLenOf<T> =
1661	MaxMessageLen<MessageOriginOf<T>, <T as Config>::Size, <T as Config>::HeapSize>;
1662/// The maximal encoded origin length.
1663pub type MaxOriginLenOf<T> = MaxEncodedLenOf<MessageOriginOf<T>>;
1664/// The `MessageOrigin` of this pallet.
1665pub type MessageOriginOf<T> = <<T as Config>::MessageProcessor as ProcessMessage>::Origin;
1666/// The maximal heap size of a page.
1667pub type HeapSizeU32Of<T> = IntoU32<<T as Config>::HeapSize, <T as Config>::Size>;
1668/// The [`Page`] of this pallet.
1669pub type PageOf<T> = Page<<T as Config>::Size, <T as Config>::HeapSize>;
1670/// The [`BookState`] of this pallet.
1671pub type BookStateOf<T> = BookState<MessageOriginOf<T>>;
1672
1673/// Converts a [`sp_core::Get`] with returns a type that can be cast into an `u32` into a `Get`
1674/// which returns an `u32`.
1675pub struct IntoU32<T, O>(core::marker::PhantomData<(T, O)>);
1676impl<T: Get<O>, O: Into<u32>> Get<u32> for IntoU32<T, O> {
1677	fn get() -> u32 {
1678		T::get().into()
1679	}
1680}
1681
1682impl<T: Config> ServiceQueues for Pallet<T> {
1683	type OverweightMessageAddress = (MessageOriginOf<T>, PageIndex, T::Size);
1684
1685	fn service_queues(weight_limit: Weight) -> Weight {
1686		Self::service_queues_impl(weight_limit, ServiceQueuesContext::ServiceQueues)
1687	}
1688
1689	/// Execute a single overweight message.
1690	///
1691	/// The weight limit must be enough for `execute_overweight` and the message execution itself.
1692	fn execute_overweight(
1693		weight_limit: Weight,
1694		(message_origin, page, index): Self::OverweightMessageAddress,
1695	) -> Result<Weight, ExecuteOverweightError> {
1696		let mut weight = WeightMeter::with_limit(weight_limit);
1697		if weight
1698			.try_consume(
1699				T::WeightInfo::execute_overweight_page_removed()
1700					.max(T::WeightInfo::execute_overweight_page_updated()),
1701			)
1702			.is_err()
1703		{
1704			return Err(ExecuteOverweightError::InsufficientWeight)
1705		}
1706
1707		Pallet::<T>::do_execute_overweight(message_origin, page, index, weight.remaining()).map_err(
1708			|e| match e {
1709				Error::<T>::InsufficientWeight => ExecuteOverweightError::InsufficientWeight,
1710				Error::<T>::AlreadyProcessed => ExecuteOverweightError::AlreadyProcessed,
1711				Error::<T>::QueuePaused => ExecuteOverweightError::QueuePaused,
1712				Error::<T>::NoPage | Error::<T>::NoMessage | Error::<T>::Queued =>
1713					ExecuteOverweightError::NotFound,
1714				Error::<T>::RecursiveDisallowed => ExecuteOverweightError::RecursiveDisallowed,
1715				_ => ExecuteOverweightError::Other,
1716			},
1717		)
1718	}
1719}
1720
1721impl<T: Config> EnqueueMessage<MessageOriginOf<T>> for Pallet<T> {
1722	type MaxMessageLen =
1723		MaxMessageLen<<T::MessageProcessor as ProcessMessage>::Origin, T::Size, T::HeapSize>;
1724
1725	fn enqueue_message(
1726		message: BoundedSlice<u8, Self::MaxMessageLen>,
1727		origin: <T::MessageProcessor as ProcessMessage>::Origin,
1728	) {
1729		Self::do_enqueue_message(&origin, message);
1730		let book_state = BookStateFor::<T>::get(&origin);
1731		T::QueueChangeHandler::on_queue_changed(origin, book_state.into());
1732	}
1733
1734	fn enqueue_messages<'a>(
1735		messages: impl Iterator<Item = BoundedSlice<'a, u8, Self::MaxMessageLen>>,
1736		origin: <T::MessageProcessor as ProcessMessage>::Origin,
1737	) {
1738		for message in messages {
1739			Self::do_enqueue_message(&origin, message);
1740		}
1741		let book_state = BookStateFor::<T>::get(&origin);
1742		T::QueueChangeHandler::on_queue_changed(origin, book_state.into());
1743	}
1744
1745	fn sweep_queue(origin: MessageOriginOf<T>) {
1746		if !BookStateFor::<T>::contains_key(&origin) {
1747			return
1748		}
1749		let mut book_state = BookStateFor::<T>::get(&origin);
1750		book_state.begin = book_state.end;
1751		if let Some(neighbours) = book_state.ready_neighbours.take() {
1752			Self::ready_ring_unknit(&origin, neighbours);
1753		}
1754		BookStateFor::<T>::insert(&origin, &book_state);
1755	}
1756
1757	fn footprint(origin: MessageOriginOf<T>) -> QueueFootprint {
1758		BookStateFor::<T>::get(&origin).into()
1759	}
1760}