pooly 0.2.1

A protobuf to Postgres adapter + connection pooling middleware.
Documentation
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
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::string::FromUtf8Error;
use std::sync::PoisonError;

use actix_web::{HttpResponse, ResponseError};
use actix_web::http::StatusCode;
use bincode::ErrorKind;
use deadpool::managed::PoolError;
use deadpool_postgres::CreatePoolError;
use ring::error::Unspecified;
use serde::{Deserialize, Serialize};
use sled::CompareAndSwapError;
use sled::transaction::TransactionError;
use tokio_postgres::Error;

use crate::models::payloads::error_response::ErrorType;
use crate::models::payloads::ErrorResponse;

#[derive(Debug)]
pub enum QueryError {

    ConnectionConfigError(String, u16),
    CreatePoolError(String),
    ForbiddenConnectionId,
    UnknownDatabaseConnection(String),
    PoolError(String),
    PostgresError(String),
    RateLimitError(RateLimitError),
    StorageError,
    UnknownPostgresValueType(String),
    WrongNumParams(usize, usize),
    ReadUtfError(String)

}

#[derive(Debug)]
pub enum ConnectionError {

    CreatePoolError(CreatePoolError),
    ConnectionConfigError(ConnectionConfigError),
    PoolError(PoolError<Error>),
    RateLimitError(RateLimitError),
    StorageError(StorageError)

}

#[derive(Debug, Serialize, Deserialize)]
pub enum ConnectionConfigError {

    AlreadyExistsError,
    ConfigStorageError(StorageError),
    ConfigSerdeError(String),
    SecretsError(String)

}

#[derive(Debug, Serialize, Deserialize)]
pub enum SecretsError {
    AeadError(String),
    AlreadyInitialized,
    AlreadyUnsealed,
    FileReadError,
    LockError,
    MasterKeyShareError(String),
    Sealed,
    SerdeError(String),
    Unspecified
}

#[derive(Debug, Serialize, Deserialize)]
pub enum StorageError {

    AlreadyExistsError,
    CouldNotFindValueToUpdate,
    OptimisticLockingError {
        old_created_at: u128,
        new_created_at: u128,
        old_version: u32,
        new_version: u32
    },
    RetrievalError(String),
    SerdeError(String),
    SecretsError(SecretsError),
    SledError(String),
    TransactionError(String),
    Utf8Error

}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub enum WildcardPatternError {

    NoStars,
    TooManyStars,
    UnsupportedPattern

}

#[derive(Debug, Serialize, Deserialize)]
pub enum AuthError {

    InvalidClaims,
    InvalidHeader,
    InvalidToken,
    HmacError,
    NoneAlgorithmProvided,
    MissingAuthService,
    MissingAuthHeader,
    PemError,
    StorageError(StorageError),
    UnsupportedAlgorithm,
    UnknownKey,
    Forbidden,
    VerificationError(String),

}

#[derive(Debug, Serialize, Deserialize)]
pub enum InitializationError {

    AuthClearError,
    TooManyShares,
    SecretsError(SecretsError),
    StorageError(StorageError)

}

#[derive(Debug, Serialize, Deserialize)]
pub enum RateLimitError {

    TooManyRequests{threshold: u32, period_millis: u128},
    PoisonedLock

}

impl RateLimitError {

    fn get_code(&self) -> u16 {
        match self {
            RateLimitError::TooManyRequests { .. } => 429,
            RateLimitError::PoisonedLock => 500
        }
    }

    fn get_message(&self) -> String {
        match self {
            RateLimitError::TooManyRequests { .. } => "Too many requests".to_string(),
            RateLimitError::PoisonedLock => "Poisoned lock error.".to_string()
        }
    }

}

impl fmt::Display for WildcardPatternError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self)
    }
}

impl ConnectionConfigError {

    fn get_message(&self) -> String {
        match self {
            ConnectionConfigError::AlreadyExistsError =>
                "Config for this connection id already exists".to_string(),
            ConnectionConfigError::ConfigStorageError(err) =>
                format!("{:?}", err),
            ConnectionConfigError::ConfigSerdeError(message) => message.clone(),
            ConnectionConfigError::SecretsError(message) => message.clone()
        }
    }

}

