aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/conversion/czi/czi.ts122
-rw-r--r--src/conversion/czi/pyramidWorker.ts18
-rw-r--r--src/conversion/leica/scn.ts3
-rw-r--r--src/conversion/types/exec.ts17
-rw-r--r--src/files.ts1
-rw-r--r--src/logger.ts112
-rw-r--r--src/ppq/index.d.ts7
-rw-r--r--src/ppq/index.js31
8 files changed, 194 insertions, 117 deletions
diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts
index 03f280e..a618b5b 100644
--- a/src/conversion/czi/czi.ts
+++ b/src/conversion/czi/czi.ts
@@ -3,18 +3,29 @@ import { CZIHeightMap, CZITile,
import { Dimension, Segment } from '../types/cziBinaryTypings';
import * as fs from 'fs';
import { SupportedViews, TileBounds, checkForOutputDirectories, writeJSONToFile, execpaths } from '../types/helpers';
-import { logger } from '../../logger';
+import { logger, Logger } from '../../logger';
import * as sharp from 'sharp';
// tslint:disable-next-line:no-duplicate-imports
import { SharpInstance } from 'sharp';
import { isTileRelated, regionToExtract } from './tileExtraction';
import * as parsexml from 'xml-parser';
import { uuid } from '../../uuid'
+import { queue as jobQueue, Promiser as Job } from '../../ppq'
+import { profiler } from '../../profiler';
+import { exec } from '../types/exec'
+sharp.concurrency(4);
+let log: Logger;
const readFile = require('util').promisify(fs.readFile);
const readdir = require('util').promisify(fs.readdir);
const exists = require('util').promisify(fs.exists);
+const queueSize = profiler.metric({
+ name: "Queued Image Jobs",
+ agg_type: "sum",
+ value : () => jobQueue.size
+})
+
// Various constants for placing files and defining tiles
let extractDirectory: string = "";
let outputImageData: string = "";
@@ -22,6 +33,7 @@ let outputImageDirectory: string = "";
let supportedViews: SupportedViews;
let totalSizeX: number = -1;
let totalSizeY: number = -1;
+let fileName: string = "unset filename";
const tileOverlap: number = 0; // Overlap is only half implemented
const tileSize: number = 1024;
const maxZoom: number = 64;
@@ -220,19 +232,19 @@ const findRegionToExtract: (
for (const segCol of segRow) {
// Find out the region of the base tile to be added to the new image
chunkToExtract = findRegionToExtract(segCol, desiredRegion);
+ let localSharp: SharpInstance = sharp(`${extractDirectory}${segCol.Data.Data}`);
// Extract this section of image data into a sharp buffer
- let data: Promise<Buffer> =
- sharp(`${extractDirectory}${segCol.Data.Data}`)
+ let data: Job<Buffer> =
+ localSharp
.extract({
left: chunkToExtract.left,
top: chunkToExtract.top,
width: chunkToExtract.right - chunkToExtract.left,
height: chunkToExtract.bottom - chunkToExtract.top
- })
- .toBuffer();
+ }).toBuffer;
// Push this data into the row buffer
- tileRow.push(await data);
+ tileRow.push(await jobQueue.enqueue(10, data, localSharp));
}
// Prepare variables to squash all of the column data into one, for this row
@@ -240,7 +252,7 @@ const findRegionToExtract: (
const bufferBound: TileBounds = findRegionToExtract(segRow[0], desiredRegion);
// Check if the inital chunk needs to be extended to support the other columns
if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) {
- imageVerticalSlice = await imageVerticalSlice.extend({
+ imageVerticalSlice = imageVerticalSlice.extend({
top: 0,
left: 0,
bottom: 0,
@@ -249,7 +261,7 @@ const findRegionToExtract: (
}
// For every column along this row, join it to the previous column data
for (let index: number = 1; index < segRow.length; index++) {
- imageVerticalSlice = await imageVerticalSlice
+ imageVerticalSlice = imageVerticalSlice
.overlayWith(tileRow[index], {
top: 0,
left: (bufferBound.right - bufferBound.left)
@@ -258,7 +270,7 @@ const findRegionToExtract: (
}
// Add this horizontal data buffer to the vertical buffer
- tileVerticalBuffer.push(await imageVerticalSlice.toBuffer());
+ tileVerticalBuffer.push(await jobQueue.enqueue(10, imageVerticalSlice.toBuffer as Job<Buffer>, imageVerticalSlice));
}
// Prepare variables used to combine all rows into one image
@@ -267,7 +279,7 @@ const findRegionToExtract: (
findRegionToExtract(segments[0][0], desiredRegion);
// Check if the inital row needs to be extended to support further rows
if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) {
- finalImage = await finalImage
+ finalImage = finalImage
.background({
r: 0,
g: 0,
@@ -288,7 +300,7 @@ const findRegionToExtract: (
}
// Return the finalised image.
- if ((await finalImage.metadata()).channels != 4) {
+ if ((await jobQueue.enqueue(5, finalImage.metadata as Job<sharp.Metadata>, finalImage)).channels != 4) {
return sharp(Buffer.alloc(tileSize, tileSize), {
create: {
width: tileSize,
@@ -296,7 +308,7 @@ const findRegionToExtract: (
channels: 4,
background: { r: 0, g: 0, b: 0, alpha: 1 }
}
- }).overlayWith(await finalImage.toBuffer())
+ }).overlayWith(await jobQueue.enqueue(5, finalImage.toBuffer as Job<Buffer>, finalImage));
} else {
return finalImage;
}
@@ -527,7 +539,7 @@ const zoomTier: (
}
let outputFileName: string =`${outputImageData}/tmp/${uuid.generate()}.png`;
- shell.exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`, {silent: true});
+ await jobQueue.enqueue(4, exec, null, `${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`);
// Rescale and push to file
if (quadrentCount !== 3) {
@@ -539,20 +551,29 @@ const zoomTier: (
extRight = tileSize;
}
- sharp(await sharp(outputFileName)
+ let fullTileQuadRef: SharpInstance = sharp(outputFileName)
.background({r: 0, g: 0, b: 0, alpha: 1})
.extend({
top: 0, left: 0,
bottom: extBottom, right: extRight
- }).toBuffer())
- .resize(tileSize, tileSize)
- .toFile(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`);
+ });
+ let fullTileQuad: Buffer = await jobQueue.enqueue(5, fullTileQuadRef.toBuffer as Job<Buffer>, fullTileQuadRef);
+
+ let rescaledTileQuadRef: SharpInstance = sharp(fullTileQuad)
+ .resize(tileSize, tileSize);
+
+ await jobQueue.enqueue(5, rescaledTileQuadRef.toFile as Job<sharp.OutputInfo>, rescaledTileQuadRef,
+ `${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`);
} else {
- await sharp(outputFileName)
+ let fullTileQuadRef: SharpInstance = sharp(outputFileName)
.resize(tileSize, tileSize)
- .toFile(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`);
+
+ await jobQueue.enqueue(5, fullTileQuadRef.toFile as Job<sharp.OutputInfo>, fullTileQuadRef,
+ `${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`);
}
- shell.exec(`rm ${outputFileName}`, {silent: true});
+ fs.unlink(`rm ${outputFileName}`, (err) => {
+ log.warn(fileName + ' Error when deleting redundant resource: \n' + err.stack)
+ });
finalCZIJson.total_files++;
return {
@@ -580,7 +601,7 @@ const zoomTier: (
// Check the condition where another zoom level does not make sense
if (previousHeightMap.plane.length === 1
&& previousHeightMap.plane[0].length === 1) {
- console.log(
+ log.notice(fileName +
' Task(1/1): ' +
'Stage 100% complete. ' +
'Stage was skipped as maximum sensible zoom level was reached.'
@@ -593,7 +614,7 @@ const zoomTier: (
for (let ys: number = 0; ys < previousHeightMap.plane.length; ys += 2) {
newplane.push(await squashRow(previousHeightMap.plane, ys, p));
- console.log(
+ log.debug(fileName +
` Task(${ys / 2 + 1}/${
Math.floor(previousHeightMap.plane.length / 2) + 1}): ` +
`Stage ${Math.ceil(((ys / previousHeightMap.plane.length)
@@ -669,13 +690,13 @@ const extrapolateDimension: (
getDimension(item, 'C').Start === cVal
);
// Begin output for the base tier
- console.log('=========================================================');
- console.log(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`);
- console.log('=========================================================');
- console.log('>> Computing base tier, this will take a while...\n');
+ // console.log('=========================================================');
+ log.notify(`${fileName} > Beginning Dimension Extrapolation for \'C\' : ${cVal}`);
+ // console.log('=========================================================');
+ // console.log('>> Computing base tier, this will take a while...\n');
const baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []};
- console.log(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`);
+ log.notify(`${fileName} > Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`);
// For all rows within the total base pixel height
const plane: CZITile[][] = [];
@@ -683,7 +704,7 @@ const extrapolateDimension: (
plane.push(await doOneRow(ys, filteredDataBlocks));
process.stdout.write("\r");
- console.log(
+ log.info(fileName +
` Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ` +
`Stage ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. `
);
@@ -693,13 +714,13 @@ const extrapolateDimension: (
baseCZIHeightMap.tile_width_count = baseCZIHeightMap.plane[0].length;
// BUILD UP THE HIGHER ZOOM LAYERS.
- console.log(`>> Base tier complete for \'C\': ${cVal
- }; Begin computing zoom tiers...\n`);
+ // console.log(`>> Base tier complete for \'C\': ${cVal
+ // }; Begin computing zoom tiers...\n`);
const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap];
writeJSONToFile(`${outputImageData}/intermediate-stage-map.json`, retHeightMap);
for (let stage: number = 1; stage <= Math.log2(maxZoom); stage++) {
- console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`);
+ log.notify(`${fileName} > Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`);
await zoomTier(retHeightMap[stage - 1], stage, cVal)
.then((v: CZIHeightMap) => {
retHeightMap.push(v);
@@ -709,7 +730,7 @@ const extrapolateDimension: (
writeJSONToFile(`${outputImageData}/intermediate-stage-map.json`, retHeightMap);
}
- console.log(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`);
+ log.notify(`${fileName} > Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`);
return retHeightMap;
};
@@ -793,18 +814,21 @@ const buildCustomPyramids: () => Promise<boolean> = async(): Promise<boolean> =>
// On error, write the error to console and set an error true.
if (err) {
console.error(err.message);
+ console.log(err);
}
successfulBuild = false;
}
);
} else {
- console.error(`\nAn error occurred while extracting dimension: ${cval}`);
- console.error('Skipping futher elements and moving to next dimension.\n\n');
+ log.error(`${fileName} > An error occurred while extracting dimension: ${cval}`);
+ log.warn(`${fileName} > Skipping futher elements and moving to next dimension.\n\n`);
}
// Write the final json data to file with most recent changes
writeJSONToFile(`${outputImageData}/layout.json`, finalCZIJson);
}
- finalCZIJson.complete = true;
+ if (successfulBuild) {
+ finalCZIJson.complete = true;
+ }
writeJSONToFile(`${outputImageData}/layout.json`, finalCZIJson);
return successfulBuild;
};
@@ -812,10 +836,10 @@ const buildCustomPyramids: () => Promise<boolean> = async(): Promise<boolean> =>
const initialExtractAndConvert: (absFilePath: string, space: string) => Promise<void> = async (absFilePath: string, space: string): Promise<void> => {
checkForOutputDirectories([outputImageData, extractDirectory]);
- logger.silly(">> This will complete at roughly 2GB/min");
+ log.silly(`${fileName} > This will complete at roughly 2GB/min`);
shell.exec(`${execpaths} CZICrunch ${absFilePath} ${extractDirectory}`);
- shell.exec(`${execpaths} python3 convertJxrs.py ${extractDirectory}`);
+ shell.exec(`${execpaths} python3 ./ext/bin/convertJxrs.py ${extractDirectory}`);
// let totalFiles: number = 0, counter: number = 0;
// console.log("=========== BEGIN JXR CONVERSION ===========")
@@ -858,9 +882,9 @@ process.on("warning", (err: any) => console.warn(err))
* extraction.
*/
export const main: (original: string, space:string) => Promise<void> = async (original: string, space:string): Promise<void> => {
-
-let fileName: string = `CZI: ${original.split('/')[original.split('/').length - 1]}`;
-logger.notice("CZI Convertor Received new file: " + fileName);
+fileName = `${original.split('/')[original.split('/').length - 1]}`;
+log = logger.for({component: "CZI Crunch", targetFile: original});
+log.notice("CZI Convertor Received new file: " + fileName);
try {
outputImageData = space;
@@ -868,16 +892,16 @@ logger.notice("CZI Convertor Received new file: " + fileName);
outputImageDirectory = outputImageData + "/data/";
if (!(await exists(`${outputImageData}/supported_views.json`))) {
- logger.info(`${fileName} > Begin Extracting and Converting to PNG`);
+ log.info(`${fileName} > Begin Extracting and Converting to PNG`);
await initialExtractAndConvert(original, space);
- logger.info(`${fileName} > Checking/Creating output directories...`);
+ log.info(`${fileName} > Checking/Creating output directories...`);
checkForOutputDirectories([outputImageDirectory, `${outputImageData}/tmp/`]);
- logger.info(`${fileName} > Creating Supported Views and writing files...`);
+ log.info(`${fileName} > Creating Supported Views and writing files...`);
await createSupportedViewsObject(false);
} else {
- logger.alert("It appears as though this CZI has already been extracted, loading files...");
+ log.alert("It appears as though this CZI has already been extracted, loading files...");
await createSupportedViewsObject(true);
supportedViews = require(`${outputImageData}/supported_views.json`);
}
@@ -889,14 +913,14 @@ logger.notice("CZI Convertor Received new file: " + fileName);
totalSizeY = supportedViews.scalable_image.height;
if (await buildCustomPyramids()) {
- logger.alert('UNCOMMENT ME AGAIN >> Removing the initial extraction bloat');
+ log.alert(`UNCOMMENT ME AGAIN ${fileName} > Removing the initial extraction bloat`);
// shell.exec(`rm -rf ${outputImageData}/extract/`)
};
- logger.success("\n>> Done");
+ log.success(`${fileName} > Done`);
} catch (Err) {
- logger.critical("This was a really big boi error, and something is sad: ");
- logger.critical(Err);
+ log.critical(`${fileName} > This was a really big boi error, and something is sad: `);
+ log.critical(Err);
throw Err;
}
};
@@ -908,7 +932,7 @@ logger.notice("CZI Convertor Received new file: " + fileName);
console.log("REMEMBER TO REMOVE THE MAIN CALL AGAIN MR GOOSEMUN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-main("/cs/scratch/trh/0701.czi", "/cs/scratch/trh/0701-extract");
+main("/cs/scratch/cjd24/0701.czi", "/cs/scratch/cjd24/0701-extract");
// /* tslint:disable */
// async function main2() {
diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts
index 8116a8d..c52aac2 100644
--- a/src/conversion/czi/pyramidWorker.ts
+++ b/src/conversion/czi/pyramidWorker.ts
@@ -1,12 +1,16 @@
import { WholeCZIHierarchy, CZIHeightMap, CZITile, CZITileRequest } from '../types/customPyramidIndex';
import { TileBounds, execpaths } from '../types/helpers';
import * as sharp from 'sharp';
+import { SharpInstance } from 'sharp';
import { isTileRelated } from './tileExtraction';
import { uuid } from '../../uuid'
import * as fs from 'fs';
import { RequestError } from '../../errors'
-import { logger } from '../../logger'
+import { logger, Logger } from '../../logger'
+import { exec } from '../types/exec'
+import { queue as jobQueue, Promiser as Job } from '../../ppq'
const readFile = require('util').promisify(fs.readFile);
+const log: Logger = logger.for({component: "CZI Live Server"});
const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] {
@@ -37,7 +41,7 @@ const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBo
};
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'));
+ let layout: WholeCZIHierarchy = JSON.parse(await jobQueue.enqueue(2, readFile, null, imageDir + "/layout.json", 'utf8'));
if (!layout.complete) {
throw new RequestError(400, "conversion_incomplete")
}
@@ -59,7 +63,6 @@ export const getTile: Function = async function(imageDir: string, cVal: string,
throw new RequestError(400, "bad_zoom_index")
}
let reqRes: CZITileRequest = await getFinalTile(imageDir, map, cVal, bound);
- logger.verbose(JSON.stringify(reqRes))
return reqRes;
}
@@ -75,19 +78,19 @@ const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHe
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}`)
+ await jobQueue.enqueue(2, exec, null, `${execpaths} vips arrayjoin "${involvedTiles}" ${intermediateFileName} --across ${imageTier.plane[0].length}`);
desiredRegion.scaleDown(imageTier.zoom_level);
- await sharp(intermediateFileName)
+ let final: SharpInstance = sharp(intermediateFileName)
.extract({
top: desiredRegion.top,
left: desiredRegion.left,
width: desiredRegion.width(),
height: desiredRegion.height()
- })
- .toFile(outputFileName);
+ });
+ await jobQueue.enqueue(2, final.toFile as Job<sharp.OutputInfo>, final, outputFileName);
fs.unlink(intermediateFileName, (err:any) => {
if (err) {
@@ -95,6 +98,7 @@ const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHe
}
})
+ log.info(`Gen new Tile: ${outputFileName} X:${desiredRegion.left} Y:${desiredRegion.top} W:${desiredRegion.width()} H:${desiredRegion.height()} Z:${cVal}`);
return {
dimensions: new TileBounds(
0, desiredRegion.width(),
diff --git a/src/conversion/leica/scn.ts b/src/conversion/leica/scn.ts
index 5d75cb3..ce9d36c 100644
--- a/src/conversion/leica/scn.ts
+++ b/src/conversion/leica/scn.ts
@@ -68,6 +68,9 @@ const crunchLeica: () => Promise<string> = async (): Promise<string> => {
metadata: {}
})
}
+ if (!supportedViews.scalable_image) {
+ throw new Error("Not a scalable image");
+ }
supportedViews.scalable_image.channels = channels;
}
diff --git a/src/conversion/types/exec.ts b/src/conversion/types/exec.ts
new file mode 100644
index 0000000..3f294b7
--- /dev/null
+++ b/src/conversion/types/exec.ts
@@ -0,0 +1,17 @@
+import * as shelljs from 'shelljs';
+import { execpaths } from '../types/helpers';
+
+export const exec = (cmd: string): Promise<{
+ code: number;
+ stdout: string;
+ stderr: string;
+}> => new Promise((res, rej) => {
+ shelljs.exec(`${execpaths} ${cmd}`, (code, stdout, stderr) => {
+ const ret = { code, stdout, stderr };
+ if (code === 0) {
+ res(ret);
+ } else {
+ rej(ret);
+ }
+ })
+});
diff --git a/src/files.ts b/src/files.ts
index 24a1dbf..fe92e3e 100644
--- a/src/files.ts
+++ b/src/files.ts
@@ -420,6 +420,7 @@ export const views: {
throw Err;
}
} else {
+ logger.debug("CACHE HIT for image tile!");
cacheHits.inc();
}
return await readFile(cacheHit);
diff --git a/src/logger.ts b/src/logger.ts
index bdd8fbc..aa8192c 100644
--- a/src/logger.ts
+++ b/src/logger.ts
@@ -121,12 +121,12 @@ const consoleTransport: winston.TransportInstance =
handleExceptions: true,
humanReadableUncaughtException: true,
formatter: (
- { level, message }:
- { level: string; message: string }
+ { level, message, meta }:
+ { level: string; message: string, meta: any }
): string => {
let out: string = '';
const stamp: string = new Date().toLocaleTimeString();
- out += `[${LOG_LEVEL_COLOURS[level](`${stamp} ${level}`)}] `;
+ out += `[${LOG_LEVEL_COLOURS[level](`${stamp} ${level}`)}${meta.component ? ` ${meta.component}` : ''}] `;
out += (level === 'critical')
? colors.red(message)
: message;
@@ -238,8 +238,8 @@ const queryLogger: winston.LoggerInstance = new winston.Logger({
type LogFunction = (message: string, meta?: LoggingMetadata) => void;
-const makeLogFunction: (level: LogLevel) => LogFunction = (
- level: LogLevel
+const makeLogFunction: (level: LogLevel, defaults: LoggingMetadata) => LogFunction = (
+ level: LogLevel, defaults: LoggingMetadata
): LogFunction => {
return (
message: string, meta: LoggingMetadata = {}
@@ -247,9 +247,9 @@ const makeLogFunction: (level: LogLevel) => LogFunction = (
if (!enabled) {
return;
}
- meta.user = meta.user || '_BE4_system';
- meta.component = meta.component || 'core';
- basicLogger.log(level, message, meta);
+ meta.user = meta.user || defaults.user ||'_BE4_system';
+ meta.component = meta.component || defaults.component || 'core';
+ basicLogger.log(level, message, { ...defaults, ...meta });
};
};
@@ -293,8 +293,55 @@ const fetchLogs2: (level?: LogLevel, params?: FetchParams) => Promise<LogItem[]>
};
/* tslint:enable */
-export const logger: {
- 7: LogFunction;
+export const setDefaults: (defaults: LoggingMetadata) => Logger = (
+ defaults: LoggingMetadata
+): Logger => {
+ return {
+ 7: makeLogFunction('7', defaults),
+ debug: makeLogFunction('debug', defaults),
+ minor: makeLogFunction('minor', defaults),
+ silly: makeLogFunction('silly', defaults),
+ testing: makeLogFunction('testing', defaults),
+ verbose: makeLogFunction('verbose', defaults),
+ 6: makeLogFunction('6', defaults),
+ information: makeLogFunction('information', defaults),
+ inform: makeLogFunction('inform', defaults),
+ info: makeLogFunction('info', defaults),
+ 5: makeLogFunction('5', defaults),
+ note: makeLogFunction('note', defaults),
+ notice: makeLogFunction('notice', defaults),
+ notify: makeLogFunction('notify', defaults),
+ success: makeLogFunction('success', defaults),
+ security: makeLogFunction('security', defaults),
+ 4: makeLogFunction('4', defaults),
+ warn: makeLogFunction('warn', defaults),
+ warning: makeLogFunction('warning', defaults),
+ 3: makeLogFunction('3', defaults),
+ err: makeLogFunction('err', defaults),
+ failure: makeLogFunction('failure', defaults),
+ fail: makeLogFunction('fail', defaults),
+ error: makeLogFunction('error', defaults),
+ 2: makeLogFunction('2', defaults),
+ crit: makeLogFunction('crit', defaults),
+ severe: makeLogFunction('severe', defaults),
+ critical: makeLogFunction('critical', defaults),
+ 1: makeLogFunction('1', defaults),
+ alert: makeLogFunction('alert', defaults),
+ breach: makeLogFunction('breach', defaults),
+ 0: makeLogFunction('0', defaults),
+ fatal: makeLogFunction('fatal', defaults),
+ emerg: makeLogFunction('emerg', defaults),
+ emergency: makeLogFunction('emergency', defaults),
+ shutdown: makeLogFunction('shutdown', defaults),
+ isEnabled: (): boolean => !basicFileTransport.silent,
+ forward: forwardLog,
+ fetch: fetchLogs2,
+ for: setDefaults
+ }
+}
+
+export interface Logger {
+ 7: LogFunction;
debug: LogFunction;
minor: LogFunction;
silly: LogFunction;
@@ -333,47 +380,10 @@ export const logger: {
isEnabled: () => boolean;
forward: (level: LogLevel, message: string, meta: LoggingMetadata) => void;
fetch: (level: LogLevel, params?: FetchParams) => Promise<LogItem[]>;
-} = {
- 7: makeLogFunction('7'),
- debug: makeLogFunction('debug'),
- minor: makeLogFunction('minor'),
- silly: makeLogFunction('silly'),
- testing: makeLogFunction('testing'),
- verbose: makeLogFunction('verbose'),
- 6: makeLogFunction('6'),
- information: makeLogFunction('information'),
- inform: makeLogFunction('inform'),
- info: makeLogFunction('info'),
- 5: makeLogFunction('5'),
- note: makeLogFunction('note'),
- notice: makeLogFunction('notice'),
- notify: makeLogFunction('notify'),
- success: makeLogFunction('success'),
- security: makeLogFunction('security'),
- 4: makeLogFunction('4'),
- warn: makeLogFunction('warn'),
- warning: makeLogFunction('warning'),
- 3: makeLogFunction('3'),
- err: makeLogFunction('err'),
- failure: makeLogFunction('failure'),
- fail: makeLogFunction('fail'),
- error: makeLogFunction('error'),
- 2: makeLogFunction('2'),
- crit: makeLogFunction('crit'),
- severe: makeLogFunction('severe'),
- critical: makeLogFunction('critical'),
- 1: makeLogFunction('1'),
- alert: makeLogFunction('alert'),
- breach: makeLogFunction('breach'),
- 0: makeLogFunction('0'),
- fatal: makeLogFunction('fatal'),
- emerg: makeLogFunction('emerg'),
- emergency: makeLogFunction('emergency'),
- shutdown: makeLogFunction('shutdown'),
- isEnabled: (): boolean => !basicFileTransport.silent,
- forward: forwardLog,
- fetch: fetchLogs2
-};
+ for: (defaults: LoggingMetadata) => Logger;
+}
+
+export const logger: Logger = setDefaults({ user: '_BE4_system', component: 'core' });
export const logQuery: (query: string, duration: string) => void = (
query: string, duration: string
diff --git a/src/ppq/index.d.ts b/src/ppq/index.d.ts
index ee12f89..21cdeaf 100644
--- a/src/ppq/index.d.ts
+++ b/src/ppq/index.d.ts
@@ -1,8 +1,11 @@
// tslint:disable:no-any
-type Promiser<T = any> = () => PromiseLike<T>;
+export type Promiser<T = any> = (args: any) => PromiseLike<T>;
export class PromisePriorityQueue {
public constructor(concurrent?: number, least?: number);
- public enqueue<T = any>(priority: number, promiser: Promiser<T>): Promise<T>;
+ public enqueue<T = any>(priority: number, promiser: Promiser<T>, binding: any, ...argv: any[]): Promise<T>;
+ public readonly size: number;
}
+
+export const queue: PromisePriorityQueue;
diff --git a/src/ppq/index.js b/src/ppq/index.js
index 37856d0..ec2f188 100644
--- a/src/ppq/index.js
+++ b/src/ppq/index.js
@@ -1,14 +1,17 @@
class PromisePriorityQueue {
- construtor(concurrent, least) {
+
+ constructor(concurrent, least) {
this.least = least || 10;
- this.concurrent = concurrent || 50;
+ this.concurrent = concurrent || 2;
this.running = 0;
this.queues = [];
- for (let i = 1; i <= this.least; ++i) {
+ for (let i = 0; i < this.least; ++i) {
this.queues[i] = [];
}
+
+ this.size = 0;
}
configure(config) {
@@ -16,17 +19,29 @@ class PromisePriorityQueue {
if (config.concurrent) this.concurrent = config.concurrent;
}
- enqueue(i, p) {
+ // enqueue(i, p, t, ...args) {
+ // return p.bind(t)(...args);
+ // }
+
+ enqueue(i, p, t, ...argv) {
+ this.size++;
return new Promise((res, rej) => {
- q[i].push([p, res, rej]);
+ this.queues[i-1].push(
+ [
+ p.bind(t, ...argv),
+ res,
+ rej
+ ]
+ );
this.run();
});
};
dequeue() {
for (let i = 0; i < this.least; ++i) {
- if (q[i][0] !== undefined) {
- return q[i].shift;
+ if (this.queues[i][0] !== undefined) {
+ this.size--;
+ return this.queues[i].shift();
}
}
return null;
@@ -35,7 +50,7 @@ class PromisePriorityQueue {
async run() {
if (this.running < this.concurrent) {
let x;
- while (this.dequeue()) {
+ while (x = this.dequeue()) {
await x[0]().then(x[1], x[2]);
}
}