athena_rs 2.9.1

Database gateway API
Documentation
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
use actix_web::{
    HttpRequest, HttpResponse, Responder, delete, get, patch, post, put,
    web::{self, Data, Json, Path, Query},
};
use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde_json::json;
use sha256::digest;
use sqlx::postgres::PgPool;
use uuid::Uuid;

use crate::AppState;
use crate::api::auth::authorize_static_admin_key;
use crate::api::response::{
    api_created, api_success, bad_request, conflict, internal_error, not_found, service_unavailable,
};
use crate::data::api_keys::{
    ApiKeyStoreError, CreateApiKeyParams, SaveApiKeyParams, create_api_key, create_api_key_right,
    delete_api_key, delete_api_key_right, delete_client_api_key_config, get_api_key,
    get_global_api_key_config, list_api_key_rights, list_api_keys, list_client_api_key_configs,
    save_api_key, set_global_api_key_config, update_api_key_right, upsert_client_api_key_config,
};
use crate::data::clients::{
    AthenaClientRecord, ClientOperationStatusFilter, SaveAthenaClientParams, delete_athena_client,
    get_athena_client_by_name, get_client_statistics, list_athena_clients,
    list_client_operation_drilldown, list_client_statistics, list_client_table_statistics,
    refresh_client_statistics, set_client_frozen_state, upsert_athena_client,
};
use crate::data::vacuum_health::{
    get_latest_vacuum_health_detail, list_latest_vacuum_health_summaries,
};
use crate::drivers::postgresql::sqlx_driver::ClientConnectionTarget;

