encore-dev 2.0.0-beta.17

Rust SDK for Encore applications
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
472
//! Sending the calls of a generated OpenAPI or GraphQL client, through
//! [`services`](crate::services). For the generated code: its API may change
//! with the generator's.

use http::header::{HeaderName, HeaderValue, CONTENT_TYPE};
use http::{HeaderMap, Method};
use serde::de::DeserializeOwned;
use serde::Serialize;

use super::{base_url_of, invalid_header, CallError, Settings};
use crate::services::{self, reqwest};
use crate::ErrCode;

/// One call, to a path of a service's.
#[must_use = "a call is sent only by `send`"]
pub struct Call {
    method: Method,
    url: String,
    builder: services::RequestBuilder,
    headers: HeaderMap,
    error: Option<CallError>,
}

impl Call {
    /// A call for `path`, already encoded, made with `call`'s settings over
    /// `client`'s.
    pub fn new(
        service: &services::Client,
        client: &Settings,
        call: &Settings,
        method: Method,
        path: &str,
    ) -> Call {
        let settings = call.under(client);
        let (url, error) = match base_url_of(service, &settings) {
            Ok(base) => (format!("{base}{path}"), None),
            Err(err) => (path.to_string(), Some(err)),
        };
        let mut builder = services::request_to(method.clone(), url.clone());
        if let Some(timeout) = settings.limit() {
            builder = builder.timeout(timeout);
        }
        let mut call = Call {
            method,
            url,
            builder,
            headers: HeaderMap::new(),
            error,
        };
        for (name, value) in &settings.headers {
            call = call.header(name, value);
        }
        call
    }

    /// Sets a header, in place of one of the same name.
    pub fn header(mut self, name: &str, value: &str) -> Self {
        let name_value = HeaderName::try_from(name)
            .map_err(|e| invalid_header(name, e))
            .and_then(|n| {
                Ok((
                    n,
                    HeaderValue::try_from(value).map_err(|e| invalid_header(name, e))?,
                ))
            });
        match name_value {
            Ok((name, value)) => {
                self.headers.insert(name, value);
            }
            Err(err) => {
                self.error.get_or_insert(err);
            }
        }
        self
    }

    /// Adds a query parameter.
    pub fn query(mut self, name: &str, value: &str) -> Self {
        self.builder = self.builder.query(&[(name, value)]);
        self
    }

    /// Sends `body` as the body, as JSON.
    pub fn json<T: Serialize + ?Sized>(mut self, body: &T) -> Self {
        self.builder = self.builder.json(body);
        self
    }

    /// Sends `body` as the body, as `content_type`.
    pub fn body(self, content_type: &str, body: Vec<u8>) -> Self {
        let mut call = self.header(CONTENT_TYPE.as_str(), content_type);
        call.builder = call.builder.body(body);
        call
    }

    /// Sends the call: the answer when it is a success, its error otherwise.
    pub async fn send(self) -> Result<reqwest::Response, CallError> {
        if let Some(err) = self.error {
            return Err(err);
        }
        let response = self
            .builder
            .headers(self.headers)
            .send()
            .await
            .map_err(|err| no_answer(&self.method, &self.url, err))?;
        if !response.status().is_success() {
            return Err(error_answer(response).await);
        }
        Ok(response)
    }

    /// Sends the call, and decodes its answer from JSON.
    pub async fn json_answer<T: DeserializeOwned>(self) -> Result<T, CallError> {
        let response = self.send().await?;
        let body = response.bytes().await.map_err(read_failed)?;
        decode(&body)
    }

    /// Sends the call, and reads its answer's body.
    pub async fn bytes_answer(self) -> Result<Vec<u8>, CallError> {
        let response = self.send().await?;
        Ok(response.bytes().await.map_err(read_failed)?.to_vec())
    }

    /// Sends the call, and drops its answer.
    pub async fn empty_answer(self) -> Result<(), CallError> {
        self.send().await.map(drop)
    }
}

/// A GraphQL operation's variables: those set, as JSON.
#[derive(Default)]
#[must_use]
pub struct Variables {
    values: serde_json::Map<String, serde_json::Value>,
    error: Option<CallError>,
}

impl Variables {
    /// No variables.
    pub fn new() -> Self {
        Variables::default()
    }

    /// Sets variable `name` to `value`.
    pub fn set<T: Serialize + ?Sized>(mut self, name: &str, value: &T) -> Self {
        match serde_json::to_value(value) {
            Ok(value) => {
                self.values.insert(name.to_string(), value);
            }
            Err(err) => {
                self.error.get_or_insert(CallError::failed(
                    ErrCode::InvalidArgument,
                    format!("encoding variable {name:?}: {err}"),
                ));
            }
        }
        self
    }

    /// Sets variable `name` to `value`, when there is one: a variable left
    /// out is the argument's default, which a `null` would not be.
    pub fn set_some<T: Serialize>(self, name: &str, value: Option<&T>) -> Self {
        match value {
            Some(value) => self.set(name, value),
            None => self,
        }
    }
}

