fortnox 0.1.3

A library for integrating with Fortnox.
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
mod article;
pub use article::Article;
mod customer;
pub use customer::Customer;
mod currency;
pub use currency::Currency;
mod order;
pub use order::{Order, Row as OrderRow};
mod add_customer;
mod add_order;
mod api_error_code;
mod cancel_order;
mod edit_order;
mod get_article;
mod get_customer;
mod get_order;
pub use api_error_code::ApiErrorCode;
mod error;
pub use error::Error;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::time::Duration;
use tokio::time::sleep;

const BASE_URL: &str = "https://api.fortnox.se/3";
const INITIAL_DELAY_MS: f64 = 100.0;
const RETRIES: u8 = 5;
const BACKOFF: f64 = 2.0;

pub struct Gateway {
    client: reqwest::Client,
}

impl Gateway {
    pub async fn new(
        _client_id: String,
        token: String,
        secret: String,
        timeout: Option<Duration>,
    ) -> Result<Gateway, Error> {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            "Content-Type",
            reqwest::header::HeaderValue::from_static("application/json"),
        );
        headers.insert(
            "Accept",
            reqwest::header::HeaderValue::from_static("application/json"),
        );

        let access_token_header = match reqwest::header::HeaderValue::from_str(&token) {
            Ok(header) => header,
            Err(err) => {
                return Err(Error::Unspecified(format!(
                    "Could not create auth header ({}).",
                    err.to_string()
                )))
            }
        };
        headers.insert("Access-Token", access_token_header);

        let client_secret_header = match reqwest::header::HeaderValue::from_str(&secret) {
            Ok(header) => header,
            Err(err) => {
                return Err(Error::Unspecified(format!(
                    "Could not create auth header ({}).",
                    err.to_string()
                )))
            }
        };
        headers.insert("Client-Secret", client_secret_header);

        let timeout = match timeout {
            Some(t) => t,
            None => Duration::new(60, 0),
        };

        let client = match reqwest::ClientBuilder::new()
            .default_headers(headers)
            .https_only(true)
            .timeout(timeout)
            .build()
        {
            Ok(r) => r,
            Err(err) => {
                return Err(Error::Unspecified(format!(
                    "Could not create reqwest client ({}).",
                    err.to_string()
                )))
            }
        };