impl QueryError {

    pub fn to_error_response(self, correlation_id: String) -> ErrorResponse {
        let error_type = self.get_error_type();

        ErrorResponse {
            message: self.get_message(),
            error_type: error_type.into(),
            correlation_id
        }
    }

    pub fn get_code(&self) -> u16 {
        match self {
            QueryError::ConnectionConfigError(_, code) => *code,
            QueryError::CreatePoolError(_) => 500,
            QueryError::ForbiddenConnectionId => 403,
            QueryError::UnknownDatabaseConnection(_) => 400,
            QueryError::PoolError(_) => 500,
            QueryError::PostgresError(_) => 500,
            QueryError::WrongNumParams(_, _) => 400,
            QueryError::UnknownPostgresValueType(_) => 500,
            QueryError::StorageError => 500,
            QueryError::ReadUtfError(_) => 500,
            QueryError::RateLimitError(err) => err.get_code()
        }
    }

    fn get_error_type(&self) -> ErrorType {
        match self {
            QueryError::UnknownDatabaseConnection(_) => ErrorType::MissingConnection,
            QueryError::PoolError(_) => ErrorType::PoolError,
            QueryError::PostgresError(_) => ErrorType::PostgresError,
            QueryError::WrongNumParams(_, _) => ErrorType::WrongNumOfParams,
            QueryError::UnknownPostgresValueType(_) => ErrorType::UnknownPgValueType,
            QueryError::CreatePoolError(_) => ErrorType::CreatePoolError,
            QueryError::ConnectionConfigError(_, _) => ErrorType::ConnectionConfigError,
            QueryError::ForbiddenConnectionId => ErrorType::ForbiddenConnectionId,
            QueryError::StorageError => ErrorType::StorageError,
            QueryError::ReadUtfError(_) => ErrorType::PostgresError,
            QueryError::RateLimitError(_) => ErrorType::LimitExceeded,
        }
    }

    fn get_message(self) -> String {
        match self {
            QueryError::UnknownDatabaseConnection(missing_name) =>
                format!("Connection not found: {}", missing_name),
            QueryError::PoolError(message) => message,
            QueryError::PostgresError(message) => message,
            QueryError::WrongNumParams(actual, expected) =>
                format!("Expected: {} argument(s), got: {}", expected, actual),
            QueryError::UnknownPostgresValueType(pg_type) =>
                format!("Unknown pg type: {}", pg_type),
            QueryError::CreatePoolError(message) => message,
            QueryError::ConnectionConfigError(message, _) => message,
            QueryError::ForbiddenConnectionId =>
                "The connection of the requested id is forbidden.".into(),
            QueryError::StorageError =>
                "Underlying storage error.".into(),
            QueryError::ReadUtfError(message) => message,
            QueryError::RateLimitError(err) => err.get_message()
        }
    }

}

impl ResponseError for AuthError {
    fn status_code(&self) -> StatusCode {
        match self {
            AuthError::PemError
            | AuthError::MissingAuthService
            | AuthError::StorageError(_) => StatusCode::INTERNAL_SERVER_ERROR,
            AuthError::Forbidden => StatusCode::FORBIDDEN,
            _ => StatusCode::UNAUTHORIZED
        }
    }

    fn error_response(&self) -> HttpResponse {
        HttpResponse::build(self.status_code())
            .json(self)
    }
}

impl fmt::Display for AuthError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&StatusCode::UNAUTHORIZED, f)
    }
}

impl From<PoolError<Error>> for QueryError {
    fn from(err: PoolError<Error>) -> Self {
        QueryError::PoolError(err.to_string())
    }
}

impl From<Error> for QueryError {
    fn from(err: Error) -> Self {
        QueryError::PostgresError(err.to_string())
    }
}

impl From<ConnectionConfigError> for QueryError {
    fn from(err: ConnectionConfigError) -> Self {
        let message = err.get_message();
        let code = match err {
            ConnectionConfigError::SecretsError(_) => 401,
            ConnectionConfigError::AlreadyExistsError => 409,
            _ => 500
        };
        QueryError::ConnectionConfigError(message, code)
    }
}

