Skip to content

Commit

Permalink
Remove caching
Browse files Browse the repository at this point in the history
Caching was introduced as a premature optimization: we probably don't
need it, and it complicates many things (see #511, #200, #533, #303 and
 #302).

I'll publish a release with this change and see what things look like
over the coming days.

Closes #200.
Closes #303.
Closes #511.
Closes #533.
  • Loading branch information
fsouza committed Jul 8, 2023
1 parent 2edc7b6 commit e150d70
Show file tree
Hide file tree
Showing 6 changed files with 12 additions and 133 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
},
"dependencies": {
"core_d": "^5.0.1",
"nanolru": "^1.0.0",
"prettier": "^2.8.8"
},
"files": [
Expand Down
6 changes: 1 addition & 5 deletions src/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,7 @@ const commands: Command[] = [
{
command: "--debug-info <path>",
description:
"Print debugging information (current cache status and automatically discovered version of prettier for the provided file path, for example `prettierd --debug-info src/my-file.js`).",
},
{
command: "flush-cache\t",
description: "Flush the cache.",
"Print debugging information (information about the version of prettier being used for the provided path, for example `prettierd --debug-info src/my-file.js`).",
},
{
command: "start\t\t",
Expand Down
16 changes: 2 additions & 14 deletions src/prettierd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { promisify } from "node:util";
// @ts-ignore
import { version } from "../package.json";
import { displayHelp } from "./args";
import { DebugInfo, flushCache, getDebugInfo, stopAll } from "./service";
import { DebugInfo, getDebugInfo, stopAll } from "./service";

const readFile = promisify(fs.readFile);
const coredCommands = ["restart", "start", "status"];
Expand All @@ -17,14 +17,12 @@ type Action =
| "INVOKE_CORE_D"
| "PRINT_HELP"
| "PRINT_DEBUG_INFO"
| "FLUSH_CACHE"
| "STOP";

function processArgs(args: string[]): [Action, string] {
const flagsToAction: { [flag: string]: Action | undefined } = {
"--version": "PRINT_VERSION",
"--help": "PRINT_HELP",
"flush-cache": "FLUSH_CACHE",
"--debug-info": "PRINT_DEBUG_INFO",
stop: "STOP",
};
Expand All @@ -43,15 +41,9 @@ function printDebugInfo(debugInfo: DebugInfo): void {
if (debugInfo.resolvedPrettier) {
console.log(
`prettier version: ${debugInfo.resolvedPrettier.module.version}
Loaded from: ${debugInfo.resolvedPrettier.filePath}
Cache: ${debugInfo.resolvedPrettier.cacheHit ? "hit" : "miss"}\n`
Loaded from: ${debugInfo.resolvedPrettier.filePath}\n`
);
}

console.log("Cache information:");
debugInfo.cacheInfo.forEach((cacheInfo) => {
console.log(`- "${cacheInfo.name}" contains ${cacheInfo.length} items`);
});
}

function getRuntimeDir(): string {
Expand Down Expand Up @@ -89,10 +81,6 @@ async function main(args: string[]): Promise<void> {
const debugInfo = await getDebugInfo(process.cwd(), args.slice(1));
printDebugInfo(debugInfo);
return;
case "FLUSH_CACHE":
flushCache();
console.log("success");
return;
}

const title = "prettierd";
Expand Down
100 changes: 9 additions & 91 deletions src/service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import LRU from "nanolru";
import path from "node:path";
import type Prettier from "prettier";
import { promisify } from "node:util";
Expand All @@ -11,14 +10,6 @@ type CliOptions = {
editorconfig?: boolean;
};

const cacheParams = { max: 500, maxAge: 60000 };

const caches: { [name: string]: LRU } = {
configCache: new LRU(cacheParams),
importCache: new LRU(cacheParams),
parentCache: new LRU(cacheParams),
};

async function isDir(path: string): Promise<boolean> {
try {
const fsStat = await stat(path);
Expand Down Expand Up @@ -60,27 +51,14 @@ async function findParent(
start: string,
search: string
): Promise<string | undefined> {
const cacheKey = `${start}|${search}`;
const cachedValue = caches.parentCache.get<string, string | false>(cacheKey);

if (cachedValue === false) {
return undefined;
}

if (cachedValue !== null) {
return cachedValue;
}

const parent = path.join(start, "..");
if (parent === start) {
caches.parentCache.set(cacheKey, false);
return undefined;
}

try {
const candidate = path.join(parent, search);
if (await isDir(candidate)) {
caches.parentCache.set(cacheKey, candidate);
return candidate;
}
} catch (e) {}
Expand Down Expand Up @@ -123,100 +101,58 @@ async function tryToResolveConfigFromEnvironmentValue(
return null;
}

async function resolveConfigNoCache(
async function resolveConfig(
env: EnvMap,
prettier: typeof Prettier,
filepath: string,
{ editorconfig = true }: Pick<CliOptions, "config" | "editorconfig">
options: Pick<CliOptions, "config" | "editorconfig">
): Promise<Prettier.Options | null> {
if (options.config === false) {
return null;
}

let config = await prettier.resolveConfig(filepath, {
editorconfig,
editorconfig: options.editorconfig,
useCache: false,
});

if (!config) {
config = await tryToResolveConfigFromEnvironmentValue(
prettier,
editorconfig,
options.editorconfig ?? false,
env.PRETTIERD_DEFAULT_CONFIG
);
}

return config;
}

async function resolveConfig(
env: EnvMap,
prettier: typeof Prettier,
filepath: string,
options: Pick<CliOptions, "config" | "editorconfig">
): Promise<Prettier.Options | null> {
if (options.config === false) {
return null;
}

const cachedValue = caches.configCache.get<string, Prettier.Options | null>(
filepath
);
if (cachedValue || cachedValue === null) {
return cachedValue;
}

const config = await resolveConfigNoCache(env, prettier, filepath, options);
caches.configCache.set(filepath, config);
return config;
}

export type ResolvedPrettier = {
module: typeof Prettier;
filePath: string;
cacheHit: boolean;
};

async function resolvePrettier(
env: EnvMap,
filePath: string
): Promise<ResolvedPrettier | undefined> {
const cacheKey = `${filePath}#${env.PRETTIERD_LOCAL_PRETTIER_ONLY}`;
const cachedValue = caches.importCache.get<
string,
[typeof Prettier, string] | false
>(cacheKey);

if (cachedValue) {
const [module, filePath] = cachedValue;
return {
module,
filePath,
cacheHit: true,
};
}

if (cachedValue === false) {
return undefined;
}

let path: string;
try {
path = require.resolve("prettier", { paths: [filePath] });
} catch (e) {
if (env.PRETTIERD_LOCAL_PRETTIER_ONLY) {
caches.importCache.set(cacheKey, false);
return undefined;
}
path = require.resolve("prettier");
}

return import(path).then((v) => {
if (v !== undefined) {
caches.importCache.set(cacheKey, [v, path]);
return {
module: v,
filePath: path,
cacheHit: false,
};
}
caches.importCache.set(cacheKey, false);
return undefined;
});
}
Expand Down Expand Up @@ -328,15 +264,8 @@ async function run(
});
}

export type CacheInfo = {
name: string;
length: number;
keys: string[];
};

export type DebugInfo = {
resolvedPrettier?: ResolvedPrettier;
cacheInfo: CacheInfo[];
};

export async function getDebugInfo(
Expand All @@ -347,19 +276,8 @@ export async function getDebugInfo(
const fullPath = resolveFile(cwd, fileName);

const resolvedPrettier = await resolvePrettier(process.env, fullPath);
const cacheInfo = Object.keys(caches).map((cacheName) => ({
name: cacheName,
length: caches[cacheName].length,
keys: caches[cacheName].keys,
}));

return { resolvedPrettier, cacheInfo };
}

export function flushCache(): void {
for (const cacheName in caches) {
caches[cacheName].clear();
}
return { resolvedPrettier };
}

export async function stopAll(
Expand Down
17 changes: 0 additions & 17 deletions src/types/nanolru.d.ts

This file was deleted.

5 changes: 0 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,6 @@ [email protected]:
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==

nanolru@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/nanolru/-/nanolru-1.0.0.tgz#0a5679cd4e4578c4ca3741e610b71c4c9b5afaf8"
integrity sha512-GyQkE8M32pULhQk7Sko5raoIbPalAk90ICG+An4fq6fCsFHsP6fB2K46WGXVdoJpy4SGMnZ/EKbo123fZJomWg==

path-type@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b"
Expand Down

0 comments on commit e150d70

Please sign in to comment.