/// Sends GraphQL `document` with `variables` to the service's `path`, and
/// decodes the answer's `field` of its data.
pub async fn graphql<T: DeserializeOwned>(
    service: &services::Client,
    client: &Settings,
    call: &Settings,
    path: &str,
    document: &str,
    variables: Variables,
    field: &str,
) -> Result<T, CallError> {
    if let Some(err) = variables.error {
        return Err(err);
    }
    let body = serde_json::json!({ "query": document, "variables": variables.values });
    let call = Call::new(service, client, call, Method::POST, path).json(&body);
    if let Some(err) = call.error {
        return Err(err);
    }
    let response = call
        .builder
        .headers(call.headers)
        .send()
        .await
        .map_err(|err| no_answer(&call.method, &call.url, err))?;
    let status = response.status();
    let body = response.bytes().await.map_err(read_failed)?;
    let mut envelope: Option<serde_json::Map<String, serde_json::Value>> =
        serde_json::from_slice(&body).ok();
    let errors = envelope.as_mut().and_then(|e| e.remove("errors"));
    if let Some(errors) =
        errors.filter(|e| !e.is_null() && e.as_array().is_none_or(|e| !e.is_empty()))
    {
        return Err(graphql_error(errors, status.as_u16()));
    }
    if !status.is_success() {
        return Err(error_body(status, &body));
    }
    let data = envelope
        .as_mut()
        .and_then(|e| e.remove("data"))
        .filter(|d| !d.is_null())
        .ok_or_else(|| {
            CallError::failed(
                ErrCode::Unknown,
                "graphql: response has neither data nor errors",
            )
        })?;
    let value = match data {
        serde_json::Value::Object(mut data) => data.remove(field),
        _ => None,
    }
    .unwrap_or(serde_json::Value::Null);
    serde_json::from_value(value).map_err(undecodable)
}

/// Percent-encodes a path segment: everything but RFC 3986's unreserved
/// characters.
pub fn encode_path(segment: &str) -> String {
    let mut out = String::with_capacity(segment.len());
    for b in segment.bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
            out.push(char::from(b));
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    out
}

/// A parameter of a structured type, as its JSON text.
pub fn json_text<T: Serialize + ?Sized>(value: &T) -> String {
    // Only a non-finite float has no JSON form.
    serde_json::to_string(value).unwrap_or_default()
}

fn decode<T: DeserializeOwned>(body: &[u8]) -> Result<T, CallError> {
    // An empty answer is JSON's `null`, for a result that is `Option`.
    let body = if body.is_empty() { b"null" } else { body };
    serde_json::from_slice(body).map_err(undecodable)
}

fn undecodable(err: serde_json::Error) -> CallError {
    CallError::failed(
        ErrCode::Internal,
        format!("failed to decode response: {err}"),
    )
    .caused_by(err)
}

/// The error reading an answer's body failed with: the call's timeout covers
/// the body too.
fn read_failed(err: reqwest::Error) -> CallError {
    // reqwest's error names the URL in full, query and all.
    let err = err.without_url();
    let code = if err.is_timeout() {
        ErrCode::DeadlineExceeded
    } else {
        ErrCode::Unavailable
    };
    CallError::failed(code, format!("failed to read response: {err}")).caused_by(err)
}

/// The error a call to `url` that got no answer is.
fn no_answer(method: &Method, url: &str, err: reqwest::Error) -> CallError {
    // reqwest's error names the URL in full, query and all: the message names
    // it as `shown_url` does.
    let err = err.without_url();
    let url = shown_url(url);
    let code = if err.is_timeout() {
        ErrCode::DeadlineExceeded
    } else if err.is_builder() {
        ErrCode::InvalidArgument
    } else {
        ErrCode::Unavailable
    };
    CallError::failed(code, format!("{method} {url}: {err}")).caused_by(err)
}

/// `url` as an error shows it: without its query, fragment or credentials,
/// which may hold secrets, as an error that escapes a handler is logged.
fn shown_url(url: &str) -> String {
    let Ok(mut url) = reqwest::Url::parse(url) else {
        return "(an invalid URL)".to_string();
    };
    // Neither fails for a URL with a host, as one that is sent has.
    let _ = url.set_username("");
    let _ = url.set_password(None);
    url.set_query(None);
    url.set_fragment(None);
    url.to_string()
}

/// The error an error answer is.
async fn error_answer(response: reqwest::Response) -> CallError {
    let status = response.status();
    match response.bytes().await {
        Ok(body) => error_body(status, &body),
        // The call's timeout ran out while the error was read.
        Err(err) if err.is_timeout() => read_failed(err).with_status(status.as_u16()),
        // The status still says what went wrong.
        Err(_) => error_body(status, &[]),
    }
}