#[derive(Debug, Deserialize)]
struct CreateApiKeyRequest {
    name: String,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    client_name: Option<String>,
    #[serde(default)]
    expires_at: Option<String>,
    #[serde(default)]
    rights: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct UpdateApiKeyRequest {
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    description: Option<Option<String>>,
    #[serde(default)]
    client_name: Option<Option<String>>,
    #[serde(default)]
    expires_at: Option<Option<String>>,
    #[serde(default)]
    is_active: Option<bool>,
    #[serde(default)]
    rights: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
struct SaveApiKeyRightRequest {
    name: String,
    #[serde(default)]
    description: Option<String>,
}

#[derive(Debug, Deserialize)]
struct SaveGlobalConfigRequest {
    enforce_api_keys: bool,
}

#[derive(Debug, Deserialize)]
struct SaveClientConfigRequest {
    enforce_api_keys: bool,
}

#[derive(Debug, Deserialize)]
struct SaveAthenaClientRequest {
    #[serde(default)]
    client_name: Option<String>,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    pg_uri: Option<String>,
    #[serde(default)]
    pg_uri_env_var: Option<String>,
    #[serde(default)]
    is_active: Option<bool>,
}

#[derive(Debug, Deserialize)]
struct FreezeAthenaClientRequest {
    is_frozen: bool,
}

#[derive(Debug, Deserialize)]
struct ClientStatisticsDrilldownQuery {
    table_name: String,
    operation: String,
    #[serde(default)]
    status: Option<String>,
    #[serde(default)]
    limit: Option<i64>,
    #[serde(default)]
    offset: Option<i64>,
}

fn auth_pool(state: &AppState) -> Result<PgPool, HttpResponse> {
    let Some(client_name) = state.gateway_auth_client_name.as_ref() else {
        return Err(service_unavailable(
            "Auth store unavailable",
            "No gateway auth client is configured.",
        ));
    };

    state.pg_registry.get_pool(client_name).ok_or_else(|| {
        service_unavailable(
            "Auth store unavailable",
            format!("Gateway auth client '{}' is not connected.", client_name),
        )
    })
}

fn client_catalog_pool(state: &AppState) -> Result<PgPool, HttpResponse> {
    let Some(client_name) = state.logging_client_name.as_ref() else {
        return Err(service_unavailable(
            "Client catalog unavailable",
            "No athena_logging client is configured.",
        ));
    };

    state.pg_registry.get_pool(client_name).ok_or_else(|| {
        service_unavailable(
            "Client catalog unavailable",
            format!("Logging client '{}' is not connected.", client_name),
        )
    })
}

fn normalize_client_name(client_name: &str) -> Result<String, HttpResponse> {
    let value = client_name.trim();
    if value.is_empty() {
        Err(bad_request(
            "Invalid client name",
            "The client name must not be empty.",
        ))
    } else {
        Ok(value.to_string())
    }
}

fn normalize_required_query_value(field_name: &str, value: &str) -> Result<String, HttpResponse> {
    let normalized = value.trim();
    if normalized.is_empty() {
        Err(bad_request(
            "Invalid query parameter",
            format!("'{}' must not be empty.", field_name),
        ))
    } else {
        Ok(normalized.to_string())
    }
}

fn parse_client_statistics_status_filter(
    status: Option<&str>,
) -> Result<ClientOperationStatusFilter, HttpResponse> {
    match status.map(|value| value.trim().to_ascii_lowercase()) {
        None => Ok(ClientOperationStatusFilter::All),
        Some(value) if value.is_empty() || value == "all" => Ok(ClientOperationStatusFilter::All),
        Some(value) if value == "errors" => Ok(ClientOperationStatusFilter::Errors),
        Some(value) if value == "normal" => Ok(ClientOperationStatusFilter::Normal),
        Some(_) => Err(bad_request(
            "Invalid status filter",
            "status must be one of: all, errors, normal",
        )),
    }
}

fn client_record_to_runtime_target(record: &AthenaClientRecord) -> ClientConnectionTarget {
    ClientConnectionTarget {
        client_name: record.client_name.clone(),
        source: record.source.clone(),
        description: record.description.clone(),
        pg_uri: record.pg_uri.clone(),
        pg_uri_env_var: record.pg_uri_env_var.clone(),
        config_uri_template: record.config_uri_template.clone(),
        is_active: record.is_active,
        is_frozen: record.is_frozen,
    }
}

async fn apply_client_record_to_runtime(
    state: &AppState,
    record: &AthenaClientRecord,
) -> Result<(), anyhow::Error> {
    let target = client_record_to_runtime_target(record);
    if !record.is_active || record.is_frozen {
        state.pg_registry.remember_client(target, false);
        state.pg_registry.mark_unavailable(&record.client_name);
        state.pg_registry.sync_connection_status();
        return Ok(());
    }

    if state.pg_registry.get_pool(&record.client_name).is_some() {
        state.pg_registry.remember_client(target, true);
        state.pg_registry.sync_connection_status();
        return Ok(());
    }

    state.pg_registry.upsert_client(target).await?;
    state.pg_registry.sync_connection_status();
    Ok(())
}

fn parse_optional_timestamp(
    value: Option<String>,
    field_name: &str,
) -> Result<Option<DateTime<Utc>>, HttpResponse> {
    match value {
        Some(value) => DateTime::parse_from_rfc3339(&value)
            .map(|timestamp| Some(timestamp.with_timezone(&Utc)))
            .map_err(|_| {
                bad_request(
                    "Invalid timestamp",
                    format!("'{}' must be an RFC3339 timestamp.", field_name),
                )
            }),
        None => Ok(None),
    }
}

fn apply_optional_timestamp_patch(
    patch_value: Option<Option<String>>,
    current: Option<DateTime<Utc>>,
    field_name: &str,
) -> Result<Option<DateTime<Utc>>, HttpResponse> {
    match patch_value {
        None => Ok(current),
        Some(None) => Ok(None),
        Some(Some(value)) => parse_optional_timestamp(Some(value), field_name),
    }
}

fn database_error_response(message: &str, err: sqlx::Error) -> HttpResponse {
    let unique_violation = err
        .as_database_error()
        .and_then(|db_err| db_err.code().map(|code| code == "23505"))
        .unwrap_or(false);

    if unique_violation {
        conflict(message, err.to_string())
    } else {
        internal_error(message, err.to_string())
    }
}

fn api_key_store_error_response(message: &str, err: ApiKeyStoreError) -> HttpResponse {
    match err {
        ApiKeyStoreError::MissingRights(missing) => bad_request(
            "Unknown API key rights",
            format!("These rights do not exist: {}", missing.join(", ")),
        ),
        ApiKeyStoreError::Database(err) => database_error_response(message, err),
    }
}

fn generate_public_id() -> String {
    Uuid::new_v4()
        .simple()
        .to_string()
        .chars()
        .take(16)
        .collect()
}

fn generate_secret() -> String {
    format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple())
}

#[get("/admin/api-keys")]
async fn admin_list_api_keys(req: HttpRequest, app_state: Data<AppState>) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    match list_api_keys(&pool).await {
        Ok(keys) => api_success("Listed API keys", json!({ "api_keys": keys })),
        Err(err) => database_error_response("Failed to list API keys", err),
    }
}