impl From<ConnectionError> for QueryError {
    fn from(err: ConnectionError) -> Self {
        match err {
            ConnectionError::CreatePoolError(err) =>
                QueryError::CreatePoolError(err.to_string()),
            ConnectionError::PoolError(err) => err.into(),
            ConnectionError::ConnectionConfigError(err) => err.into(),
            ConnectionError::StorageError(err) => err.into(),
            ConnectionError::RateLimitError(err) => err.into()
        }
    }
}

impl From<Box<ErrorKind>> for ConnectionConfigError {
    fn from(err: Box<ErrorKind>) -> Self {
        ConnectionConfigError::ConfigSerdeError(err.to_string())
    }
}

impl From<Unspecified> for SecretsError {
    fn from(_: Unspecified) -> Self {
        SecretsError::Unspecified
    }
}

impl From<chacha20poly1305::aead::Error> for SecretsError {
    fn from(err: chacha20poly1305::aead::Error) -> Self {
        SecretsError::AeadError(format!("{:?}", err))
    }
}

impl From<SecretsError> for ConnectionConfigError {
    fn from(err: SecretsError) -> Self {
        ConnectionConfigError::SecretsError(format!("Secrets error: {:?}", err))
    }
}

impl<T> From<PoisonError<T>> for SecretsError {
    fn from(_: PoisonError<T>) -> Self {
        SecretsError::LockError
    }
}

impl From<Box<bincode::ErrorKind>> for SecretsError {
    fn from(err: Box<ErrorKind>) -> Self {
        SecretsError::SerdeError(format!("{:?}", err))
    }
}

impl From<CompareAndSwapError> for StorageError {
    fn from(_: CompareAndSwapError) -> Self {
        StorageError::AlreadyExistsError
    }
}

impl<E: Debug> From<TransactionError<E>> for StorageError {
    fn from(err: TransactionError<E>) -> Self {
        StorageError::TransactionError(format!("{:?}", err))
    }
}

impl From<CompareAndSwapError> for ConnectionConfigError {
    fn from(_: CompareAndSwapError) -> Self {
        ConnectionConfigError::AlreadyExistsError
    }
}

impl From<sled::Error> for StorageError {
    fn from(err: sled::Error) -> Self {
        StorageError::SledError(err.to_string())
    }
}

impl From<Box<bincode::ErrorKind>> for StorageError {
    fn from(err: Box<ErrorKind>) -> Self {
        StorageError::SerdeError(format!("{:?}", err))
    }
}

impl From<SecretsError> for StorageError {
    fn from(err: SecretsError) -> Self {
        StorageError::SecretsError(err)
    }
}

impl From<FromUtf8Error> for StorageError {
    fn from(_: FromUtf8Error) -> Self {
        StorageError::Utf8Error
    }
}

impl From<StorageError> for ConnectionConfigError {
    fn from(err: StorageError) -> Self {
        ConnectionConfigError::ConfigStorageError(err)
    }
}

impl From<StorageError> for QueryError {
    fn from(_: StorageError) -> Self {
        QueryError::StorageError
    }
}

impl From<StorageError> for AuthError {
    fn from(err: StorageError) -> Self {
        AuthError::StorageError(err)
    }
}

impl From<FromUtf8Error> for QueryError {
    fn from(err: FromUtf8Error) -> Self {
        QueryError::ReadUtfError(format!("{:?}", err))
    }
}

impl From<SecretsError> for InitializationError {
    fn from(err: SecretsError) -> Self {
        InitializationError::SecretsError(err)
    }
}

impl From<StorageError> for InitializationError {
    fn from(err: StorageError) -> Self {
        InitializationError::StorageError(err)
    }
}

impl From<jwt::Error> for AuthError {
    fn from(err: jwt::Error) -> Self {
        AuthError::VerificationError(format!("{:?}", err))
    }
}

impl From<RateLimitError> for QueryError {
    fn from(err: RateLimitError) -> Self {
        QueryError::RateLimitError(err)
    }
}

impl From<RateLimitError> for ConnectionError {
    fn from(err: RateLimitError) -> Self {
        ConnectionError::RateLimitError(err)
    }
}