-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathproxy_json.rs
More file actions
175 lines (155 loc) · 5.83 KB
/
proxy_json.rs
File metadata and controls
175 lines (155 loc) · 5.83 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
use actson::feeder::BufReaderJsonFeeder;
use actson::options::JsonParserOptionsBuilder;
use actson::{JsonEvent, JsonParser};
use std::env;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Sender};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
fn should_add_comma(json_string: &str) -> bool {
!json_string.ends_with('{') && !json_string.ends_with('[') && !json_string.ends_with(':')
}
fn append_value(json_string: &mut String, value: &str) {
if should_add_comma(json_string) {
json_string.push(',');
}
json_string.push_str(value);
}
fn process_and_forward_json<R: Read + Send + 'static>(
reader: BufReader<R>,
output_file: Option<String>,
forward_to: Sender<String>,
) -> JoinHandle<()> {
thread::spawn(move || {
let feeder = BufReaderJsonFeeder::new(reader);
let mut parser = JsonParser::new_with_options(
feeder,
JsonParserOptionsBuilder::default()
.with_streaming(true)
.build(),
);
let mut json_string = String::new();
let mut depth = 0;
while let Some(event) = parser.next_event().unwrap_or(None) {
match event {
JsonEvent::NeedMoreInput => {
if parser.feeder.fill_buf().is_err() {
break;
}
}
JsonEvent::StartObject => {
depth += 1;
json_string.push('{');
}
JsonEvent::EndObject => {
depth -= 1;
json_string.push('}');
if depth == 0 {
if forward_to.send(json_string.clone()).is_err() {
break;
}
if let Some(file_path) = &output_file {
if let Ok(mut file) =
File::options().create(true).append(true).open(file_path)
{
let _ = writeln!(file, "{}", json_string);
}
}
json_string.clear();
}
}
JsonEvent::StartArray => {
depth += 1;
json_string.push('[');
}
JsonEvent::EndArray => {
depth -= 1;
json_string.push(']');
}
JsonEvent::FieldName => {
if json_string.ends_with('{') {
json_string.push('"');
} else {
json_string.push_str(",\"");
}
json_string.push_str(parser.current_str().unwrap_or_default());
json_string.push_str("\":");
}
JsonEvent::ValueString => {
append_value(
&mut json_string,
&format!("\"{}\"", parser.current_str().unwrap_or_default()),
);
}
JsonEvent::ValueInt => {
append_value(
&mut json_string,
&parser.current_int::<i64>().unwrap_or_default().to_string(),
);
}
JsonEvent::ValueFloat => {
append_value(
&mut json_string,
&parser.current_float().unwrap_or_default().to_string(),
);
}
JsonEvent::ValueTrue => append_value(&mut json_string, "true"),
JsonEvent::ValueFalse => append_value(&mut json_string, "false"),
JsonEvent::ValueNull => append_value(&mut json_string, "null"),
}
}
})
}
fn forward_to_writer<W: Write + Send + 'static>(
writer: W,
receiver: mpsc::Receiver<String>,
done: Arc<AtomicBool>,
) -> JoinHandle<()> {
thread::spawn(move || {
let mut writer = BufWriter::new(writer);
while !done.load(Ordering::SeqCst) {
if let Ok(json) = receiver.recv() {
if writeln!(writer, "{}", json).is_err() || writer.flush().is_err() {
break;
}
} else {
break;
}
}
})
}
fn main() -> io::Result<()> {
let proxy_to = env::var("PROXY_TO").expect("PROXY_TO environment variable must be set");
let output_file =
env::var("OUTPUT_FILE").expect("OUTPUT_FILE environment variable must be set");
File::create(&output_file)?;
let shell = if cfg!(target_os = "windows") {
("cmd", "/C")
} else {
("sh", "-c")
};
let mut child = Command::new(shell.0)
.arg(shell.1)
.arg(&proxy_to)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
let done_stdin = Arc::new(AtomicBool::new(false));
let done_stdout = Arc::new(AtomicBool::new(false));
let (tx_stdin, rx_stdin) = mpsc::channel();
let child_stdin = child.stdin.take().unwrap();
let _stdin_thread = forward_to_writer(child_stdin, rx_stdin, done_stdin.clone());
let (tx_stdout, rx_stdout) = mpsc::channel();
let stdout = io::stdout();
let _stdout_thread = forward_to_writer(stdout, rx_stdout, done_stdout.clone());
let stdin_reader = BufReader::new(io::stdin());
let _stdin_process = process_and_forward_json(stdin_reader, Some(output_file), tx_stdin);
let child_stdout = child.stdout.take().unwrap();
let stdout_reader = BufReader::new(child_stdout);
let _stdout_process = process_and_forward_json(stdout_reader, None, tx_stdout);
child.wait()?;
Ok(())
}