#[post("/admin/api-keys")]
async fn admin_create_api_key(
    req: HttpRequest,
    body: Json<CreateApiKeyRequest>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let expires_at = match parse_optional_timestamp(body.expires_at.clone(), "expires_at") {
        Ok(value) => value,
        Err(resp) => return resp,
    };

    let public_id = generate_public_id();
    let secret = generate_secret();
    let key_salt = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
    let key_hash = digest(format!("{}:{}", key_salt, secret));

    let params = CreateApiKeyParams {
        public_id: public_id.clone(),
        name: body.name.clone(),
        description: body.description.clone(),
        client_name: body.client_name.clone(),
        key_salt,
        key_hash,
        expires_at,
        rights: body.rights.clone(),
    };

    match create_api_key(&pool, params).await {
        Ok(record) => api_created(
            "Created API key",
            json!({
                "api_key": format!("ath_{}.{}", public_id, secret),
                "record": record,
            }),
        ),
        Err(err) => api_key_store_error_response("Failed to create API key", err),
    }
}

#[patch("/admin/api-keys/{id}")]
async fn admin_update_api_key(
    req: HttpRequest,
    path: Path<String>,
    body: Json<UpdateApiKeyRequest>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let id = match Uuid::parse_str(&path.into_inner()) {
        Ok(value) => value,
        Err(_) => {
            return bad_request("Invalid API key id", "The API key id must be a UUID.");
        }
    };

    let Some(existing) = (match get_api_key(&pool, id).await {
        Ok(record) => record,
        Err(err) => return database_error_response("Failed to load API key", err),
    }) else {
        return not_found(
            "API key not found",
            format!("No API key exists for '{}'.", id),
        );
    };

    let expires_at = match apply_optional_timestamp_patch(
        body.expires_at.clone(),
        existing.expires_at,
        "expires_at",
    ) {
        Ok(value) => value,
        Err(resp) => return resp,
    };

    let params = SaveApiKeyParams {
        id,
        name: body.name.clone().unwrap_or(existing.name),
        description: body.description.clone().unwrap_or(existing.description),
        client_name: body.client_name.clone().unwrap_or(existing.client_name),
        expires_at,
        is_active: body.is_active.unwrap_or(existing.is_active),
        rights: body.rights.clone().unwrap_or(existing.rights),
    };

    match save_api_key(&pool, params).await {
        Ok(Some(record)) => api_success("Updated API key", json!({ "record": record })),
        Ok(None) => not_found(
            "API key not found",
            format!("No API key exists for '{}'.", id),
        ),
        Err(err) => api_key_store_error_response("Failed to update API key", err),
    }
}

#[delete("/admin/api-keys/{id}")]
async fn admin_delete_api_key(
    req: HttpRequest,
    path: Path<String>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let id = match Uuid::parse_str(&path.into_inner()) {
        Ok(value) => value,
        Err(_) => {
            return bad_request("Invalid API key id", "The API key id must be a UUID.");
        }
    };

    match delete_api_key(&pool, id).await {
        Ok(true) => api_success("Deleted API key", json!({ "id": id })),
        Ok(false) => not_found(
            "API key not found",
            format!("No API key exists for '{}'.", id),
        ),
        Err(err) => database_error_response("Failed to delete API key", err),
    }
}

