Skip to content

Commit

Permalink
[kbn/optimizer] implement more efficient auto transpilation for node (#…
Browse files Browse the repository at this point in the history
…79052)

Co-authored-by: spalger <spalger@users.noreply.github.com>
  • Loading branch information
Spencer and spalger committed Oct 3, 2020
1 parent 92a629f commit ddf2d82
Show file tree
Hide file tree
Showing 33 changed files with 563 additions and 191 deletions.
24 changes: 24 additions & 0 deletions NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,30 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

---
MIT License

Copyright (c) 2014-present Sebastian McKenzie and other contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

---
This product bundles bootstrap@3.3.6 which is available under a
"MIT" license.
Expand Down
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@
"chokidar": "^3.4.2",
"color": "1.0.3",
"commander": "^3.0.2",
"core-js": "^3.6.4",
"cypress-promise": "^1.1.0",
"deep-freeze-strict": "^1.1.1",
"del": "^5.1.0",
Expand All @@ -178,7 +177,7 @@
"inert": "^5.1.0",
"inline-style": "^2.0.0",
"joi": "^13.5.2",
"js-yaml": "3.13.1",
"js-yaml": "^3.14.0",
"json-stable-stringify": "^1.0.1",
"json-stringify-safe": "5.0.1",
"lodash": "^4.17.20",
Expand Down Expand Up @@ -225,7 +224,7 @@
"yauzl": "^2.10.0"
},
"devDependencies": {
"@babel/core": "^7.11.1",
"@babel/core": "^7.11.6",
"@babel/parser": "^7.11.2",
"@babel/register": "^7.10.5",
"@babel/types": "^7.11.0",
Expand Down Expand Up @@ -262,7 +261,7 @@
"@types/angular": "^1.6.56",
"@types/angular-mocks": "^1.7.0",
"@types/archiver": "^3.1.0",
"@types/babel__core": "^7.1.2",
"@types/babel__core": "^7.1.10",
"@types/bluebird": "^3.1.1",
"@types/boom": "^7.2.0",
"@types/chance": "^1.0.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-apm-config-loader/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"dependencies": {
"@elastic/safer-lodash-set": "0.0.0",
"@kbn/utils": "1.0.0",
"js-yaml": "3.13.1",
"js-yaml": "^3.14.0",
"lodash": "^4.17.20"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"@kbn/logging": "1.0.0",
"@kbn/std": "1.0.0",
"@kbn/utility-types": "1.0.0",
"js-yaml": "3.13.1",
"js-yaml": "^3.14.0",
"load-json-file": "^6.2.0",
"lodash": "^4.17.20",
"moment": "^2.24.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-dev-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"kbn:watch": "yarn build --watch"
},
"dependencies": {
"@babel/core": "^7.11.1",
"@babel/core": "^7.11.6",
"@kbn/utils": "1.0.0",
"axios": "^0.19.2",
"chalk": "^4.1.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-dev-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* under the License.
*/

export { REPO_ROOT } from '@kbn/utils';
export * from '@kbn/utils';
export { withProcRunner, ProcRunner } from './proc_runner';
export * from './tooling_log';
export * from './serializers';
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-i18n/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
},
"devDependencies": {
"@babel/cli": "^7.10.5",
"@babel/core": "^7.11.1",
"@babel/core": "^7.11.6",
"@kbn/babel-preset": "1.0.0",
"@kbn/dev-utils": "1.0.0",
"@types/intl-relativeformat": "^2.1.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-interpreter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
},
"devDependencies": {
"@babel/cli": "^7.10.5",
"@babel/core": "^7.11.1",
"@babel/core": "^7.11.6",
"@babel/plugin-transform-modules-commonjs": "^7.10.4",
"@babel/plugin-transform-runtime": "^7.11.0",
"@kbn/babel-preset": "1.0.0",
Expand Down
8 changes: 8 additions & 0 deletions packages/kbn-optimizer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
},
"dependencies": {
"@babel/cli": "^7.10.5",
"@babel/core": "^7.11.6",
"@kbn/babel-preset": "1.0.0",
"@kbn/dev-utils": "1.0.0",
"@kbn/ui-shared-deps": "1.0.0",
Expand All @@ -19,21 +20,26 @@
"clean-webpack-plugin": "^3.0.0",
"compression-webpack-plugin": "^4.0.0",
"cpy": "^8.0.0",
"core-js": "^3.6.5",
"css-loader": "^3.4.2",
"del": "^5.1.0",
"execa": "^4.0.2",
"file-loader": "^4.2.0",
"istanbul-instrumenter-loader": "^3.0.1",
"jest-diff": "^26.4.2",
"js-yaml": "^3.14.0",
"json-stable-stringify": "^1.0.1",
"lmdb-store": "^0.6.10",
"loader-utils": "^1.2.3",
"node-sass": "^4.13.1",
"normalize-path": "^3.0.0",
"pirates": "^4.0.1",
"postcss": "^7.0.32",
"postcss-loader": "^3.0.0",
"raw-loader": "^3.1.0",
"rxjs": "^6.5.5",
"sass-loader": "^8.0.2",
"source-map-support": "^0.5.19",
"style-loader": "^1.1.3",
"terser-webpack-plugin": "^2.1.2",
"tinymath": "1.2.1",
Expand All @@ -44,8 +50,10 @@
"webpack-merge": "^4.2.2"
},
"devDependencies": {
"@types/babel__core": "^7.1.10",
"@types/compression-webpack-plugin": "^2.0.2",
"@types/loader-utils": "^1.1.3",
"@types/source-map-support": "^0.5.3",
"@types/watchpack": "^1.1.5",
"@types/webpack": "^4.41.3"
}
Expand Down
1 change: 1 addition & 0 deletions packages/kbn-optimizer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ export { OptimizerConfig } from './optimizer';
export * from './run_optimizer';
export * from './log_optimizer_state';
export * from './report_optimizer_stats';
export * from './node';
171 changes: 171 additions & 0 deletions packages/kbn-optimizer/src/node/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import Path from 'path';

