darkwing/server/
mod.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
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
//! # Server Module
//!
//! This module contains the server logic for the application.
//!
//! It is responsible for handling the HTTP requests and responses, as well as
//! managing the services and configuration.
//!
//! All the data transfer, handling, and services are located here.

/// API routes.
mod api;

pub mod dtos;

pub mod error;

/// # Extractors
///
/// > The things that takes the request and extract the data from it.
///
/// Like middleware takes the request and decides if its should be handled or
/// not, the Extractors take the request and extract the data from it, like
/// headers (`UserAgentExtractor`), Authorization
/// (`RequiredAuthenticationExtractor`) or even validated data!
/// (`ValidationExtractor`)
mod extractors;

/// # Services
///
/// > The things that do the work.
///
/// Services are responsible for handling the business logic, like creating a
/// new browser profile, updating the existing one, fetching files from S3,
/// decrypting data, etc.
mod services;

/// # Utils
///
/// > Utility functions and types.
mod utils;

pub use services::browser_profile_services::{
  Additional, BrowserProfileConfig, DolphinSpecific, Fonts, Geolocation, Hints,
  MediaDevices, Navigator, PortsProtection, Screen, Synchronize, Voices, WebGL,
  WebGPU, LINUX_MOCK_PROFILE, MACOS_MOCK_PROFILE, WEBSITE_URLS,
  WINDOWS_MOCK_PROFILE,
};
use utils::metrics::build_recorder;

use std::{
  net::{Ipv4Addr, SocketAddr},
  sync::Arc,
  time::{Duration, Instant},
};

use anyhow::Context;
use axum::{
  body::Body,
  error_handling::HandleErrorLayer,
  extract::MatchedPath,
  http::{HeaderValue, Request, StatusCode},
  middleware::{self, Next},
  response::IntoResponse,
  routing::get,
  BoxError, Extension, Json, Router,
};
use serde_json::json;
use services::Services;
use tower::{buffer::BufferLayer, limit::RateLimitLayer, ServiceBuilder};
use tower_http::{cors::CorsLayer, trace::TraceLayer};
use tracing::{debug, info};

use crate::{cache::Cache, config::DarkwingConfig, database::Database};

/// Application server struct.
///
/// This struct contains the methods for starting and stopping the server, as
/// well as handling errors and metrics.
///
/// Struct has no fields, as all the methods are static and storing the services
/// is handled by Axum.
pub struct ApplicationServer;

impl ApplicationServer {
  const HTTP_TIMEOUT: u64 = 60;

  /// Starts the server with the given configuration, database, and cache.
  pub async fn serve(
    config: DarkwingConfig,
    db: Database,
    cache: Cache,
  ) -> anyhow::Result<()> {
    let recorder_handle = build_recorder()?;
    debug!("installed metrics recorder. handle: {:?}", recorder_handle);

    let services =
      Services::new(db, cache, Arc::new(config.clone()), recorder_handle).await;

    let cors = CorsLayer::new()
      .allow_origin(HeaderValue::from_static("*"))
      .allow_methods(tower_http::cors::Any)
      .allow_headers(tower_http::cors::Any);

    let router = Router::new()
      .nest("/api/v1", api::app())
      .route("/", get(api::health))
      .route("/metrics", get(api::metrics))
      .layer(
        ServiceBuilder::new()
          .layer(sentry_tower::NewSentryLayer::new_from_top())
          .layer(sentry_tower::SentryHttpLayer::new())
          .layer(TraceLayer::new_for_http())
          .layer(HandleErrorLayer::new(Self::handle_timeout_error))
          .timeout(Duration::from_secs(Self::HTTP_TIMEOUT))
          .layer(cors)
          .layer(Extension(services))
          .layer(BufferLayer::new(1024))
          .layer(RateLimitLayer::new(
            config.rate_limit_per_second,
            Duration::from_secs(1),
          )),
      )
      .route_layer(middleware::from_fn(Self::track_metrics));

    let router = router.fallback(Self::handle_404);

    let addr = SocketAddr::from((Ipv4Addr::UNSPECIFIED, config.port));
    let listener = tokio::net::TcpListener::bind(addr)
      .await
      .context(format!("failed to bind to address {}", addr))?;

    info!("server is starting at {addr}");

    axum::serve(listener, router)
      .with_graceful_shutdown(Self::shutdown_signal())
      .await
      .context("error while starting axum server")?;

    Ok(())
  }

  /// Adds a custom handler for tower's `TimeoutLayer`, see <https://docs.rs/axum/latest/axum/middleware/index.html#commonly-used-middleware>.
  async fn handle_timeout_error(
    err: BoxError,
  ) -> (StatusCode, Json<serde_json::Value>) {
    if err.is::<tower::timeout::error::Elapsed>() {
      (
        StatusCode::REQUEST_TIMEOUT,
        Json(json!({
            "error":
                format!(
                    "request took longer than the configured {} second timeout",
                    Self::HTTP_TIMEOUT
                )
        })),
      )
    } else {
      (
        StatusCode::INTERNAL_SERVER_ERROR,
        Json(json!({
            "error": format!("unhandled internal error: {}", err)
        })),
      )
    }
  }

  /// Tracks the metrics for the request, i.e. latency, status code, etc.
  ///
  /// Saves the metrics to the Prometheus.
  async fn track_metrics(
    request: Request<Body>,
    next: Next,
  ) -> impl IntoResponse {
    // todo: track HTTP transfer stage metrics. mb create another layer that
    // will consume body?
    let path =
      if let Some(matched_path) = request.extensions().get::<MatchedPath>() {
        matched_path.as_str().to_owned()
      } else {
        request.uri().path().to_owned()
      };

    let start = Instant::now();
    let method = request.method().clone();
    let response = next.run(request).await;
    let latency = start.elapsed().as_secs_f64();
    let status = response.status().as_u16().to_string();

    let labels = [
      ("method", method.to_string()),
      ("path", path),
      ("status", status),
    ];

    metrics::counter!("darkwing_http_requests_total", &labels).increment(1);
    metrics::histogram!("darkwing_http_requests_duration_seconds", &labels)
      .record(latency);

    response
  }

  /// Tokio signal handler that will wait for a user to press CTRL+C.
  /// We use this in our hyper `Server` method `with_graceful_shutdown`.
  async fn shutdown_signal() {
    #[allow(
      clippy::expect_used,
      reason = "if this function panics, then something gone insanely wrong and we do not mind panicking"
    )]
    tokio::signal::ctrl_c()
      .await
      .expect("expect tokio signal ctrl-c");

    if let Some(client) = sentry::Hub::current().client() {
      client.close(Some(Duration::from_secs(2)));
    }

    eprintln!("signal shutdown");
  }

  async fn handle_404() -> impl IntoResponse {
    (
      StatusCode::NOT_FOUND,
      axum::response::Json(serde_json::json!({
      "errors":{
      "message": vec!(String::from("The requested resource does not exist on this server!")),}
      })),
    )
  }
}