#[get("/admin/api-key-rights")]
async fn admin_list_api_key_rights(req: HttpRequest, app_state: Data<AppState>) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    match list_api_key_rights(&pool).await {
        Ok(rights) => api_success("Listed API key rights", json!({ "rights": rights })),
        Err(err) => database_error_response("Failed to list API key rights", err),
    }
}

#[post("/admin/api-key-rights")]
async fn admin_create_api_key_right(
    req: HttpRequest,
    body: Json<SaveApiKeyRightRequest>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    match create_api_key_right(&pool, &body.name, body.description.as_deref()).await {
        Ok(record) => api_created("Created API key right", json!({ "right": record })),
        Err(err) => database_error_response("Failed to create API key right", err),
    }
}

#[patch("/admin/api-key-rights/{id}")]
async fn admin_update_api_key_right(
    req: HttpRequest,
    path: Path<String>,
    body: Json<SaveApiKeyRightRequest>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let id = match Uuid::parse_str(&path.into_inner()) {
        Ok(value) => value,
        Err(_) => {
            return bad_request("Invalid API key right id", "The right id must be a UUID.");
        }
    };

    match update_api_key_right(&pool, id, &body.name, body.description.as_deref()).await {
        Ok(Some(record)) => api_success("Updated API key right", json!({ "right": record })),
        Ok(None) => not_found(
            "API key right not found",
            format!("No right exists for '{}'.", id),
        ),
        Err(err) => database_error_response("Failed to update API key right", err),
    }
}

#[delete("/admin/api-key-rights/{id}")]
async fn admin_delete_api_key_right(
    req: HttpRequest,
    path: Path<String>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let id = match Uuid::parse_str(&path.into_inner()) {
        Ok(value) => value,
        Err(_) => {
            return bad_request("Invalid API key right id", "The right id must be a UUID.");
        }
    };

    match delete_api_key_right(&pool, id).await {
        Ok(true) => api_success("Deleted API key right", json!({ "id": id })),
        Ok(false) => not_found(
            "API key right not found",
            format!("No right exists for '{}'.", id),
        ),
        Err(err) => database_error_response("Failed to delete API key right", err),
    }
}

#[get("/admin/api-key-config")]
async fn admin_get_api_key_config(req: HttpRequest, app_state: Data<AppState>) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let global = match get_global_api_key_config(&pool).await {
        Ok(value) => value,
        Err(err) => return database_error_response("Failed to load API key config", err),
    };
    let clients = match list_client_api_key_configs(&pool).await {
        Ok(value) => value,
        Err(err) => return database_error_response("Failed to load API key client config", err),
    };

    api_success(
        "Loaded API key config",
        json!({
            "global": global,
            "clients": clients,
        }),
    )
}

#[put("/admin/api-key-config")]
async fn admin_set_api_key_config(
    req: HttpRequest,
    body: Json<SaveGlobalConfigRequest>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    match set_global_api_key_config(&pool, body.enforce_api_keys).await {
        Ok(global) => api_success("Updated API key config", json!({ "global": global })),
        Err(err) => database_error_response("Failed to update API key config", err),
    }
}

#[get("/admin/api-key-clients")]
async fn admin_list_api_key_clients(req: HttpRequest, app_state: Data<AppState>) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    match list_client_api_key_configs(&pool).await {
        Ok(clients) => api_success(
            "Listed API key client config",
            json!({ "clients": clients }),
        ),
        Err(err) => database_error_response("Failed to list API key client config", err),
    }
}

#[put("/admin/api-key-clients/{client_name}")]
async fn admin_upsert_api_key_client(
    req: HttpRequest,
    path: Path<String>,
    body: Json<SaveClientConfigRequest>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool: sqlx::Pool<sqlx::Postgres> = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let client_name: String = path.into_inner();
    if client_name.trim().is_empty() {
        return bad_request("Invalid client name", "The client name must not be empty.");
    }

    match upsert_client_api_key_config(&pool, &client_name, body.enforce_api_keys).await {
        Ok(record) => api_success("Updated API key client config", json!({ "client": record })),
        Err(err) => database_error_response("Failed to update API key client config", err),
    }
}