        let c = Gateway { client };
        Ok(c)
    }

    async fn post<'a, T: DeserializeOwned>(
        &self,
        url: &str,
        body: &impl Serialize,
    ) -> Result<T, Error> {
        let mut delay = INITIAL_DELAY_MS;
        for _ in 0..RETRIES {
            let res = match self.post_without_retry(url, body).await {
                Ok(res) => res,
                Err(err) => {
                    delay = self.randomized_exponential_backoff(delay).await;

                    match err {
                        Error::Throttling => {
                            continue;
                        }
                        _ => return Err(err),
                    };
                }
            };

            return Ok(res);
        }

        Err(Error::Throttling)
    }

    async fn post_without_retry<'a, T: DeserializeOwned>(
        &self,
        url: &str,
        body: &impl Serialize,
    ) -> Result<T, Error> {
        let res = match self.client.post(url).json(body).send().await {
            Ok(r) => r,
            Err(err) => {
                return Err(Error::NetworkError(format!(
                    "Could not send request ({}).",
                    err.to_string()
                )))
            }
        };

        let status = res.status().as_u16();
        let text = res
            .text()
            .await
            .unwrap_or_else(|_| String::from("Could not retrieve body text."));

        if status < 200 || status > 299 {
            if status == 429 {
                return Err(Error::Throttling);
            }

            #[derive(Deserialize, Debug, Clone, PartialEq)]
            #[serde(rename_all = "PascalCase")]
            struct ErrorInformation {
                pub error_information: ApiError,
            }

            #[derive(Deserialize, Debug, Clone, PartialEq)]
            #[serde(rename_all = "PascalCase")]
            struct ApiError {
                pub error: u32,
                pub message: String,
                pub code: ApiErrorCode,
            }

            let api_error: ErrorInformation =
                serde_json::from_str(&text).unwrap_or_else(|_| ErrorInformation {
                    error_information: ApiError {
                        error: 0,
                        message: format!("Unknown error ({}: {})", status, text),
                        code: ApiErrorCode::Unknown,
                    },
                });
            return Err(Error::ApiError(
                api_error.error_information.code,
                api_error.error_information.message,
            ));
        }

        let body: T = match serde_json::from_str(&text) {
            Ok(r) => r,
            Err(err) => {
                return Err(Error::SerializationError(format!(
                    "Could not deserialize response from \"{}\" ({}).",
                    text,
                    err.to_string()
                )))
            }
        };
        Ok(body)
    }

    async fn get<'a, T: DeserializeOwned>(&self, url: &str) -> Result<T, Error> {
        let mut delay = INITIAL_DELAY_MS;
        for _ in 0..RETRIES {
            let res = match self.get_without_retry(url).await {
                Ok(res) => res,
                Err(err) => {
                    delay = self.randomized_exponential_backoff(delay).await;

                    match err {
                        Error::Throttling => {
                            continue;
                        }
                        _ => return Err(err),
                    };
                }
            };

            return Ok(res);
        }

        Err(Error::Throttling)
    }

    async fn get_without_retry<'a, T: DeserializeOwned>(&self, url: &str) -> Result<T, Error> {
        let res = match self.client.get(url).send().await {
            Ok(r) => r,
            Err(err) => {
                return Err(Error::NetworkError(format!(
                    "Could not send request ({}).",
                    err.to_string()
                )))
            }
        };

        let status = res.status().as_u16();
        let text = res
            .text()
            .await
            .unwrap_or_else(|_| String::from("Could not retrieve body text."));

        if status < 200 || status > 299 {
            if status == 429 {
                return Err(Error::Throttling);
            }

            #[derive(Deserialize, Debug, Clone, PartialEq)]
            #[serde(rename_all = "PascalCase")]
            struct ErrorInformation {
                pub error_information: ApiError,
            }

            #[derive(Deserialize, Debug, Clone, PartialEq)]
            #[serde(rename_all = "PascalCase")]
            struct ApiError {
                pub error: u32,
                pub message: String,
                pub code: ApiErrorCode,
            }

            let api_error: ErrorInformation =
                serde_json::from_str(&text).unwrap_or_else(|_| ErrorInformation {
                    error_information: ApiError {
                        error: 0,
                        message: format!("Unknown error ({}: {})", status, text),
                        code: ApiErrorCode::Unknown,
                    },
                });
            return Err(Error::ApiError(
                api_error.error_information.code,
                api_error.error_information.message,
            ));
        }

        let body: T = match serde_json::from_str(&text) {
            Ok(r) => r,
            Err(err) => {
                return Err(Error::SerializationError(format!(
                    "Could not deserialize response from \"{}\" ({}).",
                    text,
                    err.to_string()
                )))
            }
        };
        Ok(body)
    }

    async fn put<'a, T: DeserializeOwned>(
        &self,
        url: &str,
        body: &impl Serialize,
    ) -> Result<T, Error> {
        let mut delay = INITIAL_DELAY_MS;
        for _ in 0..RETRIES {
            let res = match self.put_without_retry(url, body).await {
                Ok(res) => res,
                Err(err) => {
                    delay = self.randomized_exponential_backoff(delay).await;

                    match err {
                        Error::Throttling => {
                            continue;
                        }
                        _ => return Err(err),
                    };
                }
            };

            return Ok(res);
        }

        Err(Error::Throttling)
    }

    async fn put_without_retry<'a, T: DeserializeOwned>(
        &self,
        url: &str,
        body: &impl Serialize,
    ) -> Result<T, Error> {
        let res = match self.client.put(url).json(body).send().await {
            Ok(r) => r,
            Err(err) => {
                return Err(Error::NetworkError(format!(
                    "Could not send request ({}).",
                    err.to_string()
                )))
            }
        };

        let status = res.status().as_u16();
        let text = res
            .text()
            .await
            .unwrap_or_else(|_| String::from("Could not retrieve body text."));

        if status < 200 || status > 299 {
            if status == 429 {
                return Err(Error::Throttling);
            }

            #[derive(Deserialize, Debug, Clone, PartialEq)]
            #[serde(rename_all = "PascalCase")]
            struct ErrorInformation {
                pub error_information: ApiError,
            }

            #[derive(Deserialize, Debug, Clone, PartialEq)]
            #[serde(rename_all = "PascalCase")]
            struct ApiError {
                pub error: u32,
                pub message: String,
                pub code: ApiErrorCode,
            }

            let api_error: ErrorInformation =
                serde_json::from_str(&text).unwrap_or_else(|_| ErrorInformation {
                    error_information: ApiError {
                        error: 0,
                        message: format!("Unknown error ({}: {})", status, text),
                        code: ApiErrorCode::Unknown,
                    },
                });
            return Err(Error::ApiError(
                api_error.error_information.code,
                api_error.error_information.message,
            ));
        }

        let body: T = match serde_json::from_str(&text) {
            Ok(r) => r,
            Err(err) => {
                return Err(Error::SerializationError(format!(
                    "Could not deserialize response from \"{}\" ({}).",
                    text,
                    err.to_string()
                )))
            }
        };
        Ok(body)
    }

    // async fn delete<'a, T: DeserializeOwned>(&self, url: &str) -> Result<T, Error> {
    //     let mut delay = INITIAL_DELAY_MS;
    //     for _ in 0..RETRIES {
    //         let res = match self.delete_without_retry(url).await {
    //             Ok(res) => res,
    //             Err(err) => {
    //                 delay = self.randomized_exponential_backoff(delay).await;

    //                 match err {
    //                     Error::Throttling => {
    //                         continue;
    //                     }
    //                     _ => return Err(err),
    //                 };
    //             }
    //         };

    //         return Ok(res);
    //     }

    //     Err(Error::Throttling)
    // }

    // async fn delete_without_retry<'a, T: DeserializeOwned>(&self, url: &str) -> Result<T, Error> {
    //     let res = match self.client.delete(url).send().await {
    //         Ok(r) => r,
    //         Err(err) => {
    //             return Err(Error::NetworkError(format!(
    //                 "Could not send request ({}).",
    //                 err.to_string()
    //             )))
    //         }
    //     };

    //     let status = res.status().as_u16();
    //     let text = res
    //         .text()
    //         .await
    //         .unwrap_or_else(|_| String::from("Could not retrieve body text."));

    //     if status < 200 || status > 299 {
    //         if status == 429 {
    //             return Err(Error::Throttling);
    //         }

    //         #[derive(Deserialize, Debug, Clone, PartialEq)]
    //         #[serde(rename_all = "PascalCase")]
    //         struct ErrorInformation {
    //             pub error_information: ApiError,
    //         }

    //         #[derive(Deserialize, Debug, Clone, PartialEq)]
    //         #[serde(rename_all = "PascalCase")]
    //         struct ApiError {
    //             pub error: u32,
    //             pub message: String,
    //             pub code: ApiErrorCode,
    //         }

    //         let api_error: ErrorInformation =
    //             serde_json::from_str(&text).unwrap_or_else(|_| ErrorInformation {
    //                 error_information: ApiError {
    //                     error: 0,
    //                     message: format!("Unknown error ({}: {})", status, text),
    //                     code: ApiErrorCode::Unknown,
    //                 },
    //             });
    //         return Err(Error::ApiError(
    //             api_error.error_information.code,
    //             api_error.error_information.message,
    //         ));
    //     }

    //     let body: T = match serde_json::from_str(&text) {
    //         Ok(r) => r,
    //         Err(err) => {
    //             return Err(Error::SerializationError(format!(
    //                 "Could not deserialize response from \"{}\" ({}).",
    //                 text,
    //                 err.to_string()
    //             )))
    //         }
    //     };
    //     Ok(body)
    // }

    // Randomized exponential backoff policy (cf.
    // https://cloud.google.com/appengine/articles/scalability#backoff ).
    async fn randomized_exponential_backoff(&self, mut delay_ms: f64) -> f64 {
        //let mut rng = rand::thread_rng();

        // Random component to avoid thundering herd problem (values taken from
        // https://github.com/GoogleCloudPlatform/appengine-gcs-client/blob/master/java/src/main/
        // java/com/google/appengine/tools/cloudstorage/RetryHelper.java ).
        //delay_ms = (rng.gen::<f64>() / 2.0 + 0.75) * delay_ms;

        sleep(Duration::from_millis(delay_ms as u64)).await;

        delay_ms *= BACKOFF;
        delay_ms
    }
}