aboutsummaryrefslogtreecommitdiffstats
path: root/filamento/src/error.rs
blob: 9334793fc298cf3989699538b091d8f565d4dabf (plain) (blame)
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use std::{num::TryFromIntError, string::FromUtf8Error, sync::Arc};

use base64::DecodeError;
use image::ImageError;
use jid::JID;
use lampada::error::{ActorError, ReadError, WriteError};
use stanza::client::{Stanza, iq::Query};
use thiserror::Error;

pub use lampada::error::CommandError;
pub use lampada::error::ConnectionError;
use tokio::sync::mpsc::error::SendError;
use tokio::sync::oneshot::error::RecvError;

use crate::db::DbCommand;
use crate::files::FileStore;

// for the client logic impl
#[derive(Debug, Error, Clone)]
pub enum Error<Fs: FileStore> {
    #[error("core error: {0}")]
    Connection(#[from] ConnectionError),
    #[error("received unrecognized/unsupported content")]
    UnrecognizedContent,
    // TODO: include content
    // UnrecognizedContent(peanuts::element::Content),
    #[error("iq receive error: {0}")]
    Iq(#[from] IqProcessError),
    // TODO: change to Connecting(ConnectingError)
    #[error("connecting: {0}")]
    Connecting(#[from] ConnectionJobError),
    #[error("presence: {0}")]
    Presence(#[from] PresenceError),
    #[error("set status: {0}")]
    SetStatus(#[from] StatusError),
    // TODO: have different ones for get/update/set
    #[error("roster: {0}")]
    Roster(#[from] RosterError),
    #[error("stream error: {0}")]
    Stream(#[from] stanza::stream::Error),
    #[error("message send error: {0}")]
    MessageSend(#[from] MessageSendError),
    #[error("message receive error: {0}")]
    MessageRecv(#[from] MessageRecvError<Fs>),
    #[error("subscripbe error: {0}")]
    Subscribe(#[from] SubscribeError),
    #[error("publish error: {0}")]
    Publish(#[from] PEPError),
}

#[derive(Debug, Error, Clone)]
pub enum MessageSendError {
    #[error("could not add to message history: {0}")]
    MessageHistory(#[from] DatabaseError),
    #[error("could not mark chat as chatted: {0}")]
    MarkChatAsChatted(DatabaseError),
    #[error("could not get client user details: {0}")]
    GetUserDetails(DatabaseError),
    #[error("writing message to connection: {0}")]
    Write(#[from] WriteError),
}

#[derive(Debug, Error, Clone)]
pub enum MessageRecvError<Fs: FileStore> {
    #[error("could not add to message history: {0}")]
    MessageHistory(#[from] DatabaseError),
    #[error("missing from")]
    MissingFrom,
    #[error("could not update user nick: {0}")]
    NickUpdate(DatabaseError),
    #[error("could not update user avatar: {0}")]
    AvatarUpdate(#[from] AvatarUpdateError<Fs>),
}

#[derive(Debug, Error, Clone)]
pub enum AvatarUpdateError<Fs: FileStore> {
    #[error("could not save to disk: {0}")]
    FileStore(Fs::Err),
    #[error("could not fetch avatar data: {0}")]
    PEPError(#[from] CommandError<PEPError>),
    #[error("base64 decode: {0}")]
    Base64(#[from] DecodeError),
    #[error("pep node missing avatar data")]
    MissingData,
    #[error("database: {0}")]
    Database(#[from] DatabaseError),
}

#[derive(Debug, Error, Clone)]
pub enum StatusError {
    #[error("cache: {0}")]
    Cache(#[from] DatabaseError),
    #[error("stream write: {0}")]
    Write(#[from] WriteError),
}

#[derive(Debug, Clone, Error)]
pub enum ConnectionJobError {
    // #[error("connection failed: {0}")]
    // ConnectionFailed(#[from] luz::Error),
    #[error("failed roster retreival: {0}")]
    RosterRetreival(#[from] RosterError),
    #[error("failed to send available presence: {0}")]
    SendPresence(#[from] WriteError),
    #[error("cached status: {0}")]
    StatusCacheError(#[from] DatabaseError),
}

#[derive(Debug, Error, Clone)]
pub enum RosterError {
    #[error("cache: {0}")]
    Cache(#[from] DatabaseError),
    #[error("iq response: {0}")]
    IqResponse(#[from] IqRequestError),
    #[error("stream write: {0}")]
    Write(#[from] WriteError),
    // TODO: display for stanza, to show as xml, same for read error types.
    #[error("unexpected reply: {0:?}")]
    UnexpectedStanza(Stanza),
    #[error("stanza error: {0}")]
    StanzaError(#[from] stanza::client::error::Error),
    #[error("could not reply to roster push: {0}")]
    PushReply(WriteError),
    #[error("actor error: {0}")]
    Actor(ActorError),
}

impl From<CommandError<RosterError>> for RosterError {
    fn from(value: CommandError<RosterError>) -> Self {
        match value {
            CommandError::Actor(actor_error) => Self::Actor(actor_error),
            CommandError::Error(e) => e,
        }
    }
}

#[derive(Debug, Error, Clone)]
pub enum DiscoError {
    #[error("write error: {0}")]
    Write(#[from] WriteError),
    #[error("iq response: {0}")]
    IqResponse(#[from] IqRequestError),
    #[error("reply from incorrect entity: {0}")]
    IncorrectEntity(JID),
    #[error("unexpected reply: {0:?}")]
    UnexpectedStanza(Stanza),
    #[error("stanza error: {0}")]
    StanzaError(#[from] stanza::client::error::Error),
    #[error("disco result missing query item")]
    MissingQuery,
    #[error("disco error missing error")]
    MissingError,
    #[error("received mismatched query")]
    MismatchedQuery(Query),
}

#[derive(Debug, Error, Clone)]
pub enum IqRequestError {
    #[error("sending request: {0}")]
    Write(#[from] WriteError),
    #[error("receiving expected response: {0}")]
    Read(#[from] ReadError),
}

#[derive(Debug, Error, Clone)]
pub enum ResponseError {
    #[error("no matching id: {0}")]
    NoMatchingId(String),
}

#[derive(Debug, Error, Clone)]
pub enum DatabaseError {
    #[error("database error: {0}")]
    Database(Serializeable<Arc<rusqlite::Error>>),
    #[error("database command send: {0}")]
    Send(Arc<SendError<DbCommand>>),
    #[error("database result recv: {0}")]
    Recv(#[from] RecvError),
}

impl From<SendError<DbCommand>> for DatabaseError {
    fn from(e: SendError<DbCommand>) -> Self {
        Self::Send(Arc::new(e))
    }
}

pub enum Serializeable<T> {
    String(String),
    Unserialized(T),
}

impl<T: std::fmt::Display> std::fmt::Display for Serializeable<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            Serializeable::String(s) => s.fmt(f),
            Serializeable::Unserialized(t) => t.fmt(f),
        }
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for Serializeable<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            Serializeable::String(s) => s.fmt(f),
            Serializeable::Unserialized(t) => t.fmt(f),
        }
    }
}

impl<T: Clone> Clone for Serializeable<T> {
    fn clone(&self) -> Self {
        match self {
            Serializeable::String(s) => Self::String(s.clone()),
            Serializeable::Unserialized(t) => Self::Unserialized(t.clone()),
        }
    }
}

#[cfg(feature = "serde")]
struct StringVisitor;

#[cfg(feature = "serde")]
impl<'de> serde::de::Visitor<'de> for StringVisitor {
    type Value = String;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a string")
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(v)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for DatabaseError {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let string = deserializer.deserialize_string(StringVisitor)?;
        Ok(Self::Database(Serializeable::String(string)))
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for DatabaseError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match &self.0 {
            Serializeable::String(s) => serializer.serialize_str(s),
            Serializeable::Unserialized(u) => serializer.serialize_str(&u.to_string()),
        }
    }
}

impl From<rusqlite::Error> for DatabaseError {
    fn from(e: rusqlite::Error) -> Self {
        Self::Database(Serializeable::Unserialized(Arc::new(e)))
    }
}

impl From<rusqlite::Error> for DatabaseOpenError {
    fn from(e: rusqlite::Error) -> Self {
        Self::Error(Arc::new(e))
    }
}

#[derive(Debug, Error, Clone)]
// TODO: should probably have all iq query related errors here, including read, write, stanza error, etc.
pub enum IqError {
    #[error("writing response: {0}")]
    WriteError(#[from] WriteError),
    #[error("receiving response: `{0}`")]
    ReceivedResponse(#[from] ResponseError),
    #[error("incorrect addressee: {0}")]
    IncorrectAddressee(jid::JID),
}

#[derive(Debug, Error, Clone)]
pub enum IqProcessError {
    #[error("iq error")]
    Iq(#[from] IqError),
    #[error("roster push")]
    Roster(#[from] RosterError),
}

#[derive(Debug, Error, Clone)]
pub enum DatabaseOpenError {
    #[error("error: {0}")]
    Error(Arc<rusqlite::Error>),
    // #[error("migration: {0}")]
    // Migration(Arc<rusqlite::migrate::MigrateError>),
    #[error("io: {0}")]
    Io(Arc<tokio::io::Error>),
    #[error("invalid path")]
    InvalidPath,
    #[error("tokio oneshot recv error: {0}")]
    Recv(#[from] tokio::sync::oneshot::error::RecvError),
}

// impl From<sqlx::migrate::MigrateError> for DatabaseOpenError {
//     fn from(e: sqlx::migrate::MigrateError) -> Self {
//         Self::Migration(Arc::new(e))
//     }
// }

impl From<tokio::io::Error> for DatabaseOpenError {
    fn from(e: tokio::io::Error) -> Self {
        Self::Io(Arc::new(e))
    }
}

#[derive(Debug, Error, Clone)]
pub enum SubscribeError {
    #[error("write: {0}")]
    Write(#[from] WriteError),
    #[error("fetching client user details: {0}")]
    Database(#[from] DatabaseError),
}

#[derive(Debug, Error, Clone)]
pub enum PresenceError {
    #[error("unsupported")]
    Unsupported,
    #[error("missing from")]
    MissingFrom,
    #[error("stanza error: {0}")]
    StanzaError(#[from] stanza::client::error::Error),
}

#[derive(Debug, Error, Clone)]
pub enum PEPError {
    #[error("received mismatched query")]
    MismatchedQuery(Query),
    #[error("missing query")]
    MissingQuery,
    #[error("stanza errors: {0:?}")]
    StanzaErrors(Vec<stanza::client::error::Error>),
    #[error("reply from incorrect entity: {0}")]
    IncorrectEntity(JID),
    #[error("unexpected stanza: {0:?}")]
    UnexpectedStanza(Stanza),
    #[error("iq response: {0}")]
    IqResponse(#[from] IqRequestError),
    #[error("missing pep item")]
    MissingItem,
    #[error("incorrect item id: expected {0}, got {1}")]
    IncorrectItemID(String, String),
    #[error("unsupported pep item")]
    UnsupportedItem,
    // TODO: should the item be in the error?
}

#[derive(Debug, Error, Clone)]
pub enum NickError {
    #[error("publishing nick: {0}")]
    Publish(#[from] CommandError<PEPError>),
    #[error("updating database: {0}")]
    Database(#[from] DatabaseError),
    #[error("disconnected")]
    Disconnected,
}

#[derive(Debug, Error, Clone)]
pub enum CapsDecodeError {
    #[error("base64 decode: {0}")]
    Base64Decode(#[from] base64::DecodeError),
    #[error("utf8: {0}")]
    UTF8(#[from] FromUtf8Error),
    #[error("missing features")]
    MissingFeatures,
    #[error("missing identities")]
    MissingIdentities,
    #[error("missing identity category")]
    MissingIdentityCategory,
    #[error("missing identity type")]
    MissingIdentityType,
    #[error("missing identity language")]
    MissingIdentityLang,
    #[error("missing identity name")]
    MissingIdentityName,
}

#[derive(Debug, Error, Clone)]
pub enum CapsEncodeError {
    #[error("invalid data form in disco extensions")]
    InvalidDataForm,
}

#[derive(Debug, Error, Clone)]
pub enum HashNodeConversionError {
    #[error("no prefix")]
    NoPrefix,
    #[error("missing period")]
    MissingPeriod,
}

#[derive(Debug, Error, Clone)]
pub enum CapsNodeConversionError {
    #[error("missing hashtag")]
    MissingHashtag,
}

#[derive(Debug, Error, Clone)]
pub enum AvatarPublishError<Fs: FileStore> {
    #[error("disconnected")]
    Disconnected,
    #[error("image read: {0}")]
    Read(Arc<std::io::Error>),
    #[error("image: {0}")]
    Image(Arc<ImageError>),
    #[error("pep publish: {0}")]
    Publish(#[from] CommandError<PEPError>),
    #[error("bytes number conversion: {0}")]
    FromInt(#[from] TryFromIntError),
    #[error("could not save to disk")]
    FileStore(Fs::Err),
}

impl<Fs: FileStore> From<std::io::Error> for AvatarPublishError<Fs> {
    fn from(value: std::io::Error) -> Self {
        Self::Read(Arc::new(value))
    }
}

impl<Fs: FileStore> From<ImageError> for AvatarPublishError<Fs> {
    fn from(value: ImageError) -> Self {
        Self::Image(Arc::new(value))
    }
}