rekuiper-server 1.0.0-rc4

REST API, OpenAPI routes, Prometheus metrics, and streaming hub for rekuiper
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
use crate::state::{check_valid_name, persist_config_entry, unpersist_config_entry, AppState};
use axum::{
    body::Bytes,
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use rekuiper_conf::KuiperConfig;
use rekuiper_core::KvOperation;
use serde_json::{json, Value};

pub async fn get_configs(State(state): State<AppState>) -> impl IntoResponse {
    Json(state.config.read().clone())
}

/// Partial runtime configuration update (eKuiper `PATCH /configs`): deep
/// merges the JSON object into the live config and answers 204 No Content.
pub async fn patch_configs(State(state): State<AppState>, Json(patch): Json<Value>) -> Response {
    let Value::Object(overlay) = patch else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": 3000, "message": "Expected a JSON object"})),
        )
            .into_response();
    };
    let tz_val = overlay
        .get("timezone")
        .or_else(|| overlay.get("basic").and_then(|b| b.get("timezone")));
    if let Some(Value::String(tz_str)) = tz_val {
        if !rekuiper_sql::is_valid_timezone(tz_str) {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({"error": 3000, "message": "Invalid TZ"})),
            )
                .into_response();
        }
    }
    let mut current = serde_json::to_value(state.config.read().clone()).unwrap_or(json!({}));
    merge_json_object(&mut current, &Value::Object(overlay));
    match serde_json::from_value::<KuiperConfig>(current) {
        Ok(updated) => {
            *state.config.write() = updated;
            StatusCode::NO_CONTENT.into_response()
        }
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({
                "error": 3000,
                "message": format!("Invalid config patch: {}", e)
            })),
        )
            .into_response(),
    }
}

/// Recursively merges `overlay` objects into `base`; scalars and arrays are
/// replaced, nested objects merge key by key.
pub fn merge_json_object(base: &mut Value, overlay: &Value) {
    match (base, overlay) {
        (Value::Object(base_map), Value::Object(overlay_map)) => {
            for (k, v) in overlay_map {
                match base_map.get_mut(k) {
                    Some(existing) => merge_json_object(existing, v),
                    None => {
                        base_map.insert(k.clone(), v.clone());
                    }
                }
            }
        }
        (base_slot, v) => {
            *base_slot = v.clone();
        }
    }
}
pub async fn save_source_conf_key(
    State(state): State<AppState>,
    Path((name, conf_key)): Path<(String, String)>,
    body: Bytes,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    if let Err(resp) = check_valid_name(&conf_key) {
        return resp;
    }
    let payload = if body.is_empty() {
        json!({})
    } else {
        serde_json::from_slice::<Value>(&body).unwrap_or_else(|_| json!({}))
    };
    if name.eq_ignore_ascii_case("video") {
        if let Ok(cfg) =
            serde_json::from_value::<rekuiper_connectors::VideoSourceConfig>(payload.clone())
        {
            if let Err(e) = cfg.validate_conf() {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({
                        "error": 3000,
                        "message": format!("Invalid video source configuration: {}", e)
                    })),
                )
                    .into_response();
            }
        }
    }
    let key = format!("{}/{}", name, conf_key);
    let _guard = state.config_op_lock.lock().await;
    if let Err(e) = persist_config_entry(&state, "source_configs", &key, &payload).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to persist configuration: {}", e),
        )
            .into_response();
    }
    state.source_configs.write().insert(key, payload);
    (StatusCode::OK, Json(json!({"message": "success"}))).into_response()
}

pub async fn get_source_conf_key(
    State(state): State<AppState>,
    Path((name, conf_key)): Path<(String, String)>,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    if let Err(resp) = check_valid_name(&conf_key) {
        return resp;
    }
    let key = format!("{}/{}", name, conf_key);
    if let Some(val) = state.source_configs.read().get(&key).cloned() {
        Json(val).into_response()
    } else {
        (
            StatusCode::NOT_FOUND,
            Json(json!({
                "message": format!("Configuration key {} for {} not found", conf_key, name)
            })),
        )
            .into_response()
    }
}

