Skip to content
This repository has been archived by the owner on Apr 25, 2023. It is now read-only.

perf: add cache support to evaluation in reearth/core #573

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@
"leaflet": "1.9.3",
"localforage": "1.10.0",
"lodash-es": "4.17.21",
"lru-cache": "^8.0.4",
"mini-svg-data-uri": "1.4.4",
"parse-domain": "7.0.1",
"quickjs-emscripten": "0.21.1",
Expand Down
45 changes: 42 additions & 3 deletions src/core/mantle/evaluator/simple/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { pick } from "lodash-es";
import LRUCache from "lru-cache";

import type { EvalContext, EvalResult } from "..";
import {
Expand All @@ -15,6 +16,9 @@ import {
import { ConditionalExpression } from "./conditionalExpression";
import { clearExpressionCaches, Expression } from "./expression";
import { evalTimeInterval } from "./interval";
import { getCacheableProperties } from "./utils";

const EVAL_EXPRESSION_CACHES = new LRUCache({ max: 10000 });

export async function evalSimpleLayer(
layer: LayerSimple,
Expand All @@ -23,6 +27,11 @@ export async function evalSimpleLayer(
const features = layer.data ? await ctx.getAllFeatures(layer.data) : undefined;
const appearances: Partial<LayerAppearanceTypes> = pick(layer, appearanceKeys);
const timeIntervals = evalTimeInterval(features, layer.data?.time);

if (!features) {
return undefined;
}

return {
layer: evalLayerAppearances(appearances, layer),
features: features?.map((f, i) => evalSimpleLayerFeature(layer, f, timeIntervals?.[i])),
Expand Down Expand Up @@ -111,11 +120,41 @@ function evalExpression(
if (typeof styleExpression === "undefined") {
return undefined;
} else if (typeof styleExpression === "object" && styleExpression.conditions) {
return new ConditionalExpression(styleExpression, feature, layer.defines).evaluate();
const cacheKey = JSON.stringify([
styleExpression,
getCacheableProperties(styleExpression, feature?.properties),
Copy link
Member

@keiya01 keiya01 Mar 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't have to instantiate Expression no more, but we become to need to parse expression every time...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hopefully this will be less heavy with the cache for getReferences in place.

layer.defines,
]);

if (EVAL_EXPRESSION_CACHES.has(cacheKey)) {
return EVAL_EXPRESSION_CACHES.get(cacheKey);
}

const result = new ConditionalExpression(
styleExpression,
feature,
layer.defines,
).evaluate();
EVAL_EXPRESSION_CACHES.set(cacheKey, result);

return result;
} else if (typeof styleExpression === "boolean" || typeof styleExpression === "number") {
return new Expression(String(styleExpression), feature, layer.defines).evaluate();
return styleExpression;
} else if (typeof styleExpression === "string") {
return new Expression(styleExpression, feature, layer.defines).evaluate();
const cacheKey = JSON.stringify([
styleExpression,
getCacheableProperties(styleExpression, feature?.properties),
layer.defines,
]);

if (EVAL_EXPRESSION_CACHES.has(cacheKey)) {
return EVAL_EXPRESSION_CACHES.get(cacheKey);
}

const result = new Expression(styleExpression, feature, layer.defines).evaluate();
EVAL_EXPRESSION_CACHES.set(cacheKey, result);

return result;
}
return styleExpression;
}
Expand Down
97 changes: 97 additions & 0 deletions src/core/mantle/evaluator/simple/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { expect, test, describe } from "vitest";

import { ConditionsExpression } from "../../types";

import { getReferences, getCacheableProperties, getCombinedReferences } from "./utils";

describe("getCacheableProperties", () => {
const feature = { foo: "bar", baz: "qux" };
const styleExpression: ConditionsExpression = {
conditions: [
["${foo}", "${baz}"],
["${qux}", "121"],
],
};

test("should return properties that exist in feature and are referenced in styleExpression", () => {
const result = getCacheableProperties(styleExpression, feature);
expect(result).toEqual({ foo: "bar", baz: "qux" });
});

test("should return an empty object if no properties are referenced in styleExpression", () => {
const styleExpression = "some string";
const result = getCacheableProperties(styleExpression, feature);
expect(result).toEqual({});
});
});

describe("getCombinedReferences", () => {
const feature = { foo: "bar", baz: "qux" };

test("should return references in a single expression", () => {
const expression = "${foo}";
const result = getCombinedReferences(expression, feature);
expect(result).toEqual(["foo"]);
});

test("should return references in a style expression with multiple conditions", () => {
const expression: ConditionsExpression = {
conditions: [
["${foo}", "${baz}"],
["${qux}", "121"],
],
};
const result = getCombinedReferences(expression, feature);
expect(result).toEqual(["foo", "baz", "qux"]);
});

test("should return an empty array if expression is a string with no references", () => {
const expression = "some string";
const result = getCombinedReferences(expression, feature);
expect(result).toEqual([]);
});
});

describe("getReferences", () => {
const feature = {
foo: "bar",
baz: "qux",
obj: {
arr: [1, 2, 3],
nestedObj: {
a: "A",
b: "B",
},
},
};

test("should return references in a single expression", () => {
const expression = "${foo}";
const result = getReferences(expression, feature);
expect(result).toEqual(["foo"]);
});

test("should return references in an expression with JSONPath expressions", () => {
const expression = "${$.baz}";
const result = getReferences(expression, feature);
expect(result).toEqual(['["baz"]']);
});

test("should return references for nested JSONPath expressions", () => {
const expression = "${$.obj.nestedObj.a}";
const result = getReferences(expression, feature);
expect(result).toEqual(['["obj"]["nestedObj"]["a"]']);
});

test("should handle JSONPath expressions that return arrays", () => {
const expression = "${$.obj.arr[1]}";
const result = getReferences(expression, feature);
expect(result).toEqual(['["obj"]["arr"]["1"]']);
});

test("should return an empty array if expression has no references", () => {
const expression = "some string";
const result = getReferences(expression, feature);
expect(result).toEqual([]);
});
});
92 changes: 92 additions & 0 deletions src/core/mantle/evaluator/simple/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { JSONPath } from "jsonpath-plus";
import { pick } from "lodash-es";

import { StyleExpression } from "../../types";

export function getCacheableProperties(styleExpression: StyleExpression, feature?: any) {
const properties = pick(feature, getCombinedReferences(styleExpression, feature));
return properties;
}

export function getCombinedReferences(expression: StyleExpression, feature?: any): string[] {
if (typeof expression === "string") {
return getReferences(expression, feature);
} else {
const references: string[] = [];
for (const [condition, value] of expression.conditions) {
references.push(...getReferences(condition, feature), ...getReferences(value, feature));
}
return references;
}
}

export function getReferences(expression: string, feature?: any): string[] {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have two function to parse expression. First is this function. Second is replaceVariables.
But these are very heavy task, so it will make app slower...
I think it's better to share the result of parsing with Expression class, and if we remove replaceVariables then performance will be more improved.

Copy link
Contributor Author

@pyshx pyshx Mar 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it'll be hard to separate out alot the repetitive logic and avoid iterating over the string again in replaceVariables now that i've removed JP related evaluations.

const result: string[] = [];
let exp = expression;
let i = exp.indexOf("${");
const varExpRegex = /^\$./;
const jsonPathCache: Record<string, any[]> = {};

while (i >= 0) {
const openSingleQuote = exp.indexOf("'", i);
const openDoubleQuote = exp.indexOf('"', i);

if (openSingleQuote >= 0 && openSingleQuote < i) {
const closeQuote = exp.indexOf("'", openSingleQuote + 1);
result.push(exp.substring(0, closeQuote + 1));
exp = exp.substring(closeQuote + 1);
} else if (openDoubleQuote >= 0 && openDoubleQuote < i) {
const closeQuote = exp.indexOf('"', openDoubleQuote + 1);
result.push(exp.substring(0, closeQuote + 1));
exp = exp.substring(closeQuote + 1);
} else {
const j = exp.indexOf("}", i);

if (j < 0) {
console.log("Unmatched {.");
}
pyshx marked this conversation as resolved.
Show resolved Hide resolved
const varExp = exp.slice(i + 2, j);
if (varExpRegex.test(varExp)) {
let res = jsonPathCache[varExp];
if (!res) {
try {
res = JSONPath({ json: feature, path: varExp });
jsonPathCache[varExp] = res;
} catch (error) {
console.log("Invalid JSONPath");
pyshx marked this conversation as resolved.
Show resolved Hide resolved
}
}
if (res.length !== 0) {
console.log("JSONPathEval: ", res[0]);
pyshx marked this conversation as resolved.
Show resolved Hide resolved
const keyPath = getObjectPathByValue(feature, res[0]);
pyshx marked this conversation as resolved.
Show resolved Hide resolved
if (keyPath) result.push(keyPath);
else return Object.keys(feature);
}
} else {
result.push(exp.substring(i + 2, j));
}
exp = exp.substring(j + 1);
}

i = exp.indexOf("${");
}

return result;
}

function getObjectPathByValue(obj: any, value: any): string | undefined {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
pyshx marked this conversation as resolved.
Show resolved Hide resolved
const prop = obj[key];
if (prop === value) {
return `[${JSON.stringify(key)}]`;
} else if (typeof prop === "object") {
const nestedKey = getObjectPathByValue(prop, value);
if (nestedKey !== undefined) {
return `[${JSON.stringify(key)}]${nestedKey}`;
}
}
}
}
return undefined;
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -12945,6 +12945,11 @@ lru-cache@^6.0.0:
dependencies:
yallist "^4.0.0"

lru-cache@^8.0.4:
version "8.0.4"
resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-8.0.4.tgz#49fbbc46c0b4cedc36258885247f93dba341e7ec"
integrity sha512-E9FF6+Oc/uFLqZCuZwRKUzgFt5Raih6LfxknOSAVTjNkrCZkBf7DQCwJxZQgd9l4eHjIJDGR+E+1QKD1RhThPw==

lz-string@^1.4.4:
version "1.4.4"
resolved "https://registry.yarnpkg.com/lz-string/-/lz-string-1.4.4.tgz#c0d8eaf36059f705796e1e344811cf4c498d3a26"
Expand Down