drasi_source_sdk/
proxy.rs

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
use std::{env, fs::OpenOptions, future::Future, net::SocketAddr, panic, pin::Pin, sync::Arc, io::Write};

use axum::{
    extract::State,
    response::IntoResponse,
    routing::{get, post},
    Json, Router,
};
use axum_streams::StreamBodyAs;
use futures::Stream;
use thiserror::Error;
use tokio::net::TcpListener;

use crate::{models::{BootstrapRequest, SourceElement}, telemetry::init_tracer};

pub type BootstrapStream = Pin<Box<dyn Stream<Item = SourceElement> + Send>>;

#[derive(Error, Debug)]
pub enum BootstrapError {
    #[error("Invalid request: {0}")]
    InvalidRequest(String),

    #[error("Internal error: {0}")]
    InternalError(String),
}

pub struct SourceProxy<Response>
where
    Response: Future<Output = Result<BootstrapStream, BootstrapError>> + Send + Sync,
{
    stream_producer: fn(BootstrapRequest) -> Response,
    port: u16,
}

impl<Response> SourceProxy<Response>
where
    Response: Future<Output = Result<BootstrapStream, BootstrapError>> + Send + Sync + 'static,
{
    pub async fn start(&self) {

        panic::set_hook(Box::new(|info| {            
            if let Some(message) = info.payload().downcast_ref::<String>() {                   
                log::error!("Panic occurred: {}", message); 
                if let Ok(mut file) = OpenOptions::new().create(true).write(true).open("/dev/termination-log") {
                    let _ = writeln!(file, "Panic occurred: {}", message);
                }
            } else if let Some(message) = info.payload().downcast_ref::<&str>() {
                log::error!("Panic occurred: {}", message); 
                if let Ok(mut file) = OpenOptions::new().create(true).write(true).open("/dev/termination-log") {
                    let _ = writeln!(file, "Panic occurred: {}", message);
                }
            }           
        }));

        env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
        log::info!("Starting proxy");
        _ = init_tracer(format!("{}-proxy", env::var("SOURCE_ID").expect("SOURCE_ID required"))).unwrap();

        let app_state = Arc::new(AppState::<Response> {
            stream_producer: self.stream_producer,
        });

        let app = Router::new()
            .route("/acquire-stream", post(proxy_stream))
            .route(
                "/supports-stream",
                get(|| async { (axum::http::StatusCode::NO_CONTENT, "") }),
            )
            .with_state(app_state);

        let addr = SocketAddr::from(([0, 0, 0, 0], self.port));

        let listener = match TcpListener::bind(&addr).await {
            Ok(listener) => listener,
            Err(e) => {
                panic!("Error binding to address: {:?}", e);
            }
        };
        if let Err(e) = axum::serve(listener, app).await {
            log::error!("Error starting the server: {:?}", e);
        };
    }
}

pub struct SourceProxyBuilder<Response>
where
    Response: Future<Output = Result<BootstrapStream, BootstrapError>> + Send + Sync,
{
    stream_producer: Option<fn(BootstrapRequest) -> Response>,
    port: Option<u16>,
}

impl<Response> SourceProxyBuilder<Response>
where
    Response: Future<Output = Result<BootstrapStream, BootstrapError>> + Send + Sync,
{
    pub fn new() -> Self {
        SourceProxyBuilder {
            stream_producer: None,
            port: None,
        }
    }

    pub fn with_stream_producer(
        mut self,
        stream_producer: fn(BootstrapRequest) -> Response,
    ) -> Self {
        self.stream_producer = Some(stream_producer);
        self
    }

    pub fn with_port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    pub fn build(self) -> SourceProxy<Response> {
        SourceProxy {
            stream_producer: self.stream_producer.unwrap(),
            port: self.port.unwrap_or(80),
        }
    }
}

struct AppState<Response>
where
    Response: Future<Output = Result<BootstrapStream, BootstrapError>> + Send + Sync,
{
    stream_producer: fn(BootstrapRequest) -> Response,
}

async fn proxy_stream<Response>(
    State(state): State<Arc<AppState<Response>>>,
    Json(request): Json<BootstrapRequest>,
) -> impl IntoResponse
where
    Response: Future<Output = Result<BootstrapStream, BootstrapError>> + Send + Sync,
{
    match (state.stream_producer)(request).await {
        Ok(stream) => StreamBodyAs::json_nl(stream).into_response(),
        Err(e) => match e {
            BootstrapError::InvalidRequest(e) => (axum::http::StatusCode::BAD_REQUEST, e.to_string()).into_response(),
            BootstrapError::InternalError(e) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
        }
    }
}