Skip to main content

che_rest/
module.rs

1use std::sync::Arc;
2
3use axum::{Json, Router, response::Html, routing::get};
4use che_orm::{Migration, MigrationError, ProjectState, SchemaObjectState, SchemaSet, StateChange};
5use serde_json::{Map, Value, json};
6
7use crate::{
8    AppError, AppResult, AppState, CrudViewSet, FilterSetSpec, Model, ModelSerializer, Permission,
9    SignalAccess, ViewAction, ViewSet, ViewSetConfig, openapi_column_schema,
10};
11
12pub trait AppModule: Send + Sync + 'static {
13    fn name(&self) -> &'static str;
14    fn schema(&self) -> SchemaSet;
15    /// Compiled migrations owned by this application, including portable
16    /// project modules. Legacy project registries may still be passed to Management.
17    fn migrations(&self) -> Vec<Migration> {
18        Vec::new()
19    }
20    /// Writable source directory for makemigrations. None denotes a library
21    /// application whose migration sources are not managed by this project.
22    fn migration_path(&self) -> Option<&'static str> {
23        None
24    }
25    /// Register server synchronization tables in the desired migration state.
26    /// Several modules may expose their registries; shared server metadata
27    /// tables are included once per database.
28    fn sync_registry(&self) -> Option<che_sync::Registry> {
29        None
30    }
31    /// Triggers and views owned by this application. Their `app` field is
32    /// assigned from [`Self::name`] while collecting migration state.
33    fn schema_objects(&self) -> Vec<SchemaObjectState> {
34        Vec::new()
35    }
36    fn init(&self, context: &mut ModuleContext);
37    fn subscribe(&self, _state: &AppState) {}
38    fn start(&self, _state: &AppState) {}
39    fn middleware(&self, router: Router, _state: &AppState) -> Router {
40        router
41    }
42    fn openapi(&self, _state: &AppState) -> Value {
43        json!({})
44    }
45}
46
47#[derive(Debug, Clone)]
48pub struct ApiEndpoint {
49    /// False for standalone actions without model CRUD.
50    pub crud: bool,
51    pub app_name: &'static str,
52    pub model_name: String,
53    pub resource: String,
54    pub fields: Vec<che_orm::SerializerField>,
55    pub list_fields: Vec<che_orm::SerializerField>,
56    pub columns: Vec<ApiColumn>,
57    pub filters: Vec<ApiFilter>,
58    pub extensions: Vec<crate::ApiExtension>,
59}
60
61#[derive(Debug, Clone)]
62pub struct ApiSignal {
63    pub name: String,
64    pub access: SignalAccess,
65}
66
67#[derive(Debug, Clone)]
68pub struct ApiColumn {
69    pub name: &'static str,
70    pub field_name: &'static str,
71    pub column_type: che_orm::ColumnType,
72    pub nullable: bool,
73    pub has_default: bool,
74    pub choices: Option<Vec<&'static str>>,
75}
76
77#[derive(Debug, Clone, Copy)]
78pub struct ApiFilter {
79    pub name: &'static str,
80    pub source: &'static str,
81    pub lookup: crate::Lookup,
82}
83
84#[derive(Default)]
85pub struct InstalledApps {
86    modules: Vec<Arc<dyn AppModule>>,
87}
88
89impl InstalledApps {
90    pub fn new() -> Self {
91        Self::default()
92    }
93
94    #[allow(clippy::should_implement_trait)]
95    pub fn add<M: AppModule>(mut self, module: M) -> Self {
96        self.modules.push(Arc::new(module));
97        self
98    }
99
100    pub fn iter(&self) -> impl Iterator<Item = &dyn AppModule> {
101        self.modules.iter().map(Arc::as_ref)
102    }
103
104    pub fn find(&self, name: &str) -> Option<&dyn AppModule> {
105        self.iter().find(|module| module.name() == name)
106    }
107
108    pub fn names(&self) -> impl Iterator<Item = &'static str> + '_ {
109        self.iter().map(AppModule::name)
110    }
111
112    /// Collects a migration-state snapshot without starting the server or
113    /// connecting to the database.
114    pub fn migration_state(&self) -> Result<ProjectState, MigrationError> {
115        let schemas: Vec<_> = self
116            .iter()
117            .map(|module| (module.name(), module.schema()))
118            .collect();
119        let mut state =
120            ProjectState::from_app_schemas(schemas.iter().map(|(name, schema)| (*name, schema)))?;
121        for module in self.iter() {
122            if let Some(registry) = module.sync_registry() {
123                registry.extend_migration_state(&mut state, che_orm::ModelRole::Server)?;
124            }
125            for mut object in module.schema_objects() {
126                object.app = module.name().into();
127                state.add_schema_object(object)?;
128            }
129        }
130        Ok(state)
131    }
132
133    /// Compares compiled migration history with the current installed models.
134    /// It is side-effect free and is the input to `makemigrations`.
135    pub fn migration_diff(
136        &self,
137        history: &ProjectState,
138    ) -> Result<Vec<StateChange>, MigrationError> {
139        history.diff(&self.migration_state()?)
140    }
141
142    /// Collects migrations owned by all installed applications. The name is
143    /// retained for compatibility with the original library-only API.
144    pub fn library_migrations(&self) -> Vec<Migration> {
145        self.iter().flat_map(AppModule::migrations).collect()
146    }
147
148    pub fn api_endpoints(&self, state: AppState) -> Vec<ApiEndpoint> {
149        let mut context = ModuleContext::new(state);
150        for module in self.iter() {
151            context.current_app = module.name();
152            module.init(&mut context);
153        }
154        context.api_endpoints
155    }
156
157    pub fn api_signals(&self, state: AppState) -> Vec<ApiSignal> {
158        let mut context = ModuleContext::new(state.clone());
159        for module in self.iter() {
160            context.current_app = module.name();
161            module.init(&mut context);
162        }
163        state
164            .signals()
165            .public_signals()
166            .into_iter()
167            .map(|(name, access)| ApiSignal { name, access })
168            .collect()
169    }
170}
171
172#[derive(Default)]
173pub struct ModuleContext {
174    state: Option<AppState>,
175    routers: Vec<Router>,
176    root_routers: Vec<Router>,
177    schemas: Vec<SchemaSet>,
178    openapi_paths: Map<String, Value>,
179    openapi_components: Map<String, Value>,
180    api_endpoints: Vec<ApiEndpoint>,
181    registration_errors: Vec<String>,
182    access_models: std::collections::HashMap<&'static str, &'static str>,
183    media_access: crate::media::MediaAccess,
184    current_app: &'static str,
185}
186
187impl ModuleContext {
188    fn new(state: AppState) -> Self {
189        Self {
190            state: Some(state),
191            ..Self::default()
192        }
193    }
194
195    pub fn route(&mut self, router: Router) {
196        self.routers.push(router);
197    }
198
199    /// Register standalone typed actions without mounting model CRUD.
200    pub fn actions<V: ViewSet>(&mut self, resource: &str, name: &str, config: ViewSetConfig<V>) {
201        let (router, extensions, schemas, _) = config.into_parts();
202        let document = crate::rest::extensions::extension_openapi(&extensions);
203        if let Some(paths) = document["paths"].as_object() {
204            self.openapi_paths.extend(paths.clone());
205        }
206        for schema in schemas {
207            self.openapi_components
208                .insert(schema.name.into(), schema.openapi);
209        }
210        self.api_endpoints.push(ApiEndpoint {
211            crud: false,
212            app_name: self.current_app,
213            model_name: name.into(),
214            resource: resource.into(),
215            fields: vec![],
216            list_fields: vec![],
217            columns: vec![],
218            filters: vec![],
219            extensions,
220        });
221        self.routers.push(router);
222    }
223
224    pub fn route_at_root(&mut self, router: Router) {
225        self.root_routers.push(router);
226    }
227
228    pub fn signal(&mut self, signal: impl Into<String>, access: SignalAccess) {
229        let state = self
230            .state
231            .as_ref()
232            .expect("module context is not initialized");
233        state.signals().declare(signal, access);
234    }
235
236    pub fn model<M: Model>(&mut self) {
237        self.schemas.push(SchemaSet::new().model::<M>());
238    }
239
240    pub fn viewset<M, S>(&mut self, viewset: CrudViewSet<M, S>)
241    where
242        M: Model<PrimaryKey: crate::rest::router::RestKey> + Send + Sync + 'static,
243        S: ModelSerializer<Model = M, Input = M>
244            + che_orm::ModelWriteSerializer<Model = M>
245            + serde::Serialize
246            + Send
247            + Sync
248            + 'static,
249    {
250        self.viewset_with(viewset);
251    }
252
253    pub fn viewset_with<V>(&mut self, viewset: V)
254    where
255        V: ViewSet,
256        V::Serializer: serde::Serialize,
257    {
258        let path = viewset.path();
259        let permission = V::Permission::default();
260        if let Some(key) = permission.model_access_key()
261            && let Some(previous) = self.access_models.insert(key, V::Model::table_name())
262            && previous != V::Model::table_name()
263        {
264            self.registration_errors.push(format!(
265                "ACL model key {key} is already assigned to {previous}"
266            ));
267            return;
268        }
269        if let Err(error) = permission
270            .validate(V::Serializer::fields())
271            .and_then(|_| permission.validate(V::ListSerializer::fields()))
272        {
273            self.registration_errors.push(error.to_string());
274            return;
275        }
276        if permission.object_scoped()
277            && [
278                ViewAction::Create,
279                ViewAction::Update,
280                ViewAction::Patch,
281                ViewAction::Delete,
282            ]
283            .iter()
284            .any(|action| viewset.signal_access(*action).is_some())
285        {
286            self.registration_errors.push("object permissions require recipient-aware signals; broad CRUD signals are not supported".into());
287            return;
288        }
289        let mut config = ViewSetConfig::<V>::new(path);
290        if let Err(error) = viewset.configure(&mut config) {
291            self.registration_errors.push(error.to_string());
292        }
293        let (extension_router, extensions, extension_schemas, hooks) = config.into_parts();
294        if permission.object_scoped()
295            && hooks
296                .iter()
297                .filter_map(|hook| hook.backend())
298                .any(|backend| !backend.object_permissions())
299        {
300            self.registration_errors.push("object permissions require a transaction-aware mutation backend; the configured backend does not support this contract".into());
301            return;
302        }
303
304        self.api_endpoints.push(ApiEndpoint {
305            crud: true,
306            app_name: self.current_app,
307            model_name: std::any::type_name::<V::Model>()
308                .rsplit("::")
309                .next()
310                .unwrap_or("Model")
311                .to_owned(),
312            resource: path.trim_matches('/').to_owned(),
313            fields: V::Serializer::fields().to_vec(),
314            list_fields: V::ListSerializer::fields().to_vec(),
315            columns: V::Model::schema()
316                .columns
317                .iter()
318                .map(|column| ApiColumn {
319                    name: column.name,
320                    field_name: column.field_name,
321                    column_type: column.column_type,
322                    nullable: column.nullable,
323                    has_default: column.default.is_some() || column.auto_now || column.auto_now_add,
324                    choices: column.choices.clone(),
325                })
326                .collect(),
327            filters: V::FilterSet::default()
328                .filters()
329                .iter()
330                .map(|filter| ApiFilter {
331                    name: filter.name,
332                    source: filter.source(),
333                    lookup: filter.lookup(),
334                })
335                .collect(),
336            extensions: extensions.clone(),
337        });
338        if let (Some(signal), Some(access)) = (
339            viewset.signal_name(ViewAction::Create),
340            viewset.signal_access(ViewAction::Create),
341        ) {
342            self.signal(signal, access);
343        }
344        if let (Some(signal), Some(access)) = (
345            viewset.signal_name(ViewAction::Update),
346            viewset.signal_access(ViewAction::Update),
347        ) {
348            self.signal(signal, access);
349        }
350        if let (Some(signal), Some(access)) = (
351            viewset.signal_name(ViewAction::Delete),
352            viewset.signal_access(ViewAction::Delete),
353        ) {
354            self.signal(signal, access);
355        }
356        let state = self
357            .state
358            .as_ref()
359            .expect("module context is not initialized");
360        let document = crate::rest::router::openapi_json_for_with_list::<V::Model, V::Serializer>(
361            path,
362            V::ListSerializer::fields(),
363        );
364        let mut document = document;
365        if extensions.iter().any(|extension| extension.id == "sync") {
366            crate::sync::add_rest_openapi(&mut document);
367        }
368        if extensions
369            .iter()
370            .any(|extension| extension.id == "model-sync")
371        {
372            crate::sync::add_model_rest_openapi(&mut document);
373        }
374        if extensions
375            .iter()
376            .any(|extension| extension.id == "object-sync")
377        {
378            crate::sync::add_object_rest_openapi(&mut document);
379        }
380        add_filter_parameters::<V>(&mut document, &viewset);
381        let model_schema = V::Model::schema();
382        let primary_key = model_schema
383            .columns
384            .iter()
385            .find(|column| column.primary_key)
386            .expect("model primary key");
387        let extension_openapi = crate::rest::extensions::extension_openapi_with_id_schema(
388            &extensions,
389            crate::rest::router::openapi_column_schema(primary_key),
390        );
391        if let Some(action_paths) = extension_openapi.get("paths").and_then(Value::as_object)
392            && let Some(paths) = document["paths"].as_object_mut()
393        {
394            for (path, item) in action_paths {
395                let target = paths.entry(path.clone()).or_insert_with(|| json!({}));
396                target
397                    .as_object_mut()
398                    .expect("OpenAPI path items are objects")
399                    .extend(
400                        item.as_object()
401                            .expect("OpenAPI path item is an object")
402                            .clone(),
403                    );
404            }
405        }
406        if let Some(schemas) = document["components"]["schemas"].as_object_mut() {
407            for schema in extension_schemas {
408                if let Some(existing) = schemas.get(schema.name) {
409                    if existing != &schema.openapi {
410                        self.registration_errors
411                            .push(format!("conflicting OpenAPI schema `{}`", schema.name));
412                    }
413                } else {
414                    schemas.insert(schema.name.to_owned(), schema.openapi);
415                }
416            }
417        }
418        if let Some(paths) = document["paths"].as_object() {
419            self.openapi_paths.extend(paths.clone());
420        }
421        if let Some(schemas) = document["components"]["schemas"].as_object() {
422            self.openapi_components.extend(schemas.clone());
423        }
424        self.routers.push(crate::rest::router::router_with_media(
425            state.clone(),
426            viewset,
427            extension_router,
428            hooks,
429            self.media_access.clone(),
430        ));
431    }
432
433    fn schema(&self) -> SchemaSet {
434        self.schemas
435            .iter()
436            .cloned()
437            .fold(SchemaSet::new(), SchemaSet::merge)
438    }
439
440    pub fn api_endpoints(&self) -> &[ApiEndpoint] {
441        &self.api_endpoints
442    }
443}
444
445pub struct Server {
446    state: AppState,
447    apps: InstalledApps,
448    api_prefix: String,
449    startup_banner: bool,
450}
451
452#[cfg(all(test, feature = "sqlite"))]
453mod tests {
454    use super::*;
455
456    struct First;
457    struct Second;
458
459    #[derive(Debug, che_orm::Model)]
460    #[orm(table = "migration_items")]
461    struct MigrationItem {
462        #[orm(primary_key)]
463        id: i64,
464    }
465
466    struct MigrationApp;
467    struct SchemaObjectApp;
468
469    impl AppModule for First {
470        fn name(&self) -> &'static str {
471            "first"
472        }
473
474        fn schema(&self) -> SchemaSet {
475            SchemaSet::new()
476        }
477
478        fn init(&self, _context: &mut ModuleContext) {}
479    }
480
481    impl AppModule for Second {
482        fn name(&self) -> &'static str {
483            "second"
484        }
485
486        fn schema(&self) -> SchemaSet {
487            SchemaSet::new()
488        }
489
490        fn init(&self, _context: &mut ModuleContext) {}
491    }
492
493    impl AppModule for MigrationApp {
494        fn name(&self) -> &'static str {
495            "migration_app"
496        }
497
498        fn schema(&self) -> SchemaSet {
499            SchemaSet::new().model::<MigrationItem>()
500        }
501
502        fn init(&self, _context: &mut ModuleContext) {}
503    }
504
505    impl AppModule for SchemaObjectApp {
506        fn name(&self) -> &'static str {
507            "schema_object_app"
508        }
509
510        fn schema(&self) -> SchemaSet {
511            SchemaSet::new()
512        }
513
514        fn schema_objects(&self) -> Vec<SchemaObjectState> {
515            vec![SchemaObjectState {
516                app: String::new(),
517                kind: che_orm::SchemaObjectKind::View,
518                name: "migration_items_view".into(),
519                sql: "CREATE VIEW migration_items_view AS SELECT 1 AS id".into(),
520            }]
521        }
522
523        fn init(&self, _context: &mut ModuleContext) {}
524    }
525
526    #[test]
527    fn installed_apps_preserve_registration_order() {
528        let apps = InstalledApps::new().add(First).add(Second);
529        assert_eq!(apps.names().collect::<Vec<_>>(), ["first", "second"]);
530        assert!(apps.find("first").is_some());
531    }
532
533    #[test]
534    fn banner_uses_effective_routes_and_session_settings_without_database_secrets() {
535        let mut config = crate::AppConfig::default();
536        config.server.host = "::1".into();
537        config.server.port = 8080;
538        config.database.url = "sqlite://private-database.sqlite?secret=hidden".into();
539        let apps = InstalledApps::new().add(crate::auth::module()).add(First);
540        let banner = startup_banner(&config, "/v1/", &apps);
541        assert!(banner.contains("http://[::1]:8080/v1/openapi.json"));
542        assert!(banner.contains("Apps:      auth, first"));
543        assert!(banner.contains("Secure=false, SameSite=Lax, idle=7d"));
544        assert!(!banner.contains("private-database"));
545        assert!(!banner.contains("secret"));
546        assert!(!banner.contains("/api/"));
547    }
548
549    #[test]
550    fn banner_omits_uninstalled_auth_and_shows_actual_memory_pool_size() {
551        let mut config = crate::AppConfig::default();
552        config.database.url = ":memory:".into();
553        let banner = startup_banner(&config, "/api", &InstalledApps::new());
554        assert!(banner.contains("Apps:      none"));
555        assert!(banner.contains("Database:  SQLite, max connections: 1"));
556        assert!(!banner.contains("Session:"));
557        assert_eq!(format_duration(90), "90s");
558        assert_eq!(format_duration(0), "0s");
559    }
560
561    #[test]
562    fn installed_apps_expose_app_owned_migration_state() {
563        let apps = InstalledApps::new().add(MigrationApp);
564        let state = apps.migration_state().unwrap();
565        let models = state.models();
566        assert_eq!(models.len(), 1);
567        assert_eq!(models[0].key.app, "migration_app");
568        assert_eq!(models[0].key.name, "MigrationItem");
569        assert_eq!(models[0].table.name, "migration_items");
570        assert!(apps.migration_diff(&state).unwrap().is_empty());
571    }
572
573    #[test]
574    fn installed_apps_assign_schema_objects_to_their_module() {
575        let state = InstalledApps::new()
576            .add(SchemaObjectApp)
577            .migration_state()
578            .unwrap();
579        assert_eq!(state.objects().len(), 1);
580        assert_eq!(state.objects()[0].app, "schema_object_app");
581    }
582
583    #[tokio::test]
584    async fn lifecycle_signals_are_opt_in() {
585        let state = AppState::from_database(che_orm::Database::connect_in_memory().await.unwrap());
586        let mut context = ModuleContext::new(state.clone());
587
588        context.viewset_with(crate::auth::AdminUserViewSet);
589
590        assert!(state.signals().public_signals().is_empty());
591    }
592
593    #[tokio::test]
594    async fn viewset_path_drives_metadata_and_openapi() {
595        let state = AppState::from_database(che_orm::Database::connect_in_memory().await.unwrap());
596        let mut context = ModuleContext::new(state);
597
598        context.viewset_with(crate::auth::AdminUserViewSet);
599
600        assert_eq!(context.api_endpoints()[0].resource, "auth/users");
601        assert!(context.openapi_paths.contains_key("/auth/users/"));
602    }
603}
604
605impl Server {
606    pub fn new(state: AppState) -> Self {
607        Self {
608            state,
609            apps: InstalledApps::new(),
610            api_prefix: "/api".to_owned(),
611            startup_banner: true,
612        }
613    }
614
615    pub fn install(mut self, apps: InstalledApps) -> Self {
616        self.apps = apps;
617        self
618    }
619
620    pub fn api_prefix(mut self, prefix: impl Into<String>) -> Self {
621        self.api_prefix = prefix.into();
622        self
623    }
624
625    /// Controls the configuration banner printed after a successful router build.
626    /// Enabled by default. The address is configured, not a bound listener;
627    /// applications still bind their own listener and call `axum::serve`.
628    pub fn startup_banner(mut self, enabled: bool) -> Self {
629        self.startup_banner = enabled;
630        self
631    }
632
633    pub async fn build(self) -> AppResult<Router> {
634        let mut context = ModuleContext::new(self.state.clone());
635        for module in self.apps.iter() {
636            context.schemas.push(module.schema());
637            context.current_app = module.name();
638            module.init(&mut context);
639        }
640
641        if !context.registration_errors.is_empty() {
642            return Err(AppError::BadRequest(context.registration_errors.join("; ")));
643        }
644
645        let schema = context.schema();
646        schema
647            .validate()
648            .map_err(|error| AppError::BadRequest(format!("invalid app schema: {error:?}")))?;
649        let mut api = Router::new();
650        for route in context.routers {
651            api = api.merge(route);
652        }
653        let mut root = Router::new();
654        for route in context.root_routers {
655            root = root.merge(route);
656        }
657
658        let mut openapi_paths = context.openapi_paths;
659        let mut openapi_components = Map::new();
660        openapi_components.insert(
661            "schemas".to_owned(),
662            Value::Object(context.openapi_components),
663        );
664        for module in self.apps.iter() {
665            let metadata = module.openapi(&self.state);
666            if let Some(paths) = metadata.get("paths").and_then(Value::as_object) {
667                openapi_paths.extend(paths.clone());
668            }
669            if let Some(components) = metadata.get("components").and_then(Value::as_object) {
670                for (name, values) in components {
671                    if name == "schemas" {
672                        if let Some(target) = openapi_components
673                            .get_mut("schemas")
674                            .and_then(Value::as_object_mut)
675                            && let Some(values) = values.as_object()
676                        {
677                            target.extend(values.clone());
678                        }
679                    } else {
680                        openapi_components.insert(name.clone(), values.clone());
681                    }
682                }
683            }
684        }
685        let openapi = json!({
686            "openapi": "3.0.3",
687            "info": { "title": "che-rest API", "version": "0.1.0" },
688            "servers": [{"url": self.api_prefix.clone()}],
689            "paths": openapi_paths,
690            "components": openapi_components,
691            "x-che-rest-signals": self.state.signals().public_signals().into_iter().map(|(name, access)| json!({"name": name, "access": format!("{:?}", access)})).collect::<Vec<_>>(),
692        });
693        api = api.route(
694            "/openapi.json",
695            get(move || async move { Json(openapi.clone()) }),
696        );
697
698        for module in self.apps.iter() {
699            module.subscribe(&self.state);
700        }
701        for module in self.apps.iter() {
702            module.start(&self.state);
703        }
704
705        root = root.nest(&self.api_prefix, api);
706        let swagger_html = swagger_html(&self.state.config.auth.session.csrf_cookie_name);
707        root = root.route(
708            &format!("{}/", self.api_prefix.trim_end_matches('/')),
709            get(move || {
710                let html = swagger_html.clone();
711                async move { Html(html) }
712            }),
713        );
714        for module in self.apps.iter() {
715            root = module.middleware(root, &self.state);
716        }
717
718        if self.startup_banner {
719            println!(
720                "{}",
721                startup_banner(&self.state.config, &self.api_prefix, &self.apps)
722            );
723        }
724
725        Ok(root
726            .layer(axum::Extension(context.media_access))
727            .layer(axum::Extension(self.state)))
728    }
729}
730
731fn startup_banner(config: &crate::AppConfig, api_prefix: &str, apps: &InstalledApps) -> String {
732    let host = &config.server.host;
733    let host = if host.contains(':') && !host.starts_with('[') {
734        format!("[{host}]")
735    } else {
736        host.clone()
737    };
738    let address = format!("http://{host}:{}", config.server.port);
739    let prefix = api_prefix.trim_end_matches('/');
740    let names = apps.names().collect::<Vec<_>>();
741    let modules = if names.is_empty() {
742        "none".into()
743    } else {
744        names.join(", ")
745    };
746    // Do not print connection
747    // strings: they can contain credentials or other application secrets.
748    let mut banner = format!(
749        "\nche-rest v{}\nServer:    {address} (configured)\nAPI:       {address}{prefix}/\nOpenAPI:   {address}{prefix}/openapi.json\nApps:      {modules}\nDatabase:  {}, max connections: {}\nMedia:     {}\n",
750        env!("CARGO_PKG_VERSION"),
751        crate::config::backend_name(),
752        if cfg!(feature = "sqlite")
753            && crate::config::sqlite_path(&config.database.url) == ":memory:"
754        {
755            1
756        } else {
757            config.database.max_connections
758        },
759        config.media.root,
760    );
761    if apps.find("auth").is_some() {
762        let session = &config.auth.session;
763        banner.push_str(&format!(
764            "Session:   Secure={}, SameSite={}, idle={}, renew-window={}, absolute={}\n",
765            session.secure,
766            session.same_site,
767            format_duration(session.ttl_seconds),
768            format_duration(session.renewal_window_seconds),
769            format_duration(session.absolute_ttl_seconds),
770        ));
771    }
772    banner
773}
774
775fn format_duration(seconds: i64) -> String {
776    for (unit, suffix) in [(86_400, "d"), (3_600, "h"), (60, "m")] {
777        if seconds != 0 && seconds % unit == 0 {
778            return format!("{}{suffix}", seconds / unit);
779        }
780    }
781    format!("{seconds}s")
782}
783
784fn swagger_html(csrf_cookie_name: &str) -> String {
785    format!(
786        r##"<!doctype html>
787<html lang="en">
788<head>
789  <meta charset="utf-8">
790  <meta name="viewport" content="width=device-width, initial-scale=1">
791  <title>che-rest API</title>
792  <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css">
793</head>
794<body>
795  <div id="swagger-ui"></div>
796  <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
797  <script>
798    window.ui = SwaggerUIBundle({{
799      url: "./openapi.json",
800      dom_id: "#swagger-ui",
801      withCredentials: true,
802      requestInterceptor: (request) => {{
803        if (["POST", "PUT", "PATCH", "DELETE"].includes(request.method)) {{
804          const token = document.cookie.split("; ").find((cookie) => cookie.startsWith("{csrf_cookie_name}="));
805          if (token) request.headers["X-CSRF-Token"] = token.split("=").slice(1).join("=");
806        }}
807        return request;
808      }}
809    }});
810  </script>
811</body>
812</html>"##
813    )
814}
815
816fn add_filter_parameters<V: ViewSet>(document: &mut Value, viewset: &V) {
817    let Some(parameters) = document
818        .get_mut("paths")
819        .and_then(Value::as_object_mut)
820        .and_then(|paths| paths.values_mut().next())
821        .and_then(Value::as_object_mut)
822        .and_then(|path| path.get_mut("get"))
823        .and_then(Value::as_object_mut)
824        .map(|get| get.entry("parameters").or_insert_with(|| json!([])))
825    else {
826        return;
827    };
828    let Some(parameters) = parameters.as_array_mut() else {
829        return;
830    };
831    for filter in viewset.filterset().filters().iter() {
832        let name = match filter.lookup() {
833            crate::Lookup::Exact => filter.name.to_owned(),
834            crate::Lookup::Contains => return_filter_name(filter.name, "__contains"),
835            crate::Lookup::Gt => return_filter_name(filter.name, "__gt"),
836            crate::Lookup::Gte => return_filter_name(filter.name, "__gte"),
837            crate::Lookup::Lt => return_filter_name(filter.name, "__lt"),
838            crate::Lookup::Lte => return_filter_name(filter.name, "__lte"),
839        };
840        let model_schema = V::Model::schema();
841        let column = model_schema
842            .columns
843            .iter()
844            .find(|column| column.name == filter.source());
845        let mut schema = column
846            .map(openapi_column_schema)
847            .unwrap_or_else(|| json!({"type": "string"}));
848        schema["nullable"] = json!(false);
849        parameters.push(json!({"name": name, "in": "query", "required": false, "schema": schema}));
850    }
851    parameters.push(
852        json!({"name": "limit", "in": "query", "required": false, "schema": {"type": "integer"}}),
853    );
854    parameters.push(
855        json!({"name": "offset", "in": "query", "required": false, "schema": {"type": "integer"}}),
856    );
857    parameters.push(
858        json!({"name": "ordering", "in": "query", "required": false, "schema": {"type": "string"}}),
859    );
860}
861
862fn return_filter_name(name: &'static str, suffix: &str) -> String {
863    format!("{name}{suffix}")
864}