aviso-server 0.11.1

Notification service for data-driven workflows with live and replay APIs.
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
// (C) Copyright 2024- ECMWF and individual contributors.
//
// This software is licensed under the terms of the Apache Licence Version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation nor
// does it submit to any jurisdiction.

use std::{net::TcpListener, sync::Arc};

use actix_web::{App, HttpServer, dev::Server, middleware::Condition, web};
use tokio::task;
use tokio_util::sync::CancellationToken;
use tracing::{error, info};
use tracing_actix_web::TracingLogger;

use crate::auth::middleware::AuthMiddleware;
#[cfg(feature = "ecpds")]
use crate::configuration::validate_ecpds_settings;
use crate::configuration::{AuthSettings, validate_metrics_settings};
use crate::metrics::AppMetrics;
use crate::middleware::access_log::AvisoRootSpanBuilder;
use crate::middleware::http_metrics::HttpMetrics;
use crate::middleware::request_id::RequestIdHeader;
use crate::openapi::ApiDoc;
use crate::routes::admin::{delete_notification, wipe_all, wipe_stream};
use crate::routes::home::homepage;
use crate::routes::replay::replay;
use crate::routes::schema::{get_event_schema, get_notification_schema};
use crate::routes::watch::watch;
use crate::{
    configuration::{
        Settings, validate_auth_settings, validate_schema_storage_policy_support,
        validate_spatial_schema_settings, validate_stream_auth_settings,
        validate_stream_plugin_settings, validate_topic_schema_settings,
    },
    notification_backend::{MeteredBackend, NotificationBackend, build_backend},
    routes::{health_check::health_check, notify::notify, ready::ready},
    telemetry::{SERVICE_NAME, SERVICE_VERSION},
};
use actix_files as fs;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;

#[allow(dead_code)]
pub struct Application {
    port: u16,
    server: Server,
    metrics_server: Option<Server>,
    shutdown: CancellationToken,
    backend: Arc<dyn NotificationBackend>, // backend reference for shutdown
}

impl Application {
    // Build the server from the configuration
    pub async fn build(
        configuration: Settings,
        shutdown: CancellationToken,
    ) -> Result<Self, std::io::Error> {
        configuration.application.homepage.validate()?;
        if let Err(e) = validate_schema_storage_policy_support(&configuration) {
            error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "startup.configuration.validation.failed",
                error = %e,
                "Configuration validation failed"
            );
            return Err(std::io::Error::other(e));
        }

