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
//! PagerDuty related models.
//!
//! A PagerDuty receiver is a resource that is defined in Fiberplane. It works
//! unison with a PagerDuty webhook, which is defined in PagerDuty. A PagerDuty
//! webhook will have its target URL set to the receiver.
//!
//! Once a incident is created in PagerDuty, PagerDuty will send a webhook to a
//! webhook receiver. Depending on the configuration of the receiver this will
//! create a new notebook based on a template, it can also update any
//! front-matter values defined in any notebook.
//!
//! A shared security-key should be set in the PagerDuty webhook customer header
//! which will verified by Fiberplane. If the security-key does not match, the
//! request will be dropped. The header should be <..> and contain the
//! security-key as-is.

use crate::auth::AuthError;
use crate::names::Name;
use crate::sorting::SortField;
use crate::timestamps::Timestamp;
use serde::{Deserialize, Serialize};
use strum_macros::IntoStaticStr;
use thiserror::Error;
use typed_builder::TypedBuilder;

#[cfg(feature = "fp-bindgen")]
use fp_bindgen::prelude::Serializable;

#[cfg(feature = "axum_06")]
use {
    axum_06::http::StatusCode,
    axum_06::response::{IntoResponse, Response},
};

/// A new PagerDuty receiver. This will be used in the create endpoint.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, TypedBuilder)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct NewPagerDutyReceiver {
    /// A reference to a template that will be expanded when a incident is
    /// created. If this is empty then no template will be expanded.
    #[builder(default, setter())]
    pub incident_created_template_name: Option<Name>,
}

/// PagerDutyReceiver represents a single PagerDuty receiver in Fiberplane.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, TypedBuilder)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct PagerDutyReceiver {
    /// Unique identifier for the PagerDuty receiver for a workspace.
    pub name: Name,

    /// A reference to a template that will be expanded when a incident is
    /// created. If this is empty then no template will be expanded.
    #[builder(default, setter())]
    pub incident_created_template_name: Option<Name>,

    /// A shared security-key that should be set in the PagerDuty webhook
    /// customer header.
    pub security_key: String,

    /// The URL that should be set in the PagerDuty webhook.
    pub webhook_url: String,

    /// Timestamp that the PagerDuty receiver was created.
    #[builder(setter(into))]
    pub created_at: Timestamp,

    /// Timestamp that the PagerDuty receiver was last updated.
    #[builder(setter(into))]
    pub updated_at: Timestamp,
}

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, TypedBuilder)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct UpdatePagerDutyReceiver {
    /// A reference to a template that will be expanded when a incident is
    /// created. If this is empty then no template will be expanded.
    #[builder(default, setter())]
    #[serde(
        default,
        deserialize_with = "crate::deserialize_some",
        skip_serializing_if = "Option::is_none"
    )]
    pub incident_created_template_name: Option<Option<Name>>,

    /// If this value is set to true, then a new random security-key will be
    /// generated. This new value will be part of the response.
    #[builder(default, setter())]
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub regenerate_security_key: bool,
}

/// Errors that can occur when creating a new PagerDuty receiver.
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Error)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::pagerduty")
)]
#[non_exhaustive]
#[serde(tag = "error", rename_all = "snake_case")]
pub enum PagerDutyReceiverCreateError {
    #[error("Name of the PagerDuty receiver is already in use")]
    DuplicateName,

    #[error("Referenced creation template does not exist")]
    CreationTemplateNotFound,

    #[error("Unknown error occurred")]
    InternalServerError,

    /// Common auth errors.
    #[serde(untagged)]
    #[error(transparent)]
    Auth(AuthError),
}

impl From<AuthError> for PagerDutyReceiverCreateError {
    fn from(value: AuthError) -> Self {
        PagerDutyReceiverCreateError::Auth(value)
    }
}

#[cfg(feature = "axum_06")]
impl IntoResponse for PagerDutyReceiverCreateError {
    fn into_response(self) -> Response {
        let body = serde_json::to_string(&self).expect("should never fail!");
        let status_code = match self {
            PagerDutyReceiverCreateError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
            PagerDutyReceiverCreateError::CreationTemplateNotFound => StatusCode::BAD_REQUEST,
            PagerDutyReceiverCreateError::Auth(AuthError::Unauthenticated) => {
                StatusCode::UNAUTHORIZED
            }
            PagerDutyReceiverCreateError::Auth(AuthError::Unauthorized) => StatusCode::FORBIDDEN,
            PagerDutyReceiverCreateError::DuplicateName => StatusCode::BAD_REQUEST,
        };

        (status_code, body).into_response()
    }
}

/// Errors that can occur when retrieving a PagerDuty receiver.
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Error)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::pagerduty")
)]
#[non_exhaustive]
#[serde(tag = "error", rename_all = "snake_case")]
pub enum PagerDutyReceiverGetError {
    #[error("PagerDuty receiver not found")]
    NotFound,

    #[error("Unknown error occurred")]
    InternalServerError,

    /// Common auth errors.
    #[serde(untagged)]
    #[error(transparent)]
    Auth(AuthError),
}