pub async fn delete_source_conf_key(
    State(state): State<AppState>,
    Path((name, conf_key)): Path<(String, String)>,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    if let Err(resp) = check_valid_name(&conf_key) {
        return resp;
    }
    let key = format!("{}/{}", name, conf_key);
    let _guard = state.config_op_lock.lock().await;
    if !state.source_configs.read().contains_key(&key) {
        return (
            StatusCode::NOT_FOUND,
            Json(json!({
                "message": format!("Configuration key {} for {} not found", conf_key, name)
            })),
        )
            .into_response();
    }
    if let Err(e) = unpersist_config_entry(&state, "source_configs", &key).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to delete configuration: {}", e),
        )
            .into_response();
    }
    state.source_configs.write().remove(&key);
    (StatusCode::OK, Json(json!({"message": "success"}))).into_response()
}

pub async fn save_sink_conf_key(
    State(state): State<AppState>,
    Path((name, conf_key)): Path<(String, String)>,
    body: Bytes,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    if let Err(resp) = check_valid_name(&conf_key) {
        return resp;
    }
    let payload = if body.is_empty() {
        json!({})
    } else {
        serde_json::from_slice::<Value>(&body).unwrap_or_else(|_| json!({}))
    };
    let key = format!("{}/{}", name, conf_key);
    let _guard = state.config_op_lock.lock().await;
    if let Err(e) = persist_config_entry(&state, "sink_configs", &key, &payload).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to persist configuration: {}", e),
        )
            .into_response();
    }
    state.sink_configs.write().insert(key, payload);
    (StatusCode::OK, Json(json!({"message": "success"}))).into_response()
}

pub async fn get_sink_conf_key(
    State(state): State<AppState>,
    Path((name, conf_key)): Path<(String, String)>,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    if let Err(resp) = check_valid_name(&conf_key) {
        return resp;
    }
    let key = format!("{}/{}", name, conf_key);
    if let Some(val) = state.sink_configs.read().get(&key).cloned() {
        Json(val).into_response()
    } else {
        (
            StatusCode::NOT_FOUND,
            Json(json!({
                "message": format!("Configuration key {} for {} not found", conf_key, name)
            })),
        )
            .into_response()
    }
}

pub async fn delete_sink_conf_key(
    State(state): State<AppState>,
    Path((name, conf_key)): Path<(String, String)>,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    if let Err(resp) = check_valid_name(&conf_key) {
        return resp;
    }
    let key = format!("{}/{}", name, conf_key);
    let _guard = state.config_op_lock.lock().await;
    if !state.sink_configs.read().contains_key(&key) {
        return (
            StatusCode::NOT_FOUND,
            Json(json!({
                "message": format!("Configuration key {} for {} not found", conf_key, name)
            })),
        )
            .into_response();
    }
    if let Err(e) = unpersist_config_entry(&state, "sink_configs", &key).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to delete configuration: {}", e),
        )
            .into_response();
    }
    state.sink_configs.write().remove(&key);
    (StatusCode::OK, Json(json!({"message": "success"}))).into_response()
}

pub async fn save_connection_conf_key(
    State(state): State<AppState>,
    Path((name, conf_key)): Path<(String, String)>,
    body: Bytes,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    if let Err(resp) = check_valid_name(&conf_key) {
        return resp;
    }
    let mut payload = if body.is_empty() {
        json!({})
    } else {
        serde_json::from_slice::<Value>(&body).unwrap_or_else(|_| json!({}))
    };
    let canonical_key = format!("{}/{}", name, conf_key);
    let dot_key = format!("{}.{}", name, conf_key);
    let _guard = state.config_op_lock.lock().await;

    // Preserve existing secrets when updated with "******" placeholder
    let existing_val = {
        let conns = state.connections.read();
        conns
            .get(&canonical_key)
            .or_else(|| conns.get(&dot_key))
            .cloned()
    };
    if let Some(existing) = existing_val {
        crate::secrets::preserve_masked_secrets(&mut payload, &existing);
    }

    if let Some(kv) = state.kv.as_ref() {
        let ops = [
            KvOperation::Set {
                namespace: "connections".to_string(),
                key: canonical_key.clone(),
                val: payload.to_string(),
            },
            KvOperation::Delete {
                namespace: "connections".to_string(),
                key: dot_key.clone(),
            },
        ];
        if let Err(e) = kv.apply_transaction(&ops).await {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to persist connection: {}", e),
            )
                .into_response();
        }
    }

    let mut conns = state.connections.write();
    conns.remove(&dot_key);
    conns.insert(canonical_key, payload);
    (StatusCode::OK, Json(json!({"message": "success"}))).into_response()
}

