aviso-server 0.9.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
// (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 crate::configuration::Settings;
use crate::notification_backend::{DeleteMessageResult, NotificationBackend, WipeStreamResult};
use crate::telemetry::{SERVICE_NAME, SERVICE_VERSION};
use actix_web::{HttpResponse, Result as ActixResult, web};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tracing_actix_web::RequestId;
use utoipa::ToSchema;

#[derive(Deserialize, ToSchema)]
pub struct WipeStreamRequest {
    /// Event type or backend stream name, case-insensitive: "mars" and
    /// "MARS" both wipe the stream that serves the `mars` event type.
    pub stream_name: String,
}

#[derive(Serialize, ToSchema)]
pub struct WipeResponse {
    pub success: bool,
    pub message: String,
    /// Per-request UUID for log correlation. Same value as the
    /// `X-Request-ID` HTTP response header.
    pub request_id: String,
}

#[derive(Serialize, ToSchema)]
pub struct DeleteNotificationResponse {
    pub success: bool,
    pub message: String,
    pub notification_id: String,
    /// Per-request UUID for log correlation. Same value as the
    /// `X-Request-ID` HTTP response header.
    pub request_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ParsedNotificationId {
    stream_key: String,
    sequence: u64,
}

fn parse_notification_id(value: &str) -> Result<ParsedNotificationId, &'static str> {
    let trimmed = value.trim();
    let (raw_stream_key, raw_sequence) = trimmed
        .split_once('@')
        .ok_or("notification_id must be in '<stream>@<sequence>' format")?;
    if raw_stream_key.is_empty() || raw_sequence.is_empty() {
        return Err("notification_id must be in '<stream>@<sequence>' format");
    }
    let sequence = raw_sequence
        .parse::<u64>()
        .map_err(|_| "notification_id sequence must be a positive integer")?;
    if sequence == 0 {
        return Err("notification_id sequence must be greater than zero");
    }

    Ok(ParsedNotificationId {
        stream_key: raw_stream_key.to_string(),
        sequence,
    })
}

/// Suffix for not-found messages naming the configured event types, so a
/// typo'd wipe request tells the operator what would have worked.
fn known_event_types_suffix() -> String {
    match Settings::get_global_notification_schema().as_ref() {
        Some(schema) if !schema.is_empty() => {
            let mut names: Vec<&str> = schema.keys().map(String::as_str).collect();
            names.sort_unstable();
            format!(". Known event types: {}", names.join(", "))
        }
        _ => String::new(),
    }
}

fn resolve_stream_key_alias(stream_or_event_type: &str) -> String {
    let Some(schema) = Settings::get_global_notification_schema().as_ref() else {
        return stream_or_event_type.to_string();
    };
    let event_schema = schema.get(stream_or_event_type).or_else(|| {
        schema.iter().find_map(|(event_type, schema)| {
            if event_type.eq_ignore_ascii_case(stream_or_event_type) {
                Some(schema)
            } else {
                None
            }
        })
    });
    let Some(event_schema) = event_schema else {
        return stream_or_event_type.to_string();
    };
    event_schema
        .topic
        .as_ref()
        .map(|topic| topic.base.clone())
        .unwrap_or_else(|| stream_or_event_type.to_string())
}