impl From<AuthError> for PagerDutyReceiverGetError {
    fn from(value: AuthError) -> Self {
        PagerDutyReceiverGetError::Auth(value)
    }
}

#[cfg(feature = "axum_06")]
impl IntoResponse for PagerDutyReceiverGetError {
    fn into_response(self) -> Response {
        let body = serde_json::to_string(&self).expect("should never fail!");
        let status_code = match self {
            PagerDutyReceiverGetError::NotFound => StatusCode::NOT_FOUND,
            PagerDutyReceiverGetError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
            PagerDutyReceiverGetError::Auth(AuthError::Unauthenticated) => StatusCode::UNAUTHORIZED,
            PagerDutyReceiverGetError::Auth(AuthError::Unauthorized) => StatusCode::FORBIDDEN,
        };

        (status_code, body).into_response()
    }
}

/// Errors that can occur when updating a PagerDuty receiver.
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Error)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::pagerduty")
)]
#[non_exhaustive]
#[serde(tag = "error", rename_all = "snake_case")]
pub enum PagerDutyReceiverUpdateError {
    #[error("PagerDuty receiver not found")]
    NotFound,

    #[error("Referenced creation template does not exist")]
    CreationTemplateNotFound,

    #[error("Unknown error occurred")]
    InternalServerError,

    /// Common auth errors.
    #[serde(untagged)]
    #[error(transparent)]
    Auth(AuthError),
}

impl From<AuthError> for PagerDutyReceiverUpdateError {
    fn from(value: AuthError) -> Self {
        PagerDutyReceiverUpdateError::Auth(value)
    }
}

#[cfg(feature = "axum_06")]
impl IntoResponse for PagerDutyReceiverUpdateError {
    fn into_response(self) -> Response {
        let body = serde_json::to_string(&self).expect("should never fail!");
        let status_code = match self {
            PagerDutyReceiverUpdateError::NotFound => StatusCode::NOT_FOUND,
            PagerDutyReceiverUpdateError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
            PagerDutyReceiverUpdateError::CreationTemplateNotFound => StatusCode::BAD_REQUEST,
            PagerDutyReceiverUpdateError::Auth(AuthError::Unauthenticated) => {
                StatusCode::UNAUTHORIZED
            }
            PagerDutyReceiverUpdateError::Auth(AuthError::Unauthorized) => StatusCode::FORBIDDEN,
        };

        (status_code, body).into_response()
    }
}

/// Errors that can occur when deleting a PagerDuty receiver.
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Error)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::pagerduty")
)]
#[non_exhaustive]
#[serde(tag = "error", rename_all = "snake_case")]
pub enum PagerDutyReceiverDeleteError {
    #[error("PagerDuty receiver not found")]
    NotFound,

    #[error("Unknown error occurred")]
    InternalServerError,

    /// Common auth errors.
    #[serde(untagged)]
    #[error(transparent)]
    Auth(AuthError),
}

impl From<AuthError> for PagerDutyReceiverDeleteError {
    fn from(value: AuthError) -> Self {
        PagerDutyReceiverDeleteError::Auth(value)
    }
}

#[cfg(feature = "axum_06")]
impl IntoResponse for PagerDutyReceiverDeleteError {
    fn into_response(self) -> Response {
        let body = serde_json::to_string(&self).expect("should never fail!");
        let status_code = match self {
            PagerDutyReceiverDeleteError::NotFound => StatusCode::NOT_FOUND,
            PagerDutyReceiverDeleteError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
            PagerDutyReceiverDeleteError::Auth(AuthError::Unauthenticated) => {
                StatusCode::UNAUTHORIZED
            }
            PagerDutyReceiverDeleteError::Auth(AuthError::Unauthorized) => StatusCode::FORBIDDEN,
        };

        (status_code, body).into_response()
    }
}

/// Errors that can occur when listing PagerDuty receivers.
#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Error)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::pagerduty")
)]
#[non_exhaustive]
#[serde(tag = "error", rename_all = "snake_case")]
pub enum PagerDutyReceiverListError {
    #[error("Unknown error occurred")]
    InternalServerError,

    /// Common auth errors.
    #[serde(untagged)]
    #[error(transparent)]
    Auth(AuthError),
}

impl From<AuthError> for PagerDutyReceiverListError {
    fn from(value: AuthError) -> Self {
        PagerDutyReceiverListError::Auth(value)
    }
}

#[cfg(feature = "axum_06")]
impl IntoResponse for PagerDutyReceiverListError {
    fn into_response(self) -> Response {
        let body = serde_json::to_string(&self).expect("should never fail!");
        let status_code = match self {
            PagerDutyReceiverListError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
            PagerDutyReceiverListError::Auth(AuthError::Unauthenticated) => {
                StatusCode::UNAUTHORIZED
            }
            PagerDutyReceiverListError::Auth(AuthError::Unauthorized) => StatusCode::FORBIDDEN,
        };

        (status_code, body).into_response()
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, IntoStaticStr)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::pagerduty")
)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PagerDutyReceiverListSortFields {
    Name,
    CreatedAt,
    UpdatedAt,
}

impl SortField for PagerDutyReceiverListSortFields {
    #[inline]
    fn default_sort_field() -> Self {
        Self::Name
    }
}