pub async fn get_connection_conf_key(
    State(state): State<AppState>,
    Path((name, conf_key)): Path<(String, String)>,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    if let Err(resp) = check_valid_name(&conf_key) {
        return resp;
    }
    let canonical_key = format!("{}/{}", name, conf_key);
    let dot_key = format!("{}.{}", name, conf_key);

    let mem_val = {
        let conns = state.connections.read();
        conns
            .get(&canonical_key)
            .or_else(|| conns.get(&dot_key))
            .cloned()
    };
    if let Some(mut val) = mem_val {
        crate::secrets::mask_secrets(&mut val);
        return Json(val).into_response();
    }

    if let Some(kv) = state.kv.as_ref() {
        match kv.get("connections", &canonical_key).await {
            Ok(Some(raw)) => {
                if let Ok(mut val) = serde_json::from_str::<Value>(&raw) {
                    state.connections.write().insert(canonical_key, val.clone());
                    crate::secrets::mask_secrets(&mut val);
                    return Json(val).into_response();
                }
            }
            Ok(None) => {}
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Storage read error: {}", e),
                )
                    .into_response();
            }
        }
        match kv.get("connections", &dot_key).await {
            Ok(Some(raw)) => {
                if let Ok(mut val) = serde_json::from_str::<Value>(&raw) {
                    state.connections.write().insert(dot_key, val.clone());
                    crate::secrets::mask_secrets(&mut val);
                    return Json(val).into_response();
                }
            }
            Ok(None) => {}
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Storage read error: {}", e),
                )
                    .into_response();
            }
        }
    }

    (
        StatusCode::NOT_FOUND,
        Json(json!({
            "message": format!("Connection conf_key {} for {} not found", conf_key, name)
        })),
    )
        .into_response()
}

pub async fn delete_connection_conf_key(
    State(state): State<AppState>,
    Path((name, conf_key)): Path<(String, String)>,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    if let Err(resp) = check_valid_name(&conf_key) {
        return resp;
    }
    let canonical_key = format!("{}/{}", name, conf_key);
    let dot_key = format!("{}.{}", name, conf_key);
    let _guard = state.config_op_lock.lock().await;

    let exists = {
        let conns = state.connections.read();
        conns.contains_key(&canonical_key) || conns.contains_key(&dot_key)
    };
    if !exists {
        return (
            StatusCode::NOT_FOUND,
            Json(json!({
                "message": format!("Connection conf_key {} for {} not found", conf_key, name)
            })),
        )
            .into_response();
    }

    if let Some(kv) = state.kv.as_ref() {
        let ops = [
            KvOperation::Delete {
                namespace: "connections".to_string(),
                key: canonical_key.clone(),
            },
            KvOperation::Delete {
                namespace: "connections".to_string(),
                key: dot_key.clone(),
            },
        ];
        if let Err(e) = kv.apply_transaction(&ops).await {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to delete connection: {}", e),
            )
                .into_response();
        }
    }

    let mut conns = state.connections.write();
    conns.remove(&canonical_key);
    conns.remove(&dot_key);
    (StatusCode::OK, Json(json!({"message": "success"}))).into_response()
}

pub async fn register_source_connection(
    State(state): State<AppState>,
    Path(name): Path<String>,
    body: Bytes,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    let payload = if body.is_empty() {
        json!({ "id": name })
    } else {
        serde_json::from_slice::<Value>(&body).unwrap_or_else(|_| json!({ "id": name }))
    };
    let id = payload
        .get("id")
        .and_then(|v| v.as_str())
        .unwrap_or(&name)
        .to_string();
    let _guard = state.config_op_lock.lock().await;
    if let Err(e) = persist_config_entry(&state, "connections", &id, &payload).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to persist connection: {}", e),
        )
            .into_response();
    }
    state.connections.write().insert(id, payload);
    (StatusCode::OK, Json(json!({"message": "success"}))).into_response()
}

