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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
|
import { Request, Response } from 'express';
import * as fs from 'fs-extra';
import { logger } from './logger';
import * as Multer from 'multer';
import * as stream from 'stream';
import * as parse from 'csv-parse';
import * as stringify from 'csv-stringify';
import { default as File } from './db/model/File';
import { default as Project } from './db/model/Project';
import { uuid } from './uuid';
import { main as CZICrunch } from './conversion/czi/czi'
import { getTile } from './conversion/czi/pyramidWorker'
import { RequestError } from './errors';
import { toCSV as excelToCSV, buildSupportedViews } from './conversion/csv/excel';
import { profiler } from './profiler';
import { SupportedViews } from './conversion/types/helpers'
import { CZITileRequest } from './conversion/types/customPyramidIndex'
const readDir = require('util').promisify(fs.readdir);
const readFile = require('util').promisify(fs.readFile);
const cache = require('redis').createClient(13337);
cache.on("error", function(err: any) {
logger.error("Redis_Error: " + err);
})
const BASE_BASE: string = `/cs/scratch/${require("os").userInfo().username}/`
const CONTENT_BASE_DIRECTORY: string = BASE_BASE + 'files';
const LOG_BASE_DIRECTORY: string = BASE_BASE + 'logs';
const TEMP_BASE_DIRECTORY: string = BASE_BASE + 'files-temp';
export interface Metadata {
version: number;
namespaces: object;
[index: string]: any;
}
export const INITIAL_METADATA: Metadata = {
version: 1,
namespaces: {}
};
const writableStream: (
filename: string, projectName: string
) => fs.WriteStream = (
filename: string, projectName: string
): fs.WriteStream => {
return fs.createWriteStream(path(filename, projectName));
};
interface RawSize {
offset: number;
length: number;
}
interface TabularParameters {
rowstart: number;
rowcount: number;
cols: string[];
}
interface FileUploadParameters {
truncate: boolean;
overwrite: boolean;
offset: number;
action: 'set_metadata'
| 'delete'
| 'move'
| 'copy'
| 'mkdir';
}
interface TileQuery {
channel_name: string;
x_offset: number;
y_offset: number;
width: number;
height: number;
zoom_level: number;
}
interface Query extends
Partial<RawSize>,
Partial<TabularParameters>,
Partial<FileUploadParameters>,
Partial<TileQuery> {
children?: boolean;
}
const readableStream: (
filename: string,
projectName: string,
{ offset, length }?: Query,
view?: ViewName
) => fs.ReadStream = (
filename: string,
projectName: string,
{ offset, length }: Query = { offset: undefined, length: undefined },
view?: ViewName
): fs.ReadStream => {
const options: object = {
start: Number(offset ? offset : 0),
end: offset && length ? offset + length : undefined
};
return fs.createReadStream(path(filename, projectName, view), options);
};
export const logPath: (type: string, projectName?: string) => string = (
type: string, projectName?: string
): string => {
return projectName
? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}`
: `${LOG_BASE_DIRECTORY}/general/${type}`;
};
export const path: (file: string, project: string, view?: ViewName) => string =
(file: string, project: string, view?: ViewName): string =>
`${CONTENT_BASE_DIRECTORY}/${project}/${file}/${view || 'ORIGINAL'}`;
export const originalPath: (file: string, project: string) => string =
(file: string, project: string): string =>
`${CONTENT_BASE_DIRECTORY}/${project}/${file}/ORIGINAL`;
export const pathNoView: (file: string, project: string) => string =
(file: string, project: string): string =>
`${CONTENT_BASE_DIRECTORY}/${project}/${file}`;
export const tempPath: (file: string, project: string) => string = (
file: string
): string =>
`${TEMP_BASE_DIRECTORY}/${uuid.generate()}`;
export const saveFile: (data: Buffer, projectName: string,
fileId: string, query: Query) => Promise<void> =
async(data: Buffer, projectName: string,
fileId: string, query: Query): Promise<void> => {
// Ensure file exists
await fs.ensureFile(path(fileId, projectName));
// Truncate to offset
if (!!query.truncate) {
await truncateFile(fileId, projectName, query.offset || 0);
}
const fuckingOffset: number = query.offset || 0;
// Open file
const fd: number = await fs.open(path(fileId, projectName), 'r+');
// Write data to file
fs.write(fd, data, 0, data.length, Number(fuckingOffset), (err: any, bytesWritten: number, buffer: Buffer) => {
console.log("written: " + bytesWritten)
if (err) {
logger.failure("Error while writing to file: " + err);
}
});
};
export const deleteFile: (fileId: string, projectName: string) => void = async(
fileId: string, projectName: string
): Promise<void> => {
await fs.remove(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`);
};
export const truncateFile: (fileId: string, projectName: string, newLength: number) => Promise<void> =
async(fileId: string, projectName: string, newLength: number): Promise<void> => {
// get the file descriptor of the file to be truncated
const fd: number = await fs.open(path(fileId, projectName), 'r+');
await fs.ftruncate(fd, newLength);
};
export const copyFile: (projName: string, fromId: string, toId: string, move?: boolean)
=> Promise<void> = async(projName: string, fromId: string, toId: string, move?: boolean): Promise<void> => {
// ensure to path exists
fs.ensureDirSync(pathNoView(toId, projName));
const fromDir: string = pathNoView(fromId, projName);
const toDir: string = pathNoView(toId, projName);
// loop all views in file
fs.readdir(fromDir, (err: any, files: string[]) => {
if (err) {
logger.error(`Error while copying file: ${err}`);
} else {
files.forEach((file: string, index: number) => {
const fromPathFull = fromDir + '/' + file;
const toPathFull = toDir + '/' + file;
fs.ensureFileSync(toPathFull);
// open streams to transfer data
const rStream = fs.createReadStream(fromPathFull);
const wStream = fs.createWriteStream(toPathFull);
rStream.pipe(wStream).on('finish', async() => {
if (!!move) {
await fs.remove(fromPathFull);
}
console.log(`copy success of file from \'${fromPathFull}\' to \'${toPathFull}\'`);
}).on('error', (err: any) => {
logger.error(`Error while copying file: ${err}`);
});
});
}
});
};
export const files: {
path: (f: string, p: string) => string;
writableStream: (f: string, p: string) => fs.WriteStream;
logPath: (t: string, p?: string) => string;
} = {
path,
writableStream,
logPath
};
export type ViewName = 'raw' | 'meta' | 'tabular' | 'scalable_image';
interface Query extends Partial<RawSize> {
include_children?: boolean;
}
export interface View {
getContents: (file: File, project: Project) => object | Promise<object>;
getResponseData: (file: File, project: Project, query: Query, url: string) =>
Promise<object>;
getResponseFunction: (req: Request, res: Response) => Function | null;
preprocess: (file: File, original: string, space: string) =>
Promise<void>;
}
interface MetaResponseData {
file_path: string;
file_name: string;
id: string;
type: FileTypeName;
metadata: object;
status: string;
supported_views: {
[key: string]: object | undefined;
};
children?: MetaResponseData[];
}
const metaGetResponseData: (
file: File, project: Project, query: Query
) => Promise<MetaResponseData> = async(
file: File, project: Project, query: Query
): Promise<MetaResponseData> => {
const data: MetaResponseData = {
file_path: file.fullPath,
file_name: file.name,
id: file.uuid,
type: file.type,
metadata: file.metadata,
status: file.status,
supported_views: {}
};
for (const view of fileTypes[file.type].supportedViews) {
data.supported_views[view] =
await views[view].getContents(file, project);
}
if (query.include_children) {
data.children = [];
const children: File[] | null = await File.findAll({
where: {
parentFolderId: file.uuid
}
});
if (children != null) {
for (const child of children) {
data.children.push(await metaGetResponseData(
child,
project,
{
...query,
include_children: undefined
}
));
}
}
}
return data;
};
export const getSize: (file: File, project: Project) => Promise<number> = async(
file: File, project: Project
): Promise<number> => {
const stat: fs.Stats = await fs.stat(path(file.uuid, project.name));
return stat.size;
};
const avgReqDuration = profiler.histogram({
name: "Avg. ImgTile Request Duration (ms)",
measurement: "mean",
agg_type: "avg"
})
const cacheHits = profiler.counter({
name: "Image Tile Cache Hits",
agg_type: "sum"
})
export const views: {
[view: string]: View;
} = {
raw: {
getContents: async(file: File, project: Project): Promise<object> => {
return {
size: await getSize(file, project)
};
},
getResponseData: async(
file: File, project: Project, query: Query
): Promise<object> => {
return readableStream(file.uuid, project.name, query);
},
getResponseFunction: (req: Request, res: Response): Function | null => {
return (rStream: fs.ReadStream): fs.ReadStream =>
rStream.pipe(res as any);
},
preprocess: async(): Promise<void> => {
return;
}
},
meta: {
getContents: (file: File): object => {
return {};
},
getResponseData: metaGetResponseData,
getResponseFunction: (req: Request, res: Response): Function | null => {
return null;
},
preprocess: async(): Promise<void> => {
return;
}
},
tabular: {
getContents: async(file: File, project: Project): Promise<object> => {
return await buildSupportedViews(path(file.uuid, project.name, 'tabular'));
},
getResponseData: async(
file: File, project: Project, query: Query
): Promise<object> => {
const space: string = path(file.uuid, project.name, 'tabular');
const files: string[] = await readDir(space);
const select: string | undefined = files.find((name: string): boolean => name[0] === '_');
if (!select) {
throw new Error('no default sheet to show :s')
}
let rowTo = (query.rowcount)
? (Number(query.rowstart) || 0) + Number(query.rowcount) -1
: undefined;
console.log(rowTo)
return fs.createReadStream(`${space}/${select}`)
.pipe(parse({
columns: true,
from: query.rowstart,
to: rowTo
})).pipe(stringify({
}));
},
getResponseFunction: (req: Request, res: Response): Function | null => {
return (stream: fs.ReadStream) => stream.pipe(res);
},
preprocess: async(file: File, original: string, space: string): Promise<void> => {
const mt: string = file.originalMimetype;
let validType: boolean = false;
if (mt.includes("csv")) {
validType = true;
} else if(mt.includes("spreadsheet")) {
validType = true;
} else if(mt.includes("ods")) {
validType = true;
} else if(mt.includes("xls")) {
validType = true;
}
if (validType) {
await excelToCSV(original, space, mt);
} else {
logger.warn(`unsupported file type ${mt}`);
}
}
},
scalable_image: {
getContents: async(file: File, project: Project): Promise<object> => {
return JSON.parse(await readFile(path(file.uuid, project.name, 'scalable_image') + "/supported_views.json", 'utf8')).scalable_image;
},
getResponseData: async(
file: File, project: Project, query: Query, url: string
): Promise<object> => {
let meta: SupportedViews = JSON.parse(await readFile(path(file.uuid, project.name, 'scalable_image') + "/supported_views.json", 'utf8'));
if (!meta.scalable_image) {
throw new RequestError(400, "scalable_image_obj_missing");
}
for (let channel of meta.scalable_image.channels) {
if (channel.channel_name === query.channel_name) {
query.channel_name = channel.channel_id;
break;
}
}
let startTime: number = Date.now();
let cacheHit: string | null = await new Promise<string | null>((res, rej) => {
cache.get(url, (err:any, cacheFile: string) => {
if (cacheFile !== null) {
res(cacheFile);
}
res(null);
})
});
if (!cacheHit) {
try {
let retMe: CZITileRequest = await getTile(
path(file.uuid, project.name, 'scalable_image') + '/',
query.channel_name,
query.x_offset,
query.y_offset,
query.width,
query.height,
query.zoom_level
);
avgReqDuration.update(Date.now() - startTime)
cache.set(url, retMe.file_path);
cacheHit = retMe.file_path;
} catch (Err) {
throw Err;
}
} else {
cacheHits.inc();
}
return await readFile(cacheHit);
},
getResponseFunction: (req: Request, res: Response): Function | null => {
res.setHeader('content-type', "image/png")
return res.send;
},
preprocess: async(file: File, original: string, space: string): Promise<void> => {
let isCZI: boolean = await new Promise<boolean>((res, rej) => {
fs.open(original, 'r', function(status, fd) {
if (status) {
logger.debug(status.message);
return;
}
var buffer = new Buffer(10);
fs.read(fd, buffer, 0, 10, 0, function(err, num) {
logger.debug(buffer.toString('utf8', 0, num));
res(buffer.toString('utf8', 0, num) === 'ZISRAWFILE');
});
});
});
if (isCZI) {
CZICrunch(original, space);
} else {
const mt: string = file.originalMimetype;
let validType: boolean = false;
logger.crit("FILES OTHER THAN CZI CURRENTLY NOT IMPLEMENTED")
// if (mt.includes("tif")) {
// await lecialol(original, space, mt);
// } else {
// logger.warn(`unsupported file type ${mt}`);
// }
}
}
}
};
export type FileTypeName = 'generic' | 'directory' | 'tabular' | 'scalable_image';
export interface FileType {
supportedViews: ViewName[];
}
const fileTypes: {
[type: string]: FileType;
} = {
generic: {
supportedViews: [
'raw', 'meta'
]
},
directory: {
supportedViews: [
'meta'
]
},
tabular: {
supportedViews: [
'raw', 'meta', 'tabular'
]
},
scalable_image: {
supportedViews: [
'raw', 'meta', 'scalable_image'
]
}
};
export const preprocess: (
file: File, project: Project
) => Promise<void> = async(
file: File, project: Project
): Promise<void> => {
const promises: Promise<void>[] = [];
for (const view of fileTypes[file.type].supportedViews) {
promises.push(views[view].preprocess(
file,
originalPath(file.uuid, project.name),
path(file.uuid, project.name, view)
));
}
await Promise.all(promises);
file.status = 'ready';
await file.save();
};
class MimeTypeMap extends Map<string, string> {
public constructor(pairs: [string, FileTypeName][]) {
super(pairs);
}
public get(mime: string): FileTypeName {
const ret: string | undefined = super.get(mime);
if (ret) {
return ret as FileTypeName;
} else {
return 'generic';
}
}
}
export const mimes: MimeTypeMap = new MimeTypeMap([
[ 'inode/directory', 'directory' ],
[ 'text/csv', 'tabular' ]
]);
export const rootPathId: string = '0';
export const rootPathFile: File | null = null;
export const createRootFolder: () => Promise<void> = async(
): Promise<void> => {
try {
await fs.mkdir(CONTENT_BASE_DIRECTORY);
} catch (e) {
logger.warn(`error when creating base folder: ${e}`);
}
};
export const createProjectFolder: (name: string) => Promise<void> = async(
projName: string
): Promise<void> => {
try {
await fs.mkdir(CONTENT_BASE_DIRECTORY + '/' + projName);
} catch (e) {
logger.warn(`error when creating folder for project ${projName}: ${e}`);
}
};
export const addSubFileToFolder: (
parentId: string, subFile: File
) => Promise<void> = async(
parentId: string, subFile: File
): Promise<void> => {
logger.debug(`adding file ${subFile.uuid} to directory ${parentId}`);
// Fetch parent and subFile object from database
subFile.parentFolderId = parentId;
await subFile.save();
};
|