-
Notifications
You must be signed in to change notification settings - Fork 296
/
lib.rs
399 lines (376 loc) · 15.6 KB
/
lib.rs
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
//! A crate that groups user-facing and internal error types and codes produced
//! by the Internet Computer.
use ic_utils::str::StrEllipsize;
use serde::{Deserialize, Serialize};
use std::{convert::TryFrom, fmt};
use strum_macros::EnumIter;
#[derive(Clone, Copy, Debug)]
pub enum TryFromError {
ValueOutOfRange(u64),
}
/// Reject codes are integers that canisters should pass to msg.reject
/// system API calls. These errors are designed for programmatic error
/// handling, not for end-users. They are also used for classification
/// of user-facing errors.
///
/// See <https://sdk.dfinity.org/docs/interface-spec/index.html#reject-codes>
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, EnumIter)]
pub enum RejectCode {
SysFatal = 1,
SysTransient = 2,
DestinationInvalid = 3,
CanisterReject = 4,
CanisterError = 5,
}
impl ToString for RejectCode {
fn to_string(&self) -> String {
self.to_str().to_owned()
}
}
impl RejectCode {
fn to_str(self) -> &'static str {
match self {
RejectCode::SysFatal => "SYS_FATAL",
RejectCode::SysTransient => "SYS_TRANSIENT",
RejectCode::DestinationInvalid => "DESTINATION_INVALID",
RejectCode::CanisterReject => "CANISTER_REJECT",
RejectCode::CanisterError => "CANISTER_ERROR",
}
}
}
impl TryFrom<u64> for RejectCode {
type Error = TryFromError;
fn try_from(code: u64) -> Result<Self, Self::Error> {
match code {
1 => Ok(RejectCode::SysFatal),
2 => Ok(RejectCode::SysTransient),
3 => Ok(RejectCode::DestinationInvalid),
4 => Ok(RejectCode::CanisterReject),
5 => Ok(RejectCode::CanisterError),
_ => Err(TryFromError::ValueOutOfRange(code)),
}
}
}
impl From<ErrorCode> for RejectCode {
fn from(err: ErrorCode) -> RejectCode {
use ErrorCode::*;
use RejectCode::*;
match err {
SubnetOversubscribed => SysFatal,
MaxNumberOfCanistersReached => SysFatal,
CanisterQueueFull => SysTransient,
IngressMessageTimeout => SysTransient,
CanisterQueueNotEmpty => SysTransient,
IngressHistoryFull => SysTransient,
CanisterIdAlreadyExists => SysTransient,
StopCanisterRequestTimeout => SysTransient,
CanisterInvalidController => CanisterError,
CanisterNotFound => DestinationInvalid,
CanisterMethodNotFound => DestinationInvalid,
CanisterFunctionNotFound => CanisterError,
CanisterWasmModuleNotFound => DestinationInvalid,
CanisterAlreadyInstalled => DestinationInvalid,
CanisterNonEmpty => CanisterError,
CanisterOutOfCycles => CanisterError,
CanisterTrapped => CanisterError,
CanisterCalledTrap => CanisterError,
CanisterContractViolation => CanisterError,
CanisterInvalidWasm => CanisterError,
CanisterDidNotReply => CanisterError,
CanisterOutOfMemory => CanisterError,
CanisterStopped => CanisterError,
CanisterStopping => CanisterError,
CanisterNotStopped => CanisterError,
CanisterStoppingCancelled => CanisterError,
InsufficientCyclesForCreateCanister => CanisterReject,
CertifiedStateUnavailable => SysTransient,
InsufficientMemoryAllocation => CanisterReject,
SubnetNotFound => CanisterReject,
CanisterRejectedMessage => CanisterReject,
QueryCallGraphLoopDetected => CanisterError,
UnknownManagementMessage => CanisterReject,
InvalidManagementPayload => CanisterReject,
InsufficientCyclesInCall => CanisterError,
CanisterWasmEngineError => CanisterError,
CanisterInstructionLimitExceeded => CanisterError,
CanisterInstallCodeRateLimited => SysTransient,
CanisterMemoryAccessLimitExceeded => CanisterError,
QueryCallGraphTooDeep => CanisterError,
QueryCallGraphTotalInstructionLimitExceeded => CanisterError,
CompositeQueryCalledInReplicatedMode => CanisterError,
CanisterNotHostedBySubnet => CanisterReject,
QueryTimeLimitExceeded => CanisterError,
QueryCallGraphInternal => CanisterError,
InsufficientCyclesInComputeAllocation => CanisterError,
InsufficientCyclesInMemoryAllocation => CanisterError,
InsufficientCyclesInMemoryGrow => CanisterError,
ReservedCyclesLimitExceededInMemoryAllocation => CanisterError,
ReservedCyclesLimitExceededInMemoryGrow => CanisterError,
InsufficientCyclesInMessageMemoryGrow => CanisterError,
}
}
}
/// User-facing error codes.
///
/// The error codes are currently assigned using an HTTP-like
/// convention: the most significant digit is the corresponding reject
/// code and the rest is just a sequentially assigned two-digit
/// number.
#[derive(
PartialOrd, Ord, Clone, Copy, Debug, PartialEq, EnumIter, Eq, Hash, Serialize, Deserialize,
)]
pub enum ErrorCode {
SubnetOversubscribed = 101,
MaxNumberOfCanistersReached = 102,
CanisterQueueFull = 201,
IngressMessageTimeout = 202,
CanisterQueueNotEmpty = 203,
IngressHistoryFull = 204,
CanisterIdAlreadyExists = 205,
StopCanisterRequestTimeout = 206,
CanisterNotFound = 301,
CanisterMethodNotFound = 302,
CanisterAlreadyInstalled = 303,
CanisterWasmModuleNotFound = 304,
InsufficientMemoryAllocation = 402,
InsufficientCyclesForCreateCanister = 403,
SubnetNotFound = 404,
CanisterNotHostedBySubnet = 405,
CanisterOutOfCycles = 501,
CanisterTrapped = 502,
CanisterCalledTrap = 503,
CanisterContractViolation = 504,
CanisterInvalidWasm = 505,
CanisterDidNotReply = 506,
CanisterOutOfMemory = 507,
CanisterStopped = 508,
CanisterStopping = 509,
CanisterNotStopped = 510,
CanisterStoppingCancelled = 511,
CanisterInvalidController = 512,
CanisterFunctionNotFound = 513,
CanisterNonEmpty = 514,
CertifiedStateUnavailable = 515,
CanisterRejectedMessage = 516,
QueryCallGraphLoopDetected = 517,
UnknownManagementMessage = 518,
InvalidManagementPayload = 519,
InsufficientCyclesInCall = 520,
CanisterWasmEngineError = 521,
CanisterInstructionLimitExceeded = 522,
CanisterInstallCodeRateLimited = 523,
CanisterMemoryAccessLimitExceeded = 524,
QueryCallGraphTooDeep = 525,
QueryCallGraphTotalInstructionLimitExceeded = 526,
CompositeQueryCalledInReplicatedMode = 527,
QueryTimeLimitExceeded = 528,
QueryCallGraphInternal = 529,
InsufficientCyclesInComputeAllocation = 530,
InsufficientCyclesInMemoryAllocation = 531,
InsufficientCyclesInMemoryGrow = 532,
ReservedCyclesLimitExceededInMemoryAllocation = 533,
ReservedCyclesLimitExceededInMemoryGrow = 534,
InsufficientCyclesInMessageMemoryGrow = 535,
}
impl TryFrom<u64> for ErrorCode {
type Error = TryFromError;
fn try_from(err: u64) -> Result<ErrorCode, Self::Error> {
match err {
101 => Ok(ErrorCode::SubnetOversubscribed),
102 => Ok(ErrorCode::MaxNumberOfCanistersReached),
201 => Ok(ErrorCode::CanisterQueueFull),
202 => Ok(ErrorCode::IngressMessageTimeout),
203 => Ok(ErrorCode::CanisterQueueNotEmpty),
204 => Ok(ErrorCode::IngressHistoryFull),
205 => Ok(ErrorCode::CanisterIdAlreadyExists),
206 => Ok(ErrorCode::StopCanisterRequestTimeout),
301 => Ok(ErrorCode::CanisterNotFound),
302 => Ok(ErrorCode::CanisterMethodNotFound),
303 => Ok(ErrorCode::CanisterAlreadyInstalled),
304 => Ok(ErrorCode::CanisterWasmModuleNotFound),
402 => Ok(ErrorCode::InsufficientMemoryAllocation),
403 => Ok(ErrorCode::InsufficientCyclesForCreateCanister),
404 => Ok(ErrorCode::SubnetNotFound),
405 => Ok(ErrorCode::CanisterNotHostedBySubnet),
501 => Ok(ErrorCode::CanisterOutOfCycles),
502 => Ok(ErrorCode::CanisterTrapped),
503 => Ok(ErrorCode::CanisterCalledTrap),
504 => Ok(ErrorCode::CanisterContractViolation),
505 => Ok(ErrorCode::CanisterInvalidWasm),
506 => Ok(ErrorCode::CanisterDidNotReply),
507 => Ok(ErrorCode::CanisterOutOfMemory),
508 => Ok(ErrorCode::CanisterStopped),
509 => Ok(ErrorCode::CanisterStopping),
510 => Ok(ErrorCode::CanisterNotStopped),
511 => Ok(ErrorCode::CanisterStoppingCancelled),
512 => Ok(ErrorCode::CanisterInvalidController),
513 => Ok(ErrorCode::CanisterFunctionNotFound),
514 => Ok(ErrorCode::CanisterNonEmpty),
515 => Ok(ErrorCode::CertifiedStateUnavailable),
516 => Ok(ErrorCode::CanisterRejectedMessage),
517 => Ok(ErrorCode::QueryCallGraphLoopDetected),
518 => Ok(ErrorCode::UnknownManagementMessage),
519 => Ok(ErrorCode::InvalidManagementPayload),
520 => Ok(ErrorCode::InsufficientCyclesInCall),
521 => Ok(ErrorCode::CanisterWasmEngineError),
522 => Ok(ErrorCode::CanisterInstructionLimitExceeded),
523 => Ok(ErrorCode::CanisterInstallCodeRateLimited),
524 => Ok(ErrorCode::CanisterMemoryAccessLimitExceeded),
525 => Ok(ErrorCode::QueryCallGraphTooDeep),
526 => Ok(ErrorCode::QueryCallGraphTotalInstructionLimitExceeded),
527 => Ok(ErrorCode::CompositeQueryCalledInReplicatedMode),
528 => Ok(ErrorCode::QueryTimeLimitExceeded),
529 => Ok(ErrorCode::QueryCallGraphInternal),
530 => Ok(ErrorCode::InsufficientCyclesInComputeAllocation),
531 => Ok(ErrorCode::InsufficientCyclesInMemoryAllocation),
532 => Ok(ErrorCode::InsufficientCyclesInMemoryGrow),
533 => Ok(ErrorCode::ReservedCyclesLimitExceededInMemoryAllocation),
534 => Ok(ErrorCode::ReservedCyclesLimitExceededInMemoryGrow),
535 => Ok(ErrorCode::InsufficientCyclesInMessageMemoryGrow),
_ => Err(TryFromError::ValueOutOfRange(err)),
}
}
}
/// Maximum allowed length for UserError description.
const MAX_USER_ERROR_DESCRIPTION_LEN_BYTES: usize = 8 * 1024;
/// The error that is sent back to users of IC if something goes
/// wrong. It's designed to be copyable and serializable so that we
/// can persist it in ingress history.
#[derive(PartialOrd, Ord, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct UserError {
code: ErrorCode,
description: String,
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// E.g. "IC0301"
write!(f, "IC{:04}", *self as i32)
}
}
impl fmt::Display for UserError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// E.g. "IC0301: Canister 42 not found"
write!(f, "{}: {}", self.code, self.description)
}
}
impl UserError {
pub fn new<S: ToString>(code: ErrorCode, description: S) -> Self {
Self {
code,
description: description
.to_string()
.ellipsize(MAX_USER_ERROR_DESCRIPTION_LEN_BYTES, 50),
}
}
/// Constructs a `UserError` retaining the original description without truncation.
/// This ensures backward compatibility with ingress history.
///
/// # Safety
///
/// This constructor is specifically intended for state-loading. Avoid usage in other contexts.
pub fn from_proto<S: ToString>(code: ErrorCode, description: S) -> Self {
Self {
code,
description: description.to_string(),
}
}
pub fn code(&self) -> ErrorCode {
self.code
}
pub fn description(&self) -> &str {
&self.description
}
pub fn reject_code(&self) -> RejectCode {
self.code().into()
}
pub fn is_system_error(&self) -> bool {
match self.code {
ErrorCode::CanisterWasmEngineError | ErrorCode::QueryCallGraphInternal => true,
ErrorCode::SubnetOversubscribed
| ErrorCode::MaxNumberOfCanistersReached
| ErrorCode::CanisterQueueFull
| ErrorCode::IngressMessageTimeout
| ErrorCode::StopCanisterRequestTimeout
| ErrorCode::CanisterQueueNotEmpty
| ErrorCode::CanisterNotFound
| ErrorCode::CanisterMethodNotFound
| ErrorCode::CanisterAlreadyInstalled
| ErrorCode::CanisterWasmModuleNotFound
| ErrorCode::InsufficientMemoryAllocation
| ErrorCode::InsufficientCyclesForCreateCanister
| ErrorCode::SubnetNotFound
| ErrorCode::CanisterIdAlreadyExists
| ErrorCode::CanisterNotHostedBySubnet
| ErrorCode::CanisterOutOfCycles
| ErrorCode::CanisterTrapped
| ErrorCode::CanisterCalledTrap
| ErrorCode::CanisterContractViolation
| ErrorCode::CanisterInvalidWasm
| ErrorCode::CanisterDidNotReply
| ErrorCode::CanisterOutOfMemory
| ErrorCode::CanisterStopped
| ErrorCode::CanisterStopping
| ErrorCode::CanisterNotStopped
| ErrorCode::CanisterStoppingCancelled
| ErrorCode::CanisterInvalidController
| ErrorCode::CanisterFunctionNotFound
| ErrorCode::CanisterNonEmpty
| ErrorCode::CertifiedStateUnavailable
| ErrorCode::CanisterRejectedMessage
| ErrorCode::QueryCallGraphLoopDetected
| ErrorCode::UnknownManagementMessage
| ErrorCode::IngressHistoryFull
| ErrorCode::InvalidManagementPayload
| ErrorCode::InsufficientCyclesInCall
| ErrorCode::CanisterInstructionLimitExceeded
| ErrorCode::CanisterInstallCodeRateLimited
| ErrorCode::CanisterMemoryAccessLimitExceeded
| ErrorCode::QueryCallGraphTooDeep
| ErrorCode::QueryCallGraphTotalInstructionLimitExceeded
| ErrorCode::CompositeQueryCalledInReplicatedMode
| ErrorCode::QueryTimeLimitExceeded
| ErrorCode::InsufficientCyclesInComputeAllocation
| ErrorCode::InsufficientCyclesInMemoryAllocation
| ErrorCode::InsufficientCyclesInMemoryGrow
| ErrorCode::ReservedCyclesLimitExceededInMemoryAllocation
| ErrorCode::ReservedCyclesLimitExceededInMemoryGrow
| ErrorCode::InsufficientCyclesInMessageMemoryGrow => false,
}
}
pub fn count_bytes(&self) -> usize {
std::mem::size_of_val(self) + self.description.len()
}
}
impl std::error::Error for UserError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use strum::IntoEnumIterator;
#[test]
fn test_user_error_display() {
assert_eq!(
format!(
"{}",
UserError::new(
ErrorCode::CanisterOutOfCycles,
"Canister 42 ran out of cycles"
)
),
"IC0501: Canister 42 ran out of cycles"
);
}
#[test]
fn can_decode_error_code_from_u64() {
for code in ErrorCode::iter() {
let int_code = code as u64;
match ErrorCode::try_from(int_code) {
Ok(decoded_code) => assert_eq!(code, decoded_code),
Err(err) => panic!("Could not decode {} to an ErrorCode: {:?}.", int_code, err),
}
}
}
}