pub async fn register_sink_connection(
    State(state): State<AppState>,
    Path(name): Path<String>,
    body: Bytes,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    let payload = if body.is_empty() {
        json!({ "id": name })
    } else {
        serde_json::from_slice::<Value>(&body).unwrap_or_else(|_| json!({ "id": name }))
    };
    let id = payload
        .get("id")
        .and_then(|v| v.as_str())
        .unwrap_or(&name)
        .to_string();
    let _guard = state.config_op_lock.lock().await;
    if let Err(e) = persist_config_entry(&state, "connections", &id, &payload).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to persist connection: {}", e),
        )
            .into_response();
    }
    state.connections.write().insert(id, payload);
    (StatusCode::OK, Json(json!({"message": "success"}))).into_response()
}

pub async fn register_lookup_connection(
    State(state): State<AppState>,
    Path(name): Path<String>,
    body: Bytes,
) -> Response {
    if let Err(resp) = check_valid_name(&name) {
        return resp;
    }
    let payload = if body.is_empty() {
        json!({ "id": name })
    } else {
        serde_json::from_slice::<Value>(&body).unwrap_or_else(|_| json!({ "id": name }))
    };
    let id = payload
        .get("id")
        .and_then(|v| v.as_str())
        .unwrap_or(&name)
        .to_string();
    let _guard = state.config_op_lock.lock().await;
    if let Err(e) = persist_config_entry(&state, "connections", &id, &payload).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to persist connection: {}", e),
        )
            .into_response();
    }
    state.connections.write().insert(id, payload);
    (StatusCode::OK, Json(json!({"message": "success"}))).into_response()
}

pub async fn list_connections(State(state): State<AppState>) -> impl IntoResponse {
    let mut conns: Vec<Value> = state.connections.read().values().cloned().collect();
    for c in &mut conns {
        crate::secrets::mask_secrets(c);
    }
    Json(conns)
}

pub async fn create_connection(
    State(state): State<AppState>,
    Json(mut payload): Json<Value>,
) -> Response {
    let id = payload
        .get("id")
        .and_then(|v| v.as_str())
        .or_else(|| payload.get("name").and_then(|v| v.as_str()))
        .unwrap_or("")
        .to_string();
    if id.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"message": "Missing connection id"})),
        )
            .into_response();
    }
    let canonical = id.replace('.', "/");
    let dot = id.replace('/', ".");
    {
        let conns = state.connections.read();
        if conns.contains_key(&id) || conns.contains_key(&canonical) || conns.contains_key(&dot) {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({
                    "message": format!("connection {} already been created", id)
                })),
            )
                .into_response();
        }
    }
    crate::secrets::interpolate_secrets(&mut payload, state.kv.as_deref());
    let _guard = state.config_op_lock.lock().await;
    if let Err(e) = persist_config_entry(&state, "connections", &id, &payload).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "message": format!("Failed to persist connection: {}", e)
            })),
        )
            .into_response();
    }
    state.connections.write().insert(id.clone(), payload);
    (StatusCode::CREATED, "success").into_response()
}

pub async fn get_connection(State(state): State<AppState>, Path(id): Path<String>) -> Response {
    let canonical = id.replace('.', "/");
    let dot = id.replace('/', ".");
    let mem_val = {
        let conns = state.connections.read();
        conns
            .get(&id)
            .or_else(|| conns.get(&canonical))
            .or_else(|| conns.get(&dot))
            .cloned()
    };
    if let Some(mut conn) = mem_val {
        crate::secrets::mask_secrets(&mut conn);
        return Json(conn).into_response();
    }

    if let Some(kv) = state.kv.as_ref() {
        for candidate in [&id, &canonical, &dot] {
            match kv.get("connections", candidate).await {
                Ok(Some(raw)) => {
                    if let Ok(mut val) = serde_json::from_str::<Value>(&raw) {
                        state
                            .connections
                            .write()
                            .insert(candidate.to_string(), val.clone());
                        crate::secrets::mask_secrets(&mut val);
                        return Json(val).into_response();
                    }
                }
                Ok(None) => {}
                Err(e) => {
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        Json(json!({
                            "message": format!("Storage read error: {}", e)
                        })),
                    )
                        .into_response();
                }
            }
        }
    }

    (
        StatusCode::NOT_FOUND,
        Json(json!({
            "message": format!("Connection {} not found", id)
        })),
    )
        .into_response()
}