#[delete("/admin/api-key-clients/{client_name}")]
async fn admin_delete_api_key_client(
    req: HttpRequest,
    path: Path<String>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool: sqlx::Pool<sqlx::Postgres> = match auth_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let client_name = path.into_inner();
    match delete_client_api_key_config(&pool, &client_name).await {
        Ok(true) => api_success(
            "Deleted API key client config",
            json!({ "client_name": client_name }),
        ),
        Ok(false) => not_found(
            "API key client config not found",
            format!("No client config exists for '{}'.", client_name),
        ),
        Err(err) => database_error_response("Failed to delete API key client config", err),
    }
}

#[get("/admin/clients")]
async fn admin_list_clients(req: HttpRequest, app_state: Data<AppState>) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let runtime_clients = app_state.pg_registry.list_registered_clients();
    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(_) => {
            return api_success(
                "Listed runtime Athena clients",
                json!({ "clients": runtime_clients }),
            );
        }
    };

    match list_athena_clients(&pool).await {
        Ok(clients) => api_success(
            "Listed Athena clients",
            json!({
                "clients": clients,
                "runtime": runtime_clients,
            }),
        ),
        Err(err) => database_error_response("Failed to list Athena clients", err),
    }
}

#[post("/admin/clients")]
async fn admin_create_client(
    req: HttpRequest,
    body: Json<SaveAthenaClientRequest>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool: sqlx::Pool<sqlx::Postgres> = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let client_name = match normalize_client_name(body.client_name.as_deref().unwrap_or("")) {
        Ok(value) => value,
        Err(_) => {
            return bad_request(
                "Missing client name",
                "Provide client_name in the request body when creating a client.",
            );
        }
    };

    if body.pg_uri.as_deref().unwrap_or("").trim().is_empty()
        && body
            .pg_uri_env_var
            .as_deref()
            .unwrap_or("")
            .trim()
            .is_empty()
    {
        return bad_request(
            "Missing connection details",
            "Provide either pg_uri or pg_uri_env_var for database-backed clients.",
        );
    }

    match get_athena_client_by_name(&pool, &client_name).await {
        Ok(Some(_)) => {
            return conflict(
                "Athena client already exists",
                format!("A client named '{}' already exists.", client_name),
            );
        }
        Ok(None) => {}
        Err(err) => return database_error_response("Failed to load Athena client", err),
    }

    let record = match upsert_athena_client(
        &pool,
        SaveAthenaClientParams {
            client_name,
            description: body.description.clone(),
            pg_uri: body.pg_uri.clone(),
            pg_uri_env_var: body.pg_uri_env_var.clone(),
            config_uri_template: None,
            source: "database".to_string(),
            is_active: body.is_active.unwrap_or(true),
            is_frozen: false,
            metadata: json!({ "managed_by": "admin_api" }),
        },
    )
    .await
    {
        Ok(record) => record,
        Err(err) => return database_error_response("Failed to create Athena client", err),
    };

    if let Err(err) = apply_client_record_to_runtime(app_state.get_ref(), &record).await {
        return internal_error("Failed to activate Athena client", err.to_string());
    }

    api_created("Created Athena client", json!({ "client": record }))
}

#[patch("/admin/clients/{client_name}")]
async fn admin_update_client(
    req: HttpRequest,
    path: Path<String>,
    body: Json<SaveAthenaClientRequest>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let client_name = match normalize_client_name(&path.into_inner()) {
        Ok(value) => value,
        Err(resp) => return resp,
    };

    let existing = match get_athena_client_by_name(&pool, &client_name).await {
        Ok(Some(record)) => record,
        Ok(None) => {
            return not_found(
                "Athena client not found",
                format!("No client exists for '{}'.", client_name),
            );
        }
        Err(err) => return database_error_response("Failed to load Athena client", err),
    };

    let record = match upsert_athena_client(
        &pool,
        SaveAthenaClientParams {
            client_name: client_name.clone(),
            description: body.description.clone().or(existing.description.clone()),
            pg_uri: body.pg_uri.clone().or(existing.pg_uri.clone()),
            pg_uri_env_var: body
                .pg_uri_env_var
                .clone()
                .or(existing.pg_uri_env_var.clone()),
            config_uri_template: existing.config_uri_template.clone(),
            source: existing.source.clone(),
            is_active: body.is_active.unwrap_or(existing.is_active),
            is_frozen: existing.is_frozen,
            metadata: existing.metadata.clone(),
        },
    )
    .await
    {
        Ok(record) => record,
        Err(err) => return database_error_response("Failed to update Athena client", err),
    };

    if let Err(err) = apply_client_record_to_runtime(app_state.get_ref(), &record).await {
        return internal_error("Failed to refresh Athena client", err.to_string());
    }

    api_success("Updated Athena client", json!({ "client": record }))
}

