@sjcrh/proteinpaint-rust 2.99.0 → 2.108.6-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +136 -17
  2. package/package.json +2 -2
  3. package/src/gdcmaf.rs +215 -49
package/index.js CHANGED
@@ -1,7 +1,10 @@
1
1
  const path = require('path'),
2
- spawn = require('child_process').spawn,
2
+ { spawn, exec } = require('child_process'),
3
3
  Readable = require('stream').Readable,
4
- Transform = require('stream').Transform
4
+ Transform = require('stream').Transform,
5
+ { promisify } = require('util')
6
+
7
+ const execPromise = promisify(exec)
5
8
 
6
9
  exports.run_rust = function (binfile, input_data) {
7
10
  return new Promise((resolve, reject) => {
@@ -43,30 +46,146 @@ exports.run_rust = function (binfile, input_data) {
43
46
  })
44
47
  }
45
48
 
46
- exports.run_rust_stream = function (binfile, input_data) {
49
+ exports.stream_rust = function (binfile, input_data, emitJson) {
47
50
  const binpath = path.join(__dirname, '/target/release/', binfile)
48
- const ps = spawn(binpath)
49
- try {
50
- Readable.from(input_data).pipe(ps.stdin)
51
- } catch (error) {
52
- ps.kill()
53
- let errmsg = error
54
- if (stderr.length) errmsg += `killed run_rust('${binfile}'), stderr: ${stderr.join('').trim()}`
55
- reject(errmsg)
56
- }
57
51
 
52
+ const ps = spawn(binpath)
58
53
  const childStream = new Transform({
59
54
  transform(chunk, encoding, callback) {
60
55
  this.push(chunk)
61
56
  callback()
62
57
  }
63
58
  })
64
- ps.stdout.pipe(childStream)
65
- childStream.on('error', err => {
66
- reject(err)
59
+ // we only want to run this interval loop inside a container, not in dev/test CI
60
+ if (binfile == 'gdcmaf') trackByPid(ps.pid, binfile)
61
+ const stderr = []
62
+ try {
63
+ // from route handler -> input_data -> ps.stdin -> ps.stdout -> transformed stream -> express response.pipe()
64
+ Readable.from(input_data)
65
+ .pipe(ps.stdin)
66
+ .on('error', err => {
67
+ emitErrors({ error: `error piping input data to spawned ${binfile} process` })
68
+ })
69
+ } catch (error) {
70
+ console.log(`Error piping input_data into ${binfile}`, error)
71
+ return
72
+ }
73
+
74
+ // uncomment to trigger childStream.destroy()
75
+ // setTimeout(() => { console.log(74, 'childStream.destroy()'); childStream.destroy();}, 1000)
76
+ // childStream.destroy() does not seem to trigger ps.stdout.pipe('...').on('error') callback,
77
+ // which is okay as long as the server doesn't crash and ps get's killed eventually
78
+ ps.stdout.pipe(childStream).on('error', console.log)
79
+
80
+ ps.stderr.on('data', data => stderr.push(data))
81
+
82
+ ps.on('close', code => {
83
+ if (trackedPids.has(ps.pid)) trackedPids.delete(ps.pid)
84
+ if (stderr.length || killedPids.has(ps.pid) || code !== 0) {
85
+ emitErrors(null, ps.pid, code)
86
+ } else {
87
+ emitJson({ ok: true, status: 'ok', message: 'Processing complete' })
88
+ }
67
89
  })
68
- childStream.on('close', code => {
69
- childStream.end()
90
+ ps.on('error', err => {
91
+ if (trackedPids.has(ps.pid)) trackedPids.delete(ps.pid)
92
+ // console.log(74, `stream_rust().on('error')`, err)
93
+ emitErrors(null, ps.pid)
70
94
  })
95
+ ps.on('SIGTERM', err => {
96
+ console.log(err)
97
+ })
98
+
99
+ function emitErrors(error, pid, code = 0) {
100
+ const errors = stderr
101
+ .join('')
102
+ .trim()
103
+ .split('\n')
104
+ .map(d => {
105
+ try {
106
+ return JSON.parse(d)
107
+ } catch (e) {
108
+ return null
109
+ }
110
+ })
111
+ .filter(d => d !== null)
112
+ if (error) errors.push(error)
113
+ if (pid && killedPids.has(ps.pid) && !trackedPids.has(ps.pid)) {
114
+ errors.push({ error: `server error: MAF file processing terminated (expired process)` })
115
+ killedPids.delete(pid)
116
+ } else if (pid && code !== 0) {
117
+ // may result from errors in spawned process code, or external signal (like `kill -9` in terminal)
118
+ errors.push({ error: `server error: MAF file processing terminated (code=${code})` })
119
+ }
120
+ emitJson({ errors })
121
+ }
122
+
123
+ // on('end') will duplicate ps.on('close') event above
124
+ // childStream.on('end', () => console.log(`-- childStream done --`))
125
+
126
+ // this may duplicate ps.on('error'), unless the error happened within the transform
127
+ childStream.on('error', err => {
128
+ console.log('stream_rust childStream.on(error)', err)
129
+ try {
130
+ childStream.destroy(err)
131
+ } catch (e) {
132
+ console.log(e)
133
+ }
134
+ })
135
+
71
136
  return childStream
72
137
  }
138
+
139
+ const trackedPids = new Map() // will be used to monitor expired processes
140
+ const killedPids = new Set() // will be used to detect killed processes, to help with error detection
141
+ const PSKILL_INTERVAL_MS = 30000 // every 30 seconds
142
+ let psKillInterval
143
+
144
+ // default maxElapsed = 5 * 60 * 1000 millisecond = 300000 or 5 minutes, change to 0 to test
145
+ // may allow configuration of maxElapsed by dataset/argument
146
+ function trackByPid(pid, name, maxElapsed = 300000) {
147
+ if (!pid) return
148
+ // only track by value (integer, string), not reference object
149
+ // NOTE: a reused/reassigned process.pid will be replaced by the most recent process
150
+ trackedPids.set(pid, { name, expires: Date.now() + maxElapsed })
151
+ if (!psKillInterval) psKillInterval = setInterval(killExpiredProcesses, PSKILL_INTERVAL_MS)
152
+ // uncomment below to test
153
+ // console.log([...trackedPids.entries()])
154
+ // if (maxElapsed < 10000) setTimeout(killExpiredProcesses, 1000) // uncomment for testing only
155
+ }
156
+
157
+ //
158
+ // Use one setInterval() to monitor >= 1 process,
159
+ // instead of a separate setTimeout() for each process.
160
+ // This is more reliable as setTimeout would use spawned ps.kill(),
161
+ // which may not exist when the timeout callback is executed and
162
+ // thus would require clearTimeout(closured_variable). Tracking by
163
+ // pid does not rely on a usable 'ps' variable to kill itself.
164
+ //
165
+ function killExpiredProcesses() {
166
+ //console.log(149, 'killExpiredProcesses()')
167
+ killedPids.clear()
168
+ const time = Date.now()
169
+ for (const [pid, info] of trackedPids.entries()) {
170
+ if (info.expires > time) continue
171
+ try {
172
+ // true if process exists
173
+ process.kill(pid, 0)
174
+ } catch (_) {
175
+ // no need to kill, but remove from tracking
176
+ trackedPids.delete(pid)
177
+ // prevent misleading logs of 'unable to kill ...'
178
+ continue
179
+ }
180
+ const label = `rust process ${info.name} (pid=${pid})`
181
+ try {
182
+ // detect if process exists before killing it
183
+ process.kill(pid, 'SIGTERM')
184
+ trackedPids.delete(pid)
185
+ killedPids.add(pid)
186
+ console.log(`killed ${label}`)
187
+ } catch (err) {
188
+ console.log(`unable to kill ${label}`, err)
189
+ }
190
+ }
191
+ }
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.99.0",
2
+ "version": "2.108.6-0",
3
3
  "name": "@sjcrh/proteinpaint-rust",
4
4
  "description": "Rust-based utilities for proteinpaint",
5
5
  "main": "index.js",
@@ -38,5 +38,5 @@
38
38
  "devDependencies": {
39
39
  "tape": "^5.2.2"
40
40
  },
41
- "pp_release_tag": "v2.99.0"
41
+ "pp_release_tag": "v2.108.6-0"
42
42
  }
package/src/gdcmaf.rs CHANGED
@@ -1,40 +1,56 @@
1
1
  /*
2
- This script download cohort maf files from GDC, concatenate them into a single file that includes user specified columns.
2
+ This script download cohort maf files from GDC, concatenate them into a single file that includes user specified columns.
3
3
 
4
- Input JSON:
5
- host: GDC host
6
- fileIdLst: An array of uuid
7
- Output gzip compressed maf file to stdout.
4
+ Input JSON:
5
+ host: GDC host
6
+ fileIdLst: An array of uuid
7
+ Output gzip compressed maf file to stdout.
8
8
 
9
- Example of usage:
10
- echo '{"host": "https://api.gdc.cancer.gov/data/","columns": ["Hugo_Symbol", "Entrez_Gene_Id", "Center", "NCBI_Build", "Chromosome", "Start_Position"], "fileIdLst": ["8b31d6d1-56f7-4aa8-b026-c64bafd531e7", "b429fcc1-2b59-4b4c-a472-fb27758f6249"]}'|./target/release/gdcmaf
9
+ Example of usage:
10
+ echo '{"host": "https://api.gdc.cancer.gov/data/","columns": ["Hugo_Symbol", "Entrez_Gene_Id", "Center", "NCBI_Build", "Chromosome", "Start_Position"], "fileIdLst": ["8b31d6d1-56f7-4aa8-b026-c64bafd531e7", "b429fcc1-2b59-4b4c-a472-fb27758f6249"]}'|./target/release/gdcmaf
11
11
  */
12
12
 
13
13
  use flate2::read::GzDecoder;
14
14
  use flate2::write::GzEncoder;
15
15
  use flate2::Compression;
16
- use serde_json::Value;
17
- use std::path::Path;
16
+ use serde_json::{Value};
18
17
  use futures::StreamExt;
19
18
  use std::io::{self,Read,Write};
19
+ use std::time::Duration;
20
+ use tokio::io::{AsyncReadExt, BufReader};
21
+ use tokio::time::timeout;
22
+ use std::sync::{Arc, Mutex};
20
23
 
24
+ // Struct to hold error information
25
+ #[derive(serde::Serialize)]
26
+ struct ErrorEntry {
27
+ url: String,
28
+ error: String,
29
+ }
21
30
 
22
-
23
- fn select_maf_col(d:String,columns:&Vec<String>) -> Vec<u8> {
31
+ fn select_maf_col(d:String,columns:&Vec<String>,url:&str) -> Result<(Vec<u8>,i32), (String, String)> {
24
32
  let mut maf_str: String = String::new();
25
33
  let mut header_indices: Vec<usize> = Vec::new();
26
34
  let lines = d.trim_end().split("\n");
35
+ let mut mafrows = 0;
27
36
  for line in lines {
28
37
  if line.starts_with("#") {
29
38
  continue
30
39
  } else if line.contains("Hugo_Symbol") {
31
40
  let header: Vec<String> = line.split("\t").map(|s| s.to_string()).collect();
32
41
  for col in columns {
33
- if let Some(index) = header.iter().position(|x| x == col) {
34
- header_indices.push(index);
35
- } else {
36
- panic!("{} was not found!",col);
42
+ match header.iter().position(|x| x == col) {
43
+ Some(index) => {
44
+ header_indices.push(index);
45
+ }
46
+ None => {
47
+ let error_msg = format!("Column {} was not found", col);
48
+ return Err((url.to_string(), error_msg));
49
+ }
37
50
  }
51
+ };
52
+ if header_indices.is_empty() {
53
+ return Err((url.to_string(), "No matching columns found".to_string()));
38
54
  }
39
55
  } else {
40
56
  let maf_cont_lst: Vec<String> = line.split("\t").map(|s| s.to_string()).collect();
@@ -44,25 +60,80 @@ fn select_maf_col(d:String,columns:&Vec<String>) -> Vec<u8> {
44
60
  };
45
61
  maf_str.push_str(maf_out_lst.join("\t").as_str());
46
62
  maf_str.push_str("\n");
63
+ mafrows += 1;
47
64
  }
48
65
  };
49
- maf_str.as_bytes().to_vec()
66
+ Ok((maf_str.as_bytes().to_vec(),mafrows))
50
67
  }
51
68
 
52
69
 
70
+
53
71
  #[tokio::main]
54
72
  async fn main() -> Result<(),Box<dyn std::error::Error>> {
55
73
  // Accepting the piped input json from jodejs and assign to the variable
56
74
  // host: GDC host
57
75
  // url: urls to download single maf files
58
- let mut buffer = String::new();
59
- io::stdin().read_line(&mut buffer)?;
60
- let file_id_lst_js = serde_json::from_str::<Value>(&buffer).expect("Error reading input and serializing to JSON");
76
+ let timeout_duration = Duration::from_secs(5); // Set a 10-second timeout
77
+
78
+ // Wrap the read operation in a timeout
79
+ let result = timeout(timeout_duration, async {
80
+ let mut buffer = String::new(); // Initialize an empty string to store input
81
+ let mut reader = BufReader::new(tokio::io::stdin()); // Create a buffered reader for stdin
82
+ reader.read_to_string(&mut buffer).await?; // Read a line asynchronously
83
+ Ok::<String, io::Error>(buffer) // Return the input as a Result
84
+ })
85
+ .await;
86
+ // Handle the result of the timeout operation
87
+ let file_id_lst_js: Value = match result {
88
+ Ok(Ok(buffer)) => {
89
+ match serde_json::from_str(&buffer) {
90
+ Ok(js) => js,
91
+ Err(e) => {
92
+ let stdin_error = ErrorEntry {
93
+ url: String::new(),
94
+ error: format!("JSON parsing error: {}", e),
95
+ };
96
+ writeln!(io::stderr(), "{}", serde_json::to_string(&stdin_error).unwrap()).unwrap();
97
+ return Err(Box::new(std::io::Error::new(
98
+ std::io::ErrorKind::InvalidInput,
99
+ "JSON parsing error!",
100
+ )) as Box<dyn std::error::Error>);
101
+ }
102
+ }
103
+ }
104
+ Ok(Err(_e)) => {
105
+ let stdin_error = ErrorEntry {
106
+ url: String::new(),
107
+ error: "Error reading from stdin.".to_string(),
108
+ };
109
+ let stdin_error_js = serde_json::to_string(&stdin_error).unwrap();
110
+ writeln!(io::stderr(), "{}", stdin_error_js).expect("Failed to output stderr!");
111
+ return Err(Box::new(std::io::Error::new(
112
+ std::io::ErrorKind::InvalidInput,
113
+ "Failed to output stderr!",
114
+ )) as Box<dyn std::error::Error>);
115
+ }
116
+ Err(_) => {
117
+ let stdin_error = ErrorEntry {
118
+ url: String::new(),
119
+ error: "Timeout while reading from stdin.".to_string(),
120
+ };
121
+ let stdin_error_js = serde_json::to_string(&stdin_error).unwrap();
122
+ writeln!(io::stderr(), "{}", stdin_error_js).expect("Failed to output stderr!");
123
+ return Err(Box::new(std::io::Error::new(
124
+ std::io::ErrorKind::InvalidInput,
125
+ "The columns in arg is not an array",
126
+ )) as Box<dyn std::error::Error>);
127
+ }
128
+ };
129
+
130
+ // reading the input from PP
61
131
  let host = file_id_lst_js.get("host").expect("Host was not provided").as_str().expect("Host is not a string");
62
132
  let mut url: Vec<String> = Vec::new();
63
133
  let file_id_lst = file_id_lst_js.get("fileIdLst").expect("File ID list is missed!").as_array().expect("File ID list is not an array");
64
134
  for v in file_id_lst {
65
- url.push(Path::new(&host).join(&v.as_str().unwrap()).display().to_string());
135
+ //url.push(Path::new(&host).join(&v.as_str().unwrap()).display().to_string());
136
+ url.push(format!("{}/{}",host.trim_end_matches('/'), v.as_str().unwrap()));
66
137
  };
67
138
 
68
139
  // read columns as array from input json and convert data type from Vec<Value> to Vec<String>
@@ -75,49 +146,144 @@ async fn main() -> Result<(),Box<dyn std::error::Error>> {
75
146
  .map(|v| v.to_string().replace("\"",""))
76
147
  .collect::<Vec<String>>();
77
148
  } else {
78
- panic!("Columns is not an array");
149
+ let column_error = ErrorEntry {
150
+ url: String::new(),
151
+ error: "The columns in arg is not an array".to_string(),
152
+ };
153
+ let column_error_js = serde_json::to_string(&column_error).unwrap();
154
+ writeln!(io::stderr(), "{}", column_error_js).expect("Failed to output stderr!");
155
+ return Err(Box::new(std::io::Error::new(
156
+ std::io::ErrorKind::InvalidInput,
157
+ "The columns in arg is not an array",
158
+ )) as Box<dyn std::error::Error>);
79
159
  }
80
160
  } else {
81
- panic!("Columns was not selected");
161
+ let column_error = ErrorEntry {
162
+ url: String::new(),
163
+ error: "Columns was not selected".to_string(),
164
+ };
165
+ let column_error_js = serde_json::to_string(&column_error).unwrap();
166
+ writeln!(io::stderr(), "{}", column_error_js).expect("Failed to output stderr!");
167
+ return Err(Box::new(std::io::Error::new(
168
+ std::io::ErrorKind::InvalidInput,
169
+ "Columns was not selected",
170
+ )) as Box<dyn std::error::Error>);
82
171
  };
83
172
 
84
173
  //downloading maf files parallelly and merge them into single maf file
85
174
  let download_futures = futures::stream::iter(
86
175
  url.into_iter().map(|url|{
87
176
  async move {
88
- let result = reqwest::get(&url).await;
89
- if let Ok(resp) = result {
90
- let content = resp.bytes().await.unwrap();
91
- let mut decoder = GzDecoder::new(&content[..]);
92
- let mut decompressed_content = Vec::new();
93
- let read_content = decoder.read_to_end(&mut decompressed_content);
94
- if let Ok(_) = read_content {
95
- let text = String::from_utf8_lossy(&decompressed_content).to_string();
96
- text
97
- } else {
98
- let error_msg = "Failed to read content downloaded from: ".to_string() + &url;
99
- error_msg
177
+ let client = reqwest::Client::builder()
178
+ .timeout(Duration::from_secs(60)) // 60-second timeout per request
179
+ .connect_timeout(Duration::from_secs(15))
180
+ .build()
181
+ .map_err(|_e| {
182
+ let client_error = ErrorEntry{
183
+ url: url.clone(),
184
+ error: "Client build error".to_string(),
185
+ };
186
+ let client_error_js = serde_json::to_string(&client_error).unwrap();
187
+ writeln!(io::stderr(), "{}", client_error_js).expect("Failed to build reqwest client!");
188
+ });
189
+ match client.unwrap().get(&url).send().await {
190
+ Ok(resp) if resp.status().is_success() => {
191
+ match resp.bytes().await {
192
+ Ok(content) => {
193
+ let mut decoder = GzDecoder::new(&content[..]);
194
+ let mut decompressed_content = Vec::new();
195
+ match decoder.read_to_end(&mut decompressed_content) {
196
+ Ok(_) => {
197
+ let text = String::from_utf8_lossy(&decompressed_content).to_string();
198
+ return Ok((url.clone(),text))
199
+ }
200
+ Err(e) => {
201
+ let error_msg = format!("Failed to decompress downloaded maf file: {}", e);
202
+ Err((url.clone(), error_msg))
203
+ }
204
+ }
205
+ }
206
+ Err(e) => {
207
+ let error_msg = format!("Failed to decompress downloaded maf file: {}", e);
208
+ Err((url.clone(), error_msg))
209
+ }
210
+ }
211
+ }
212
+ Ok(resp) => {
213
+ let error_msg = format!("HTTP error: {}", resp.status());
214
+ Err((url.clone(), error_msg))
215
+ }
216
+ Err(e) => {
217
+ let error_msg = format!("Server request failed: {}", e);
218
+ Err((url.clone(), error_msg))
100
219
  }
101
- } else {
102
- let error_msg = "Failed to download: ".to_string() + &url;
103
- error_msg
104
220
  }
105
221
  }
106
222
  })
107
223
  );
108
224
 
109
- // output
110
- let mut encoder = GzEncoder::new(io::stdout(), Compression::default());
111
- let _ = encoder.write_all(&maf_col.join("\t").as_bytes().to_vec()).expect("Failed to write header");
112
- let _ = encoder.write_all(b"\n").expect("Failed to write newline");
113
- download_futures.buffer_unordered(20).for_each(|item| {
114
- if item.starts_with("Failed") {
115
- eprintln!("{}",item);
116
- } else {
117
- let maf_bit = select_maf_col(item,&maf_col);
118
- let _ = encoder.write_all(&maf_bit).expect("Failed to write file");
119
- };
120
- async {}
225
+ // binary output
226
+ let encoder = Arc::new(Mutex::new(GzEncoder::new(io::stdout(), Compression::default())));
227
+
228
+ // Write the header
229
+ {
230
+ let mut encoder_guard = encoder.lock().unwrap(); // Lock the Mutex to get access to the inner GzEncoder
231
+ encoder_guard.write_all(&maf_col.join("\t").as_bytes().to_vec()).expect("Failed to write header");
232
+ encoder_guard.write_all(b"\n").expect("Failed to write newline");
233
+ }
234
+
235
+ download_futures.buffer_unordered(20).for_each( |result| {
236
+ let encoder = Arc::clone(&encoder); // Clone the Arc for each task
237
+ let maf_col_cp = maf_col.clone();
238
+ async move {
239
+ match result {
240
+ Ok((url, content)) => {
241
+ match select_maf_col(content, &maf_col_cp, &url) {
242
+ Ok((maf_bit,mafrows)) => {
243
+ if mafrows > 0 {
244
+ let mut encoder_guard = encoder.lock().unwrap();
245
+ encoder_guard.write_all(&maf_bit).expect("Failed to write file");
246
+ } else {
247
+ let error = ErrorEntry {
248
+ url: url.clone(),
249
+ error: "Empty maf file".to_string(),
250
+ };
251
+ let error_js = serde_json::to_string(&error).unwrap();
252
+ writeln!(io::stderr(), "{}", error_js).expect("Failed to output stderr!");
253
+ }
254
+ }
255
+ Err((url,error)) => {
256
+ let error = ErrorEntry {
257
+ url,
258
+ error,
259
+ };
260
+ let error_js = serde_json::to_string(&error).unwrap();
261
+ writeln!(io::stderr(), "{}", error_js).expect("Failed to output stderr!");
262
+ }
263
+ }
264
+ }
265
+ Err((url, error)) => {
266
+ let error = ErrorEntry {
267
+ url,
268
+ error,
269
+ };
270
+ let error_js = serde_json::to_string(&error).unwrap();
271
+ writeln!(io::stderr(), "{}", error_js).expect("Failed to output stderr!");
272
+ }
273
+ };
274
+ }
121
275
  }).await;
276
+
277
+ // Finalize output
278
+
279
+ // Replace the value inside the Mutex with a dummy value (e.g., None)
280
+ let mut encoder_guard = encoder.lock().unwrap();
281
+ let encoder = std::mem::replace(&mut *encoder_guard, GzEncoder::new(io::stdout(), Compression::default()));
282
+ // Finalize the encoder
283
+ encoder.finish().expect("Maf file output error!");
284
+
285
+ // Manually flush stdout and stderr
286
+ io::stdout().flush().expect("Failed to flush stdout");
287
+ io::stderr().flush().expect("Failed to flush stderr");
122
288
  Ok(())
123
289
  }