@sjcrh/proteinpaint-rust 2.108.3-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 +129 -29
  2. package/package.json +2 -2
  3. package/src/gdcmaf.rs +131 -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) => {
@@ -45,47 +48,144 @@ exports.run_rust = function (binfile, input_data) {
45
48
 
46
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
- const stderr = []
50
- try {
51
- // from GDC API -> ps.stdin -> ps.stdout -> transformed stream
52
- Readable.from(input_data).pipe(ps.stdin)
53
- //reader.on('data', ps.stdout.pipe)
54
- //reader.on('error', ps.stderr.pipe)
55
- //return reader
56
- } catch (error) {
57
- ps.kill()
58
- let errmsg = error
59
- //if (stderr.length) errmsg += `killed run_rust('${binfile}'), stderr: ${stderr.join('').trim()}`
60
- //reject(errmsg)
61
- console.log(59, error)
62
- }
63
51
 
52
+ const ps = spawn(binpath)
64
53
  const childStream = new Transform({
65
54
  transform(chunk, encoding, callback) {
66
55
  this.push(chunk)
67
56
  callback()
68
57
  }
69
58
  })
70
- ps.stdout.pipe(childStream)
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
+
71
80
  ps.stderr.on('data', data => stderr.push(data))
72
- ps.on('close', code => { //console.log(72, stderr.length)
73
- if (stderr.length) {
74
- // handle rust stderr
75
- const errors = stderr.join('').trim().split('\n').map(JSON.parse)
76
- //const errmsg = `!!! stream_rust('${binfile}') stderr: !!!`
77
- //console.log(errmsg, errors)
78
- emitJson({errors})
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)
79
86
  } else {
80
87
  emitJson({ ok: true, status: 'ok', message: 'Processing complete' })
81
88
  }
82
89
  })
83
90
  ps.on('error', err => {
84
- //console.log(74, `stream_rust().on('error')`, err)
85
- const errors = stderr.join('').trim().split('\n').map(JSON.parse)
86
- emitJson({errors})
91
+ if (trackedPids.has(ps.pid)) trackedPids.delete(ps.pid)
92
+ // console.log(74, `stream_rust().on('error')`, err)
93
+ emitErrors(null, ps.pid)
94
+ })
95
+ ps.on('SIGTERM', err => {
96
+ console.log(err)
87
97
  })
88
- // below will duplicate ps.on('close') event above
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
89
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
+
90
136
  return childStream
91
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.108.3-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.108.3-0"
41
+ "pp_release_tag": "v2.108.6-0"
42
42
  }
package/src/gdcmaf.rs CHANGED
@@ -1,23 +1,25 @@
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};
20
-
19
+ use std::time::Duration;
20
+ use tokio::io::{AsyncReadExt, BufReader};
21
+ use tokio::time::timeout;
22
+ use std::sync::{Arc, Mutex};
21
23
 
22
24
  // Struct to hold error information
23
25
  #[derive(serde::Serialize)]
@@ -46,6 +48,9 @@ fn select_maf_col(d:String,columns:&Vec<String>,url:&str) -> Result<(Vec<u8>,i32
46
48
  return Err((url.to_string(), error_msg));
47
49
  }
48
50
  }
51
+ };
52
+ if header_indices.is_empty() {
53
+ return Err((url.to_string(), "No matching columns found".to_string()));
49
54
  }
50
55
  } else {
51
56
  let maf_cont_lst: Vec<String> = line.split("\t").map(|s| s.to_string()).collect();
@@ -68,16 +73,67 @@ async fn main() -> Result<(),Box<dyn std::error::Error>> {
68
73
  // Accepting the piped input json from jodejs and assign to the variable
69
74
  // host: GDC host
70
75
  // url: urls to download single maf files
71
- let mut buffer = String::new();
72
- io::stdin().read_line(&mut buffer)?;
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
+ };
73
129
 
74
130
  // reading the input from PP
75
- let file_id_lst_js = serde_json::from_str::<Value>(&buffer).expect("Error reading input and serializing to JSON");
76
131
  let host = file_id_lst_js.get("host").expect("Host was not provided").as_str().expect("Host is not a string");
77
132
  let mut url: Vec<String> = Vec::new();
78
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");
79
134
  for v in file_id_lst {
80
- 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()));
81
137
  };
82
138
 
83
139
  // read columns as array from input json and convert data type from Vec<Value> to Vec<String>
@@ -118,7 +174,19 @@ async fn main() -> Result<(),Box<dyn std::error::Error>> {
118
174
  let download_futures = futures::stream::iter(
119
175
  url.into_iter().map(|url|{
120
176
  async move {
121
- match reqwest::get(&url).await {
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 {
122
190
  Ok(resp) if resp.status().is_success() => {
123
191
  match resp.bytes().await {
124
192
  Ok(content) => {
@@ -155,53 +223,67 @@ async fn main() -> Result<(),Box<dyn std::error::Error>> {
155
223
  );
156
224
 
157
225
  // binary output
158
- let mut encoder = GzEncoder::new(io::stdout(), Compression::default());
159
- let _ = encoder.write_all(&maf_col.join("\t").as_bytes().to_vec()).expect("Failed to write header");
160
- let _ = encoder.write_all(b"\n").expect("Failed to write newline");
226
+ let encoder = Arc::new(Mutex::new(GzEncoder::new(io::stdout(), Compression::default())));
161
227
 
162
- download_futures.buffer_unordered(20).for_each(|result| {
163
- match result {
164
- Ok((url, content)) => {
165
- match select_maf_col(content, &maf_col, &url) {
166
- Ok((maf_bit,mafrows)) => {
167
- if mafrows > 0 {
168
- encoder.write_all(&maf_bit).expect("Failed to write file");
169
- } else {
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)) => {
170
256
  let error = ErrorEntry {
171
- url: url.clone(),
172
- error: "Empty maf file".to_string(),
257
+ url,
258
+ error,
173
259
  };
174
260
  let error_js = serde_json::to_string(&error).unwrap();
175
261
  writeln!(io::stderr(), "{}", error_js).expect("Failed to output stderr!");
176
262
  }
177
263
  }
178
- Err((url,error)) => {
179
- let error = ErrorEntry {
180
- url,
181
- error,
182
- };
183
- let error_js = serde_json::to_string(&error).unwrap();
184
- writeln!(io::stderr(), "{}", error_js).expect("Failed to output stderr!");
185
- }
186
264
  }
187
- }
188
- Err((url, error)) => {
189
- let error = ErrorEntry {
190
- url,
191
- error,
192
- };
193
- let error_js = serde_json::to_string(&error).unwrap();
194
- writeln!(io::stderr(), "{}", error_js).expect("Failed to output stderr!");
195
- }
196
- };
197
- async {}
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
+ }
198
275
  }).await;
199
276
 
200
- // Finalize output and printing errors
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
201
283
  encoder.finish().expect("Maf file output error!");
284
+
202
285
  // Manually flush stdout and stderr
203
286
  io::stdout().flush().expect("Failed to flush stdout");
204
287
  io::stderr().flush().expect("Failed to flush stderr");
205
-
206
288
  Ok(())
207
289
  }