encore-dev 2.0.0-beta.9

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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! The calls of a generated gRPC client: one per kind of RPC, each sent by
//! `.await`, over one tonic channel per service that the SDK keeps.

use std::collections::HashMap;
use std::future::{Future, IntoFuture};
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::{Mutex, OnceLock};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

use futures_core::Stream;
use tonic::client::Grpc;
use tonic::codegen::http::uri::PathAndQuery;
use tonic::metadata::{MetadataKey, MetadataValue};
use tonic::transport::{Channel, Endpoint};
use tonic_prost::ProstCodec;
use tower_layer::Layer;

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

/// A call's future.
type Sending<'c, T> = Pin<Box<dyn Future<Output = Result<T, CallError>> + Send + 'c>>;

/// What every kind of call holds: where it goes, and its settings.
struct Call<'c> {
    service: &'c services::Client,
    client: &'c Settings,
    settings: Settings,
    path: &'static str,
}

/// A call ready to send.
struct Prepared<T> {
    /// The channel it goes over.
    grpc: Grpc<Propagate<Channel>>,
    /// The request it sends its message or messages in.
    request: tonic::Request<T>,
    /// When it times out.
    deadline: Option<Instant>,
}

impl Call<'_> {
    /// The call, sending `message`.
    fn prepare<T>(&self, message: T) -> Result<Prepared<T>, CallError> {
        let settings = self.settings.under(self.client);
        let grpc = grpc(base_url_of(self.service, &settings)?)?;
        let mut request = tonic::Request::new(message);
        for (name, value) in &settings.headers {
            let key = MetadataKey::from_bytes(name.to_ascii_lowercase().as_bytes())
                .map_err(|e| invalid_header(name, e))?;
            let value =
                MetadataValue::try_from(value.as_str()).map_err(|e| invalid_header(name, e))?;
            request.metadata_mut().insert(key, value);
        }
        let deadline = deadline(&mut request, settings.limit());
        Ok(Prepared {
            grpc,
            request,
            deadline,
        })
    }

    fn path(&self) -> PathAndQuery {
        PathAndQuery::from_static(self.path)
    }
}

/// The client calls to `base` go over: the service's channel, which tells
/// the app's services from others by `base`'s origin.
fn grpc(base: &str) -> Result<Grpc<Propagate<Channel>>, CallError> {
    static CHANNELS: OnceLock<Mutex<HashMap<String, Channel>>> = OnceLock::new();
    let origin: http::Uri = base.parse().map_err(|e| {
        CallError::failed(
            ErrCode::InvalidArgument,
            format!("invalid base URL {base:?}: {e}"),
        )
    })?;
    let mut channels = CHANNELS
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let channel = match channels.get(base) {
        Some(channel) => channel.clone(),
        None => {
            let endpoint = Endpoint::from_shared(base.to_string()).map_err(|e| {
                CallError::failed(
                    ErrCode::InvalidArgument,
                    format!("invalid base URL {base:?}: {e}"),
                )
            })?;
            // On the core's runtime, which outlives the one a call is made
            // in, as each test's does: the channel's worker runs there.
            let _runtime = crate::runtime::core().tokio_handle().enter();
            let channel = endpoint.connect_lazy();
            channels.insert(base.to_string(), channel.clone());
            channel
        }
    };
    Ok(Grpc::with_origin(PropagateLayer.layer(channel), origin))
}

/// The longest timeout gRPC can send: 8 digits of hours.
const MAX_TIMEOUT: Duration = Duration::from_secs(99_999_999 * 3600);

/// When a call with `timeout` times out, sent with `request` as its
/// deadline. A timeout longer than gRPC can send, or than the clock counts
/// to, is none.
fn deadline<T>(request: &mut tonic::Request<T>, timeout: Option<Duration>) -> Option<Instant> {
    let timeout = timeout.filter(|t| *t <= MAX_TIMEOUT)?;
    let deadline = Instant::now().checked_add(timeout)?;
    request.set_timeout(timeout);
    Some(deadline)
}

