Repository navigation
Expand file tree
/
Copy pathcache.ts
More file actions
147 lines (133 loc) · 4.36 KB
/
Copy pathcache.ts
File metadata and controls
147 lines (133 loc) · 4.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import * as fs from "fs";
import * as path from "path";
import { getTemporaryDirectory } from "./actions-util";
import * as json from "./json";
/** The name of the temporary file backing the cache (tier 2). */
const COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json";
/**
* The keys under which the output of cached `codeql` commands is stored. Each
* key is shared by the producer (the corresponding method in `codeql.ts`) and
* any consumers (e.g. `status-report.ts`, which peeks the cached version
* without invoking the CLI).
*/
export enum CommandCacheKey {
Version = "version",
ResolveLanguages = "resolveLanguages",
}
/** A single cached command output together with the CLI path it came from. */
interface CacheEntry {
/**
* The path to the CodeQL CLI that produced `output`. Persisted so that a
* different step using a different CodeQL bundle doesn't pick up a stale
* value.
*/
cmd: string;
output: unknown;
}
/**
* Tier 1: the in-process memo. Consulted first on every lookup and populated
* whenever a value is read from the file (tier 2) or computed via the CLI
* (tier 3).
*/
const inMemoryCache = new Map<string, CacheEntry>();
function getCommandCacheFilePath(): string {
return path.join(getTemporaryDirectory(), COMMAND_CACHE_FILENAME);
}
/**
* Reads and parses the temporary cache file. Best-effort: a missing, malformed,
* or otherwise unreadable file is treated as an empty cache.
*/
function readCommandCacheFile(): Record<string, CacheEntry> {
let contents: string;
try {
contents = fs.readFileSync(getCommandCacheFilePath(), "utf8");
} catch {
return {};
}
try {
const parsed = json.parseString(contents);
if (json.isObject(parsed)) {
return parsed;
}
} catch {
// Fall through and treat a malformed file as empty.
}
return {};
}
/**
* Persists the cache to the temporary file. Best-effort: a failure to write
* just means a later step re-runs the CLI.
*/
function writeCommandCacheFile(data: Record<string, CacheEntry>): void {
try {
fs.writeFileSync(getCommandCacheFilePath(), JSON.stringify(data));
} catch {
// Best-effort; ignore write failures.
}
}
/**
* Stores the output of a command under `key`, writing it to both the in-memory
* memo (tier 1) and the temporary file (tier 2).
*
* Should only be called once per key within a single process; doing otherwise
* indicates a logic error, since a value that has already been cached should be
* served from the memo rather than recomputed.
*/
export function cacheCommandOutput(
key: string,
cmd: string,
output: unknown,
): void {
if (inMemoryCache.has(key)) {
throw new Error(
`cacheCommandOutput() should be called only once per key, but was called more than once for '${key}'.`,
);
}
const entry: CacheEntry = { cmd, output };
inMemoryCache.set(key, entry);
const data = readCommandCacheFile();
data[key] = entry;
writeCommandCacheFile(data);
}
/**
* Returns the cached output for `key`, or `undefined` if it isn't cached.
*
* Resolves tier 1 (in-memory memo) first, then tier 2 (temporary file). A value
* loaded from the file is ignored unless its `cmd` matches the optional `cmd`
* argument, and it satisfies the optional `validate` type guard; valid values
* are memoized into tier 1 before being returned.
*
* A return value of `undefined` signals the caller to fall back to tier 3 (the
* CLI).
*/
export function getCachedCommandOutput<T>(
key: string,
cmd?: string,
validate?: (output: unknown) => output is T,
): T | undefined {
// Tier 1: the in-memory variable.
const memoized = inMemoryCache.get(key);
if (memoized !== undefined) {
return memoized.output as T;
}
// Tier 2: the temporary file persisted by an earlier step, if any.
const entry = readCommandCacheFile()[key] as unknown;
if (
!json.isObject<CacheEntry>(entry) ||
!json.isString(entry.cmd) ||
(cmd !== undefined && entry.cmd !== cmd) ||
(validate !== undefined && !validate(entry.output))
) {
return undefined;
}
// Memoize so subsequent lookups in this process hit tier 1.
inMemoryCache.set(key, { cmd: entry.cmd, output: entry.output });
return entry.output as T;
}
/**
* Clears the in-process memo (tier 1). Only for use in tests, which exercise
* multiple "steps" within a single process.
*/
export function resetCachedCommandOutputs(): void {
inMemoryCache.clear();
}