From 6dda3ae3288e7d57b3157007817d14ed6da983ff Mon Sep 17 00:00:00 2001 From: cjd24 Date: Mon, 23 Apr 2018 15:28:46 +0100 Subject: PANIC COMMITS OMMGGGGG --- src/FileRouter.ts | 56 +++++++++++++++----------- src/app.ts | 12 +++--- src/conversion/czi/czi.ts | 1 + src/conversion/czi/pyramidWorker.ts | 63 ++++++++++++++++++------------ src/files.ts | 78 ++++++++++++++++++++++++++++++------- src/index.ts | 2 +- src/profiler/index.js | 2 +- 7 files changed, 145 insertions(+), 69 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index c8884f7..e977073 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -726,17 +726,23 @@ const getFileFromPath: (req: Request, res: Response) => Promise = async( const getFile: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { + req.query.view = req.query.view || 'meta'; logger.debug(`Getting file in ${req.query.view} view`); - const file: File | null = res.locals.file; - if (file == null) { - return next(new RequestError(404, 'file_not_found')); + try { + const file: File | null = res.locals.file; + if (file == null) { + return next(new RequestError(404, 'file_not_found')); + } + const project: Project = res.locals.project; + const view: View = views[req.query.view || 'meta']; + // TODO return 400 for unsupported views + // TODO raw view accepts extra query params offset and length + res.locals.function = view.getResponseFunction(req, res); + + res.locals.data = view.getResponseData(file, project, req.query, req.url); + } catch (err) { + next(err); } - const project: Project = res.locals.project; - const view: View = views[req.query.view || 'meta']; - // TODO return 400 for unsupported views - // TODO raw view accepts extra query params offset and length - res.locals.function = view.getResponseFunction(req, res); - res.locals.data = view.getResponseData(file, project, req.query); next(); }; @@ -937,20 +943,24 @@ const postFilePath: Middleware = async( } } else { /* tslint:disable-next-line:curly */ - if (req.query.action) switch (req.query.action) { - case 'mkdir': { - await makeFile(req, res); - res.locals.file.status = 'final'; - break; - } - case 'set_metadata': - case 'delete': - case 'move': - case 'copy': - logger.debug(`Action '${req.query.action - }' not valid if file does not exist`); - return next(new RequestError(404, 'file_not_found')); - } else { + if (req.query.action) { + switch (req.query.action) { + case 'mkdir': { + await makeFile(req, res); + res.locals.file.status = 'final'; + break; + } + case 'set_metadata': + case 'delete': + case 'move': + case 'copy': + logger.debug(`Action '${req.query.action + }' not valid if file does not exist`); + return next(new RequestError(404, 'file_not_found')); + } + } + + if (!req.query.action || req.query.action === 'upload') { if (!req.body) { logger.debug('No file attached. Sending 400'); next(new RequestError(400, 'no_file_attached')); diff --git a/src/app.ts b/src/app.ts index 7b398fd..7270149 100644 --- a/src/app.ts +++ b/src/app.ts @@ -44,6 +44,12 @@ class App { logger.debug('Constructing router'); this.logEnabled = enableLog; this.express = ex(); + this.express.use((req, res, next) => { + if (req.headers.authorisation) { + (req.headers.authorization as any) = req.headers.authorisation; + } + next(); + }); this.express.use(cors()); this.express.use( (req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { @@ -82,12 +88,6 @@ class App { '/cs3099group-be-4/_supported_protocols_' ] }) ); - this.express.use((req, res, next) => { - if (req.headers.authorisation) { - (req.headers.authorization as any) = req.headers.authorisation; - } - next(); - }) this.express.use(passport.initialize()); this.express.use(async( req: ex.Request, res: ex.Response, next: ex.NextFunction diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 33bc738..1c0bc4d 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -800,6 +800,7 @@ const buildCustomPyramids: () => Promise = async(): Promise => writeJSONToFile(`${outputImageData}/layout.json`, finalCZIJson); } finalCZIJson.complete = true; + writeJSONToFile(`${outputImageData}/layout.json`, finalCZIJson); return errorOccurred; }; diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index 6b12409..8116a8d 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -5,6 +5,7 @@ import { isTileRelated } from './tileExtraction'; import { uuid } from '../../uuid' import * as fs from 'fs'; import { RequestError } from '../../errors' +import { logger } from '../../logger' const readFile = require('util').promisify(fs.readFile); const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] { @@ -35,24 +36,35 @@ const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBo return relatedTiles; }; -export const getTile: Function = async function(imageDir: string, cVal: string, x:number = 0, y:number = 0, w:number = 1024, h:number = 1024, zoom: number = 1): Promise { +export const getTile: Function = async function(imageDir: string, cVal: string, x:number = 0, y:number = 0, w:number = 1024, h:number = 1024, zoom: number = 1): Promise { let layout: WholeCZIHierarchy = JSON.parse(await readFile(imageDir + "/layout.json", 'utf8')); + if (!layout.complete) { + throw new RequestError(400, "conversion_incomplete") + } + - let bound: TileBounds = new TileBounds(x, x + w, y, y + h); + let bound: TileBounds = new TileBounds(Number(x), Number(x) + Number(w), Number(y), Number(y) + Number(h)); let map: CZIHeightMap; try { - map = layout.c_values[Number(cVal)].height_map[Math.floor(Math.log2(zoom))] - } catch { + let reqZoom: number = Math.floor(Math.log2(zoom)); + if (reqZoom > layout.zoom_level_count - 1) { + reqZoom = layout.zoom_level_count - 1; + } + map = layout.c_values[Number(cVal)].height_map[reqZoom]; + } catch (err) { + logger.error(err); + throw new RequestError(500, "missing_layout_item") + } + if (!map) { throw new RequestError(400, "bad_zoom_index") } - - return readFile((await getFinalTile(imageDir, map, cVal, bound)).file_path); + let reqRes: CZITileRequest = await getFinalTile(imageDir, map, cVal, bound); + logger.verbose(JSON.stringify(reqRes)) + return reqRes; } const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHeightMap, cVal: string, desiredRegion: TileBounds): Promise { - console.error("Has the calling function checked that the image has completed processing in WholeCZIHierarchy??"); - let involvedTiles: string = ''; for (const row of imageTier.plane) { for (const tile of row) { @@ -60,30 +72,33 @@ const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHe } } - let outputFileName: string =`${imageDir}/tmp/${uuid.generate()}.png` - require('shelljs').exec(`${execpaths} vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`) + let id: string = uuid.generate(); + let intermediateFileName: string = `${imageDir}tmp/${id}.png` + let outputFileName: string = `${imageDir}tmp/${id}-out.png` + require('shelljs').exec(`${execpaths} vips arrayjoin "${involvedTiles}" ${intermediateFileName} --across ${imageTier.plane[0].length}`) + - let extractionRegion = new TileBounds( - desiredRegion.left - imageTier.plane[0][0].width, - desiredRegion.right - imageTier.plane[0][0].width, - desiredRegion.top - imageTier.plane[0][0].height, - desiredRegion.bottom - imageTier.plane[0][0].height - ); - extractionRegion.scaleDown(imageTier.zoom_level); + desiredRegion.scaleDown(imageTier.zoom_level); - await sharp(outputFileName) + await sharp(intermediateFileName) .extract({ - top: extractionRegion.top, - left: extractionRegion.left, - width: extractionRegion.width(), - height: extractionRegion.height() + top: desiredRegion.top, + left: desiredRegion.left, + width: desiredRegion.width(), + height: desiredRegion.height() }) .toFile(outputFileName); + fs.unlink(intermediateFileName, (err:any) => { + if (err) { + logger.warn("Couldn't delete: " + intermediateFileName); + } + }) + return { dimensions: new TileBounds( - 0, extractionRegion.width(), - 0, extractionRegion.height() + 0, desiredRegion.width(), + 0, desiredRegion.height() ), original_bounds: desiredRegion, zoom_level: imageTier.zoom_level, diff --git a/src/files.ts b/src/files.ts index 19862d1..6e793d5 100644 --- a/src/files.ts +++ b/src/files.ts @@ -12,9 +12,15 @@ 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/cjd24/' const CONTENT_BASE_DIRECTORY: string = BASE_BASE + 'files'; @@ -201,7 +207,7 @@ interface Query extends Partial { export interface View { getContents: (file: File, project: Project) => object | Promise; - getResponseData: (file: File, project: Project, query: Query) => + getResponseData: (file: File, project: Project, query: Query, url: string) => Promise; getResponseFunction: (req: Request, res: Response) => Function | null; preprocess: (file: File, original: string, space: string) => @@ -269,6 +275,16 @@ export const getSize: (file: File, project: Project) => Promise = async( 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; } = { @@ -354,23 +370,57 @@ export const views: { }, scalable_image: { getContents: async(file: File, project: Project): Promise => { - return JSON.parse(await readFile(path(file.uuid, project.name, 'scalable_image') + "/supported_views.json", 'utf8')); + 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 + file: File, project: Project, query: Query, url: string ): Promise => { - return getTile( - path(file.uuid, project.name, 'scalable_image') + '/', - query.channel_name, - query.x_offset, - query.y_offset, - query.width, - query.height, - query.zoom_level - ); + 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((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 => { - return (stream: fs.ReadStream) => stream.pipe(res); + res.setHeader('content-type', "image/png") + return res.send; }, preprocess: async(file: File, original: string, space: string): Promise => { let isCZI: boolean = await new Promise((res, rej) => { diff --git a/src/index.ts b/src/index.ts index e99aa1a..ad0d43e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -166,7 +166,7 @@ async function reset(): Promise { process.exit(1); } - await reset(); +// await reset(); logger.info('Booting ExpressJS server'); diff --git a/src/profiler/index.js b/src/profiler/index.js index 59934fe..24c187e 100644 --- a/src/profiler/index.js +++ b/src/profiler/index.js @@ -3,4 +3,4 @@ let pmx = require('pmx').init({ ports: true }); -module.export.profiler = pmx.probe(); +module.exports = { profiler: pmx.probe() }; -- cgit v1.2.1