/// Wipe an entire stream
#[utoipa::path(
    delete,
    path = "/api/v1/admin/wipe/stream",
    tag = "admin",
    request_body = WipeStreamRequest,
    responses(
        (status = 200, description = "Stream wiped successfully", body = WipeResponse),
        (status = 401, description = "Missing or invalid credentials"),
        (status = 403, description = "Valid credentials but missing admin role"),
        (status = 404, description = "No stream by that name", body = WipeResponse),
        (status = 500, description = "Failed to wipe stream", body = WipeResponse),
        (status = 503, description = "Authentication service unavailable (direct mode)")
    ),
    security(
        ("bearer_jwt" = []),
        ("basic" = []),
    )
)]
pub async fn wipe_stream(
    backend: web::Data<Arc<dyn NotificationBackend>>,
    req: web::Json<WipeStreamRequest>,
    request_id: RequestId,
) -> ActixResult<HttpResponse> {
    let request_id_str = request_id.to_string();
    let resolved_stream_key = resolve_stream_key_alias(&req.stream_name);
    tracing::info!(
        service_name = SERVICE_NAME,
        service_version = SERVICE_VERSION,
        event_name = "admin.stream.wipe.requested",
        stream_name = %req.stream_name,
        stream_key = %resolved_stream_key,
        request_id = %request_id_str,
        "Received request to wipe stream"
    );

    match backend.wipe_stream(&resolved_stream_key).await {
        Ok(WipeStreamResult::Wiped) => {
            tracing::info!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "admin.stream.wipe.succeeded",
                stream_name = %req.stream_name,
                stream_key = %resolved_stream_key,
                request_id = %request_id_str,
                "Successfully wiped stream"
            );
            Ok(HttpResponse::Ok().json(WipeResponse {
                success: true,
                message: format!("Successfully wiped stream: {}", req.stream_name),
                request_id: request_id_str,
            }))
        }
        Ok(WipeStreamResult::NotFound) => {
            tracing::warn!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "admin.stream.wipe.not_found",
                stream_name = %req.stream_name,
                stream_key = %resolved_stream_key,
                request_id = %request_id_str,
                "Stream not found"
            );
            Ok(HttpResponse::NotFound().json(WipeResponse {
                success: false,
                message: format!(
                    "Stream not found: {}{}",
                    req.stream_name,
                    known_event_types_suffix()
                ),
                request_id: request_id_str,
            }))
        }
        Err(e) => {
            tracing::error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "admin.stream.wipe.failed",
                stream_name = %req.stream_name,
                stream_key = %resolved_stream_key,
                error = %e,
                request_id = %request_id_str,
                "Failed to wipe stream"
            );
            Ok(HttpResponse::InternalServerError().json(WipeResponse {
                success: false,
                message: format!("Failed to wipe stream: {}", e),
                request_id: request_id_str,
            }))
        }
    }
}

/// Wipe all data from all streams
#[utoipa::path(
    delete,
    path = "/api/v1/admin/wipe/all",
    tag = "admin",
    responses(
        (status = 200, description = "All data wiped successfully", body = WipeResponse),
        (status = 401, description = "Missing or invalid credentials"),
        (status = 403, description = "Valid credentials but missing admin role"),
        (status = 500, description = "Failed to wipe all data", body = WipeResponse),
        (status = 503, description = "Authentication service unavailable (direct mode)")
    ),
    security(
        ("bearer_jwt" = []),
        ("basic" = []),
    )
)]

pub async fn wipe_all(
    backend: web::Data<Arc<dyn NotificationBackend>>,
    request_id: RequestId,
) -> ActixResult<HttpResponse> {
    let request_id_str = request_id.to_string();
    tracing::warn!(
        service_name = SERVICE_NAME,
        service_version = SERVICE_VERSION,
        event_name = "admin.all.wipe.requested",
        request_id = %request_id_str,
        "Received request to wipe ALL data - this will remove everything!"
    );

    match backend.wipe_all().await {
        Ok(()) => {
            tracing::warn!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "admin.all.wipe.succeeded",
                request_id = %request_id_str,
                "Successfully wiped ALL data from backend"
            );
            Ok(HttpResponse::Ok().json(WipeResponse {
                success: true,
                message: "Successfully wiped all data".to_string(),
                request_id: request_id_str,
            }))
        }
        Err(e) => {
            tracing::error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "admin.all.wipe.failed",
                error = %e,
                request_id = %request_id_str,
                "Failed to wipe all data"
            );
            Ok(HttpResponse::InternalServerError().json(WipeResponse {
                success: false,
                message: format!("Failed to wipe all data: {}", e),
                request_id: request_id_str,
            }))
        }
    }
}

