tarpc_lib/context.rs
1// Copyright 2018 Google LLC
2//
3// Use of this source code is governed by an MIT-style
4// license that can be found in the LICENSE file or at
5// https://opensource.org/licenses/MIT.
6
7//! Provides a request context that carries a deadline and trace context. This context is sent from
8//! client to server and is used by the server to enforce response deadlines.
9
10use std::time::{Duration, SystemTime};
11use trace::{self, TraceId};
12
13/// A request context that carries request-scoped information like deadlines and trace information.
14/// It is sent from client to server and is used by the server to enforce response deadlines.
15///
16/// The context should not be stored directly in a server implementation, because the context will
17/// be different for each request in scope.
18#[derive(Clone, Copy, Debug)]
19#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
20#[non_exhaustive]
21pub struct Context {
22 /// When the client expects the request to be complete by. The server should cancel the request
23 /// if it is not complete by this time.
24 #[cfg_attr(
25 feature = "serde1",
26 serde(serialize_with = "crate::util::serde::serialize_epoch_secs")
27 )]
28 #[cfg_attr(
29 feature = "serde1",
30 serde(deserialize_with = "crate::util::serde::deserialize_epoch_secs")
31 )]
32 #[cfg_attr(feature = "serde1", serde(default = "ten_seconds_from_now"))]
33 pub deadline: SystemTime,
34 /// Uniquely identifies requests originating from the same source.
35 /// When a service handles a request by making requests itself, those requests should
36 /// include the same `trace_id` as that included on the original request. This way,
37 /// users can trace related actions across a distributed system.
38 pub trace_context: trace::Context,
39}
40
41#[cfg(feature = "serde1")]
42fn ten_seconds_from_now() -> SystemTime {
43 return SystemTime::now() + Duration::from_secs(10);
44}
45
46/// Returns the context for the current request, or a default Context if no request is active.
47// TODO: populate Context with request-scoped data, with default fallbacks.
48pub fn current() -> Context {
49 Context {
50 deadline: SystemTime::now() + Duration::from_secs(10),
51 trace_context: trace::Context::new_root(),
52 }
53}
54
55impl Context {
56 /// Returns the ID of the request-scoped trace.
57 pub fn trace_id(&self) -> &TraceId {
58 &self.trace_context.trace_id
59 }
60}