/// The error an error answer with `body` is: the code and message of
/// Encore's error body, else those its status means.
fn error_body(status: http::StatusCode, body: &[u8]) -> CallError {
    #[derive(serde::Deserialize)]
    struct ErrorBody {
        code: Option<String>,
        message: Option<String>,
    }
    let parsed: Option<ErrorBody> = serde_json::from_slice(body).ok();
    let code = parsed
        .as_ref()
        .and_then(|b| b.code.as_deref())
        // In either case, as Go's client reads it.
        .and_then(|c| {
            c.to_ascii_lowercase()
                .parse::<encore_sdk_core::api::ErrCode>()
                .ok()
        })
        .map(ErrCode::from)
        .unwrap_or_else(|| status_code(status.as_u16()));
    let message = parsed
        .and_then(|b| b.message)
        .unwrap_or_else(|| match String::from_utf8_lossy(body).into_owned() {
            text if text.is_empty() => status.canonical_reason().unwrap_or_default().to_string(),
            text => text,
        });
    let err = CallError::new(code, message);
    if status.as_u16() >= 400 {
        err.with_status(status.as_u16())
    } else {
        err
    }
}

/// The code an error answer without Encore's error body means: as the
/// other SDKs' generated clients read it.
fn status_code(status: u16) -> ErrCode {
    match status {
        400 => ErrCode::InvalidArgument,
        401 => ErrCode::Unauthenticated,
        403 => ErrCode::PermissionDenied,
        404 => ErrCode::NotFound,
        408 | 504 => ErrCode::DeadlineExceeded,
        409 => ErrCode::AlreadyExists,
        429 => ErrCode::ResourceExhausted,
        499 => ErrCode::Canceled,
        500 => ErrCode::Internal,
        501 => ErrCode::Unimplemented,
        502 | 503 => ErrCode::Unavailable,
        _ => ErrCode::Unknown,
    }
}

/// The error a GraphQL answer with `errors` in it is.
fn graphql_error(errors: serde_json::Value, status: u16) -> CallError {
    let errors: Vec<serde_json::Value> = match errors {
        serde_json::Value::Array(errors) => errors,
        other => vec![other],
    }
    .into_iter()
    .map(|e| match e {
        serde_json::Value::Object(_) => e,
        other => serde_json::json!({ "message": other.to_string() }),
    })
    .collect();
    let code = errors
        .first()
        .and_then(|e| e.pointer("/extensions/code"))
        .and_then(|c| c.as_str())
        .and_then(|c| {
            c.to_ascii_lowercase()
                .parse::<encore_sdk_core::api::ErrCode>()
                .ok()
        })
        .map_or(ErrCode::Unknown, ErrCode::from);
    let message = errors
        .iter()
        .map(|e| {
            e.get("message")
                .and_then(|m| m.as_str())
                .unwrap_or_default()
        })
        .collect::<Vec<_>>()
        .join("; ");
    let mut err = CallError::new(code, message);
    if status >= 400 {
        err = err.with_status(status);
    }
    err.graphql_errors = errors;
    err
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn path_segments_are_percent_encoded() {
        assert_eq!(encode_path("a b/c~d"), "a%20b%2Fc~d");
        assert_eq!(encode_path("é"), "%C3%A9");
    }

    #[test]
    fn errors_show_no_query_or_credentials() {
        assert_eq!(
            shown_url("http://user:pass@127.0.0.1:1/users/1?token=s3cret#frag"),
            "http://127.0.0.1:1/users/1"
        );
    }

    #[test]
    fn error_answers_take_encores_error_body() {
        let err = error_body(
            http::StatusCode::NOT_FOUND,
            br#"{"code":"not_found","message":"no such product","details":null}"#,
        );
        assert_eq!((err.code, err.status), (ErrCode::NotFound, 404));
        assert_eq!(err.message, "no such product");

        // In either case, as Go's client reads it.
        let err = error_body(
            http::StatusCode::BAD_REQUEST,
            br#"{"code":"PERMISSION_DENIED","message":"not yours"}"#,
        );
        assert_eq!(err.code, ErrCode::PermissionDenied);

        let err = error_body(http::StatusCode::BAD_GATEWAY, b"upstream down");
        assert_eq!((err.code, err.status), (ErrCode::Unavailable, 502));
        assert_eq!(err.message, "upstream down");

        let err = error_body(http::StatusCode::IM_A_TEAPOT, b"");
        assert_eq!((err.code, err.status), (ErrCode::Unknown, 418));
        assert_eq!(err.message, "I'm a teapot");
    }

    #[test]
    fn graphql_errors_take_the_first_ones_code() {
        let err = graphql_error(
            serde_json::json!([
                {"message": "no user", "extensions": {"code": "NOT_FOUND"}},
                {"message": "and more"},
            ]),
            200,
        );
        assert_eq!((err.code, err.status), (ErrCode::NotFound, 404));
        assert_eq!(err.message, "no user; and more");
        assert_eq!(err.graphql_errors.len(), 2);

        let err = graphql_error(serde_json::json!("boom"), 500);
        assert_eq!((err.code, err.status), (ErrCode::Unknown, 500));
        assert_eq!(
            err.graphql_errors,
            [serde_json::json!({"message": "\"boom\""})]
        );
    }
}