/// The error a failed call's status is. tonic fails a call past its
/// deadline as `Cancelled`, which is `DeadlineExceeded` here. A status tonic
/// made of an error of its own, which it keeps as the status's source, or of
/// the deadline, is no answer: it has no HTTP status.
fn status_error(status: tonic::Status, deadline: Option<Instant>) -> CallError {
    let past_deadline = deadline.is_some_and(|d| Instant::now() >= d);
    let answered = std::error::Error::source(&status).is_none()
        && !(past_deadline && status.code() == tonic::Code::Cancelled);
    let code = match status.code() {
        tonic::Code::Ok | tonic::Code::Unknown => ErrCode::Unknown,
        tonic::Code::Cancelled if past_deadline => ErrCode::DeadlineExceeded,
        tonic::Code::Cancelled => ErrCode::Canceled,
        tonic::Code::InvalidArgument => ErrCode::InvalidArgument,
        tonic::Code::DeadlineExceeded => ErrCode::DeadlineExceeded,
        tonic::Code::NotFound => ErrCode::NotFound,
        tonic::Code::AlreadyExists => ErrCode::AlreadyExists,
        tonic::Code::PermissionDenied => ErrCode::PermissionDenied,
        tonic::Code::ResourceExhausted => ErrCode::ResourceExhausted,
        tonic::Code::FailedPrecondition => ErrCode::FailedPrecondition,
        tonic::Code::Aborted => ErrCode::Aborted,
        tonic::Code::OutOfRange => ErrCode::OutOfRange,
        tonic::Code::Unimplemented => ErrCode::Unimplemented,
        tonic::Code::Internal => ErrCode::Internal,
        tonic::Code::Unavailable => ErrCode::Unavailable,
        tonic::Code::DataLoss => ErrCode::DataLoss,
        tonic::Code::Unauthenticated => ErrCode::Unauthenticated,
    };
    let message = status.message().to_string();
    let err = if answered {
        CallError::new(code, message)
    } else {
        CallError::failed(code, message)
    };
    err.caused_by(status)
}

/// Waits for the channel to take a call.
async fn ready(grpc: &mut Grpc<Propagate<Channel>>) -> Result<(), CallError> {
    grpc.ready().await.map_err(|err| {
        CallError::failed(ErrCode::Unavailable, format!("connecting: {err}")).caused_by(err)
    })
}

/// The settings methods every kind of call has.
macro_rules! settings {
    () => {
        /// Fails the call when it takes longer than `timeout`, with
        /// `DeadlineExceeded`, in place of its client's timeout. It is sent
        /// as the call's deadline.
        pub fn timeout(mut self, timeout: Duration) -> Self {
            self.call.settings = self.call.settings.timeout(timeout);
            self
        }

        /// Sets the call no timeout, in place of its client's.
        pub fn no_timeout(mut self) -> Self {
            self.call.settings = self.call.settings.no_timeout();
            self
        }

        /// Sends a header, as gRPC metadata, in place of one of the same
        /// name its client would send.
        pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
            self.call.settings = self.call.settings.header(name, value);
            self
        }
    };
}

/// A unary call: one message each way.
#[must_use = "a call is sent only when awaited"]
pub struct Unary<'c, Req, Resp> {
    call: Call<'c>,
    message: Req,
    answer: PhantomData<fn() -> Resp>,
}

impl<'c, Req, Resp> Unary<'c, Req, Resp> {
    /// A call of `path`, `/package.Service/Method`, sending `message`.
    #[doc(hidden)]
    pub fn new(
        service: &'c services::Client,
        client: &'c Settings,
        path: &'static str,
        message: Req,
    ) -> Self {
        Unary {
            call: Call {
                service,
                client,
                settings: Settings::new(),
                path,
            },
            message,
            answer: PhantomData,
        }
    }

    settings!();
}

impl<'c, Req, Resp> IntoFuture for Unary<'c, Req, Resp>
where
    Req: prost::Message + Send + Sync + 'static,
    Resp: prost::Message + Default + Send + Sync + 'static,
{
    type Output = Result<Resp, CallError>;
    type IntoFuture = Sending<'c, Resp>;

    /// Sends the call in the context `into_future` is called in, as awaiting
    /// it does, so a call spawned still carries the context of the code that
    /// made it.
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(super::sent(async move {
            let Prepared {
                mut grpc,
                request,
                deadline,
            } = self.call.prepare(self.message)?;
            ready(&mut grpc).await?;
            let codec = ProstCodec::<Req, Resp>::default();
            grpc.unary(request, self.call.path(), codec)
                .await
                .map(tonic::Response::into_inner)
                .map_err(|s| status_error(s, deadline))
        }))
    }
}

