fbthrift_git/
request_context.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use std::marker::PhantomData;
18
19use anyhow::Error;
20
21use crate::bufext::BufExt;
22use crate::context_stack::ContextStack;
23use crate::context_stack::DummyContextStack;
24use crate::framing::Framing;
25use crate::framing::FramingEncodedFinal;
26
27pub trait RequestContext {
28    type ContextStack: ContextStack;
29    type Name: ?Sized;
30
31    // This should return a ContextStack with a lifetime bounded by &self and the
32    // names, but that needs GATs, so require 'static for now.
33    fn get_context_stack(
34        &self,
35        service_name: &'static Self::Name,
36        fn_name: &'static Self::Name,
37    ) -> Result<Self::ContextStack, Error>;
38
39    fn set_user_exception_header(&self, ex_type: &str, ex_reason: &str) -> Result<(), Error>;
40}
41
42pub struct DummyRequestContext<Name: ?Sized, Frame> {
43    _phantom: PhantomData<(Frame, Name)>,
44}
45
46impl<Name: ?Sized, Frame> DummyRequestContext<Name, Frame> {
47    pub fn new() -> Self {
48        Self {
49            _phantom: PhantomData,
50        }
51    }
52}
53
54impl<Name: ?Sized, Frame: Framing> RequestContext for DummyRequestContext<Name, Frame>
55where
56    FramingEncodedFinal<Frame>: BufExt,
57{
58    type ContextStack = crate::context_stack::DummyContextStack<Name, Frame>;
59    type Name = Name;
60
61    fn get_context_stack(
62        &self,
63        _service_name: &Self::Name,
64        _fn_name: &Self::Name,
65    ) -> Result<Self::ContextStack, Error> {
66        Ok(DummyContextStack::new())
67    }
68
69    fn set_user_exception_header(&self, _ex_type: &str, _ex_reason: &str) -> Result<(), Error> {
70        Ok(())
71    }
72}
73
74#[cfg(test)]
75mod test {
76    use bytes::Bytes;
77
78    use super::*;
79
80    fn assert_context_stack(_: &impl RequestContext) {}
81
82    #[test]
83    fn check_unsized() {
84        assert_context_stack(&DummyRequestContext::<std::ffi::CStr, Bytes>::new());
85    }
86}