-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.js
209 lines (170 loc) · 5.76 KB
/
util.js
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
import fs from "fs/promises"
import fsSync from "fs"
import path from "path"
import archiver from "archiver"
import fetch from "node-fetch"
import { log } from "./logger.js"
import { WritableStreamBuffer } from "stream-buffers"
import { pipeline } from "stream/promises"
/*
File handling
*/
export async function pathExists(testPath) {
try {
await fs.access(testPath)
return true
} catch {
return false
}
}
export async function mkdirTough(dir) {
if (!await pathExists(dir))
await fs.mkdir(dir)
}
export function getBaseFileName(fileName) {
return path.basename(fileName).match(/(.+?)(\.[^.]*$|$)/)?.[1]
}
/*
Parameter handling
*/
const ParserMap = {
'float': parseFloat,
'integer': parseInt,
'string': str => str,
'lowercaseString': str => str.toLowerCase(),
'bool': str => str === 'true'
}
export class Parameter {
constructor(commandFlag, type = 'float', defaultValue) {
this.commandFlag = commandFlag
this.defaultValue = defaultValue
this.process = paramVal => {
return ParserMap[type]?.(paramVal) ?? paramVal
}
}
}
export function processParameters(requestBody, parameterMap) {
return Object.fromEntries(
Object.entries(parameterMap)
.map(
([key, paramDefinition]) => [
key,
requestBody[key] ?? paramDefinition.defaultValue
]
)
.filter(([, entryValue]) => entryValue != null)
)
// return Object.fromEntries(
// Object.entries(requestBody)
// .map(
// ([key, val]) => parameterMap[key] && [
// key,
// parameterMap[key].process(val)
// ]
// )
// .filter(entry => !!entry)
// )
}
/*
Zipping & Archiving
*/
export function zip(dir, { glob, finalize = true }) {
const archive = archiver('zip', {
zlib: { level: 9 } // compression level
})
// error handling
archive.on('error', err => { throw err })
// append files
glob ?
archive.glob(glob, { cwd: dir }) :
archive.directory(dir, false)
finalize && archive.finalize()
return archive
}
export function generateMetadata(sbmlFileNames) {
return {
manifest: `<?xml version="1.0" encoding="UTF-8"?>
<omexManifest xmlns="http://identifiers.org/combine.specifications/omex-manifest">
<content location="." format="http://identifiers.org/combine.specifications/omex" />
<content location="./manifest.xml" format="http://identifiers.org/combine.specifications/omex-manifest" />
<content location="./metadata.rdf" format="http://identifiers.org/combine.specifications/omex-metadata" />
${sbmlFileNames.map(fileName =>
` <content location="./${fileName}" format="http://identifiers.org/combine.specifications/sbml.level-3.version-2.core" />`
).join('\n')}
</omexManifest>`,
metadata: `<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2006/vcard/ns#" />
`
}
}
/*
Verification
*/
export async function wasAnalysisSuccessful(analysisDir) {
// iBioSim doesn't report as many errors as it should,
// so we're gonna check if it actually produced something
return await pathExists(path.join(analysisDir, 'statistics.txt'))
}
export function wasConversionSuccessful(convertedFile) {
// iBioSim doesn't report as many errors as it should,
// so we're gonna check if the converted file contains
// SBML tags
const stream = fsSync.createReadStream(convertedFile)
return new Promise((resolve, reject) => {
// search data for SBML tag
stream.on('data', chunk => {
if (('' + chunk).includes('<sbml')) {
resolve(true)
stream.destroy() // end stream if found
}
})
// reject if we reach the end of the stream
stream.on('end', () => resolve(false))
// error handling
stream.on('error', err => reject(err))
})
}
export function doResultsContainNaN(analysisDir) {
// if an analysis completed but the input model
// wasn't quite right, it may produce a lot of NaNs
// in the output.
const stream = fsSync.createReadStream(path.join(analysisDir, 'run-1.tsd'))
return new Promise((resolve, reject) => {
// search data for NaN values
stream.on('data', chunk => {
if (('' + chunk).toLowerCase().includes('nan')) {
resolve(true)
stream.destroy() // end stream if found
}
})
// reject if we reach the end of the stream
stream.on('end', () => resolve(false))
// error handling
stream.on('error', err => reject(err))
})
}
/*
Async handling
*/
export function executeCallback(callbackUrlTemplate, event, payload, json = false) {
const callbackUrl = callbackUrlTemplate.replace("{event}", event)
return fetch(callbackUrl, {
method: 'POST',
body: json ? JSON.stringify(payload) : payload,
headers: {
'Content-Type': json ? 'application/json' : 'application/octet-stream'
}
})
.then(res => {
log(`Sent output to callback URL: ${callbackUrl}. Received ${res.status}.`, "magenta", "Async")
})
.catch(error => {
log("Error attempting to hit callback:", "red", "Async")
log(error, "grey")
})
}
export async function convertStreamToJSON(stream) {
const writableStreamBuffer = new WritableStreamBuffer()
await pipeline(stream, writableStreamBuffer)
return writableStreamBuffer.getContents()
}