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
// Copyright 2021 rust-ipfs-api Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//

use crate::{request::ApiRequest, Backend, BoxStream};
use async_trait::async_trait;
use bytes::Bytes;
use common_multipart_rfc7578::client::multipart;
use serde::{Serialize, Serializer};
use std::time::Duration;

/// Options valid on any IPFS Api request
///
/// Can be set on a client using [BackendWithGlobalOptions]
///
#[cfg_attr(feature = "with-builder", derive(TypedBuilder))]
#[derive(Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct GlobalOptions {
    #[cfg_attr(feature = "with-builder", builder(default, setter(strip_option)))]
    pub offline: Option<bool>,

    #[cfg_attr(feature = "with-builder", builder(default, setter(strip_option)))]
    #[serde(serialize_with = "duration_as_secs_ns")]
    pub timeout: Option<Duration>,
}

fn duration_as_secs_ns<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match duration {
        Some(duration) => serializer.serialize_str(&format!(
            "{}s{}ns",
            duration.as_secs(),
            duration.subsec_nanos(),
        )),
        None => serializer.serialize_none(),
    }
}

/// A wrapper for [Backend] / [IpfsApi](crate::api::IpfsApi) that adds global options
pub struct BackendWithGlobalOptions<Back: Backend> {
    backend: Back,
    options: GlobalOptions,
}

#[derive(Serialize)]
struct OptCombiner<'a, Req>
where
    Req: ApiRequest,
{
    #[serde(flatten)]
    global: &'a GlobalOptions,

    #[serde(flatten)]
    request: Req,
}

impl<Back: Backend> BackendWithGlobalOptions<Back> {
    /// Return the wrapped [Backend]
    pub fn into_inner(self) -> Back {
        self.backend
    }

    /// Construct
    ///
    /// While possible, it is not recommended to wrap a [Backend] twice.
    pub fn new(backend: Back, options: GlobalOptions) -> Self {
        Self { backend, options }
    }

    fn combine<'a, Req>(&'a self, req: Req) -> OptCombiner<'a, Req>
    where
        Req: ApiRequest,
    {
        OptCombiner {
            global: &self.options,
            request: req,
        }
    }
}

impl<'a, Req> ApiRequest for OptCombiner<'a, Req>
where
    Req: ApiRequest,
{
    const PATH: &'static str = <Req as ApiRequest>::PATH;

    const METHOD: http::Method = http::Method::POST;
}

#[cfg(feature = "with-send-sync")]
#[async_trait]
impl<Back: Backend + Send + Sync> Backend for BackendWithGlobalOptions<Back> {
    type HttpRequest = Back::HttpRequest;

    type HttpResponse = Back::HttpResponse;

    type Error = Back::Error;

    fn build_base_request<Req>(
        &self,
        req: Req,
        form: Option<multipart::Form<'static>>,
    ) -> Result<Self::HttpRequest, Self::Error>
    where
        Req: ApiRequest,
    {
        self.backend.build_base_request(self.combine(req), form)
    }

    fn get_header(
        res: &Self::HttpResponse,
        key: http::header::HeaderName,
    ) -> Option<&http::HeaderValue> {
        Back::get_header(res, key)
    }

    async fn request_raw<Req>(
        &self,
        req: Req,
        form: Option<multipart::Form<'static>>,
    ) -> Result<(http::StatusCode, bytes::Bytes), Self::Error>
    where
        Req: ApiRequest,
    {
        self.backend.request_raw(self.combine(req), form).await
    }

    fn response_to_byte_stream(res: Self::HttpResponse) -> BoxStream<Bytes, Self::Error> {
        Back::response_to_byte_stream(res)
    }

    fn request_stream<Res, F>(
        &self,
        req: Self::HttpRequest,
        process: F,
    ) -> BoxStream<Res, Self::Error>
    where
        F: 'static + Send + Fn(Self::HttpResponse) -> BoxStream<Res, Self::Error>,
    {
        self.backend.request_stream(req, process)
    }
}

#[cfg(not(feature = "with-send-sync"))]
#[async_trait(?Send)]
impl<Back: Backend> Backend for BackendWithGlobalOptions<Back> {
    type HttpRequest = Back::HttpRequest;

    type HttpResponse = Back::HttpResponse;

    type Error = Back::Error;

    fn build_base_request<Req>(
        &self,
        req: Req,
        form: Option<multipart::Form<'static>>,
    ) -> Result<Self::HttpRequest, Self::Error>
    where
        Req: ApiRequest,
    {
        self.backend.build_base_request(self.combine(req), form)
    }

    fn get_header(
        res: &Self::HttpResponse,
        key: http::header::HeaderName,
    ) -> Option<&http::HeaderValue> {
        Back::get_header(res, key)
    }

    async fn request_raw<Req>(
        &self,
        req: Req,
        form: Option<multipart::Form<'static>>,
    ) -> Result<(http::StatusCode, bytes::Bytes), Self::Error>
    where
        Req: ApiRequest,
    {
        self.backend.request_raw(self.combine(req), form).await
    }

    fn response_to_byte_stream(res: Self::HttpResponse) -> BoxStream<Bytes, Self::Error> {
        Back::response_to_byte_stream(res)
    }

    fn request_stream<Res, F>(
        &self,
        req: Self::HttpRequest,
        process: F,
    ) -> BoxStream<Res, Self::Error>
    where
        F: 'static + Send + Fn(Self::HttpResponse) -> BoxStream<Res, Self::Error>,
    {
        self.backend.request_stream(req, process)
    }
}