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
use std::collections::BTreeMap;

use k8s_openapi::{
    api::core::v1::{ResourceRequirements, Volume, VolumeMount},
    apimachinery::pkg::api::resource::Quantity,
};

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

pub const COMPONENT_NAME: &str = "appService";

/// StorageConfig is used to configure the storage for the appService.
/// This uses the `Volume` and `VolumeMount` types from the Kubernetes API.
///
/// See the [Kubernetes docs](https://kubernetes.io/docs/concepts/storage/volumes/).
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct StorageConfig {
    pub volumes: Option<Vec<Volume>>,
    #[serde(rename = "volumeMounts")]
    pub volume_mounts: Option<Vec<VolumeMount>>,
}

/// AppService significantly extends the functionality of your Tembo Postgres
/// instance by running tools and software built by the Postgres open source community.
///
/// **Example**: This will configure and install a Postgrest container along side
/// the Postgres instance, install pg_graphql extension, and configure the
/// ingress routing to expose the Postgrest service.
///
/// ```yaml
/// apiVersion: coredb.io/v1alpha1
/// kind: CoreDB
/// metadata:
///   name: test-db
/// spec:
///   trunk_installs:
///     - name: pg_graphql
///       version: 1.2.0
///   extensions:
///     - name: pg_graphql
///       locations:
///       - database: postgres
///         enabled: true
///  
///   appServices:
///     - name: postgrest
///       image: postgrest/postgrest:v10.0.0
///       routing:
///       # only expose /rest/v1 and /graphql/v1
///         - port: 3000
///           ingressPath: /rest/v1
///           middlewares:
///             - my-headers
///         - port: 3000
///           ingressPath: /graphql/v1
///           middlewares:
///             - map-gql
///             - my-headers
///       middlewares:
///         - customRequestHeaders:
///           name: my-headers
///           config:
///             # removes auth header from request
///             Authorization: ""
///             Content-Profile: graphql
///             Accept-Profile: graphql
///         - stripPrefix:
///           name: my-strip-prefix
///           config:
///             - /rest/v1
///         # reroute gql and rest requests
///         - replacePathRegex:
///           name: map-gql
///           config:
///             regex: \/graphql\/v1\/?
///             replacement: /rpc/resolve
///       env:
///         - name: PGRST_DB_URI
///           valueFromPlatform: ReadWriteConnection
///         - name: PGRST_DB_SCHEMA
///           value: "public, graphql"
///         - name: PGRST_DB_ANON_ROLE
///           value: postgres
///         - name: PGRST_LOG_LEVEL
///           value: info
/// ```
#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct AppService {
    /// Defines the name of the appService.
    pub name: String,

    /// Defines the container image to use for the appService.
    pub image: String,

    /// Defines the arguments to pass into the container if needed.
    /// You define this in the same manner as you would for all Kubernetes containers.
    /// See the [Kubernetes docs](https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container).
    pub args: Option<Vec<String>>,

    /// Defines the command into the container if needed.
    /// You define this in the same manner as you would for all Kubernetes containers.
    /// See the [Kubernetes docs](https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container).
    pub command: Option<Vec<String>>,

    /// Defines the environment variables to pass into the container if needed.
    /// You define this in the same manner as you would for all Kubernetes containers.
    /// See the [Kubernetes docs](https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container).
    pub env: Option<Vec<EnvVar>>,

    /// Defines the resources to allocate to the container.
    /// You define this in the same manner as you would for all Kubernetes containers.
    /// See the [Kubernetes docs](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/).
    #[serde(default = "default_resources")]
    pub resources: ResourceRequirements,

    /// Defines the probes to use for the container.
    /// You define this in the same manner as you would for all Kubernetes containers.
    /// See the [Kubernetes docs](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/).
    pub probes: Option<Probes>,

    /// Defines the ingress middeware configuration for the appService.
    /// This is specifically configured for the ingress controller Traefik.
    pub middlewares: Option<Vec<Middleware>>,

    /// Defines the routing configuration for the appService.
    pub routing: Option<Vec<Routing>>,

    /// Defines the storage configuration for the appService.
    pub storage: Option<StorageConfig>,
}

pub fn default_resources() -> ResourceRequirements {
    let limits: BTreeMap<String, Quantity> = BTreeMap::from([
        ("cpu".to_owned(), Quantity("400m".to_string())),
        ("memory".to_owned(), Quantity("256Mi".to_string())),
    ]);
    let requests: BTreeMap<String, Quantity> = BTreeMap::from([
        ("cpu".to_owned(), Quantity("100m".to_string())),
        ("memory".to_owned(), Quantity("256Mi".to_string())),
    ]);
    ResourceRequirements {
        limits: Some(limits),
        requests: Some(requests),
    }
}

// Secrets are injected into the container as environment variables
// ths allows users to map these secrets to environment variable of their choice
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct EnvVar {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
    #[serde(rename = "valueFromPlatform", skip_serializing_if = "Option::is_none")]
    pub value_from_platform: Option<EnvVarRef>,
}

// we will map these from secrets to env vars, if desired
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub enum EnvVarRef {
    ReadOnlyConnection,
    ReadWriteConnection,
}