pub async fn delete_connection(State(state): State<AppState>, Path(id): Path<String>) -> Response {
    let _guard = state.config_op_lock.lock().await;
    let canonical = id.replace('.', "/");
    let dot = id.replace('/', ".");
    let exists = {
        let conns = state.connections.read();
        conns.contains_key(&id) || conns.contains_key(&canonical) || conns.contains_key(&dot)
    };
    if !exists {
        return (
            StatusCode::NOT_FOUND,
            Json(json!({
                "message": format!("Connection {} not found", id)
            })),
        )
            .into_response();
    }

    if let Some(kv) = state.kv.as_ref() {
        let mut ops = vec![KvOperation::Delete {
            namespace: "connections".to_string(),
            key: id.clone(),
        }];
        if canonical != id {
            ops.push(KvOperation::Delete {
                namespace: "connections".to_string(),
                key: canonical.clone(),
            });
        }
        if dot != id && dot != canonical {
            ops.push(KvOperation::Delete {
                namespace: "connections".to_string(),
                key: dot.clone(),
            });
        }
        if let Err(e) = kv.apply_transaction(&ops).await {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to delete connection: {}", e),
            )
                .into_response();
        }
    }

    let mut conns = state.connections.write();
    conns.remove(&id);
    conns.remove(&canonical);
    conns.remove(&dot);
    (StatusCode::OK, "success").into_response()
}

/// Update-or-insert connection properties (eKuiper `PUT /connections/:id`):
/// merges the JSON body into the stored entry and returns it for readback.
pub async fn update_connection(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Json(mut payload): Json<Value>,
) -> Response {
    let _guard = state.config_op_lock.lock().await;
    let mut stored = state
        .connections
        .read()
        .get(&id)
        .cloned()
        .unwrap_or_else(|| json!({"id": id}));
    crate::secrets::preserve_masked_secrets(&mut payload, &stored);
    crate::secrets::interpolate_secrets(&mut payload, state.kv.as_deref());
    merge_json_object(&mut stored, &payload);
    if let Some(obj) = stored.as_object_mut() {
        obj.insert("id".to_string(), Value::String(id.clone()));
    }
    if let Err(e) = persist_config_entry(&state, "connections", &id, &stored).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to persist connection: {}", e),
        )
            .into_response();
    }
    state.connections.write().insert(id, stored.clone());
    let mut masked = stored;
    crate::secrets::mask_secrets(&mut masked);
    Json(masked).into_response()
}

#[cfg(test)]
mod tests {
    use super::*;
    use rekuiper_core::{RuleManager, StreamBus, StreamManager, TableManager};

    #[tokio::test]
    async fn test_save_source_conf_key_rejects_disallowed_video_url() {
        let bus = StreamBus::new();
        let state = AppState::new(
            "test".to_string(),
            rekuiper_conf::KuiperConfig::default(),
            StreamManager::new(),
            TableManager::new(),
            RuleManager::new(bus.clone()),
            bus,
        );
        let payload = json!({
            "url": "file:///etc/shadow"
        });
        let body = Bytes::from(payload.to_string());
        let resp = save_source_conf_key(
            State(state),
            Path(("video".to_string(), "bad_conf".to_string())),
            body,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_save_source_conf_key_accepts_valid_video_conf() {
        let bus = StreamBus::new();
        let state = AppState::new(
            "test".to_string(),
            rekuiper_conf::KuiperConfig::default(),
            StreamManager::new(),
            TableManager::new(),
            RuleManager::new(bus.clone()),
            bus,
        );
        let payload = json!({
            "interval": 500,
            "url": "rtsp://camera.internal:554/live"
        });
        let body = Bytes::from(payload.to_string());
        let resp = save_source_conf_key(
            State(state),
            Path(("video".to_string(), "good_conf".to_string())),
            body,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
    }
}