aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xgetmeredis.sh5
-rw-r--r--package.json3
-rw-r--r--src/FileRouter.ts56
-rw-r--r--src/app.ts12
-rw-r--r--src/conversion/czi/czi.ts1
-rw-r--r--src/conversion/czi/pyramidWorker.ts63
-rw-r--r--src/files.ts77
-rw-r--r--src/profiler/index.js2
-rw-r--r--yarn.lock37
9 files changed, 189 insertions, 67 deletions
diff --git a/getmeredis.sh b/getmeredis.sh
new file mode 100755
index 0000000..b60927f
--- /dev/null
+++ b/getmeredis.sh
@@ -0,0 +1,5 @@
+wget http://download.redis.io/redis-stable.tar.gz
+tar xvzf redis-stable.tar.gz
+rm redis-stable.tar.gz
+cd redis-stable
+make
diff --git a/package.json b/package.json
index 6a849eb..5cf3f12 100644
--- a/package.json
+++ b/package.json
@@ -63,6 +63,7 @@
"@types/node": "9.6.6",
"@types/passport": "^0.4.2",
"@types/passport-local": "^1.0.32",
+ "@types/redis": "^2.8.6",
"@types/sequelize": "^4.27.5",
"@types/sharp": "^0.17.6",
"@types/sqlite3": "^3.1.1",
@@ -91,6 +92,8 @@
"pg-native": "^2.2.0",
"pm2": "^2.10.2",
"pmx": "^1.6.4",
+ "redis": "^2.8.0",
+ "redis-server": "^1.2.0",
"reflect-metadata": "^0.1.12",
"sequelize": "^4.32.7",
"sequelize-typescript": "^0.6.2",
diff --git a/src/FileRouter.ts b/src/FileRouter.ts
index 546c694..e2b7eeb 100644
--- a/src/FileRouter.ts
+++ b/src/FileRouter.ts
@@ -724,17 +724,23 @@ const getFileFromPath: (req: Request, res: Response) => Promise<void> = async(
const getFile: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
+ 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();
};
@@ -927,20 +933,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 1d684ab..393a89e 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<boolean> = async(): Promise<boolean> =>
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<Buffer> {
+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<CZITileRequest> {
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<CZITileRequest> {
- 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 412f0c3..72947e9 100644
--- a/src/files.ts
+++ b/src/files.ts
@@ -12,8 +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/${require("os").userInfo().username}/`
const CONTENT_BASE_DIRECTORY: string = BASE_BASE + 'files';
@@ -205,7 +212,7 @@ interface Query extends Partial<RawSize> {
export interface View {
getContents: (file: File, project: Project) => object | Promise<object>;
- getResponseData: (file: File, project: Project, query: Query) =>
+ 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) =>
@@ -273,6 +280,16 @@ export const getSize: (file: File, project: Project) => Promise<number> = 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;
} = {
@@ -358,23 +375,57 @@ export const views: {
},
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'));
+ 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<object> => {
- 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<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 => {
- 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<void> => {
let isCZI: boolean = await new Promise<boolean>((res, rej) => {
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() };
diff --git a/yarn.lock b/yarn.lock
index e6b7d78..98d8843 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -208,6 +208,13 @@
dependencies:
"@types/express" "*"
+"@types/redis@^2.8.6":
+ version "2.8.6"
+ resolved "https://registry.yarnpkg.com/@types/redis/-/redis-2.8.6.tgz#3674d07a13ad76bccda4c37dc3909e4e95757e7e"
+ dependencies:
+ "@types/events" "*"
+ "@types/node" "*"
+
"@types/reflect-metadata@0.0.4":
version "0.0.4"
resolved "https://registry.yarnpkg.com/@types/reflect-metadata/-/reflect-metadata-0.0.4.tgz#b6477ca9a97e5265f2ac67f9ea704eae5e0eaf4d"
@@ -1144,6 +1151,10 @@ dottie@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/dottie/-/dottie-2.0.0.tgz#da191981c8b8d713ca0115d5898cf397c2f0ddd0"
+double-ended-queue@^2.1.0-0:
+ version "2.1.0-0"
+ resolved "https://registry.yarnpkg.com/double-ended-queue/-/double-ended-queue-2.1.0-0.tgz#103d3527fd31528f40188130c841efdd78264e5c"
+
duplexer3@^0.1.4:
version "0.1.4"
resolved "https://registry.yarnpkg.com/duplexer3/-/duplexer3-0.1.4.tgz#ee01dd1cac0ed3cbc7fdbea37dc0a8f1ce002ce2"
@@ -3032,6 +3043,10 @@ progress@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.0.tgz#8a1be366bf8fc23db2bd23f10c6fe920b4389d1f"
+promise-queue@^2.2.5:
+ version "2.2.5"
+ resolved "https://registry.yarnpkg.com/promise-queue/-/promise-queue-2.2.5.tgz#2f6f5f7c0f6d08109e967659c79b88a9ed5e93b4"
+
promptly@2.2.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/promptly/-/promptly-2.2.0.tgz#2a13fa063688a2a5983b161fff0108a07d26fc74"
@@ -3176,6 +3191,28 @@ redent@^1.0.0:
indent-string "^2.1.0"
strip-indent "^1.0.1"
+redis-commands@^1.2.0:
+ version "1.3.5"
+ resolved "https://registry.yarnpkg.com/redis-commands/-/redis-commands-1.3.5.tgz#4495889414f1e886261180b1442e7295602d83a2"
+
+redis-parser@^2.6.0:
+ version "2.6.0"
+ resolved "https://registry.yarnpkg.com/redis-parser/-/redis-parser-2.6.0.tgz#52ed09dacac108f1a631c07e9b69941e7a19504b"
+
+redis-server@^1.2.0:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/redis-server/-/redis-server-1.2.0.tgz#766f594c65c78e4df7fd6911b5b3d5f9c3e95c53"
+ dependencies:
+ promise-queue "^2.2.5"
+
+redis@^2.8.0:
+ version "2.8.0"
+ resolved "https://registry.yarnpkg.com/redis/-/redis-2.8.0.tgz#202288e3f58c49f6079d97af7a10e1303ae14b02"
+ dependencies:
+ double-ended-queue "^2.1.0-0"
+ redis-commands "^1.2.0"
+ redis-parser "^2.6.0"
+
reflect-metadata@^0.1.12:
version "0.1.12"
resolved "https://registry.yarnpkg.com/reflect-metadata/-/reflect-metadata-0.1.12.tgz#311bf0c6b63cd782f228a81abe146a2bfa9c56f2"