Skip to content

Commit

Permalink
perf - use explicit isCircular code to avoid slow JSON.stringify sett…
Browse files Browse the repository at this point in the history
…ings
  • Loading branch information
cscheid committed Jan 13, 2025
1 parent 48d9ee9 commit 767f128
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 17 deletions.
27 changes: 27 additions & 0 deletions src/core/lib/is-circular.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* is-circular.ts
*
* Copyright (C) 2025 Posit Software, PBC
*/

// deno-lint-ignore no-explicit-any
export const isCircular = (obj: any): unknown => {
const objectSet = new WeakSet();
// deno-lint-ignore no-explicit-any
const detect = (obj: any): boolean => {
if (obj && typeof obj === "object") {
if (objectSet.has(obj)) {
return true;
}
objectSet.add(obj);
for (const key in obj) {
if (Object.hasOwn(obj, key) && detect(obj[key])) {
return true;
}
}
objectSet.delete(obj);
}
return false;
};
return detect(obj);
};
22 changes: 5 additions & 17 deletions src/core/lib/yaml-intelligence/annotated-yaml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { QuartoJSONSchema } from "./js-yaml-schema.ts";
import { createSourceContext } from "../yaml-validation/errors.ts";
import { tidyverseInfo } from "../errors.ts";
import { InternalError } from "../error.ts";
import { isCircular } from "../is-circular.ts";

// deno-lint-ignore no-explicit-any
type TreeSitterParse = any;
Expand Down Expand Up @@ -268,23 +269,10 @@ export function buildJsYamlAnnotation(mappedYaml: MappedString) {
);
}

// console.log(results[0]);
try {
JSON.stringify(results[0]); // this is here so that we throw on circular structures
} catch (e) {
if (e.message.match("invalid string length")) {
// https://github.com/quarto-dev/quarto-cli/issues/10504
// It seems to be relatively easy to hit string length limits in
// JSON.stringify. Since this call is only here to check for circular
// structures, we chose to ignore this error, even though it's not
// ideal
} else if (e.message.match(/circular structure/)) {
throw new InternalError(
`Circular structure detected in parsed yaml: ${e.message}`,
);
} else {

}
if (isCircular(results[0])) {
throw new InternalError(
`Circular structure detected in yaml`,
);
}
return postProcessAnnotation(results[0]);
}
Expand Down

0 comments on commit 767f128

Please sign in to comment.