ng_repo/
errors.rs

1// Copyright (c) 2022-2024 Niko Bonnieure, Par le Peuple, NextGraph.org developers
2// All rights reserved.
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
5// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
6// at your option. All files in the project carrying such
7// notice may not be copied, modified, or distributed except
8// according to those terms.
9
10//! Errors
11
12use core::fmt;
13use std::error::Error;
14
15use num_enum::IntoPrimitive;
16use num_enum::TryFromPrimitive;
17
18pub use crate::commit::{CommitLoadError, CommitVerifyError};
19use crate::file::FileError;
20use crate::object::Object;
21use crate::types::BlockId;
22
23#[derive(Debug, Eq, PartialEq, Clone)]
24#[repr(u16)]
25pub enum NgError {
26    InvalidSignature,
27    IncompleteSignature,
28    SerializationError,
29    EncryptionError,
30    DecryptionError,
31    InvalidValue,
32    ConnectionNotFound,
33    InvalidKey,
34    InvalidInvitation,
35    InvalidCreateAccount,
36    InvalidFileFormat,
37    InvalidArgument,
38    PermissionDenied,
39    InvalidPazzle,
40    CommitLoadError(CommitLoadError),
41    ObjectParseError(ObjectParseError),
42    StorageError(StorageError),
43    NotFound,
44    JsStorageKeyNotFound,
45    IoError,
46    CommitVerifyError(CommitVerifyError),
47    LocalBrokerNotInitialized,
48    JsStorageReadError,
49    JsStorageWriteError(String),
50    CannotSaveWhenInMemoryConfig,
51    WalletNotFound,
52    WalletAlreadyAdded,
53    WalletAlreadyOpened,
54    WalletError(String),
55    BrokerError,
56    SessionNotFound,
57    SessionAlreadyStarted,
58    RepoNotFound,
59    BranchNotFound,
60    StoreNotFound,
61    UserNotFound,
62    TopicNotFound,
63    NotConnected,
64    ActorError,
65    ProtocolError(ProtocolError),
66    ServerError(ServerError),
67    InvalidResponse,
68    BootstrapError(String),
69    NotAServerError,
70    VerifierError(VerifierError),
71    SiteNotFoundOnBroker,
72    BrokerConfigErrorStr(&'static str),
73    BrokerConfigError(String),
74    MalformedEvent,
75    InvalidPayload,
76    WrongUploadId,
77    FileError(FileError),
78    InternalError,
79    OxiGraphError(String),
80    ConfigError(String),
81    LocalBrokerIsHeadless,
82    LocalBrokerIsNotHeadless,
83    InvalidNuri,
84}
85
86impl Error for NgError {}
87
88impl fmt::Display for NgError {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::WalletError(string) => write!(f, "WalletError: {}", string),
92            Self::JsStorageWriteError(string) => write!(f, "JsStorageWriteError: {}", string),
93            Self::CommitVerifyError(commit_verify_error) => {
94                write!(f, "CommitVerifyError: {:?}", commit_verify_error)
95            }
96            Self::ProtocolError(error) => write!(f, "ProtocolError: {:?}", error),
97            Self::ServerError(error) => write!(f, "ServerError: {:?}", error),
98            Self::VerifierError(error) => write!(f, "VerifierError: {:?}", error),
99            Self::CommitLoadError(commit_load_error) => {
100                write!(f, "CommitLoadError: {:?}", commit_load_error)
101            }
102            Self::BootstrapError(error) => {
103                write!(f, "BootstrapError: {:?}", error)
104            }
105            Self::ObjectParseError(error) => write!(f, "ObjectParseError: {:?}", error),
106            Self::StorageError(storage_error) => write!(f, "StorageError: {:?}", storage_error),
107            Self::BrokerConfigErrorStr(s) => write!(f, "BrokerConfigError: {s}"),
108            Self::BrokerConfigError(s) => write!(f, "BrokerConfigError: {s}"),
109            _ => write!(f, "{:?}", self),
110        }
111    }
112}
113
114impl From<NgError> for std::io::Error {
115    fn from(err: NgError) -> std::io::Error {
116        match err {
117            NgError::InvalidArgument => std::io::Error::from(std::io::ErrorKind::InvalidInput),
118            NgError::PermissionDenied => std::io::Error::from(std::io::ErrorKind::PermissionDenied),
119            NgError::NotFound => std::io::Error::from(std::io::ErrorKind::NotFound),
120            _ => std::io::Error::new(std::io::ErrorKind::Other, err.to_string().as_str()),
121        }
122    }
123}
124
125impl From<serde_bare::error::Error> for NgError {
126    fn from(_e: serde_bare::error::Error) -> Self {
127        NgError::SerializationError
128    }
129}
130
131impl From<ed25519_dalek::ed25519::Error> for NgError {
132    fn from(_e: ed25519_dalek::ed25519::Error) -> Self {
133        NgError::InvalidSignature
134    }
135}
136
137impl From<CommitLoadError> for NgError {
138    fn from(e: CommitLoadError) -> Self {
139        NgError::CommitLoadError(e)
140    }
141}
142
143impl From<FileError> for NgError {
144    fn from(e: FileError) -> Self {
145        NgError::FileError(e)
146    }
147}
148
149impl From<CommitVerifyError> for NgError {
150    fn from(e: CommitVerifyError) -> Self {
151        NgError::CommitVerifyError(e)
152    }
153}
154
155impl From<StorageError> for NgError {
156    fn from(e: StorageError) -> Self {
157        NgError::StorageError(e)
158    }
159}
160
161impl From<VerifierError> for NgError {
162    fn from(e: VerifierError) -> Self {
163        match e {
164            VerifierError::InvalidKey => NgError::InvalidKey,
165            VerifierError::SerializationError => NgError::SerializationError,
166            VerifierError::CommitLoadError(e) => NgError::CommitLoadError(e),
167            VerifierError::StorageError(e) => NgError::StorageError(e),
168            VerifierError::ObjectParseError(e) => NgError::ObjectParseError(e),
169            VerifierError::TopicNotFound => NgError::TopicNotFound,
170            VerifierError::RepoNotFound => NgError::RepoNotFound,
171            VerifierError::StoreNotFound => NgError::StoreNotFound,
172            VerifierError::BranchNotFound => NgError::BranchNotFound,
173            _ => NgError::VerifierError(e),
174        }
175    }
176}
177
178/// Object parsing errors
179#[derive(Debug, PartialEq, Eq, Clone)]
180pub enum ObjectParseError {
181    /// Missing blocks
182    MissingBlocks(Vec<BlockId>),
183    /// Missing root key
184    MissingRootKey,
185    /// Invalid BlockId encountered in the tree
186    InvalidBlockId,
187    /// Too many or too few children of a block
188    InvalidChildren,
189    /// Number of keys does not match number of children of a block
190    InvalidKeys,
191    /// Invalid CommitHeader object content
192    InvalidHeader,
193    /// Error deserializing content of a block
194    BlockDeserializeError,
195    /// Error deserializing content of the object
196    ObjectDeserializeError,
197
198    MissingHeaderBlocks((Object, Vec<BlockId>)),
199
200    MalformedDag,
201    FilterDeserializationError,
202}
203
204#[derive(Debug, PartialEq, Eq, Clone)]
205pub enum StorageError {
206    NotFound,
207    InvalidValue,
208    DifferentValue,
209    BackendError,
210    SerializationError,
211    AlreadyExists,
212    DataCorruption,
213    UnknownColumnFamily,
214    PropertyNotFound,
215    NotAStoreRepo,
216    OverlayBranchNotFound,
217    Abort,
218    NotEmpty,
219}
220
221impl core::fmt::Display for StorageError {
222    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
223        write!(f, "{:?}", self)
224    }
225}
226
227impl From<serde_bare::error::Error> for StorageError {
228    fn from(_e: serde_bare::error::Error) -> Self {
229        StorageError::SerializationError
230    }
231}
232
233#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone)]
234#[repr(u16)]
235pub enum ServerError {
236    Ok = 0,
237    PartialContent,
238    EndOfStream,
239    False,
240    SequenceMismatch,
241    FileError,
242    RepoAlreadyOpened,
243    NotFound,
244    EmptyStream,
245    StorageError,
246    InvalidRequest,
247    InvalidSignature,
248    OtherError,
249    OverlayMismatch,
250    OverlayNotFound,
251    TopicNotFound,
252    AccessDenied,
253    InvalidHeader,
254    MalformedBranch,
255    BrokerError,
256    ProtocolError,
257    PeerAlreadySubscribed,
258    SubscriptionNotFound,
259    SessionNotFound,
260    SessionDetached,
261    OxiGraphError,
262}
263
264impl From<StorageError> for ServerError {
265    fn from(e: StorageError) -> Self {
266        match e {
267            StorageError::NotFound => ServerError::NotFound,
268            _ => ServerError::StorageError,
269        }
270    }
271}
272
273impl From<ProtocolError> for ServerError {
274    fn from(e: ProtocolError) -> Self {
275        match e {
276            ProtocolError::NotFound => ServerError::NotFound,
277            ProtocolError::BrokerError => ServerError::BrokerError,
278            _ => ServerError::ProtocolError,
279        }
280    }
281}
282
283impl From<NgError> for ServerError {
284    fn from(e: NgError) -> Self {
285        match e {
286            NgError::InvalidSignature => ServerError::InvalidSignature,
287            NgError::OxiGraphError(_) => ServerError::OxiGraphError,
288            _ => ServerError::OtherError,
289        }
290    }
291}
292
293impl ServerError {
294    pub fn is_stream(&self) -> bool {
295        *self == ServerError::PartialContent || *self == ServerError::EndOfStream
296    }
297    pub fn is_err(&self) -> bool {
298        *self != ServerError::Ok && !self.is_stream()
299    }
300}
301
302#[derive(Debug, Eq, PartialEq, Clone)]
303pub enum VerifierError {
304    MalformedDag,
305    MissingCommitInDag,
306    CommitBodyNotFound,
307    InvalidKey,
308    SerializationError,
309    OtherError(String),
310    CommitLoadError(CommitLoadError),
311    InvalidRepositoryCommit,
312    MissingRepoWriteCapSecret,
313    StorageError(StorageError),
314    ObjectParseError(ObjectParseError),
315    NotImplemented,
316    InvalidSignatureObject,
317    MalformedSyncSignatureAcks,
318    MalformedSyncSignatureDeps,
319    TopicNotFound,
320    RepoNotFound,
321    StoreNotFound,
322    OverlayNotFound,
323    BranchNotFound,
324    InvalidBranch,
325    NoBlockStorageAvailable,
326    RootBranchNotFound,
327    BranchNotOpened,
328    DoubleBranchSubscription,
329    InvalidCommit,
330    LocallyConnected,
331}
332
333impl From<NgError> for VerifierError {
334    fn from(e: NgError) -> Self {
335        match e {
336            NgError::InvalidKey => VerifierError::InvalidKey,
337            NgError::RepoNotFound => VerifierError::RepoNotFound,
338            NgError::BranchNotFound => VerifierError::BranchNotFound,
339            NgError::SerializationError => VerifierError::SerializationError,
340            // NgError::JsStorageReadError
341            // NgError::JsStorageWriteError(String)
342            // NgError::JsStorageKeyNotFound
343            // NgError::InvalidFileFormat
344            _ => VerifierError::OtherError(e.to_string()),
345        }
346    }
347}
348
349impl From<CommitLoadError> for VerifierError {
350    fn from(e: CommitLoadError) -> Self {
351        VerifierError::CommitLoadError(e)
352    }
353}
354
355impl From<ObjectParseError> for VerifierError {
356    fn from(e: ObjectParseError) -> Self {
357        VerifierError::ObjectParseError(e)
358    }
359}
360
361impl From<StorageError> for VerifierError {
362    fn from(e: StorageError) -> Self {
363        VerifierError::StorageError(e)
364    }
365}
366
367#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone)]
368#[repr(u16)]
369pub enum NetError {
370    DirectionAlreadySet = 1,
371    WsError,
372    IoError,
373    ConnectionError,
374    SerializationError,
375    ProtocolError,
376    AccessDenied,
377    InternalError,
378    PeerAlreadyConnected,
379    Closing,
380} //MAX 50 NetErrors
381
382impl Error for NetError {}
383
384impl fmt::Display for NetError {
385    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386        write!(f, "{:?}", self)
387    }
388}
389
390#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone)]
391#[repr(u16)]
392pub enum ProtocolError {
393    NoError = 0,
394
395    IoError,
396    WsError,
397    ActorError,
398    InvalidState,
399    InvalidSignature,
400    SerializationError,
401    AccessDenied,
402    InvitationRequired,
403    BrokerError,
404    NoLocalBrokerFound,
405    NotFound,
406    MissingBlocks,
407    ObjectParseError,
408    InvalidValue,
409    AlreadyExists,
410    RepoIdRequired,
411    InvalidPublisherAdvert,
412
413    ConnectionError,
414    Timeout,
415    Expired,
416
417    PeerAlreadyConnected,
418    UserNotConnected,
419    PeerNotConnected,
420    OtherError,
421    NetError,
422    StorageError,
423    ServerError,
424    Closing,
425    FsmNotReady,
426    MustBeEncrypted,
427    NoiseHandshakeFailed,
428    DecryptionError,
429    EncryptionError,
430    WhereIsTheMagic,
431
432    InvalidNonce,
433    InvalidMessage,
434} //MAX 949 ProtocolErrors
435
436impl From<NetError> for ProtocolError {
437    fn from(e: NetError) -> Self {
438        match e {
439            NetError::IoError => ProtocolError::IoError,
440            NetError::WsError => ProtocolError::WsError,
441            NetError::ConnectionError => ProtocolError::ConnectionError,
442            NetError::SerializationError => ProtocolError::SerializationError,
443            NetError::ProtocolError => ProtocolError::OtherError,
444            NetError::AccessDenied => ProtocolError::AccessDenied,
445            NetError::PeerAlreadyConnected => ProtocolError::PeerAlreadyConnected,
446            NetError::Closing => ProtocolError::Closing,
447            _ => ProtocolError::NetError,
448        }
449    }
450}
451
452impl From<StorageError> for ProtocolError {
453    fn from(e: StorageError) -> Self {
454        match e {
455            StorageError::NotFound => ProtocolError::NotFound,
456            StorageError::InvalidValue => ProtocolError::InvalidValue,
457            StorageError::BackendError => ProtocolError::StorageError,
458            StorageError::SerializationError => ProtocolError::SerializationError,
459            StorageError::AlreadyExists => ProtocolError::AlreadyExists,
460            _ => ProtocolError::StorageError,
461        }
462    }
463}
464
465impl From<ProtocolError> for NgError {
466    fn from(e: ProtocolError) -> Self {
467        NgError::ProtocolError(e)
468    }
469}
470
471impl From<ServerError> for NgError {
472    fn from(e: ServerError) -> Self {
473        NgError::ServerError(e)
474    }
475}
476
477impl ProtocolError {
478    pub fn is_err(&self) -> bool {
479        *self != ProtocolError::NoError
480    }
481}
482
483impl Error for ProtocolError {}
484
485impl fmt::Display for ProtocolError {
486    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487        write!(f, "{:?}", self)
488    }
489}
490
491impl From<NgError> for ProtocolError {
492    fn from(e: NgError) -> Self {
493        match e {
494            NgError::InvalidSignature => ProtocolError::InvalidSignature,
495            NgError::SerializationError => ProtocolError::SerializationError,
496            _ => ProtocolError::OtherError,
497        }
498    }
499}
500
501impl From<ObjectParseError> for ProtocolError {
502    fn from(_e: ObjectParseError) -> Self {
503        ProtocolError::ObjectParseError
504    }
505}
506
507impl From<serde_bare::error::Error> for ProtocolError {
508    fn from(_e: serde_bare::error::Error) -> Self {
509        ProtocolError::SerializationError
510    }
511}
512
513impl From<serde_bare::error::Error> for NetError {
514    fn from(_e: serde_bare::error::Error) -> Self {
515        NetError::SerializationError
516    }
517}