// @ts-expect-error no types available
import * as LmdbStore from 'lmdb-store';
import { REPO_ROOT, UPSTREAM_BRANCH } from '@kbn/dev-utils';

const CACHE_DIR = Path.resolve(REPO_ROOT, 'data/node_auto_transpilation_cache', UPSTREAM_BRANCH);
const reportError = () => {
// right now I'm not sure we need to worry about errors, the cache isn't actually
// necessary, and if the cache is broken it should just rebuild on the next restart
// of the process. We don't know how often errors occur though and what types of
// things might fail on different machines so we probably want some way to signal
// to users that something is wrong
};

const GLOBAL_ATIME = `${Date.now()}`;
const MINUTE = 1000 * 60;
const HOUR = MINUTE * 60;
const DAY = HOUR * 24;

interface Lmdb<T> {
get(key: string): T | undefined;
put(key: string, value: T, version?: number, ifVersion?: number): Promise<boolean>;
remove(key: string, ifVersion?: number): Promise<boolean>;
openDB<T>(options: { name: string; encoding: 'msgpack' | 'string' | 'json' | 'binary' }): Lmdb<T>;
getRange(options?: {
start?: T;
end?: T;
reverse?: boolean;
limit?: number;
versions?: boolean;
}): Iterable<{ key: string; value: T }>;
}

export class Cache {
private readonly codes: Lmdb<string>;
private readonly atimes: Lmdb<string>;
private readonly mtimes: Lmdb<string>;
private readonly sourceMaps: Lmdb<any>;
private readonly prefix: string;

constructor(config: { prefix: string }) {
this.prefix = config.prefix;

this.codes = LmdbStore.open({
name: 'codes',
path: CACHE_DIR,
});

this.atimes = this.codes.openDB({
name: 'atimes',
encoding: 'string',
});

this.mtimes = this.codes.openDB({
name: 'mtimes',
encoding: 'string',
});

this.sourceMaps = this.codes.openDB({
name: 'sourceMaps',
encoding: 'msgpack',
});

// after the process has been running for 30 minutes prune the
// keys which haven't been used in 30 days. We use `unref()` to
// make sure this timer doesn't hold other processes open
// unexpectedly
setTimeout(() => {
this.pruneOldKeys();
}, 30 * MINUTE).unref();
}

getMtime(path: string) {
return this.mtimes.get(this.getKey(path));
}

getCode(path: string) {
const key = this.getKey(path);

// when we use a file from the cache set the "atime" of that cache entry
// so that we know which cache items we use and which haven't been
// touched in a long time (currently 30 days)
this.atimes.put(key, GLOBAL_ATIME).catch(reportError);

return this.codes.get(key);
}

getSourceMap(path: string) {
return this.sourceMaps.get(this.getKey(path));
}

update(path: string, file: { mtime: string; code: string; map: any }) {
const key = this.getKey(path);

Promise.all([
this.atimes.put(key, GLOBAL_ATIME),
this.mtimes.put(key, file.mtime),
this.codes.put(key, file.code),
this.sourceMaps.put(key, file.map),
]).catch(reportError);
}

private getKey(path: string) {
return `${this.prefix}${path}`;
}

private async pruneOldKeys() {
try {
const ATIME_LIMIT = Date.now() - 30 * DAY;
const BATCH_SIZE = 1000;

const validKeys: string[] = [];
const invalidKeys: string[] = [];

for (const { key, value } of this.atimes.getRange()) {
const atime = parseInt(value, 10);
if (atime < ATIME_LIMIT) {
invalidKeys.push(key);
} else {
validKeys.push(key);
}

if (validKeys.length + invalidKeys.length >= BATCH_SIZE) {
const promises = new Set();

if (invalidKeys.length) {
for (const k of invalidKeys) {
// all these promises are the same currently, so Set() will
// optimise this to a single promise, but I wouldn't be shocked
// if a future version starts returning independent promises so
// this is just for some future-proofing
promises.add(this.atimes.remove(k));
promises.add(this.mtimes.remove(k));
promises.add(this.codes.remove(k));
promises.add(this.sourceMaps.remove(k));
}
} else {
// delay a smidge to allow other things to happen before the next batch of checks
promises.add(new Promise((resolve) => setTimeout(resolve, 1)));
}

invalidKeys.length = 0;
validKeys.length = 0;
await Promise.all(Array.from(promises));
}
}
} catch {
// ignore errors, the cache is totally disposable and will rebuild if there is some sort of corruption
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,4 @@
* under the License.
*/

// register and polyfill need to happen in this
// order and in separate files. Checkout each file
// for a much more detailed explanation
require('./register');
require('./polyfill');
export * from './node_auto_tranpilation';
Loading

0 comments on commit ddf2d82

Please sign in to comment.