        if let Err(e) = validate_topic_schema_settings(&configuration) {
            error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "startup.topic_schema.validation.failed",
                error = %e,
                "Topic schema configuration validation failed"
            );
            return Err(std::io::Error::other(e));
        }

        if let Err(e) = validate_spatial_schema_settings(&configuration) {
            error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "startup.spatial_schema.validation.failed",
                error = %e,
                "Spatial schema configuration validation failed"
            );
            return Err(std::io::Error::other(e));
        }

        if let Err(e) = validate_auth_settings(&configuration.auth) {
            error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "startup.auth.validation.failed",
                error = %e,
                "Auth configuration validation failed"
            );
            return Err(std::io::Error::other(e));
        }

        if let Err(e) = validate_stream_plugin_settings(&configuration) {
            error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "startup.auth.plugin_validation.failed",
                error = %e,
                "Stream plugin configuration validation failed"
            );
            return Err(std::io::Error::other(e));
        }

        if let Err(e) = validate_stream_auth_settings(&configuration) {
            error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "startup.auth.stream_validation.failed",
                error = %e,
                "Stream auth configuration validation failed"
            );
            return Err(std::io::Error::other(e));
        }

        if let Err(e) = validate_metrics_settings(&configuration) {
            error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "startup.metrics.validation.failed",
                error = %e,
                "Metrics configuration validation failed"
            );
            return Err(std::io::Error::other(e));
        }

        #[cfg(feature = "ecpds")]
        let ecpds_checker: Option<Arc<aviso_ecpds::checker::EcpdsChecker>> = {
            if let Err(e) = validate_ecpds_settings(&configuration) {
                error!(
                    service_name = SERVICE_NAME,
                    service_version = SERVICE_VERSION,
                    event_name = "startup.ecpds.validation.failed",
                    error = %e,
                    "ECPDS configuration validation failed"
                );
                return Err(std::io::Error::other(e));
            }
            // Tell the subcrate which service identity to use in its
            // own structured tracing events (auth.ecpds.fetch.* and
            // auth.ecpds.cache.*) so log routing/filtering by
            // service_name groups them with the rest of the binary's
            // events instead of leaving them under aviso-ecpds/0.1.0.
            aviso_ecpds::set_service_identity(SERVICE_NAME, SERVICE_VERSION);
            match configuration.build_ecpds_checker() {
                Ok(checker) => checker.map(Arc::new),
                Err(e) => {
                    error!(
                        service_name = SERVICE_NAME,
                        service_version = SERVICE_VERSION,
                        event_name = "startup.ecpds.checker_init.failed",
                        error = %e,
                        "ECPDS checker initialization failed"
                    );
                    return Err(std::io::Error::other(e));
                }
            }
        };

        let address = format!(
            "{}:{}",
            configuration.application.host, configuration.application.port
        );
        let listener = TcpListener::bind(&address)?;
        let port = listener.local_addr()?.port();

        // Initialize the configured notification backend before binding routes.
        let notification_backend = match build_backend(&configuration.notification_backend).await {
            Ok(backend) => backend,
            Err(e) => {
                error!(
                    service_name = SERVICE_NAME,
                    service_version = SERVICE_VERSION,
                    event_name = "startup.backend.initialization.failed",
                    error = %e,
                    "Failed to initialize notification backend"
                );
                return Err(std::io::Error::other(e));
            }
        };

        let (app_metrics, metrics_server) = if configuration.metrics.enabled {
            let metrics = AppMetrics::new();
            crate::metrics::register_process_metrics(&metrics.registry);
            if let Some(schema) = Settings::get_global_notification_schema() {
                metrics.preinit_notification_series(schema.keys().map(String::as_str));
            }

            let metrics_port = configuration.metrics.port.expect("validated above");
            let metrics_host = &configuration.metrics.host;
            let metrics_addr = format!("{metrics_host}:{metrics_port}");
            let metrics_listener = TcpListener::bind(&metrics_addr)?;

            info!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "startup.metrics.server.binding",
                host = %metrics_host,
                port = metrics_port,
                "Metrics server binding"
            );

            let server =
                crate::metrics::run_metrics_server(metrics_listener, metrics.registry.clone())?;
            (Some(metrics), Some(server))
        } else {
            (None, None)
        };

        // Wrap the backend so trait-boundary operations record metrics. Only
        // when metrics are enabled; otherwise the bare backend is used.
        let notification_backend: Arc<dyn NotificationBackend> = match &app_metrics {
            Some(metrics) => Arc::new(MeteredBackend::new(
                notification_backend,
                metrics.clone(),
                &configuration.notification_backend.kind,
            )),
            None => notification_backend,
        };

        let server = run(
            listener,
            notification_backend.clone(),
            shutdown.clone(),
            Arc::new(configuration.auth.clone()),
            app_metrics,
            configuration.application,
            #[cfg(feature = "ecpds")]
            ecpds_checker,
        )?;

        // stop Actix when the cancellation token is triggered
        let handle = server.handle();
        let metrics_handle = metrics_server.as_ref().map(|s| s.handle());
        let backend_for_shutdown = notification_backend.clone();
        task::spawn({
            let token = shutdown.clone();
            async move {
                token.cancelled().await;

                info!(
                    service_name = SERVICE_NAME,
                    service_version = SERVICE_VERSION,
                    event_name = "startup.shutdown.received",
                    "Shutdown signal received, stopping Actix server"
                );

                // Stop metrics server gracefully, then the main server.
                if let Some(mh) = metrics_handle {
                    mh.stop(true).await;
                }
                handle.stop(true).await;

                info!(
                    service_name = SERVICE_NAME,
                    service_version = SERVICE_VERSION,
                    event_name = "startup.server.stopped",
                    "Actix server stopped, shutting down backend"
                );

                // Then shutdown the backend
                if let Err(e) = shutdown_backend(backend_for_shutdown).await {
                    error!(
                        service_name = SERVICE_NAME,
                        service_version = SERVICE_VERSION,
                        event_name = "startup.backend.shutdown.failed",
                        error = %e,
                        "Error during backend shutdown"
                    );
                } else {
                    info!(
                        service_name = SERVICE_NAME,
                        service_version = SERVICE_VERSION,
                        event_name = "startup.backend.shutdown.succeeded",
                        "Backend shutdown completed successfully"
                    );
                }
            }
        });

        Ok(Self {
            port,
            server,
            metrics_server,
            shutdown,
            backend: notification_backend,
        })
    }

    // This is to get the port number from the TcpListener
    // it is useful when a random port is used
    pub fn port(&self) -> u16 {
        self.port
    }

    // This function is used to run the server
    pub async fn run_until_stopped(self) -> Result<(), std::io::Error> {
        match self.metrics_server {
            Some(metrics) => {
                tokio::try_join!(self.server, metrics)?;
                Ok(())
            }
            None => self.server.await,
        }
    }
}

