/
simulation-run.controller.ts
360 lines (342 loc) · 10.6 KB
/
simulation-run.controller.ts
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
/* eslint-disable @typescript-eslint/member-ordering */
/**
* @file Contains the controller for CRUD operations on simulation runs
* @author Bilal Shaikh
* @copyright Biosimulations Team 2020
* @license MIT
*/
import { DispatchJob } from '@biosimulations/messages/messages';
import { OptionalAuth, permissions } from '@biosimulations/auth/nest';
import {
ErrorResponseDocument,
FieldsQueryParameters,
} from '@biosimulations/datamodel/api';
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
Logger,
NotFoundException,
Param,
Patch,
Post,
Req,
Res,
UploadedFile,
UseInterceptors,
UnsupportedMediaTypeException,
Query,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
ApiBadRequestResponse,
ApiCreatedResponse,
ApiExtraModels,
ApiOkResponse,
ApiOperation,
ApiPayloadTooLargeResponse,
ApiTags,
ApiUnsupportedMediaTypeResponse,
getSchemaPath,
ApiParam,
} from '@nestjs/swagger';
import { Response, Request } from 'express';
import {
SimulationRun,
SimulationUpload,
UpdateSimulationRun,
UploadSimulationRun,
UploadSimulationRunUrl,
} from '@biosimulations/dispatch/api-models';
import { SimulationRunService } from './simulation-run.service';
import { SimulationRunModelReturnType } from './simulation-run.model';
import { AuthToken } from '@biosimulations/auth/common';
import { InjectQueue } from '@nestjs/bull';
import { Queue } from 'bull';
// hack to get typing to work see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/47780
// eslint-disable-next-line unused-imports/no-unused-imports-ts
import multer from 'multer';
type multipartSimulationRunBody = { simulationRun: string };
// 1gb in bytes plus a buffer to be used as file size limits
const ONE_GIGABYTE = 1100000000;
@ApiTags('Simulation runs')
@Controller(['runs', 'run'])
@ApiExtraModels(UploadSimulationRun, UploadSimulationRunUrl, SimulationUpload)
export class SimulationRunController {
private TIMEOUT_INTERVAL = 10000;
private RETRY_COUNT = 2;
private logger: Logger;
public constructor(
private service: SimulationRunService,
@InjectQueue('dispatch') private readonly dispatchQueue: Queue<DispatchJob>,
) {
this.logger = new Logger(SimulationRunController.name);
}
private isFileUploadBody(
body: multipartSimulationRunBody | UploadSimulationRunUrl,
): body is multipartSimulationRunBody {
return (<multipartSimulationRunBody>body).simulationRun != undefined;
}
private isUrlBody(
body: multipartSimulationRunBody | UploadSimulationRunUrl,
): body is UploadSimulationRunUrl {
return (<UploadSimulationRunUrl>body).url != undefined;
}
@ApiOperation({
summary: 'Get all of the simulation runs',
description:
'Returns an array of all the simulation run objects in the database',
})
@ApiOkResponse({ description: 'OK', type: [SimulationRun] })
@permissions('read:SimulationRuns')
@Get()
public async getRuns(
@Query() queryparams: FieldsQueryParameters,
): Promise<{ id: string; status: string }[]> {
const res = await this.service.getAll(queryparams.fields);
return res;
}
@ApiOperation({
summary: 'Submit a simulation to run',
description:
'Upload an COMBINE/OMEX archive file along with a description of the simulator to use to execute the archive.\
The simulation will be excecuted and the status of the simulation run object will be updated. \
\nThe simulation can be uploaded as a COMBINE archive by using the multipart/form-data accept header.\
Alternatively, use the application/json accept header to provide a URL to an external COMBINE archive',
requestBody: {
content: {
'application/json': {
encoding: { body: { contentType: 'application/json' } },
schema: { $ref: getSchemaPath(UploadSimulationRunUrl) },
},
'multipart/form-data': {
encoding: { body: { contentType: 'multipart/form-data' } },
schema: { $ref: getSchemaPath(SimulationUpload) },
},
},
},
})
@ApiCreatedResponse({
type: SimulationRun,
description: 'Simulation run submitted',
})
@ApiPayloadTooLargeResponse({
type: ErrorResponseDocument,
description:
'COMBINE/OMEX file is too large. Files must be less than 1 GB.',
})
@ApiBadRequestResponse({
type: ErrorResponseDocument,
description: 'Request did not adhere to schema',
})
@ApiUnsupportedMediaTypeResponse({
type: ErrorResponseDocument,
description:
'The mediatype is unsupported. Mediatype must be application/json or multipart/form-data',
})
// Set a file size limit of 1GB
@UseInterceptors(
FileInterceptor('file', { limits: { fileSize: ONE_GIGABYTE } }),
)
@Post()
public async createRun(
@Body() body: multipartSimulationRunBody | UploadSimulationRunUrl,
@UploadedFile() file: Express.Multer.File,
@Req() req: Request,
): Promise<SimulationRun> {
const contentType = req.header('Content-Type');
let run: SimulationRunModelReturnType;
if (!contentType) {
throw new UnsupportedMediaTypeException(' Must specifiy a Content-Type');
} else if (contentType?.startsWith('multipart/form-data')) {
run = await this.createRunWithFile(body, file);
} else if (
contentType?.startsWith('application/json') &&
this.isUrlBody(body)
) {
run = await this.service.createRunWithURL(body);
} else {
throw new UnsupportedMediaTypeException(
'Can only accept application/json or multipart/form-data content',
);
}
const response = this.makeSimulationRun(run);
const message: DispatchJob = {
simId: run.id,
fileName: file?.originalname || 'input.omex',
simulator: run.simulator,
version: run.simulatorVersion,
cpus: run.cpus,
memory: run.memory,
maxTime: run.maxTime,
envVars: run.envVars,
academicUse: run.academicUse,
isPublic: run.public,
};
const sim = await this.dispatchQueue.add(message);
return response;
}
private async createRunWithFile(
body: multipartSimulationRunBody | UploadSimulationRunUrl,
file: Express.Multer.File,
): Promise<SimulationRunModelReturnType> {
let parsedRun: UploadSimulationRun;
try {
if (this.isFileUploadBody(body)) {
// We are making an unsafe assertion here, since the body could have any type.
// This should be caught by the database validation however
parsedRun = JSON.parse(body.simulationRun) as UploadSimulationRun;
} else {
throw new Error('Body is invalid');
}
} catch (e) {
throw new BadRequestException(
'The provided input was not valid: ' + e.message,
);
}
const run = this.service.createRunWithFile(parsedRun, file);
return run;
}
/**
* Creates the controllers return type SimulationRun
* @param run The value that is returned from the service.
*/
public makeSimulationRun(run: SimulationRunModelReturnType): SimulationRun {
return new SimulationRun(
run.id,
run.name,
run.simulator,
run.simulatorVersion,
run.cpus,
run.memory,
run.maxTime,
run.envVars,
run.academicUse,
run.submitted,
run.updated,
run.public,
run.status,
run.runtime,
run.projectSize,
run.resultsSize,
run.email,
);
}
@ApiOperation({
summary: 'Get a simulation run',
description: 'Get information about a simulation run',
})
@ApiParam({
name: 'id',
description: 'Id of a simulation run',
required: true,
type: String,
})
@ApiOkResponse({ type: SimulationRun })
@Get(':id')
@OptionalAuth()
public async getRun(
@Param('id') id: string,
@Req() req: Request,
): Promise<SimulationRun> {
const user = req?.user as AuthToken;
let permission = false;
if (user) {
user.permissions = user.permissions || [];
permission = user.permissions.includes('read:Email');
}
const run = await this.service.get(id);
if (run) {
permission ? null : (run.email = null);
return this.makeSimulationRun(run);
} else {
throw new NotFoundException(`No simulation run with id ${id}`);
}
}
@ApiOperation({
summary: 'Modify a simulation run',
description: 'Change the status or information of a simulation run',
})
@ApiParam({
name: 'id',
description: 'Id of a simulation run',
required: true,
type: String,
})
@permissions('write:SimulationRuns')
@Patch(':id')
public async modfiyRun(
@Param('id') id: string,
@Body() body: UpdateSimulationRun,
): Promise<SimulationRun> {
this.logger.log(`Patch called for ${id} with ${JSON.stringify(body)}`);
const run = await this.service.update(id, body);
return this.makeSimulationRun(run);
}
@ApiOperation({
summary: 'Delete a simulation run',
description: 'Delete a simulation run',
})
@ApiParam({
name: 'id',
description: 'Id of a simulation run',
required: true,
type: String,
})
@permissions('delete:SimulationRuns')
@Delete(':id')
public async deleteRun(
@Param('id') id: string,
): Promise<SimulationRun | null> {
const res = await this.service.delete(id);
if (!res) {
throw new NotFoundException(`No simulation run with id ${id} found`);
}
return this.makeSimulationRun(res);
}
@ApiOperation({
summary: 'Delete all simulation runs',
description: 'Delete all simulation runs',
})
@permissions('delete:SimulationRuns')
@Delete()
public deleteAll(): Promise<void> {
return this.service.deleteAll();
}
@ApiOperation({
summary: 'Download the COMBINE/OMEX archive for the simulation run',
description: 'Download the COMBINE/OMEX archive for the simulation run',
})
@ApiParam({
name: 'id',
description: 'Id of a simulation run',
required: true,
type: String,
})
@Get(':id/download')
@ApiTags('Downloads')
public async download(
@Param('id') id: string,
@Res({ passthrough: true }) response: Response,
): Promise<void> {
const file = await this.service.download(id);
if (file.mimetype) {
response.setHeader('Content-Type', file.mimetype);
}
if (file.originalname) {
const contentDisposition = `attachment; filename=${file.originalname}`;
response.setHeader('Content-Disposition', contentDisposition);
}
if (file.size) {
response.setHeader('Content-Size', file.size);
}
if (file.url) {
response.redirect(file.url);
} else {
// Should never happen since url is a required property of the file model now
throw new NotFoundException('Unable to locate the file');
}
}
}