/// Routing is used if there is a routing port, then a service is created using
/// that Port when ingress_path is present, an ingress is created. Otherwise, no
/// ingress is created
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema, JsonSchema)]
pub struct Routing {
    pub port: u16,
    #[serde(rename = "ingressPath")]
    pub ingress_path: Option<String>,

    /// provide name of the middleware resources to apply to this route
    pub middlewares: Option<Vec<String>>,
    #[serde(rename = "entryPoints")]
    #[serde(default = "default_entry_points")]
    pub entry_points: Option<Vec<String>>,
    #[serde(rename = "ingressType")]
    #[serde(default = "default_ingress_type")]
    pub ingress_type: Option<IngressType>,
}

#[allow(non_camel_case_types)]
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema, JsonSchema)]
pub enum IngressType {
    http,
    tcp,
}

pub fn default_ingress_type() -> Option<IngressType> {
    Some(IngressType::http)
}

pub fn default_entry_points() -> Option<Vec<String>> {
    Some(vec!["websecure".to_owned()])
}

/// Probes are used to determine the health of a container.
/// You define this in the same manner as you would for all Kubernetes containers.
/// See the [Kubernetes docs](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/).
#[allow(non_snake_case)]
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct Probes {
    pub readiness: Probe,
    pub liveness: Probe,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct Probe {
    pub path: String,
    pub port: i32,
    // this should never be negative
    #[serde(rename = "initialDelaySeconds")]
    pub initial_delay_seconds: u32,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct Ingress {
    pub enabled: bool,
    pub path: Option<String>,
}

/// Midddleware is used to configure the middleware for the appService.
/// This is specifically configured for the ingress controller Traefik.
///
/// Please refer to the example in the `AppService` documentation.
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub enum Middleware {
    #[serde(rename = "customRequestHeaders")]
    CustomRequestHeaders(HeaderConfig),
    #[serde(rename = "stripPrefix")]
    StripPrefix(StripPrefixConfig),
    #[serde(rename = "replacePathRegex")]
    ReplacePathRegex(ReplacePathRegexConfig),
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct HeaderConfig {
    pub name: String,
    #[schemars(schema_with = "preserve_arbitrary")]
    pub config: BTreeMap<String, String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct StripPrefixConfig {
    pub name: String,
    pub config: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct ReplacePathRegexConfig {
    pub name: String,
    pub config: ReplacePathRegexConfigType,
}

#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, JsonSchema, PartialEq)]
pub struct ReplacePathRegexConfigType {
    pub regex: String,
    pub replacement: String,
}

// source: https://github.com/kube-rs/kube/issues/844
fn preserve_arbitrary(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
    let mut obj = schemars::schema::SchemaObject::default();
    obj.extensions
        .insert("x-kubernetes-preserve-unknown-fields".into(), true.into());
    schemars::schema::Schema::Object(obj)
}

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

    #[test]
    fn test_middleware_config() {
        let middleware = serde_json::json!([
        {
            "customRequestHeaders": {
                "name": "my-custom-headers",
                "config":
                    {
                        //remove a header
                        "Authorization": "",
                        // add a header
                        "My-New-Header": "yolo"
                    }
            },
        },
        {
            "stripPrefix": {
                "name": "strip-my-prefix",
                "config": [
                    "/removeMe"
                ]
            },
        },
        {
            "replacePathRegex": {
                "name": "replace-my-regex",
                "config":
                    {
                        "regex": "/replace/me",
                        "replacement": "/with/me"
                    }
            },
        }
        ]);

        let mws = serde_json::from_value::<Vec<Middleware>>(middleware).unwrap();
        for mw in mws {
            match mw {
                Middleware::CustomRequestHeaders(mw) => {
                    assert_eq!(mw.name, "my-custom-headers");
                    assert_eq!(mw.config["My-New-Header"], "yolo");
                    assert_eq!(mw.config["Authorization"], "");
                }
                Middleware::StripPrefix(mw) => {
                    assert_eq!(mw.name, "strip-my-prefix");
                    assert_eq!(mw.config[0], "/removeMe");
                }
                Middleware::ReplacePathRegex(mw) => {
                    assert_eq!(mw.name, "replace-my-regex");
                    assert_eq!(mw.config.regex, "/replace/me");
                    assert_eq!(mw.config.replacement, "/with/me");
                }
            }
        }

        // malformed middlewares
        let unsupported_mw = serde_json::json!({
            "unsupportedMiddlewareType": {
                "name": "my-custom-headers",
                "config":
                    {
                        //remove a header
                        "Authorization": "",
                        // add a header
                        "My-New-Header": "yolo"
                    }
            },
        });
        let failed = serde_json::from_value::<Middleware>(unsupported_mw);
        assert!(failed.is_err());

        // provide a supported middleware but with malformed configuration
        let supported_bad_config = serde_json::json!({
            "replacePath": {
                "name": "my-custom-headers",
                "config":
                    {
                        "replacePath": "expects_a_vec<string>",
                    }
            },
        });
        let failed = serde_json::from_value::<Middleware>(supported_bad_config);
        assert!(failed.is_err());
    }
}