#[put("/admin/clients/{client_name}/freeze")]
async fn admin_freeze_client(
    req: HttpRequest,
    path: Path<String>,
    body: Json<FreezeAthenaClientRequest>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let client_name = match normalize_client_name(&path.into_inner()) {
        Ok(value) => value,
        Err(resp) => return resp,
    };

    let record = match set_client_frozen_state(&pool, &client_name, body.is_frozen).await {
        Ok(Some(record)) => record,
        Ok(None) => {
            return not_found(
                "Athena client not found",
                format!("No client exists for '{}'.", client_name),
            );
        }
        Err(err) => return database_error_response("Failed to update Athena client", err),
    };

    if let Err(err) = apply_client_record_to_runtime(app_state.get_ref(), &record).await {
        return internal_error("Failed to refresh Athena client", err.to_string());
    }

    api_success(
        "Updated Athena client freeze state",
        json!({ "client": record }),
    )
}

#[delete("/admin/clients/{client_name}")]
async fn admin_delete_client(
    req: HttpRequest,
    path: Path<String>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let client_name = match normalize_client_name(&path.into_inner()) {
        Ok(value) => value,
        Err(resp) => return resp,
    };

    match delete_athena_client(&pool, &client_name).await {
        Ok(Some(record)) => {
            app_state.pg_registry.remove_client(&record.client_name);
            api_success("Deleted Athena client", json!({ "client": record }))
        }
        Ok(None) => not_found(
            "Athena client not found",
            format!("No client exists for '{}'.", client_name),
        ),
        Err(err) => database_error_response("Failed to delete Athena client", err),
    }
}

#[get("/admin/clients/statistics")]
async fn admin_list_client_statistics(
    req: HttpRequest,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    match list_client_statistics(&pool).await {
        Ok(statistics) => api_success(
            "Listed client statistics",
            json!({ "statistics": statistics }),
        ),
        Err(err) => database_error_response("Failed to list client statistics", err),
    }
}

#[post("/admin/clients/statistics/refresh")]
async fn admin_refresh_client_statistics(
    req: HttpRequest,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    if let Err(err) = refresh_client_statistics(&pool).await {
        return database_error_response("Failed to refresh client statistics", err);
    }

    match list_client_statistics(&pool).await {
        Ok(statistics) => api_success(
            "Refreshed client statistics",
            json!({ "statistics": statistics }),
        ),
        Err(err) => database_error_response("Failed to list client statistics", err),
    }
}

#[get("/admin/clients/{client_name}/statistics")]
async fn admin_get_client_statistics(
    req: HttpRequest,
    path: Path<String>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let client_name = match normalize_client_name(&path.into_inner()) {
        Ok(value) => value,
        Err(resp) => return resp,
    };

    let statistics = match get_client_statistics(&pool, &client_name).await {
        Ok(Some(record)) => record,
        Ok(None) => {
            return not_found(
                "Client statistics not found",
                format!("No statistics exist for '{}'.", client_name),
            );
        }
        Err(err) => return database_error_response("Failed to load client statistics", err),
    };

    match list_client_table_statistics(&pool, &client_name).await {
        Ok(table_statistics) => api_success(
            "Loaded client statistics",
            json!({
                "statistics": statistics,
                "tables": table_statistics,
            }),
        ),
        Err(err) => database_error_response("Failed to load client table statistics", err),
    }
}

