aviso-server 0.6.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// (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.

//! HTTP-facing error model for the Aviso API.

use crate::handlers::RequestParseError;
use crate::notification::decode_subject_for_display;
use crate::telemetry::{SERVICE_NAME, SERVICE_VERSION};
use actix_web::{HttpResponse, ResponseError, http::StatusCode};
use serde_json::json;
use thiserror::Error;
use tracing::{error, warn};

/// Stable machine-readable API error codes.
///
/// These values are part of the external HTTP contract and should be treated
/// as stable once released.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApiErrorCode {
    InvalidJson,
    UnknownField,
    InvalidRequestShape,
    InvalidNotificationRequest,
    InvalidWatchRequest,
    InvalidReplayRequest,
    NotificationProcessingFailed,
    NotificationStorageFailed,
    SseStreamInitializationFailed,
    InternalError,
}

impl ApiErrorCode {
    pub fn as_str(self) -> &'static str {
        match self {
            ApiErrorCode::InvalidJson => "INVALID_JSON",
            ApiErrorCode::UnknownField => "UNKNOWN_FIELD",
            ApiErrorCode::InvalidRequestShape => "INVALID_REQUEST_SHAPE",
            ApiErrorCode::InvalidNotificationRequest => "INVALID_NOTIFICATION_REQUEST",
            ApiErrorCode::InvalidWatchRequest => "INVALID_WATCH_REQUEST",
            ApiErrorCode::InvalidReplayRequest => "INVALID_REPLAY_REQUEST",
            ApiErrorCode::NotificationProcessingFailed => "NOTIFICATION_PROCESSING_FAILED",
            ApiErrorCode::NotificationStorageFailed => "NOTIFICATION_STORAGE_FAILED",
            ApiErrorCode::SseStreamInitializationFailed => "SSE_STREAM_INITIALIZATION_FAILED",
            ApiErrorCode::InternalError => "INTERNAL_ERROR",
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum RequestKind {
    Notification,
    Watch,
    Replay,
}

impl RequestKind {
    // Request kind drives a single 4xx code family per endpoint to keep client
    // handling predictable even when validation rules evolve.
    fn code(self) -> ApiErrorCode {
        match self {
            RequestKind::Notification => ApiErrorCode::InvalidNotificationRequest,
            RequestKind::Watch => ApiErrorCode::InvalidWatchRequest,
            RequestKind::Replay => ApiErrorCode::InvalidReplayRequest,
        }
    }

    fn label(self) -> &'static str {
        match self {
            RequestKind::Notification => "Invalid Notification Request",
            RequestKind::Watch => "Invalid Watch Request",
            RequestKind::Replay => "Invalid Replay Request",
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum ProcessingKind {
    NotificationProcessing,
    NotificationStorage,
}

impl ProcessingKind {
    fn code(self) -> ApiErrorCode {
        match self {
            ProcessingKind::NotificationProcessing => ApiErrorCode::NotificationProcessingFailed,
            ProcessingKind::NotificationStorage => ApiErrorCode::NotificationStorageFailed,
        }
    }

    fn label(self) -> &'static str {
        match self {
            ProcessingKind::NotificationProcessing => "Notification Processing Failed",
            ProcessingKind::NotificationStorage => "Notification Storage Failed",
        }
    }
}

#[derive(Debug, Error)]
pub enum ApiError {
    // Parse errors are syntactic/shape failures before domain validation.
    #[error("{error}")]
    Parse {
        code: ApiErrorCode,
        error: &'static str,
        request_id: String,
        #[source]
        source: RequestParseError,
    },
    #[error("{error}")]
    Validation {
        code: ApiErrorCode,
        error: &'static str,
        request_id: String,
        #[source]
        source: anyhow::Error,
    },
    #[error("{error}")]
    Processing {
        code: ApiErrorCode,
        error: &'static str,
        request_id: String,
        #[source]
        source: anyhow::Error,
    },
    #[error("SSE stream creation failed")]
    Sse {
        code: ApiErrorCode,
        topic: String,
        request_id: String,
        #[source]
        source: anyhow::Error,
    },
}

impl ApiError {
    // Parse error codes are determined by the parser variant, never by message text.
    fn parse(kind: RequestKind, source: RequestParseError, request_id: &str) -> Self {
        let code = match source {
            RequestParseError::InvalidJson(_) => ApiErrorCode::InvalidJson,
            RequestParseError::UnknownField(_) => ApiErrorCode::UnknownField,
            RequestParseError::InvalidShape(_) => ApiErrorCode::InvalidRequestShape,
        };

        Self::Parse {
            code,
            error: kind.label(),
            request_id: request_id.to_string(),
            source,
        }
    }

    fn validation(kind: RequestKind, source: anyhow::Error, request_id: &str) -> Self {
        Self::Validation {
            code: kind.code(),
            error: kind.label(),
            request_id: request_id.to_string(),
            source,
        }
    }

    fn processing(kind: ProcessingKind, source: anyhow::Error, request_id: &str) -> Self {
        Self::Processing {
            code: kind.code(),
            error: kind.label(),
            request_id: request_id.to_string(),
            source,
        }
    }

    fn sse(topic: &str, request_id: &str, source: anyhow::Error) -> Self {
        Self::Sse {
            code: ApiErrorCode::SseStreamInitializationFailed,
            topic: topic.to_string(),
            request_id: request_id.to_string(),
            source,
        }
    }
}

impl ResponseError for ApiError {
    fn status_code(&self) -> StatusCode {
        match self {
            ApiError::Parse { .. } | ApiError::Validation { .. } => StatusCode::BAD_REQUEST,
            ApiError::Processing { .. } | ApiError::Sse { .. } => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }

    fn error_response(&self) -> HttpResponse {
        match self {
            ApiError::Parse {
                code,
                error: error_label,
                request_id,
                source,
            } => {
                let message = source.to_string();
                warn!(
                    service_name = SERVICE_NAME,
                    service_version = SERVICE_VERSION,
                    event_name = "api.request.parse.failed",
                    outcome = "error",
                    error_code = code.as_str(),
                    error = %error_label,
                    // Keep both stable type and human message for query + debugging.
                    error_type = %error_label,
                    error_message = %message,
                    details = %message,
                    "Request parsing failed"
                );
                HttpResponse::build(self.status_code()).json(json!({
                    "code": code.as_str(),
                    "error": error_label,
                    "message": message,
                    "details": message,
                    "request_id": request_id,
                }))
            }
            ApiError::Validation {
                code,
                error: error_label,
                request_id,
                source,
            } => {
                let (message, details, chain) = error_summary(source);
                warn!(
                    service_name = SERVICE_NAME,
                    service_version = SERVICE_VERSION,
                    event_name = "api.request.validation.failed",
                    outcome = "error",
                    error_code = code.as_str(),
                    error = %error_label,
                    // `error_type` is stable across deployments; `error_message` carries context.
                    error_type = %error_label,
                    error_message = %message,
                    error_chain = ?chain,
                    "Request validation failed"
                );
                HttpResponse::build(self.status_code()).json(json!({
                    "code": code.as_str(),
                    "error": error_label,
                    "message": message,
                    "details": details,
                    "request_id": request_id,
                }))
            }
            ApiError::Processing {
                code,
                error: error_label,
                request_id,
                source,
            } => {
                let (message, details, chain) = error_summary(source);
                error!(
                    service_name = SERVICE_NAME,
                    service_version = SERVICE_VERSION,
                    event_name = "api.request.processing.failed",
                    outcome = "error",
                    error_code = code.as_str(),
                    error = %error_label,
                    // Emit machine-friendly type and operator-friendly message together.
                    error_type = %error_label,
                    error_message = %message,
                    error_chain = ?chain,
                    "Request processing failed"
                );
                HttpResponse::build(self.status_code()).json(json!({
                    "code": code.as_str(),
                    "error": error_label,
                    "message": message,
                    "details": details,
                    "request_id": request_id,
                }))
            }
            ApiError::Sse {
                code,
                topic,
                request_id,
                source,
            } => {
                let (message, details, chain) = error_summary(source);
                let display_topic = decode_subject_for_display(topic);
                error!(
                    service_name = SERVICE_NAME,
                    service_version = SERVICE_VERSION,
                    event_name = "stream.sse.initialization.failed",
                    outcome = "error",
                    error_code = code.as_str(),
                    // SSE failures use a fixed type plus the concrete failure message.
                    error_type = "SSE stream creation failed",
                    error_message = %message,
                    error_chain = ?chain,
                    topic = %display_topic,
                    request_id = request_id,
                    "SSE stream creation failed"
                );
                HttpResponse::build(self.status_code()).json(json!({
                    "code": code.as_str(),
                    "error": "SSE stream creation failed",
                    "message": message,
                    "details": details,
                    "topic": display_topic,
                    "request_id": request_id,
                }))
            }
        }
    }
}

fn error_summary(error: &anyhow::Error) -> (String, String, Vec<String>) {
    // Keep response payloads stable: first chain item is the user-facing message,
    // last item is the deepest detail, full chain is logged for operators.
    let chain = error
        .chain()
        .map(ToString::to_string)
        .collect::<Vec<String>>();
    let message = chain
        .first()
        .cloned()
        .unwrap_or_else(|| "Unknown error".to_string());
    let details = chain.last().cloned().unwrap_or_else(|| message.clone());
    (message, details, chain)
}

pub fn request_parse_error_response(
    kind: RequestKind,
    error: RequestParseError,
    request_id: &str,
) -> HttpResponse {
    ApiError::parse(kind, error, request_id).error_response()
}

pub fn request_validation_error_response(
    kind: RequestKind,
    error: anyhow::Error,
    request_id: &str,
) -> HttpResponse {
    ApiError::validation(kind, error, request_id).error_response()
}

pub fn processing_error_response(
    kind: ProcessingKind,
    error: anyhow::Error,
    request_id: &str,
) -> HttpResponse {
    ApiError::processing(kind, error, request_id).error_response()
}

pub fn sse_error_response(error: anyhow::Error, topic: &str, request_id: &str) -> HttpResponse {
    ApiError::sse(topic, request_id, error).error_response()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::handlers::RequestParseError;
    use actix_web::body::to_bytes;
    use anyhow::anyhow;
    use serde_json::{Value, json};

    async fn response_json(response: HttpResponse) -> Value {
        let body = response.into_body();
        let bytes = to_bytes(body)
            .await
            .expect("response body should be readable");
        serde_json::from_slice(&bytes).expect("response should be valid json")
    }

    const TEST_REQUEST_ID: &str = "req-test-1234";

    #[test]
    fn parse_error_uses_specific_code_for_json() {
        let parse_error = RequestParseError::InvalidJson(
            serde_json::from_slice::<serde_json::Value>(b"{").expect_err("must fail"),
        );

        let response =
            ApiError::parse(RequestKind::Replay, parse_error, TEST_REQUEST_ID).error_response();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn validation_error_maps_to_bad_request() {
        let response = ApiError::validation(
            RequestKind::Watch,
            anyhow!("from_id must be positive"),
            TEST_REQUEST_ID,
        )
        .error_response();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn processing_error_maps_to_internal_server_error() {
        let response = ApiError::processing(
            ProcessingKind::NotificationStorage,
            anyhow!("failed to write to backend"),
            TEST_REQUEST_ID,
        )
        .error_response();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn sse_error_maps_to_internal_server_error() {
        let response = ApiError::sse("test.topic", "request-1", anyhow!("stream setup failed"))
            .error_response();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[actix_web::test]
    async fn parse_error_body_has_stable_shape_and_code() {
        let parse_error = RequestParseError::InvalidJson(
            serde_json::from_slice::<serde_json::Value>(b"{").expect_err("must fail"),
        );
        let response =
            request_parse_error_response(RequestKind::Replay, parse_error, TEST_REQUEST_ID);
        let json = response_json(response).await;

        assert_eq!(json["code"], "INVALID_JSON");
        assert_eq!(json["error"], "Invalid Replay Request");
        assert!(json["message"].is_string());
        assert!(json["details"].is_string());
        assert_eq!(json["request_id"], TEST_REQUEST_ID);
    }

    #[actix_web::test]
    async fn parse_error_maps_unknown_field_and_shape_codes() {
        let unknown_field_response = request_parse_error_response(
            RequestKind::Watch,
            RequestParseError::UnknownField(anyhow!("Unknown field 'foo' in request")),
            TEST_REQUEST_ID,
        );
        let unknown_field_json = response_json(unknown_field_response).await;
        assert_eq!(unknown_field_json["code"], "UNKNOWN_FIELD");
        assert_eq!(unknown_field_json["request_id"], TEST_REQUEST_ID);

        let invalid_shape_source =
            serde_json::from_value::<std::collections::HashMap<String, String>>(json!(1))
                .expect_err("must fail to create invalid shape error");
        let invalid_shape_response = request_parse_error_response(
            RequestKind::Notification,
            RequestParseError::InvalidShape(invalid_shape_source),
            TEST_REQUEST_ID,
        );
        let invalid_shape_json = response_json(invalid_shape_response).await;
        assert_eq!(invalid_shape_json["code"], "INVALID_REQUEST_SHAPE");
        assert_eq!(invalid_shape_json["request_id"], TEST_REQUEST_ID);
    }

    #[actix_web::test]
    async fn validation_error_body_has_stable_shape() {
        let response = request_validation_error_response(
            RequestKind::Watch,
            anyhow!("Cannot specify both identifier.polygon and identifier.point"),
            TEST_REQUEST_ID,
        );
        let json = response_json(response).await;

        assert_eq!(json["code"], "INVALID_WATCH_REQUEST");
        assert_eq!(json["error"], "Invalid Watch Request");
        assert!(json["message"].is_string());
        assert!(json["details"].is_string());
        assert_eq!(json["request_id"], TEST_REQUEST_ID);
        assert!(json.get("error_chain").is_none());
    }

    #[actix_web::test]
    async fn processing_and_sse_errors_have_expected_contract() {
        let processing_response = processing_error_response(
            ProcessingKind::NotificationStorage,
            anyhow!("backend write failed"),
            TEST_REQUEST_ID,
        );
        let processing_json = response_json(processing_response).await;
        assert_eq!(processing_json["code"], "NOTIFICATION_STORAGE_FAILED");
        assert_eq!(processing_json["error"], "Notification Storage Failed");
        assert_eq!(processing_json["request_id"], TEST_REQUEST_ID);

        let sse_response =
            sse_error_response(anyhow!("stream setup failed"), "mars.ens%2Emember", "req-1");
        let sse_json = response_json(sse_response).await;
        assert_eq!(sse_json["code"], "SSE_STREAM_INITIALIZATION_FAILED");
        assert_eq!(sse_json["error"], "SSE stream creation failed");
        assert_eq!(sse_json["request_id"], "req-1");
        assert_eq!(sse_json["topic"], "mars.ens.member");
    }

    #[test]
    fn api_error_code_strings_are_stable() {
        assert_eq!(ApiErrorCode::InvalidJson.as_str(), "INVALID_JSON");
        assert_eq!(
            ApiErrorCode::InvalidReplayRequest.as_str(),
            "INVALID_REPLAY_REQUEST"
        );
        assert_eq!(
            ApiErrorCode::SseStreamInitializationFailed.as_str(),
            "SSE_STREAM_INITIALIZATION_FAILED"
        );
    }
}