/// Delete one notification by `<stream_or_event_type>@<sequence>`
#[utoipa::path(
    delete,
    path = "/api/v1/admin/notification/{notification_id}",
    tag = "admin",
    params(
        ("notification_id" = String, Path, description = "Notification identifier in the form '<stream_or_event_type>@<sequence>'")
    ),
    responses(
        (status = 200, description = "Notification deleted", body = DeleteNotificationResponse),
        (status = 400, description = "Invalid notification ID format", body = DeleteNotificationResponse),
        (status = 401, description = "Missing or invalid credentials"),
        (status = 403, description = "Valid credentials but missing admin role"),
        (status = 404, description = "Notification not found", body = DeleteNotificationResponse),
        (status = 500, description = "Delete operation failed", body = DeleteNotificationResponse),
        (status = 503, description = "Authentication service unavailable (direct mode)")
    ),
    security(
        ("bearer_jwt" = []),
        ("basic" = []),
    )
)]
pub async fn delete_notification(
    backend: web::Data<Arc<dyn NotificationBackend>>,
    path: web::Path<String>,
    request_id: RequestId,
) -> ActixResult<HttpResponse> {
    let request_id_str = request_id.to_string();
    let raw_id = path.into_inner();
    let parsed = match parse_notification_id(&raw_id) {
        Ok(parsed) => parsed,
        Err(message) => {
            tracing::warn!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "admin.notification.delete.invalid_id",
                notification_id = %raw_id,
                request_id = %request_id_str,
                "Invalid notification ID format"
            );
            return Ok(HttpResponse::BadRequest().json(DeleteNotificationResponse {
                success: false,
                message: message.to_string(),
                notification_id: raw_id,
                request_id: request_id_str,
            }));
        }
    };
    let resolved_stream_key = resolve_stream_key_alias(&parsed.stream_key);

    match backend
        .delete_message(&resolved_stream_key, parsed.sequence)
        .await
    {
        Ok(DeleteMessageResult::Deleted) => {
            tracing::info!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "admin.notification.delete.succeeded",
                notification_id = %raw_id,
                stream_key = %resolved_stream_key,
                sequence = parsed.sequence,
                request_id = %request_id_str,
                "Deleted notification"
            );
            Ok(HttpResponse::Ok().json(DeleteNotificationResponse {
                success: true,
                message: "Notification deleted".to_string(),
                notification_id: raw_id,
                request_id: request_id_str,
            }))
        }
        Ok(DeleteMessageResult::NotFound) => {
            tracing::warn!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "admin.notification.delete.not_found",
                notification_id = %raw_id,
                stream_key = %resolved_stream_key,
                sequence = parsed.sequence,
                request_id = %request_id_str,
                "Notification not found"
            );
            Ok(HttpResponse::NotFound().json(DeleteNotificationResponse {
                success: false,
                message: "Notification not found".to_string(),
                notification_id: raw_id,
                request_id: request_id_str,
            }))
        }
        Err(error) => {
            tracing::error!(
                service_name = SERVICE_NAME,
                service_version = SERVICE_VERSION,
                event_name = "admin.notification.delete.failed",
                notification_id = %raw_id,
                stream_key = %resolved_stream_key,
                sequence = parsed.sequence,
                error = %error,
                request_id = %request_id_str,
                "Failed to delete notification"
            );
            Ok(
                HttpResponse::InternalServerError().json(DeleteNotificationResponse {
                    success: false,
                    message: format!("Failed to delete notification: {error}"),
                    notification_id: raw_id,
                    request_id: request_id_str,
                }),
            )
        }
    }
}

#[cfg(test)]
mod tests {
    use super::parse_notification_id;

    #[test]
    fn parses_valid_notification_id() {
        let parsed = parse_notification_id("test_polygon@42").expect("valid id should parse");
        assert_eq!(parsed.stream_key, "test_polygon");
        assert_eq!(parsed.sequence, 42);
    }

    #[test]
    fn rejects_missing_separator() {
        let error = parse_notification_id("test_polygon42").expect_err("must fail");
        assert_eq!(
            error,
            "notification_id must be in '<stream>@<sequence>' format"
        );
    }

    #[test]
    fn rejects_zero_sequence() {
        let error = parse_notification_id("test_polygon@0").expect_err("must fail");
        assert_eq!(error, "notification_id sequence must be greater than zero");
    }
}