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
//! The framed stdin/stdout protocol between the runner and a worker.
//!
//! One frame is a four-byte big-endian length prefix followed by
//! exactly that many bytes of one UTF-8 JSON value. The same frame
//! format runs both directions. The declared length is checked
//! against a limit before any allocation, so an oversized declaration
//! is refused without buying its buffer. EOF inside the header or the
//! payload is a truncated frame, the footprint of a killed writer,
//! and never parses.
//!
//! A response frame alone is not success. The runner also requires a
//! clean child exit and no trailing stdout bytes, so a worker that
//! crashes after writing plausible JSON, or logs past its frame, is
//! refused.
use std::io::{self, Read, Write};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::segments::Segment;
/// The schema identifier carried by every adapter request.
pub const REQUEST_SCHEMA: &str = "text-mirror/adapter-request@1";
/// The schema identifier carried by every adapter response.
pub const RESPONSE_SCHEMA: &str = "text-mirror/adapter-response@1";
/// Ceiling on request frame payload bytes, enforced by the worker
/// before allocation. Requests carry paths and options, never file
/// content, so they stay small.
pub const MAX_REQUEST_BYTES: u32 = 1024 * 1024;
macro_rules! literal_schema {
($name:ident, $value:expr) => {
/// A schema field pinned to one literal value. Serializes to
/// that literal and rejects every other value on read.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct $name;
impl Serialize for $name {
fn serialize<S: Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_str($value)
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
let value = String::deserialize(deserializer)?;
if value == $value {
Ok($name)
} else {
Err(D::Error::custom(format!(
"unrecognized schema {value:?}, expected {:?}",
$value
)))
}
}
}
};
}
literal_schema!(RequestSchema, REQUEST_SCHEMA);
literal_schema!(ResponseSchema, RESPONSE_SCHEMA);
/// One request frame from the runner to a worker.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
/// The literal string `text-mirror/adapter-request@1`.
pub schema: RequestSchema,
/// The adapter mode this request addresses.
pub adapter: String,
/// The adapter-specific request body.
pub payload: serde_json::Value,
}
/// One response frame from a worker to the runner.
///
/// Exactly one of `ok` and `error` is present. [`Response::validate`]
/// enforces that, and the runner refuses any frame that fails it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Response {
/// The literal string `text-mirror/adapter-response@1`.
pub schema: ResponseSchema,
/// The adapter-specific success body.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub ok: Option<serde_json::Value>,
/// The failure body.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub error: Option<WireError>,
}
impl Response {
/// A success response.
pub fn ok(value: serde_json::Value) -> Response {
Response {
schema: ResponseSchema,
ok: Some(value),
error: None,
}
}
/// A failure response.
pub fn err(code: &str, message: String) -> Response {
Response {
schema: ResponseSchema,
ok: None,
error: Some(WireError {
code: code.to_string(),
message,
}),
}
}
/// Checks that exactly one of `ok` and `error` is present.
pub fn validate(&self) -> std::result::Result<(), ResponseValidationError> {
match (&self.ok, &self.error) {
(Some(_), None) | (None, Some(_)) => Ok(()),
(Some(_), Some(_)) => Err(ResponseValidationError::BothBodies),
(None, None) => Err(ResponseValidationError::NoBody),
}
}
}
/// Why a response violates the one-body wire shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponseValidationError {
/// Both the success and failure bodies are present.
BothBodies,
/// Neither body is present.
NoBody,
}
/// A machine-readable failure carried over the wire.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WireError {
/// Stable reason code, such as `pdf_no_text_layer`.
pub code: String,
/// Detail for a human reading the manifest.
pub message: String,
}
/// How reading one frame ended.
#[derive(Debug)]
pub enum FrameRead {
/// A complete frame payload.
Complete(Vec<u8>),
/// EOF before any header byte. The writer produced nothing.
Empty,
/// EOF inside the header or the payload. The writer died mid-frame.
Truncated,
/// The header declared more bytes than the limit allows. Nothing
/// was allocated or read past the header.
Oversized {
/// The declared payload length.
declared: u64,
},
}
/// Reads one length-prefixed frame, checking the declared length
/// against `max_bytes` before allocating.
pub fn read_frame(reader: &mut impl Read, max_bytes: u32) -> io::Result<FrameRead> {
let mut header = [0u8; 4];
match read_exact_or_eof(reader, &mut header)? {
Fill::Empty => return Ok(FrameRead::Empty),
Fill::Partial => return Ok(FrameRead::Truncated),
Fill::Full => {}
}
let declared = u32::from_be_bytes(header);
if declared > max_bytes {
return Ok(FrameRead::Oversized {
declared: u64::from(declared),
});
}
let mut payload = vec![0u8; declared as usize];
match read_exact_or_eof(reader, &mut payload)? {
Fill::Full => Ok(FrameRead::Complete(payload)),
Fill::Empty | Fill::Partial => Ok(FrameRead::Truncated),
}
}
enum Fill {
Full,
Partial,
Empty,
}
fn read_exact_or_eof(reader: &mut impl Read, buffer: &mut [u8]) -> io::Result<Fill> {
let mut filled = 0;
while filled < buffer.len() {
match reader.read(&mut buffer[filled..]) {
Ok(0) => {
return Ok(if filled == 0 {
Fill::Empty
} else {
Fill::Partial
});
}
Ok(n) => filled += n,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(Fill::Full)
}
/// Writes one value as one frame and flushes.
pub fn write_frame<T: Serialize>(writer: &mut impl Write, value: &T) -> io::Result<()> {
let payload = serde_json::to_vec(value).map_err(io::Error::other)?;
let length = u32::try_from(payload.len())
.map_err(|_| io::Error::other("frame payload exceeds the u32 length prefix"))?;
writer.write_all(&length.to_be_bytes())?;
writer.write_all(&payload)?;
writer.flush()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_non_recovered_pdf_response_omits_the_recovered_field() {
use bodies::PdfOk;
// A non-recovered outcome serializes byte-identical to the
// pre-recovery wire: the `recovered` field is skipped entirely,
// so a mixed-version worker pairing can only trip on an
// actually-recovered document.
let plain = PdfOk {
text: "hi".to_string(),
warnings: Vec::new(),
segments: Vec::new(),
recovered: false,
};
let encoded = serde_json::to_string(&plain).unwrap();
assert!(
!encoded.contains("recovered"),
"false recovered is off the wire: {encoded}"
);
// The default fills it back in when the field is absent.
let back: PdfOk = serde_json::from_str(&encoded).unwrap();
assert!(!back.recovered);
let recovered = PdfOk {
recovered: true,
..plain
};
let encoded = serde_json::to_string(&recovered).unwrap();
assert!(
encoded.contains("\"recovered\":true"),
"a recovered outcome carries the field: {encoded}"
);
}
#[test]
fn frames_roundtrip() {
let mut buffer = Vec::new();
let request = Request {
schema: RequestSchema,
adapter: "pdf".to_string(),
payload: serde_json::json!({"input": "input.pdf"}),
};
write_frame(&mut buffer, &request).unwrap();
let mut cursor = std::io::Cursor::new(buffer);
let FrameRead::Complete(payload) = read_frame(&mut cursor, MAX_REQUEST_BYTES).unwrap()
else {
panic!("expected a complete frame");
};
let back: Request = serde_json::from_slice(&payload).unwrap();
assert_eq!(back.adapter, "pdf");
}
#[test]
fn oversized_declarations_are_refused_before_allocation() {
let mut bytes = u32::MAX.to_be_bytes().to_vec();
bytes.extend_from_slice(b"junk");
let mut cursor = std::io::Cursor::new(bytes);
let FrameRead::Oversized { declared } = read_frame(&mut cursor, 1024).unwrap() else {
panic!("expected an oversized refusal");
};
assert_eq!(declared, u64::from(u32::MAX));
}
#[test]
fn truncation_is_detected_in_header_and_payload() {
let mut cursor = std::io::Cursor::new(vec![0u8, 0, 0]);
assert!(matches!(
read_frame(&mut cursor, 1024).unwrap(),
FrameRead::Truncated
));
let mut bytes = 10u32.to_be_bytes().to_vec();
bytes.extend_from_slice(b"half");
let mut cursor = std::io::Cursor::new(bytes);
assert!(matches!(
read_frame(&mut cursor, 1024).unwrap(),
FrameRead::Truncated
));
let mut cursor = std::io::Cursor::new(Vec::<u8>::new());
assert!(matches!(
read_frame(&mut cursor, 1024).unwrap(),
FrameRead::Empty
));
}
#[test]
fn responses_require_exactly_one_body() {
assert!(Response::ok(serde_json::json!({})).validate().is_ok());
assert!(Response::err("io", "detail".to_string()).validate().is_ok());
let both = Response {
schema: ResponseSchema,
ok: Some(serde_json::json!({})),
error: Some(WireError {
code: "io".to_string(),
message: "detail".to_string(),
}),
};
assert_eq!(both.validate(), Err(ResponseValidationError::BothBodies));
let neither = Response {
schema: ResponseSchema,
ok: None,
error: None,
};
assert_eq!(neither.validate(), Err(ResponseValidationError::NoBody));
}
#[test]
fn probe_attempts_roundtrip_as_closed_wire_values() {
use bodies::{ProbeAttempt, ProbeName, ProbeOutcome, ProbeReport};
let report = ProbeReport {
attempts: crate::runner::runner_message_tests::IO_KINDS
.iter()
.copied()
.map(|error_kind| ProbeAttempt {
name: ProbeName::UnixSocket,
outcome: ProbeOutcome::Denied,
error_kind,
})
.collect(),
};
let value = serde_json::to_value(&report).unwrap();
let back: ProbeReport = serde_json::from_value(value).unwrap();
assert_eq!(
back.attempts.len(),
crate::runner::runner_message_tests::IO_KINDS.len()
);
for (attempt, expected_kind) in back
.attempts
.iter()
.zip(crate::runner::runner_message_tests::IO_KINDS)
{
assert_eq!(attempt.name, ProbeName::UnixSocket);
assert_eq!(attempt.outcome, ProbeOutcome::Denied);
assert_eq!(attempt.error_kind, *expected_kind);
}
let deadlock = serde_json::to_value(ProbeAttempt {
name: ProbeName::UnixSocket,
outcome: ProbeOutcome::Denied,
error_kind: io::ErrorKind::Deadlock,
})
.unwrap();
assert_eq!(deadlock["error_kind"], "deadlock");
let future_kind = serde_json::json!({
"name": "unix_socket",
"outcome": "denied",
"error_kind": "future_kind"
});
let fallback: ProbeAttempt = serde_json::from_value(future_kind).unwrap();
assert_eq!(fallback.error_kind, io::ErrorKind::Other);
let unknown = serde_json::json!({
"attempts": [{
"name": "unix_socket",
"outcome": "detail_from_worker",
"error_kind": "permission_denied"
}]
});
assert!(serde_json::from_value::<ProbeReport>(unknown).is_err());
}
#[test]
fn wrong_schema_values_are_rejected() {
let json = serde_json::to_string(&Response::ok(serde_json::json!({}))).unwrap();
let bumped = json.replace("adapter-response@1", "adapter-response@2");
assert!(serde_json::from_str::<Response>(&bumped).is_err());
}
}
/// Typed request and response bodies for the shipped adapters. Each
/// adapter's `payload` and `ok` values are these shapes.
pub mod bodies {
use std::io;
use super::*;
/// The fixed capability-probe attempts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProbeName {
/// IPv4 TCP connection.
Ipv4Tcp,
/// IPv6 TCP connection.
Ipv6Tcp,
/// Local Unix socket connection.
UnixSocket,
/// IPv4 UDP send.
UdpSend,
}
/// The closed result classes for one capability-probe attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProbeOutcome {
/// The connection succeeded.
Connected,
/// The attempt returned an immediate error.
Denied,
/// The attempt reached its time limit.
Timeout,
/// The parent supplied an invalid target.
InvalidTarget,
}
mod error_kind_wire {
use super::*;
// This enum mirrors every io::ErrorKind stable at the crate MSRV, Rust 1.88.
// Keep Other for kinds newer than the MSRV. Revisit the list when the MSRV changes.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum WireErrorKind {
NotFound,
PermissionDenied,
ConnectionRefused,
ConnectionReset,
HostUnreachable,
NetworkUnreachable,
ConnectionAborted,
NotConnected,
AddrInUse,
AddrNotAvailable,
NetworkDown,
BrokenPipe,
AlreadyExists,
WouldBlock,
NotADirectory,
IsADirectory,
DirectoryNotEmpty,
ReadOnlyFilesystem,
StaleNetworkFileHandle,
InvalidInput,
InvalidData,
TimedOut,
WriteZero,
StorageFull,
NotSeekable,
QuotaExceeded,
FileTooLarge,
ResourceBusy,
ExecutableFileBusy,
Deadlock,
CrossesDevices,
TooManyLinks,
InvalidFilename,
ArgumentListTooLong,
Interrupted,
Unsupported,
UnexpectedEof,
OutOfMemory,
Other,
#[serde(other)]
Unknown,
}
fn from_io_kind(kind: io::ErrorKind) -> Option<WireErrorKind> {
match kind {
io::ErrorKind::NotFound => Some(WireErrorKind::NotFound),
io::ErrorKind::PermissionDenied => Some(WireErrorKind::PermissionDenied),
io::ErrorKind::ConnectionRefused => Some(WireErrorKind::ConnectionRefused),
io::ErrorKind::ConnectionReset => Some(WireErrorKind::ConnectionReset),
io::ErrorKind::HostUnreachable => Some(WireErrorKind::HostUnreachable),
io::ErrorKind::NetworkUnreachable => Some(WireErrorKind::NetworkUnreachable),
io::ErrorKind::ConnectionAborted => Some(WireErrorKind::ConnectionAborted),
io::ErrorKind::NotConnected => Some(WireErrorKind::NotConnected),
io::ErrorKind::AddrInUse => Some(WireErrorKind::AddrInUse),
io::ErrorKind::AddrNotAvailable => Some(WireErrorKind::AddrNotAvailable),
io::ErrorKind::NetworkDown => Some(WireErrorKind::NetworkDown),
io::ErrorKind::BrokenPipe => Some(WireErrorKind::BrokenPipe),
io::ErrorKind::AlreadyExists => Some(WireErrorKind::AlreadyExists),
io::ErrorKind::WouldBlock => Some(WireErrorKind::WouldBlock),
io::ErrorKind::NotADirectory => Some(WireErrorKind::NotADirectory),
io::ErrorKind::IsADirectory => Some(WireErrorKind::IsADirectory),
io::ErrorKind::DirectoryNotEmpty => Some(WireErrorKind::DirectoryNotEmpty),
io::ErrorKind::ReadOnlyFilesystem => Some(WireErrorKind::ReadOnlyFilesystem),
io::ErrorKind::StaleNetworkFileHandle => {
Some(WireErrorKind::StaleNetworkFileHandle)
}
io::ErrorKind::InvalidInput => Some(WireErrorKind::InvalidInput),
io::ErrorKind::InvalidData => Some(WireErrorKind::InvalidData),
io::ErrorKind::TimedOut => Some(WireErrorKind::TimedOut),
io::ErrorKind::WriteZero => Some(WireErrorKind::WriteZero),
io::ErrorKind::StorageFull => Some(WireErrorKind::StorageFull),
io::ErrorKind::NotSeekable => Some(WireErrorKind::NotSeekable),
io::ErrorKind::QuotaExceeded => Some(WireErrorKind::QuotaExceeded),
io::ErrorKind::FileTooLarge => Some(WireErrorKind::FileTooLarge),
io::ErrorKind::ResourceBusy => Some(WireErrorKind::ResourceBusy),
io::ErrorKind::ExecutableFileBusy => Some(WireErrorKind::ExecutableFileBusy),
io::ErrorKind::Deadlock => Some(WireErrorKind::Deadlock),
io::ErrorKind::CrossesDevices => Some(WireErrorKind::CrossesDevices),
io::ErrorKind::TooManyLinks => Some(WireErrorKind::TooManyLinks),
io::ErrorKind::InvalidFilename => Some(WireErrorKind::InvalidFilename),
io::ErrorKind::ArgumentListTooLong => Some(WireErrorKind::ArgumentListTooLong),
io::ErrorKind::Interrupted => Some(WireErrorKind::Interrupted),
io::ErrorKind::Unsupported => Some(WireErrorKind::Unsupported),
io::ErrorKind::UnexpectedEof => Some(WireErrorKind::UnexpectedEof),
io::ErrorKind::OutOfMemory => Some(WireErrorKind::OutOfMemory),
io::ErrorKind::Other => Some(WireErrorKind::Other),
_ => None,
}
}
impl From<WireErrorKind> for io::ErrorKind {
fn from(kind: WireErrorKind) -> io::ErrorKind {
match kind {
WireErrorKind::NotFound => io::ErrorKind::NotFound,
WireErrorKind::PermissionDenied => io::ErrorKind::PermissionDenied,
WireErrorKind::ConnectionRefused => io::ErrorKind::ConnectionRefused,
WireErrorKind::ConnectionReset => io::ErrorKind::ConnectionReset,
WireErrorKind::HostUnreachable => io::ErrorKind::HostUnreachable,
WireErrorKind::NetworkUnreachable => io::ErrorKind::NetworkUnreachable,
WireErrorKind::ConnectionAborted => io::ErrorKind::ConnectionAborted,
WireErrorKind::NotConnected => io::ErrorKind::NotConnected,
WireErrorKind::AddrInUse => io::ErrorKind::AddrInUse,
WireErrorKind::AddrNotAvailable => io::ErrorKind::AddrNotAvailable,
WireErrorKind::NetworkDown => io::ErrorKind::NetworkDown,
WireErrorKind::BrokenPipe => io::ErrorKind::BrokenPipe,
WireErrorKind::AlreadyExists => io::ErrorKind::AlreadyExists,
WireErrorKind::WouldBlock => io::ErrorKind::WouldBlock,
WireErrorKind::NotADirectory => io::ErrorKind::NotADirectory,
WireErrorKind::IsADirectory => io::ErrorKind::IsADirectory,
WireErrorKind::DirectoryNotEmpty => io::ErrorKind::DirectoryNotEmpty,
WireErrorKind::ReadOnlyFilesystem => io::ErrorKind::ReadOnlyFilesystem,
WireErrorKind::StaleNetworkFileHandle => io::ErrorKind::StaleNetworkFileHandle,
WireErrorKind::InvalidInput => io::ErrorKind::InvalidInput,
WireErrorKind::InvalidData => io::ErrorKind::InvalidData,
WireErrorKind::TimedOut => io::ErrorKind::TimedOut,
WireErrorKind::WriteZero => io::ErrorKind::WriteZero,
WireErrorKind::StorageFull => io::ErrorKind::StorageFull,
WireErrorKind::NotSeekable => io::ErrorKind::NotSeekable,
WireErrorKind::QuotaExceeded => io::ErrorKind::QuotaExceeded,
WireErrorKind::FileTooLarge => io::ErrorKind::FileTooLarge,
WireErrorKind::ResourceBusy => io::ErrorKind::ResourceBusy,
WireErrorKind::ExecutableFileBusy => io::ErrorKind::ExecutableFileBusy,
WireErrorKind::Deadlock => io::ErrorKind::Deadlock,
WireErrorKind::CrossesDevices => io::ErrorKind::CrossesDevices,
WireErrorKind::TooManyLinks => io::ErrorKind::TooManyLinks,
WireErrorKind::InvalidFilename => io::ErrorKind::InvalidFilename,
WireErrorKind::ArgumentListTooLong => io::ErrorKind::ArgumentListTooLong,
WireErrorKind::Interrupted => io::ErrorKind::Interrupted,
WireErrorKind::Unsupported => io::ErrorKind::Unsupported,
WireErrorKind::UnexpectedEof => io::ErrorKind::UnexpectedEof,
WireErrorKind::OutOfMemory => io::ErrorKind::OutOfMemory,
WireErrorKind::Other => io::ErrorKind::Other,
WireErrorKind::Unknown => io::ErrorKind::Other,
}
}
}
pub(super) fn serialize<S: Serializer>(
kind: &io::ErrorKind,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
from_io_kind(*kind)
.ok_or_else(|| {
serde::ser::Error::custom("I/O error kind is absent from the wire schema")
})?
.serialize(serializer)
}
pub(super) fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<io::ErrorKind, D::Error> {
WireErrorKind::deserialize(deserializer).map(io::ErrorKind::from)
}
}
/// Request body for the `pdf` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PdfRequest {
/// Input file name inside the jail.
pub input: String,
}
/// Success body for the `pdf` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PdfOk {
/// The converted text, UTF-8, NFC, LF line endings.
pub text: String,
/// Non-fatal notes about the conversion.
pub warnings: Vec<String>,
/// Structure spans over the text.
pub segments: Vec<Segment>,
/// Whether the text came from the direct recovery extractor
/// rather than the markdown path. The parent adapter maps this
/// to the manifest converter id, so a recovered document is
/// never recorded under the markdown path's id.
///
/// Skipped from the wire when false, so every non-recovered
/// outcome serializes byte-identical to the pre-recovery wire
/// and a mixed-version worker pairing can only ever trip on an
/// actually-recovered document. `deny_unknown_fields` above then
/// fails such a pairing loudly rather than dropping the field.
#[serde(default, skip_serializing_if = "is_false")]
pub recovered: bool,
}
/// Whether a boolean is false, for `skip_serializing_if`.
fn is_false(value: &bool) -> bool {
!*value
}
/// Request body for the `records` adapter, which reads parquet,
/// avro, and sqlite behind the jail.
///
/// The ceilings travel in the request because the worker, not the
/// parent, enforces them, and they are rules data the parent reads
/// from the registry. A source over any ceiling fails closed with
/// reason `record-limit-exceeded`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RecordsRequest {
/// Input file name inside the jail.
pub input: String,
/// The detected format: `parquet`, `avro`, or `sqlite`.
pub format: String,
/// Ceiling on records per parquet or avro file, or per sqlite
/// table.
pub max_records: u64,
/// Ceiling on tables per sqlite database.
pub max_tables: u64,
/// Ceiling on rendered output bytes.
pub max_output_bytes: u64,
}
/// Success body for the `records` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RecordsOk {
/// The rendered text, UTF-8, NFC, LF line endings.
pub text: String,
/// Non-fatal notes about the conversion.
pub warnings: Vec<String>,
/// Structure spans over the text. Sqlite carries a sheet
/// boundary per table.
pub segments: Vec<Segment>,
}
/// Request body for the `image-metadata` adapter, which lifts
/// textual metadata out of a raster behind the jail.
///
/// The ceilings travel in the request because the worker, not the
/// parent, enforces them, and they are rules data the parent reads
/// from the registry, matching [`RecordsRequest`]. A source over any
/// ceiling fails closed with a stable `image-metadata-*` reason.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageMetadataRequest {
/// Input file name inside the jail.
pub input: String,
/// The detected carrier format: `png`, `jpeg`, `webp`, or
/// `heic`.
pub format: String,
/// Ceiling on the inflated size of any single compressed text
/// block, checked incrementally during inflation.
pub max_decompressed_bytes: u64,
/// Ceiling on the nesting depth of an xmp parse.
pub max_xml_depth: u32,
/// Ceiling on the event count of an xmp parse.
pub max_xml_events: u64,
/// Ceiling on the box count walked in an iso base media file
/// format carrier.
pub max_boxes: u64,
/// Ceiling on emitted metadata rows across all surfaces.
pub max_rows: u64,
/// Ceiling on the rendered artifact text, under the runner
/// response cap.
pub max_output_bytes: u64,
}
/// One extracted metadata value, addressed by carrier, surface, and
/// path. The parent renders these to the tabular artifact and builds
/// one hidden segment per row, so the output contract and the hidden
/// marking stay in the crate rather than the worker.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MetadataRow {
/// The container the value came from, such as `exif`,
/// `png-itxt`, `jpeg-app1-xmp`, `webp-xmp`, `iptc-iim`, or
/// `heic-uuid`.
pub carrier: String,
/// The surface family, such as `exif-imagedescription`,
/// `xmp-dc-description`, or `iptc-2-120-caption`.
pub surface: String,
/// The addressing detail, such as the exif tag number, the xmp
/// property path, or the iptc dataset.
pub path: String,
/// The language tag when the surface carries one, such as an
/// `iTXt` language tag or an xmp `xml:lang`.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub language: Option<String>,
/// The extracted text.
pub value: String,
}
/// Success body for the `image-metadata` adapter.
///
/// An empty `rows` is the not-applicable outcome: the parent writes
/// nothing for the metadata leg. One or more rows renders to a
/// non-empty artifact and records a converted child.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageMetadataOk {
/// Extracted rows, one per metadata value. Zero rows is the
/// no-metadata outcome.
pub rows: Vec<MetadataRow>,
}
/// What an OCR request asks the engine to read.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum OcrInput {
/// A standalone raster image.
Image,
/// One page of a paginated source rendered to raster.
PageRender {
/// Zero-based page index.
page: u32,
/// Render resolution in dots per inch.
dpi: u32,
},
}
/// Request body for the `ocr` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OcrRequest {
/// Input file name inside the jail.
pub input: String,
/// What the engine should read.
pub kind: OcrInput,
/// The pinned runtime files for the recognition stage, when a
/// deployment supplies them. Skipped from the wire when empty,
/// so a request without an inventory serializes exactly as it
/// did before this field existed.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inventory: Vec<InventoryEntry>,
}
/// One recognized text span with its confidence.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OcrSpan {
/// The recognized text.
pub text: String,
/// Engine confidence in the closed range 0 to 1.
pub confidence: f64,
}
/// Success body for the `ocr` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OcrOk {
/// Recognized spans in reading order.
pub spans: Vec<OcrSpan>,
/// Non-fatal notes from the worker, such as the long-edge
/// validation note. Skipped from the wire when empty, so the
/// pre-existing engine-unpinned scaffold serializes unchanged.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// One pinned runtime component a worker must verify before any
/// engine work: a generic role label, the deployment-resolved
/// path, and the expected BLAKE3 from the versioned rules. The
/// worker re-hashes the file itself immediately before preflight
/// and execution, so a swap after parent-side validation still
/// fails closed. Failures name the role label only.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InventoryEntry {
/// Generic role label, such as `asr-cli`.
pub role: String,
/// Absolute path of the pinned file.
pub path: String,
/// Expected lowercase hex BLAKE3 of the file bytes.
pub expected_blake3: String,
}
/// Request body for the `asr` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AsrRequest {
/// Input file name inside the jail.
pub input: String,
/// Language hint, when the caller has one. The worker honors
/// it only when it equals the pinned language.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub language: Option<String>,
/// Ruled decoded-duration ceiling in seconds. Rules data the
/// parent reads from the registry; the worker enforces it from
/// the decoded frame count and fails an over-cap source closed
/// with `asr-duration-exceeded`, never truncating.
pub max_duration_seconds: u64,
/// The pinned runtime files the worker verifies and execs.
/// Empty on the fake-engine path, which replaces only the
/// engine stage and needs no runtime.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inventory: Vec<InventoryEntry>,
}
/// One transcribed speech segment.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AsrSegment {
/// Segment start in seconds from the recording start.
pub start_seconds: f64,
/// Segment end in seconds.
pub end_seconds: f64,
/// One-based speaker index from diarization.
pub speaker: u32,
/// The transcribed text.
pub text: String,
}
/// Success body for the `asr` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AsrOk {
/// Speech segments ordered by start time.
pub segments: Vec<AsrSegment>,
/// Detected language tag, when the engine reports one.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub language: Option<String>,
/// Source duration in seconds, when the engine reports it.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub duration_seconds: Option<f64>,
}
/// One provider component the svg raster worker verifies
/// immediately before it executes: a generic role label, the
/// deployment-resolved path, the expected BLAKE3 and version, and,
/// when the deployment pinned one, the enumerated closure the
/// component loads its helpers from and that closure's aggregate
/// digest. The worker re-hashes everything itself, so a swap after
/// any parent-side validation still fails closed, and failures name
/// the role label only.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SvgRoleEntry {
/// Generic role label, such as `raster-browser`.
pub role: String,
/// Absolute path of the pinned executable.
pub path: String,
/// Expected lowercase hex BLAKE3 of the executable's bytes.
pub expected_blake3: String,
/// Exact version string the executable must report.
pub version: String,
/// The enumerated closure this component loads
/// from: directories and files, each granted as its own
/// subpath.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub closure_roots: Vec<String>,
/// Expected aggregate digest over that whole closure.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub closure_blake3: Option<String>,
/// An additional environment variable the worker points at the
/// jail's temp directory for this component.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub jail_temp_env: Option<String>,
}
/// Request body for the `svg-raster` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SvgRasterRequest {
/// Input file name inside the jail.
pub input: String,
/// The provider components, in verification order.
pub roles: Vec<SvgRoleEntry>,
}
/// Success body for the `svg-raster` adapter: the flattened raster
/// as lowercase hex, with the dimensions the geometry assertion
/// already accepted.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SvgRasterOk {
/// The flattened raster's bytes, lowercase hex.
pub raster_png_hex: String,
/// The flattened raster's width in pixels.
pub width: u32,
/// The flattened raster's height in pixels.
pub height: u32,
}
/// Request body for the `video` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VideoRequest {
/// Input file name inside the jail.
pub input: String,
/// Seconds between sampled frames.
pub sample_interval_seconds: f64,
/// Ceiling on sampled frames.
pub max_frames: u32,
}
/// One deduplicated on-screen text state.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScreenState {
/// When this state first appeared, in seconds.
pub first_seen_seconds: f64,
/// The on-screen text.
pub text: String,
}
/// Success body for the `video` adapter.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VideoOk {
/// Screen states deduplicated by content, ordered by first
/// appearance.
pub states: Vec<ScreenState>,
/// Source duration in seconds, when the engine reports it.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub duration_seconds: Option<f64>,
}
/// Success body for the `probe-net` mode.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProbeReport {
/// One entry per attempted egress path.
pub attempts: Vec<ProbeAttempt>,
}
/// One egress attempt and how it ended.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProbeAttempt {
/// Which fixed capability was attempted.
pub name: ProbeName,
/// How the attempt ended.
pub outcome: ProbeOutcome,
/// The I/O class reported by the attempt.
#[serde(with = "error_kind_wire")]
pub error_kind: io::ErrorKind,
}
/// Request body for the `probe-net` mode.
///
/// Every target is one the parent controls and holds reachable
/// while the probe runs, so a connection that fails from inside
/// the jail is evidence of the jail and not of an unreachable
/// address. From an unjailed process every leg would succeed.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProbeNetRequest {
/// A Unix socket target the parent listens on outside the
/// jail. An abstract name on Linux, a filesystem path
/// elsewhere.
pub unix_target: String,
/// An IPv4 TCP address the parent listens on, such as
/// `127.0.0.1:49152`.
pub tcp4_target: String,
/// An IPv6 TCP address the parent listens on, such as
/// `[::1]:49152`.
pub tcp6_target: String,
}
}