/// A call answered with a stream of messages.
#[must_use = "a call is sent only when awaited"]
pub struct ServerStreaming<'c, Req, Resp> {
    call: Call<'c>,
    message: Req,
    answer: PhantomData<fn() -> Resp>,
}

impl<'c, Req, Resp> ServerStreaming<'c, Req, Resp> {
    /// A call of `path`, `/package.Service/Method`, sending `message`.
    #[doc(hidden)]
    pub fn new(
        service: &'c services::Client,
        client: &'c Settings,
        path: &'static str,
        message: Req,
    ) -> Self {
        ServerStreaming {
            call: Call {
                service,
                client,
                settings: Settings::new(),
                path,
            },
            message,
            answer: PhantomData,
        }
    }

    settings!();
}

impl<'c, Req, Resp> IntoFuture for ServerStreaming<'c, Req, Resp>
where
    Req: prost::Message + Send + Sync + 'static,
    Resp: prost::Message + Default + Send + Sync + 'static,
{
    type Output = Result<Streaming<Resp>, CallError>;
    type IntoFuture = Sending<'c, Streaming<Resp>>;

    /// Sends the call in the context `into_future` is called in, as awaiting
    /// it does, so a call spawned still carries the context of the code that
    /// made it.
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(super::sent(async move {
            let Prepared {
                mut grpc,
                request,
                deadline,
            } = self.call.prepare(self.message)?;
            ready(&mut grpc).await?;
            let codec = ProstCodec::<Req, Resp>::default();
            let inner = grpc
                .server_streaming(request, self.call.path(), codec)
                .await
                .map_err(|s| status_error(s, deadline))?
                .into_inner();
            Ok(Streaming { inner, deadline })
        }))
    }
}

/// A call sending a stream of messages, answered with one.
#[must_use = "a call is sent only when awaited"]
pub struct ClientStreaming<'c, S, Resp> {
    call: Call<'c>,
    messages: S,
    answer: PhantomData<fn() -> Resp>,
}

impl<'c, S, Resp> ClientStreaming<'c, S, Resp> {
    /// A call of `path`, `/package.Service/Method`, sending `messages`.
    #[doc(hidden)]
    pub fn new(
        service: &'c services::Client,
        client: &'c Settings,
        path: &'static str,
        messages: S,
    ) -> Self {
        ClientStreaming {
            call: Call {
                service,
                client,
                settings: Settings::new(),
                path,
            },
            messages,
            answer: PhantomData,
        }
    }

    settings!();
}

impl<'c, S, Resp> IntoFuture for ClientStreaming<'c, S, Resp>
where
    S: Stream + Send + 'static,
    S::Item: prost::Message + Send + Sync + 'static,
    Resp: prost::Message + Default + Send + Sync + 'static,
{
    type Output = Result<Resp, CallError>;
    type IntoFuture = Sending<'c, Resp>;

    /// Sends the call in the context `into_future` is called in, as awaiting
    /// it does, so a call spawned still carries the context of the code that
    /// made it.
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(super::sent(async move {
            let Prepared {
                mut grpc,
                request,
                deadline,
            } = self.call.prepare(self.messages)?;
            ready(&mut grpc).await?;
            let codec = ProstCodec::<S::Item, Resp>::default();
            grpc.client_streaming(request, self.call.path(), codec)
                .await
                .map(tonic::Response::into_inner)
                .map_err(|s| status_error(s, deadline))
        }))
    }
}

/// A call sending a stream of messages, answered with another.
#[must_use = "a call is sent only when awaited"]
pub struct BidiStreaming<'c, S, Resp> {
    call: Call<'c>,
    messages: S,
    answer: PhantomData<fn() -> Resp>,
}