/// Shutdown the notification backend gracefully
///
/// This function calls the shutdown method on the NotificationBackend trait object,
/// allowing all backend implementations to handle their own cleanup.
async fn shutdown_backend(backend: Arc<dyn NotificationBackend>) -> anyhow::Result<()> {
    info!(
        service_name = SERVICE_NAME,
        service_version = SERVICE_VERSION,
        event_name = "startup.backend.shutdown.started",
        "Shutting down notification backend"
    );

    // Call the shutdown method defined in the trait
    backend.shutdown().await?;

    info!(
        service_name = SERVICE_NAME,
        service_version = SERVICE_VERSION,
        event_name = "startup.backend.shutdown.completed",
        "Notification backend shutdown completed"
    );
    Ok(())
}

/// Configure operational/infrastructure routes
fn configure_ops_routes(cfg: &mut web::ServiceConfig, static_path: &str) {
    cfg.service(fs::Files::new("/static", static_path).show_files_listing())
        .route("/health", web::get().to(health_check))
        .route("/ready", web::get().to(ready))
        .route("/", web::get().to(homepage));
}

/// Configure API v1 routes
fn configure_api_v1(cfg: &mut web::ServiceConfig, auth_settings: Arc<AuthSettings>) {
    cfg.service(
        web::scope("/api/v1")
            .wrap(AuthMiddleware::with_arc_settings(auth_settings))
            .route("/notification", web::post().to(notify))
            .route("/watch", web::post().to(watch))
            .route("/replay", web::post().to(replay))
            .route("/schema", web::get().to(get_notification_schema))
            .route("/schema/{event_type}", web::get().to(get_event_schema))
            .service(
                web::scope("/admin")
                    .route("/wipe/stream", web::delete().to(wipe_stream))
                    .route("/wipe/all", web::delete().to(wipe_all))
                    .route(
                        "/notification/{notification_id}",
                        web::delete().to(delete_notification),
                    ),
            ),
    );
}

// Run the server
pub fn run(
    listener: TcpListener,
    notification_backend: Arc<dyn NotificationBackend>,
    shutdown: CancellationToken,
    auth_settings: Arc<AuthSettings>,
    app_metrics: Option<AppMetrics>,
    application_settings: crate::configuration::ApplicationSettings,
    #[cfg(feature = "ecpds")] ecpds_checker: Option<Arc<aviso_ecpds::checker::EcpdsChecker>>,
) -> Result<Server, std::io::Error> {
    let metrics_data = app_metrics.map(web::Data::new);
    let application_data = web::Data::new(application_settings);
    #[cfg(feature = "ecpds")]
    let ecpds_data = ecpds_checker.map(web::Data::new);
    let server = HttpServer::new(move || {
        let mut app = App::new()
            .wrap(Condition::new(metrics_data.is_some(), HttpMetrics))
            .wrap(RequestIdHeader)
            .wrap(TracingLogger::<AvisoRootSpanBuilder>::new())
            .service(
                SwaggerUi::new("/swagger-ui/{_:.*}")
                    .url("/api-docs/openapi.json", ApiDoc::openapi()),
            )
            .app_data(application_data.clone())
            .configure(|cfg| configure_ops_routes(cfg, &application_data.static_files_path))
            .configure({
                let auth_settings = Arc::clone(&auth_settings);
                move |cfg| configure_api_v1(cfg, Arc::clone(&auth_settings))
            })
            .app_data(web::Data::new(notification_backend.clone()))
            .app_data(web::Data::new(shutdown.clone()))
            .app_data(web::Data::new(auth_settings.clone()));

        if let Some(ref metrics) = metrics_data {
            app = app.app_data(metrics.clone());
        }

        #[cfg(feature = "ecpds")]
        if let Some(ref ecpds) = ecpds_data {
            app = app.app_data(ecpds.clone());
        }

        app
    })
    .listen(listener)?
    .shutdown_timeout(30)
    .disable_signals()
    .run();
    Ok(server)
}