-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.rs
More file actions
1074 lines (998 loc) · 38.9 KB
/
Copy pathserve.rs
File metadata and controls
1074 lines (998 loc) · 38.9 KB
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
// SPDX-License-Identifier: AGPL-3.0
//! # Registry Container Mode (HTTP Server)
//!
//! Serve a Regedited document over HTTP as a REST API. This enables:
//! - Remote registry access
//! - Containerized configuration
//! - CI-friendly configuration queries
//! - Testable registry endpoints
//!
//! ## Endpoints
//!
//! | Method | Path | Description |
//! |--------|------|-------------|
//! | GET | `/` | Server status + index list |
//! | GET | `/sections` | List all indexes (compatibility route name) |
//! | GET | `/section/{index}` | Get fixed-record metadata (legacy route name) |
//! | GET | `/section/{index}/db` | Get database table |
//! | GET | `/section/{index}/hexline` | Get hex-word line |
//! | GET | `/section/{index}/ascii` | Legacy alias for `/hexline` |
//! | GET | `/section/{index}/zone/{slot}` | Extract absolute zone content |
//! | GET | `/grep?pattern={p}&index={i}` | Validate an index and search shared text |
//! | GET | `/state` | Current Regedited state JSON |
//! | GET | `/ref?spec={spec}` | Read a native ref spec |
//! | GET | `/ref-bool?left={a}&op={op}&right={b}` | Boolean comparison over refs/literals |
//! | GET | `/types` | List zone types |
//! | GET | `/wal` | WAL status |
//! | POST | `/query` | Execute boolean query |
//!
//! ## Example Usage
//!
//! ```bash
//! # Start the server
//! regedited serve --file config.regd --port 5000
//!
//! # Query from anywhere
//! curl http://localhost:5000/sections
//! curl http://localhost:5000/section/64/db
//! curl "http://localhost:5000/grep?pattern=enabled&index=64"
//! ```
use crate::{
db_line::{parse_numeric_line, DecimalValue},
fast_ops::{fast_scan_content, ScannedSection},
header::{scan_content, DocumentHeader},
wal::WalStatus,
zone_editor::extract_zone_content,
zone_type::{decode_hex_word, encode_hex_word},
Result,
};
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use tiny_http::{Method, Request, Response, Server, StatusCode};
/// Server configuration
#[derive(Debug, Clone)]
pub struct ServeConfig {
/// Port to listen on
pub port: u16,
/// Document file path
pub file_path: String,
/// Enable CORS
pub cors: bool,
/// Read-only mode (no modifications)
pub read_only: bool,
}
impl Default for ServeConfig {
fn default() -> Self {
Self {
port: 5000,
file_path: String::new(),
cors: true,
read_only: true,
}
}
}
/// Shared server state
struct ServerState {
config: ServeConfig,
/// Cached document header
header: Mutex<DocumentHeader>,
/// Cached file content
content: Mutex<String>,
}
/// Start the HTTP server
pub fn serve(config: ServeConfig) -> Result<()> {
let addr = format!("0.0.0.0:{}", config.port);
let server = Server::http(&addr).map_err(|e| {
crate::RegeditedError::Io(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to bind to {}: {}", addr, e),
))
})?;
// Load document
let content = std::fs::read_to_string(&config.file_path)?;
let header = scan_content(&content)?;
let state = Arc::new(ServerState {
config: config.clone(),
header: Mutex::new(header),
content: Mutex::new(content),
});
println!("Regedited server running on http://{}", addr);
println!("Serving: {}", config.file_path);
println!("Read-only: {}", config.read_only);
println!("\nEndpoints:");
println!(" GET / — Status + indexes");
println!(" GET /sections — List all indexes (legacy route name)");
println!(" GET /section/{{index}} — Index metadata");
println!(" GET /section/{{index}}/db — Database table");
println!(" GET /section/{{index}}/hexline — Hex-word line");
println!(" GET /section/{{index}}/ascii — Legacy alias for /hexline");
println!(" GET /section/{{index}}/zone/{{i}} — Zone content");
println!(" GET /grep?pattern= &index= — Search an index");
println!(" GET /state — Current Regedited state");
println!(" GET /ref?spec= — Read native ref spec");
println!(" GET /ref-bool?left=&op=&right= — Boolean ref check");
println!(" GET /types — Zone types");
println!(" GET /wal — WAL status");
for request in server.incoming_requests() {
let state = Arc::clone(&state);
handle_request(request, state);
}
Ok(())
}
fn handle_request(request: Request, state: Arc<ServerState>) {
// Handle /query specially since it needs to consume the request body
if *request.method() == Method::Post && request.url() == "/query" {
handle_query(request, &state);
return;
}
let response = match (request.method(), request.url()) {
(Method::Get, "/") => handle_root(&state),
(Method::Get, "/sections") => handle_sections(&state),
(Method::Get, path) if path.starts_with("/section/") && path.ends_with("/db") => {
handle_section_db(path, &state)
}
(Method::Get, path) if path.starts_with("/section/") && path.contains("/zone/") => {
handle_section_zone(path, &state)
}
(Method::Get, path)
if path.starts_with("/section/")
&& (path.ends_with("/hexline")
|| path.ends_with("/hex-word-line")
|| path.ends_with("/ascii")) =>
{
handle_section_ascii(path, &state)
}
(Method::Get, path) if path.starts_with("/section/") => handle_section(path, &state),
(Method::Get, path) if path.starts_with("/grep") => handle_grep(request.url(), &state),
(Method::Get, "/state") => handle_state(&state),
(Method::Get, path) if path.starts_with("/ref?") => handle_ref(request.url(), &state),
(Method::Get, path) if path.starts_with("/ref-bool?") => {
handle_ref_bool(request.url(), &state)
}
(Method::Get, "/types") => handle_types(),
(Method::Get, "/wal") => handle_wal(&state),
(Method::Get, "/health") => handle_health(&state),
_ => json_response(404, r#"{"error": "Not found"}"#),
};
if let Err(e) = request.respond(response) {
eprintln!("Response error: {}", e);
}
}
// ==================== HANDLERS ====================
fn handle_root(state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let header = state.header.lock().unwrap();
let sections: Vec<String> = header
.sections
.values()
.map(|info| info.index_label())
.collect();
let body = format!(
r#"{{"status":"ok","regedited":"0.2.0","sections":{},"read_only":{},"sections_count":{}}}"#,
serde_json::to_string(§ions).unwrap_or_default(),
state.config.read_only,
header.section_count()
);
json_response(200, &body)
}
fn handle_sections(state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let header = state.header.lock().unwrap();
let sections: Vec<BTreeMap<String, String>> = header
.sections
.iter()
.map(|(name, info)| {
let mut map = BTreeMap::new();
map.insert("index".to_string(), info.index_label());
let _ = name;
map.insert("marker_line".to_string(), info.header_line.to_string());
map.insert("record_start".to_string(), info.index_line.to_string());
map.insert("record_end".to_string(), info.string3_line.to_string());
map.insert("record_lines".to_string(), info.total_lines().to_string());
map
})
.collect();
let body = serde_json::to_string(§ions).unwrap_or_default();
json_response(200, &body)
}
fn handle_section(path: &str, state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let name = path.trim_start_matches("/section/");
let name = name.trim_end_matches("/");
let header = state.header.lock().unwrap();
let content = state.content.lock().unwrap();
if let Ok(info) = header.resolve_section(name) {
let lines: Vec<&str> = content.lines().collect();
let db_line = if info.numeric_line < lines.len() {
lines[info.numeric_line]
} else {
""
};
let body = serde_json::json!({
"index": info.registry_index,
"index_key": info.index_label(),
"marker_line": info.header_line,
"index_line": info.index_line,
"hex_word_line": info.ascii_line,
"numeric_line": info.numeric_line,
"string1_line": info.string1_line,
"string2_line": info.string2_line,
"string3_line": info.string3_line,
"db_line": db_line,
"record_lines": info.total_lines()
});
json_response(200, &body.to_string())
} else {
json_response(
404,
&format!(r#"{{"error":{}}}"#, json_escape(&format!("Index '{}' not found", name))),
)
}
}
fn handle_section_db(path: &str, state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let name = path.trim_start_matches("/section/");
let name = name.trim_end_matches("/db");
let header = state.header.lock().unwrap();
let content = state.content.lock().unwrap();
if let Ok(info) = header.resolve_section(name) {
let lines: Vec<&str> = content.lines().collect();
// Extract index, hex-word line, numeric line, and strings.
let ascii = if info.header_line + 2 < lines.len() {
lines[info.header_line + 2]
} else {
""
};
let numeric = if info.numeric_line < lines.len() {
lines[info.numeric_line]
} else {
""
};
let str1 = if info.string1_line < lines.len() {
lines[info.string1_line]
} else {
""
};
let str2 = if info.string2_line < lines.len() {
lines[info.string2_line]
} else {
""
};
let str3 = if info.string3_line < lines.len() {
lines[info.string3_line]
} else {
""
};
let db_values: Vec<DecimalValue> = parse_numeric_line(numeric)
.map(|values| values.to_vec())
.unwrap_or_default();
let body = serde_json::json!({
"section": info.index_label(),
"index": info.registry_index,
"hex_word_line": ascii,
"ascii_store": ascii,
"db_values": db_values,
"strings": [str1, str2, str3]
});
json_response(200, &body.to_string())
} else {
json_response(
404,
&format!(r#"{{"error":{}}}"#, json_escape(&format!("Index '{}' not found", name))),
)
}
}
fn handle_section_ascii(path: &str, state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let name = path.trim_start_matches("/section/");
let name = name
.trim_end_matches("/hex-word-line")
.trim_end_matches("/hexline")
.trim_end_matches("/ascii");
let header = state.header.lock().unwrap();
let content = state.content.lock().unwrap();
if let Ok(info) = header.resolve_section(name) {
let lines: Vec<&str> = content.lines().collect();
let ascii = if info.header_line + 2 < lines.len() {
lines[info.header_line + 2]
} else {
""
};
let body = serde_json::json!({
"section": info.index_label(),
"index": info.registry_index,
"hex_word_line": ascii,
"ascii_store": ascii
});
json_response(200, &body.to_string())
} else {
json_response(
404,
&format!(r#"{{"error":{}}}"#, json_escape(&format!("Index '{}' not found", name))),
)
}
}
fn handle_section_zone(path: &str, state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
// Format: /section/{name}/zone/{index}
let parts: Vec<&str> = path.split('/').collect();
if parts.len() < 5 {
return json_response(
400,
r#"{"error": "Invalid path. Use /section/{index}/zone/{zone}"}"#,
);
}
let name = parts[2];
let zone_idx: usize = match parts[4].parse() {
Ok(value) => value,
Err(error) => {
return json_response(
400,
&serde_json::json!({
"error": format!("Invalid zero-based zone slot '{}': {}", parts[4], error)
})
.to_string(),
)
}
};
let header = state.header.lock().unwrap();
let content = state.content.lock().unwrap();
if let Ok(info) = header.resolve_section(name) {
match extract_zone_content(&content, info, zone_idx) {
Ok(zone_content) => {
let body = serde_json::json!({
"section": info.index_label(),
"index": info.registry_index,
"zone": zone_idx,
"content": zone_content
});
json_response(200, &body.to_string())
}
Err(e) => json_response(
500,
&serde_json::json!({ "error": e.to_string() }).to_string(),
),
}
} else {
json_response(
404,
&format!(r#"{{"error":{}}}"#, json_escape(&format!("Index '{}' not found", name))),
)
}
}
fn handle_grep(url: &str, state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let params = parse_query_string(url);
let pattern = params.get("pattern").map(|s| s.as_str()).unwrap_or("");
let index_filter = params.get("index").or_else(|| params.get("section"));
if pattern.is_empty() {
return json_response(400, r#"{"error": "Missing 'pattern' parameter"}"#);
}
let header = state.header.lock().unwrap();
let content = state.content.lock().unwrap();
let selected_index = match index_filter {
Some(reference) => match header.resolve_section(reference) {
Ok(info) => Some(info.index_label()),
Err(_) => {
return json_response(
404,
&format!(r#"{{"error":"Index '{}' not found"}}"#, reference),
)
}
},
None => None,
};
let mut matches: Vec<BTreeMap<String, String>> = Vec::new();
for (i, line) in content.lines().enumerate() {
if line.to_lowercase().contains(&pattern.to_lowercase()) {
let mut m = BTreeMap::new();
m.insert(
"context".to_string(),
selected_index.clone().unwrap_or_else(|| "__all__".to_string()),
);
m.insert("line".to_string(), i.to_string());
m.insert("content".to_string(), line.to_string());
matches.push(m);
}
}
let body = serde_json::json!({
"pattern": pattern,
"matches": matches
});
json_response(200, &body.to_string())
}
#[derive(Debug, Clone)]
enum ServeRef {
Literal(String),
IndexAll { registry_index: u64 },
IndexString { registry_index: u64, slot: usize },
IndexDb { registry_index: u64, slot: usize },
IndexDbLine { registry_index: u64 },
IndexAscii { registry_index: u64 },
IndexZone { registry_index: u64, zone: usize },
IndexZoneHex { registry_index: u64, zone: usize },
HexRange { start: String, end: String },
}
fn json_escape(value: &str) -> String {
serde_json::to_string(value).unwrap_or_else(|_| "\"\"".to_string())
}
fn parse_user_slot(raw: &str, max: usize, label: &str) -> std::result::Result<usize, String> {
let value = raw
.parse::<usize>()
.map_err(|e| format!("Invalid {} slot '{}': {}", label, raw, e))?;
if value == 0 || value > max {
return Err(format!(
"{} slot {} out of range; use 1-{}",
label, value, max
));
}
Ok(value - 1)
}
fn parse_hex_ref(rest: &str) -> ServeRef {
let trimmed = rest.trim();
if let Some((start, end)) = trimmed.split_once("..") {
return ServeRef::HexRange {
start: start.trim().to_string(),
end: end.trim().to_string(),
};
}
if let Some((start, end)) = trimmed.split_once(" : ") {
return ServeRef::HexRange {
start: start.trim().to_string(),
end: end.trim().to_string(),
};
}
if let Some((start, end)) = trimmed.split_once(',') {
return ServeRef::HexRange {
start: start.trim().to_string(),
end: end.trim().to_string(),
};
}
ServeRef::HexRange {
start: trimmed.to_string(),
end: trimmed.to_string(),
}
}
fn parse_ref_spec(spec: &str) -> std::result::Result<ServeRef, String> {
let trimmed = spec.trim();
if let Some(value) = trimmed
.strip_prefix("text:")
.or_else(|| trimmed.strip_prefix("literal:"))
{
return Ok(ServeRef::Literal(value.to_string()));
}
if let Some(rest) = trimmed.strip_prefix("hex:") {
return Ok(parse_hex_ref(rest));
}
if decode_hex_word(trimmed).is_ok() {
return Ok(ServeRef::HexRange {
start: trimmed.to_string(),
end: trimmed.to_string(),
});
}
let parts: Vec<&str> = trimmed.split(':').collect();
if parts.len() == 2 && parts[0].eq_ignore_ascii_case("index") {
return Ok(ServeRef::IndexAll {
registry_index: parts[1]
.parse::<u64>()
.map_err(|e| format!("Invalid registry index '{}': {}", parts[1], e))?,
});
}
if parts.len() >= 3 && parts[0].eq_ignore_ascii_case("index") {
let registry_index = parts[1]
.parse::<u64>()
.map_err(|e| format!("Invalid registry index '{}': {}", parts[1], e))?;
let kind = parts[2].to_ascii_lowercase();
return match kind.as_str() {
"str" | "string" => {
if parts.len() != 4 {
return Err("index string spec must be index:<n>:string:<1-3>".to_string());
}
Ok(ServeRef::IndexString {
registry_index,
slot: parse_user_slot(parts[3], 3, "string")?,
})
}
"db" | "num" | "number" => {
if parts.len() != 4 {
return Err("index DB spec must be index:<n>:db:<1-9>".to_string());
}
Ok(ServeRef::IndexDb {
registry_index,
slot: parse_user_slot(parts[3], 9, "DB")?,
})
}
"dbline" | "db-line" => Ok(ServeRef::IndexDbLine { registry_index }),
"hexline" | "hex-word-line" | "hex_word_line" | "ascii" | "ranges" => {
Ok(ServeRef::IndexAscii { registry_index })
}
"zone" | "range" | "defined" => {
if parts.len() != 4 {
return Err("index zone spec must be index:<n>:zone:<1-3>".to_string());
}
Ok(ServeRef::IndexZone {
registry_index,
zone: parse_user_slot(parts[3], 3, "zone")?,
})
}
"zonehex" | "rangehex" | "defhex" | "definedhex" => {
if parts.len() != 4 {
return Err("index zonehex spec must be index:<n>:zonehex:<1-3>".to_string());
}
Ok(ServeRef::IndexZoneHex {
registry_index,
zone: parse_user_slot(parts[3], 3, "zone")?,
})
}
_ => Err(format!("Unknown index ref kind '{}'", parts[2])),
};
}
Ok(ServeRef::Literal(trimmed.to_string()))
}
fn line_range_text(
content: &str,
start_line: usize,
end_line: usize,
) -> std::result::Result<String, String> {
let lines: Vec<&str> = content.lines().collect();
if start_line >= lines.len() || end_line >= lines.len() {
return Err(format!(
"Line range {}-{} is out of bounds for {} lines",
start_line,
end_line,
lines.len()
));
}
Ok(lines[start_line..=end_line].join("\n"))
}
fn find_scanned_section(
content: &str,
registry_index: u64,
) -> std::result::Result<ScannedSection, String> {
let matches: Vec<_> = fast_scan_content(content)
.map_err(|e| e.to_string())?
.into_iter()
.filter(|section| section.index == registry_index)
.collect();
match matches.len() {
0 => Err(format!("Registry index {} not found", registry_index)),
1 => Ok(matches[0].clone()),
_ => Err(format!("Registry index {} is ambiguous", registry_index)),
}
}
fn read_ref_value(content: &str, spec: &ServeRef) -> std::result::Result<String, String> {
match spec {
ServeRef::Literal(value) => Ok(value.clone()),
ServeRef::IndexAll { registry_index } => {
let section = find_scanned_section(content, *registry_index)?;
crate::fast_ops::aggregate_index_content(content, §ion)
.map_err(|error| error.to_string())
}
ServeRef::IndexString {
registry_index,
slot,
} => Ok(find_scanned_section(content, *registry_index)?.strings[*slot].clone()),
ServeRef::IndexDb {
registry_index,
slot,
} => Ok(find_scanned_section(content, *registry_index)?.db_values[*slot].to_string()),
ServeRef::IndexDbLine { registry_index } => {
let section = find_scanned_section(content, *registry_index)?;
Ok(section
.db_values
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" | "))
}
ServeRef::IndexAscii { registry_index } => {
let section = find_scanned_section(content, *registry_index)?;
let lines: Vec<&str> = content.lines().collect();
Ok(lines.get(section.ascii_line).unwrap_or(&"").to_string())
}
ServeRef::IndexZone {
registry_index,
zone,
} => {
let section = find_scanned_section(content, *registry_index)?;
let (start, end) = section.zone_pairs[*zone];
if start == 0 && end == 0 {
return Ok(String::new());
}
line_range_text(content, start as usize, end as usize)
}
ServeRef::IndexZoneHex {
registry_index,
zone,
} => {
let section = find_scanned_section(content, *registry_index)?;
let (start, end) = section.zone_pairs[*zone];
Ok(format!(
"{} : {}",
encode_hex_word(start, section.zone_types[*zone]),
encode_hex_word(end, section.zone_types[*zone])
))
}
ServeRef::HexRange { start, end } => {
let (start_line, _) = decode_hex_word(start).map_err(|e| e.to_string())?;
let (end_line, _) = decode_hex_word(end).map_err(|e| e.to_string())?;
if start_line > end_line {
return Err(format!("Hex range start {} is after end {}", start, end));
}
line_range_text(content, start_line as usize, end_line as usize)
}
}
}
fn state_json(content: &str, file_path: &str) -> std::result::Result<String, String> {
let scan = fast_scan_content(content).map_err(|e| e.to_string())?;
let lines: Vec<&str> = content.lines().collect();
let mut sections = Vec::new();
for section in scan {
let ascii = lines.get(section.ascii_line).unwrap_or(&"").to_string();
let mut zones = Vec::new();
for slot in 0..3 {
let (start, end) = section.zone_pairs[slot];
let zone_text = if start == 0 && end == 0 {
String::new()
} else {
line_range_text(content, start as usize, end as usize).unwrap_or_default()
};
let mut zone = BTreeMap::new();
zone.insert("slot".to_string(), serde_json::json!(slot + 1));
zone.insert("start".to_string(), serde_json::json!(start));
zone.insert("end".to_string(), serde_json::json!(end));
zone.insert(
"zone_type".to_string(),
serde_json::json!(section.zone_types[slot].short()),
);
zone.insert(
"content_len".to_string(),
serde_json::json!(zone_text.len()),
);
zone.insert(
"content_checksum".to_string(),
serde_json::json!(crate::checksum_hex(zone_text.as_bytes())),
);
zones.push(zone);
}
let mut item = BTreeMap::new();
item.insert("index".to_string(), serde_json::json!(section.index));
item.insert("name".to_string(), serde_json::json!(section.name));
item.insert("hex_word_line".to_string(), serde_json::json!(ascii));
item.insert("ascii".to_string(), serde_json::json!(ascii));
item.insert(
"db_values".to_string(),
serde_json::json!(section.db_values),
);
item.insert("strings".to_string(), serde_json::json!(section.strings));
item.insert("zones".to_string(), serde_json::json!(zones));
sections.push(item);
}
let body = serde_json::json!({
"format": "regedited-native-state-v1",
"file": file_path,
"file_checksum": crate::checksum_hex(content.as_bytes()),
"sections": sections
});
Ok(body.to_string())
}
fn handle_state(state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let content = state.content.lock().unwrap();
match state_json(&content, &state.config.file_path) {
Ok(body) => json_response(200, &body),
Err(e) => json_response(500, &format!(r#"{{"error":{}}}"#, json_escape(&e))),
}
}
fn handle_ref(url: &str, state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let params = parse_query_string(url);
let Some(spec) = params.get("spec") else {
return json_response(400, r#"{"error":"Missing spec parameter"}"#);
};
let content = state.content.lock().unwrap();
match parse_ref_spec(spec).and_then(|parsed| read_ref_value(&content, &parsed)) {
Ok(value) => {
let body = format!(
r#"{{"spec":{},"value":{},"bytes":{}}}"#,
json_escape(spec),
json_escape(&value),
value.len()
);
json_response(200, &body)
}
Err(e) => json_response(400, &format!(r#"{{"error":{}}}"#, json_escape(&e))),
}
}
fn resolve_literal_or_ref(content: &str, value: &str) -> std::result::Result<String, String> {
let looks_like_ref = value.starts_with("index:")
|| value.starts_with("hex:")
|| value.starts_with("text:")
|| value.starts_with("literal:")
|| decode_hex_word(value).is_ok();
if looks_like_ref {
parse_ref_spec(value).and_then(|parsed| read_ref_value(content, &parsed))
} else {
Ok(value.to_string())
}
}
fn read_bool_scope(content: &str, scope: &str) -> std::result::Result<String, String> {
if scope == "__all__" {
return Ok(content.to_string());
}
let expanded = crate::qol::compact_ref(scope).unwrap_or_else(|| scope.to_string());
let parsed = parse_ref_spec(&expanded)?;
if matches!(parsed, ServeRef::Literal(_)) {
return Err(format!(
"Boolean scope '{}' is not a reference; use __all__, i<INDEX>, i<INDEX>s<SLOT>, i<INDEX>db<SLOT>, i<INDEX>dbl, i<INDEX>hl, or i<INDEX>z<ZONE>",
scope
));
}
read_ref_value(content, &parsed)
}
fn compare_ref_values(
left_value: &str,
op: &str,
right_value: &str,
) -> std::result::Result<bool, String> {
let normalized = op.to_ascii_lowercase();
match normalized.as_str() {
"contains" => Ok(left_value
.to_lowercase()
.contains(&right_value.to_lowercase())),
"eq" | "==" | "=" => match (
DecimalValue::parse(left_value.trim()),
DecimalValue::parse(right_value.trim()),
) {
(Ok(left), Ok(right)) => Ok(left == right),
_ => Ok(left_value == right_value),
},
"ne" | "!=" => match (
DecimalValue::parse(left_value.trim()),
DecimalValue::parse(right_value.trim()),
) {
(Ok(left), Ok(right)) => Ok(left != right),
_ => Ok(left_value != right_value),
},
"gt" | ">" | "gte" | ">=" | "lt" | "<" | "lte" | "<=" => {
let left_num = DecimalValue::parse(left_value.trim()).map_err(|error| {
format!("Left value '{}' is not numeric: {}", left_value.trim(), error)
})?;
let right_num = DecimalValue::parse(right_value.trim()).map_err(|error| {
format!(
"Right value '{}' is not numeric: {}",
right_value.trim(),
error
)
})?;
Ok(match normalized.as_str() {
"gt" | ">" => left_num > right_num,
"gte" | ">=" => left_num >= right_num,
"lt" | "<" => left_num < right_num,
"lte" | "<=" => left_num <= right_num,
_ => unreachable!(),
})
}
_ => Err(format!("Unknown op '{}'", op)),
}
}
fn handle_ref_bool(url: &str, state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let params = parse_query_string(url);
let Some(left) = params.get("left") else {
return json_response(400, r#"{"error":"Missing left parameter"}"#);
};
let Some(op) = params.get("op") else {
return json_response(400, r#"{"error":"Missing op parameter"}"#);
};
let Some(right) = params.get("right") else {
return json_response(400, r#"{"error":"Missing right parameter"}"#);
};
let content = state.content.lock().unwrap();
let result = (|| -> std::result::Result<bool, String> {
let left_value = resolve_literal_or_ref(&content, left)?;
let right_value = resolve_literal_or_ref(&content, right)?;
compare_ref_values(&left_value, op, &right_value)
})();
match result {
Ok(value) => json_response(200, &format!(r#"{{"value":{}}}"#, value)),
Err(e) => json_response(400, &format!(r#"{{"error":{}}}"#, json_escape(&e))),
}
}
fn handle_types() -> Response<std::io::Cursor<Vec<u8>>> {
use crate::typed_value::list_registry_types;
let types: Vec<BTreeMap<String, String>> = list_registry_types()
.into_iter()
.map(|(name, desc)| {
let mut m = BTreeMap::new();
m.insert("name".to_string(), name.to_string());
m.insert("description".to_string(), desc.to_string());
m
})
.collect();
json_response(200, &serde_json::to_string(&types).unwrap_or_default())
}
fn handle_wal(state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let status = WalStatus::check(&state.config.file_path);
match status {
Ok(s) => {
let body = format!(
r#"{{"has_wal":{},"is_committed":{},"entry_count":{},"wal_path":"{}"}}"#,
s.has_wal,
s.is_committed,
s.entry_count,
s.wal_path.display()
);
json_response(200, &body)
}
Err(e) => json_response(
500,
&serde_json::json!({ "error": e.to_string() }).to_string(),
),
}
}
fn handle_health(state: &ServerState) -> Response<std::io::Cursor<Vec<u8>>> {
let header = state.header.lock().unwrap();
let body = format!(
r#"{{"status":"healthy","sections":{},"read_only":{}}}"#,
header.section_count(),
state.config.read_only
);
json_response(200, &body)
}
fn handle_query(mut request: Request, state: &ServerState) {
let mut body_text = String::new();
let response = if request.as_reader().read_to_string(&mut body_text).is_ok() {
let parsed: serde_json::Value = match serde_json::from_str(&body_text) {
Ok(value) => value,
Err(e) => {
let response = json_response(400, &format!(r#"{{"error":"Invalid JSON: {}"}}"#, e));
if let Err(e) = request.respond(response) {
eprintln!("Query response error: {}", e);
}
return;
}
};
let content = state.content.lock().unwrap();
if let (Some(left), Some(op), Some(right)) = (
parsed.get("left").and_then(|v| v.as_str()),
parsed.get("op").and_then(|v| v.as_str()),
parsed.get("right").and_then(|v| v.as_str()),
) {
let left_value = resolve_literal_or_ref(&content, left);
let right_value = resolve_literal_or_ref(&content, right);
match (left_value, right_value) {
(Ok(left_value), Ok(right_value)) => {
let value = compare_ref_values(&left_value, op, &right_value);
match value {
Ok(value) => json_response(200, &format!(r#"{{"value":{}}}"#, value)),
Err(e) => {
json_response(400, &format!(r#"{{"error":{}}}"#, json_escape(&e)))
}
}
}
(Err(e), _) | (_, Err(e)) => {
json_response(400, &format!(r#"{{"error":{}}}"#, json_escape(&e)))
}
}
} else if let (Some(section), Some(operation), Some(patterns)) = (
parsed.get("section").and_then(|v| v.as_str()),
parsed.get("operation").and_then(|v| v.as_str()),
parsed.get("patterns").and_then(|v| v.as_array()),
) {
let section_text = match read_bool_scope(&content, section) {
Ok(value) => value,
Err(error) => {
let response =
json_response(400, &format!(r#"{{"error":{}}}"#, json_escape(&error)));
if let Err(error) = request.respond(response) {
eprintln!("Query response error: {}", error);
}
return;
}
};
let pats: Vec<String> = patterns
.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect();
let lower = section_text.to_lowercase();
let value = match operation.to_ascii_lowercase().as_str() {
"and" => pats.iter().all(|p| lower.contains(&p.to_lowercase())),
"or" => pats.iter().any(|p| lower.contains(&p.to_lowercase())),
_ => {
let response = json_response(
400,
&format!(r#"{{"error":"Unknown operation '{}'"}}"#, operation),
);
if let Err(e) = request.respond(response) {
eprintln!("Query response error: {}", e);
}
return;
}
};
json_response(200, &format!(r#"{{"value":{}}}"#, value))
} else {
json_response(
400,
r#"{"error":"Use {left,op,right} or {section,operation,patterns}"}"#,
)
}
} else {
json_response(400, r#"{"error": "Failed to read request body"}"#)
};
if let Err(e) = request.respond(response) {
eprintln!("Query response error: {}", e);
}
}
// ==================== UTILITIES ====================
fn json_response(status: u16, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
let data = body.as_bytes().to_vec();
let status = match status {
200 => StatusCode(200),
400 => StatusCode(400),
404 => StatusCode(404),
500 => StatusCode(500),
_ => StatusCode(status),
};
Response::new(
status,
vec![
tiny_http::Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap(),
],