#[get("/admin/clients/{client_name}/statistics/drilldown")]
async fn admin_get_client_statistics_drilldown(
    req: HttpRequest,
    path: Path<String>,
    query: Query<ClientStatisticsDrilldownQuery>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let client_name = match normalize_client_name(&path.into_inner()) {
        Ok(value) => value,
        Err(resp) => return resp,
    };

    let table_name = match normalize_required_query_value("table_name", &query.table_name) {
        Ok(value) => value,
        Err(resp) => return resp,
    };
    let operation = match normalize_required_query_value("operation", &query.operation) {
        Ok(value) => value,
        Err(resp) => return resp,
    };

    let status_filter = match parse_client_statistics_status_filter(query.status.as_deref()) {
        Ok(value) => value,
        Err(resp) => return resp,
    };
    let limit = query.limit.unwrap_or(100).clamp(1, 500);
    let offset = query.offset.unwrap_or(0).max(0);

    match list_client_operation_drilldown(
        &pool,
        &client_name,
        &table_name,
        &operation,
        status_filter,
        limit,
        offset,
    )
    .await
    {
        Ok(rows) => api_success(
            "Loaded client statistics drilldown",
            json!({
                "client_name": client_name,
                "table_name": table_name,
                "operation": operation,
                "status": query.status.as_deref().map(str::trim).filter(|s| !s.is_empty()).unwrap_or("all"),
                "limit": limit,
                "offset": offset,
                "rows": rows,
            }),
        ),
        Err(err) => database_error_response("Failed to load client statistics drilldown", err),
    }
}

#[get("/admin/vacuum-health")]
async fn admin_list_vacuum_health(req: HttpRequest, app_state: Data<AppState>) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    match list_latest_vacuum_health_summaries(&pool).await {
        Ok(snapshots) => api_success(
            "Loaded vacuum health snapshots",
            json!({
                "snapshots": snapshots,
            }),
        ),
        Err(err) => database_error_response("Failed to load vacuum health snapshots", err),
    }
}

#[get("/admin/vacuum-health/{client_name}")]
async fn admin_get_vacuum_health(
    req: HttpRequest,
    path: Path<String>,
    app_state: Data<AppState>,
) -> impl Responder {
    if let Err(resp) = authorize_static_admin_key(&req) {
        return resp;
    }

    let pool = match client_catalog_pool(app_state.get_ref()) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    let client_name = match normalize_client_name(&path.into_inner()) {
        Ok(value) => value,
        Err(resp) => return resp,
    };

    match get_latest_vacuum_health_detail(&pool, &client_name).await {
        Ok(Some((snapshot, tables))) => api_success(
            "Loaded vacuum health detail",
            json!({
                "snapshot": snapshot,
                "tables": tables,
            }),
        ),
        Ok(None) => not_found(
            "Vacuum health not found",
            format!("No vacuum health snapshots exist for '{}'.", client_name),
        ),
        Err(err) => database_error_response("Failed to load vacuum health detail", err),
    }
}

pub fn services(cfg: &mut web::ServiceConfig) {
    cfg.service(admin_list_api_keys)
        .service(admin_create_api_key)
        .service(admin_update_api_key)
        .service(admin_delete_api_key)
        .service(admin_list_api_key_rights)
        .service(admin_create_api_key_right)
        .service(admin_update_api_key_right)
        .service(admin_delete_api_key_right)
        .service(admin_get_api_key_config)
        .service(admin_set_api_key_config)
        .service(admin_list_api_key_clients)
        .service(admin_upsert_api_key_client)
        .service(admin_delete_api_key_client)
        .service(admin_list_clients)
        .service(admin_create_client)
        .service(admin_update_client)
        .service(admin_freeze_client)
        .service(admin_delete_client)
        .service(admin_list_client_statistics)
        .service(admin_refresh_client_statistics)
        .service(admin_get_client_statistics)
        .service(admin_get_client_statistics_drilldown)
        .service(admin_list_vacuum_health)
        .service(admin_get_vacuum_health);
}