impl<'c, S, Resp> BidiStreaming<'c, S, Resp> {
    /// A call of `path`, `/package.Service/Method`, sending `messages`.
    #[doc(hidden)]
    pub fn new(
        service: &'c services::Client,
        client: &'c Settings,
        path: &'static str,
        messages: S,
    ) -> Self {
        BidiStreaming {
            call: Call {
                service,
                client,
                settings: Settings::new(),
                path,
            },
            messages,
            answer: PhantomData,
        }
    }

    settings!();
}

impl<'c, S, Resp> IntoFuture for BidiStreaming<'c, S, Resp>
where
    S: Stream + Send + 'static,
    S::Item: prost::Message + Send + Sync + 'static,
    Resp: prost::Message + Default + Send + Sync + 'static,
{
    type Output = Result<Streaming<Resp>, CallError>;
    type IntoFuture = Sending<'c, Streaming<Resp>>;

    /// Sends the call in the context `into_future` is called in, as awaiting
    /// it does, so a call spawned still carries the context of the code that
    /// made it.
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(super::sent(async move {
            let Prepared {
                mut grpc,
                request,
                deadline,
            } = self.call.prepare(self.messages)?;
            ready(&mut grpc).await?;
            let codec = ProstCodec::<S::Item, Resp>::default();
            let inner = grpc
                .streaming(request, self.call.path(), codec)
                .await
                .map_err(|s| status_error(s, deadline))?
                .into_inner();
            Ok(Streaming { inner, deadline })
        }))
    }
}

/// The messages a call is answered with: a [`Stream`] of them, which ends
/// after the last, or with the call's error.
pub struct Streaming<T> {
    inner: tonic::Streaming<T>,
    deadline: Option<Instant>,
}

impl<T> Streaming<T> {
    /// The next message; `None` after the last.
    pub async fn message(&mut self) -> Result<Option<T>, CallError> {
        std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx))
            .await
            .transpose()
    }
}

impl<T> std::fmt::Debug for Streaming<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Streaming").finish_non_exhaustive()
    }
}

impl<T> Stream for Streaming<T> {
    type Item = Result<T, CallError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let deadline = self.deadline;
        Pin::new(&mut self.inner)
            .poll_next(cx)
            .map(|item| item.map(|r| r.map_err(|s| status_error(s, deadline))))
    }
}

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

    #[test]
    fn a_cancel_past_the_deadline_is_deadline_exceeded() {
        let past = Some(Instant::now() - Duration::from_millis(1));
        let future = Some(Instant::now() + Duration::from_secs(60));
        assert_eq!(
            status_error(tonic::Status::cancelled("Timeout expired"), past).code,
            ErrCode::DeadlineExceeded
        );
        assert_eq!(
            status_error(tonic::Status::cancelled("Timeout expired"), future).code,
            ErrCode::Canceled
        );
        assert_eq!(
            status_error(tonic::Status::cancelled("Timeout expired"), None).code,
            ErrCode::Canceled
        );
        let err = status_error(tonic::Status::not_found("no such product"), None);
        assert_eq!((err.code, err.status), (ErrCode::NotFound, 404));
        assert_eq!(err.message, "no such product");
    }

    #[test]
    fn a_timeout_too_long_to_send_is_none() {
        let mut request = tonic::Request::new(());
        assert_eq!(deadline(&mut request, Some(Duration::MAX)), None);
        assert!(request.metadata().get("grpc-timeout").is_none());
        assert!(deadline(&mut request, Some(Duration::from_secs(1))).is_some());
        assert!(request.metadata().get("grpc-timeout").is_some());
    }

    #[test]
    fn only_a_status_the_service_sent_has_an_http_status() {
        let past = Some(Instant::now() - Duration::from_millis(1));
        let timed_out = status_error(tonic::Status::cancelled("Timeout expired"), past);
        assert_eq!(timed_out.status, 0);
        let refused = tonic::Status::from_error(Box::new(std::io::Error::from(
            std::io::ErrorKind::ConnectionRefused,
        )));
        assert_eq!(status_error(refused, None).status, 0);
        let sent = status_error(tonic::Status::unavailable("draining"), None);
        assert_eq!((sent.code, sent.status), (ErrCode::Unavailable, 503));
    }
}