@stateward/core 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/engine.js CHANGED
@@ -100,13 +100,37 @@ export const LOOSE_NULLS_FIX = `\`strictNullChecks\` is off in this project, so
100
100
  export function missingTypesReason(library) {
101
101
  return `${library}'s types are not installed (install the app's dependencies)`;
102
102
  }
103
+ function unitNotes(unit, rules, facts) {
104
+ const missing = [];
105
+ if (unit.files.length > 0) {
106
+ for (const entry of rules) {
107
+ const needs = entry.rule.meta.needsTypes;
108
+ if (needs === undefined || needs.modules.some((module) => unit.typesResolve(module)))
109
+ continue;
110
+ // A project that uses none of the library's modules has nothing for the rule to check:
111
+ // installing the types would not change that, so there is nothing to say.
112
+ if (!needs.modules.some((module) => unit.importsModule(module)))
113
+ continue;
114
+ missing.push({ library: needs.library, id: entry.id });
115
+ }
116
+ }
117
+ return {
118
+ tsconfig: unit.tsconfig,
119
+ files: unit.files,
120
+ strictNullChecks: unit.strictNullChecks,
121
+ unreadTestConfigs: unit.unreadTestConfigs,
122
+ missing,
123
+ // A line one project's types resolve is matched (0041: keys resolve through the type checker).
124
+ factKeys: Object.keys(facts).length === 0 || unit.files.length === 0 ? undefined : unit.factKeys(facts),
125
+ };
126
+ }
103
127
  /**
104
- * What the run cannot check as a whole (`CheckResult.notes`): the rules among `rules` whose
105
- * library's types do not resolve in some project with files that import it, and the projects without
106
- * `strictNullChecks`, and the test-runner configs whose test files could not be read. Undefined
107
- * when there is nothing to say.
128
+ * What the run cannot check as a whole (`CheckResult.notes`), from each project's `unitNotes`:
129
+ * the rules whose library's types do not resolve in some project with files that import it, the
130
+ * projects without `strictNullChecks`, and the test-runner configs whose test files could not be
131
+ * read. Undefined when there is nothing to say.
108
132
  */
109
- function notesOf(units, rules, facts, gate) {
133
+ function notesOf(units, facts, gate) {
110
134
  const missing = new Map();
111
135
  const looseNulls = [];
112
136
  const unreadTestConfigs = new Set();
@@ -117,23 +141,13 @@ function notesOf(units, rules, facts, gate) {
117
141
  looseNulls.push(unit.tsconfig);
118
142
  for (const file of unit.unreadTestConfigs)
119
143
  unreadTestConfigs.add(file);
120
- for (const entry of rules) {
121
- const needs = entry.rule.meta.needsTypes;
122
- if (needs === undefined || needs.modules.some((module) => unit.typesResolve(module)))
123
- continue;
124
- // A project that uses none of the library's modules has nothing for the rule to check:
125
- // installing the types would not change that, so there is nothing to say.
126
- if (!needs.modules.some((module) => unit.importsModule(module)))
127
- continue;
128
- const ids = missing.get(needs.library) ?? new Set();
129
- ids.add(entry.id);
130
- missing.set(needs.library, ids);
144
+ for (const { library, id } of unit.missing) {
145
+ const ids = missing.get(library) ?? new Set();
146
+ ids.add(id);
147
+ missing.set(library, ids);
131
148
  }
132
149
  }
133
- // A line one project's types resolve is matched (0041: keys resolve through the type checker).
134
- const matched = unmatchedFacts(Object.keys(facts).length === 0
135
- ? []
136
- : units.filter((unit) => unit.files.length > 0).map((unit) => unit.factKeys(facts)), facts);
150
+ const matched = unmatchedFacts(units.flatMap((unit) => (unit.factKeys === undefined ? [] : [unit.factKeys])), facts);
137
151
  // The config's facts a project's version leaves out, once each: by the first file of each project.
138
152
  const outOfRange = new Set();
139
153
  for (const unit of units) {
@@ -564,11 +578,12 @@ function fileContext(entry, sourceFile, types, findings, ledger = [], marks = []
564
578
  },
565
579
  };
566
580
  }
567
- function projectContext(entry, findings, marks = [], analyses = {}, unstated = []) {
581
+ function projectContext(entry, findings, marks, read, unstated) {
568
582
  const { id, options } = entry;
569
583
  return {
570
584
  options,
571
- analyses,
585
+ analyses: read.analyses,
586
+ analysisSummaries: read.summaries,
572
587
  unstated({ location, needs, unnamed }) {
573
588
  unstated.push({
574
589
  ruleId: id,
@@ -757,11 +772,20 @@ export function drain(steps) {
757
772
  return next.value;
758
773
  }
759
774
  }
775
+ /** Units built already, kept after the phase (`release` lets nothing go). */
776
+ export function builtSources(units) {
777
+ return units.map((unit) => ({
778
+ tsconfig: unit.tsconfig,
779
+ built: unit,
780
+ open: () => unit,
781
+ release: () => undefined,
782
+ }));
783
+ }
760
784
  /** `runFilePhase`, one file per step. */
761
- export function filePhaseRun(config, cwd, units, selection = { kind: "configured" }, cache, ignores = true, timing) {
785
+ export function filePhaseRun(config, cwd, units, selection = { kind: "configured" }, cache, ignores = true, timing, slicing) {
762
786
  const nextFiles = new Map();
763
787
  return {
764
- steps: filePhaseSteps(config, cwd, units, selection, nextFiles, cache, ignores, timing),
788
+ steps: filePhaseSteps(config, cwd, units, selection, nextFiles, cache, ignores, timing, slicing),
765
789
  abandon: () => {
766
790
  if (cache === undefined || nextFiles.size === 0)
767
791
  return;
@@ -774,8 +798,9 @@ export function filePhaseRun(config, cwd, units, selection = { kind: "configured
774
798
  }
775
799
  function* filePhaseSteps(config, cwd, units, selection,
776
800
  /** This run's cache entries, by file; read by `abandon` when the run stops early. */
777
- nextFiles, cache, ignores, timing) {
778
- const total = units.reduce((sum, unit) => sum + unit.files.length, 0);
801
+ nextFiles, cache, ignores, timing, slicing) {
802
+ // A project built when the phase reaches it adds its files then.
803
+ let total = units.reduce((sum, source) => sum + (source.built?.files.length ?? 0), 0);
779
804
  const sets = ruleSets(config, selection);
780
805
  const rules = sets.anywhere;
781
806
  const testFiles = config.replacesDefaultExclude
@@ -804,15 +829,24 @@ nextFiles, cache, ignores, timing) {
804
829
  }
805
830
  const analysisSummaries = new Map(sets.analyses.map((run) => [run.id, new Map()]));
806
831
  const analysisFailures = new Map();
807
- for (const unit of units) {
832
+ const opened = [];
833
+ for (const source of slicing?.reversed === true ? [...units].reverse() : units) {
834
+ const unit = timing === undefined ? source.open() : timed(timing, "program", () => source.open());
835
+ if (source.built === undefined)
836
+ total += unit.files.length;
808
837
  fileCount += unit.files.length;
809
- for (const file of unit.files) {
838
+ const perChecker = slicing?.filesPerChecker(unit.tsconfig);
839
+ const files = slicing?.reversed === true ? [...unit.files].reverse() : unit.files;
840
+ for (const [at, file] of files.entries()) {
841
+ if (perChecker !== undefined && at > 0 && at % perChecker === 0)
842
+ unit.renewChecker();
810
843
  if (testFiles !== undefined) {
811
844
  const relative = path.relative(cwd, file).split(path.sep).join("/");
812
845
  const hit = testFiles.find((entry) => entry.matches(relative));
813
846
  if (hit !== undefined)
814
847
  testsByPattern.set(hit.pattern, (testsByPattern.get(hit.pattern) ?? 0) + 1);
815
848
  }
849
+ cache?.progress?.started(file);
816
850
  const fingerprint = cache === undefined
817
851
  ? undefined
818
852
  : timing === undefined
@@ -966,18 +1000,26 @@ nextFiles, cache, ignores, timing) {
966
1000
  analysisSummaries.get(run.id)?.set(file, result.summary);
967
1001
  }
968
1002
  if (fingerprint !== undefined) {
969
- nextFiles.set(file, {
1003
+ const next = {
970
1004
  fingerprint,
971
1005
  rules: results,
972
1006
  reads: readsAfter(unit, file, holding, results),
973
- });
1007
+ };
1008
+ nextFiles.set(file, next);
1009
+ cache?.progress?.finished(file, next);
974
1010
  }
975
1011
  done += 1;
976
1012
  yield { phase: "files", done, total };
977
1013
  }
1014
+ if (timing?.secondPass === true)
1015
+ secondPass(unit, sets, timing);
1016
+ // Everything the run needs of this program, asked before it is let go.
1017
+ opened.push(unitNotes(unit, rules, config.facts));
1018
+ timing?.filesDone();
1019
+ source.release();
978
1020
  }
979
- if (timing?.secondPass === true)
980
- secondPass(units, sets, timing);
1021
+ if (slicing?.reversed === true)
1022
+ opened.reverse();
981
1023
  if (cache !== undefined) {
982
1024
  // Only the files of this run: a deleted or excluded file's results go.
983
1025
  if (cache.files.size !== nextFiles.size)
@@ -996,11 +1038,11 @@ nextFiles, cache, ignores, timing) {
996
1038
  fileCount,
997
1039
  testsByPattern: testFiles === undefined ? undefined : testsByPattern,
998
1040
  tsconfigLocation: { file: failureFile(config, cwd, units), start: 0, end: 0 },
999
- projects: units.length > 1
1000
- ? units.map((unit) => ({ tsconfig: unit.tsconfig, files: unit.files.length }))
1041
+ projects: opened.length > 1
1042
+ ? opened.map((unit) => ({ tsconfig: unit.tsconfig, files: unit.files.length }))
1001
1043
  : undefined,
1002
- notes: notesOf(units, rules, config.facts, sets.gate),
1003
- looseNulls: looseNullFiles(units),
1044
+ notes: notesOf(opened, config.facts, sets.gate),
1045
+ looseNulls: looseNullFiles(opened),
1004
1046
  silenced,
1005
1047
  stated,
1006
1048
  ledger: {
@@ -1030,6 +1072,13 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
1030
1072
  const rules = sets.anywhere;
1031
1073
  const total = rules.filter((entry) => entry.rule.kind === "project" && summaries.has(entry.id)).length;
1032
1074
  const analysisOf = solvedAnalyses(sets.analyses, phase.analysisSummaries, phase.analysisFailures, cache, timing);
1075
+ // An analysis's summaries, for the editor contributions and `silentReason` of its publisher.
1076
+ for (const run of sets.analyses) {
1077
+ keepSummaries?.set(run.id, () => {
1078
+ const found = analysisOf(run.id);
1079
+ return found?.kind === "solved" ? found.summaries() : new Map();
1080
+ });
1081
+ }
1033
1082
  let done = 0;
1034
1083
  let previous;
1035
1084
  for (const entry of rules) {
@@ -1079,7 +1128,7 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
1079
1128
  const runCheck = () => {
1080
1129
  const asJson = summaryMap(sorted);
1081
1130
  keepSummaries?.set(entry.id, () => asJson);
1082
- rule.check(asJson, projectContext(entry, own, settled, read.values(), ownUnstated));
1131
+ rule.check(asJson, projectContext(entry, own, settled, { analyses: read.values(), summaries: read.summaries }, ownUnstated));
1083
1132
  return asJson;
1084
1133
  };
1085
1134
  try {
@@ -1141,6 +1190,17 @@ export function* projectPhaseSteps(config, phase, started, keepSummaries, cache,
1141
1190
  },
1142
1191
  };
1143
1192
  }
1193
+ /** A rule asked for the summaries of an analysis it may not read them of. */
1194
+ class AnalysisSummariesError extends Error {
1195
+ constructor(ruleId, id) {
1196
+ super(`${ruleId} asked for the summaries of ${id}: a rule reads the summaries only of an analysis it lists in \`reads\` and its own plugin publishes`);
1197
+ this.name = "AnalysisSummariesError";
1198
+ }
1199
+ }
1200
+ /** Whether `id` (`"<plugin>/<name>"`) is an analysis of `plugin`. */
1201
+ function publishes(plugin, id) {
1202
+ return id.slice(0, id.indexOf("/")) === plugin;
1203
+ }
1144
1204
  /**
1145
1205
  * Each analysis of the run, solved at most once and only when a rule asks: an analysis whose
1146
1206
  * summaries are as the cache last saw them keeps its fingerprint, and is solved again only when a
@@ -1165,28 +1225,43 @@ function solvedAnalyses(runs, summaries, failures, cache, timing) {
1165
1225
  }
1166
1226
  const sorted = [...(summaries.get(id) ?? [])].sort(([a], [b]) => compareText(a, b));
1167
1227
  const inputs = sha1(sorted.map(([file, summary]) => `${file}\u0000${summary.hash}`).join("\n"));
1228
+ const before = cache?.analyses.get(run.key);
1229
+ const kept = before?.inputs === inputs ? before : undefined;
1230
+ // One map for `solve` and the publisher's rules, kept with the entry while it holds.
1231
+ let map;
1232
+ const summariesNow = () => {
1233
+ map ??= kept === undefined ? summaryMap(sorted) : (kept.summaries ??= summaryMap(sorted));
1234
+ return map;
1235
+ };
1168
1236
  const solve = () => {
1169
- const solveNow = () => deepFreeze(run.analysis.solve(summaryMap(sorted)));
1237
+ const solveNow = () => deepFreeze(run.analysis.solve(summariesNow()));
1170
1238
  return timing === undefined ? solveNow() : timing.projectSide(id, solveNow);
1171
1239
  };
1172
1240
  let solved;
1173
- const before = cache?.analyses.get(run.key);
1174
1241
  try {
1175
- if (before?.inputs === inputs) {
1176
- const entry = before;
1242
+ if (kept !== undefined) {
1243
+ const entry = kept;
1177
1244
  solved = {
1178
1245
  kind: "solved",
1179
1246
  fingerprint: entry.fingerprint,
1180
1247
  value: () => (entry.value ??= solve()),
1248
+ inputs,
1249
+ summaries: summariesNow,
1181
1250
  };
1182
1251
  }
1183
1252
  else {
1184
1253
  const value = solve();
1185
1254
  const fingerprint = sha1(JSON.stringify(value));
1186
- cache?.analyses.set(run.key, { inputs, fingerprint, value });
1255
+ cache?.analyses.set(run.key, { inputs, fingerprint, value, summaries: summariesNow() });
1187
1256
  if (cache !== undefined)
1188
1257
  cache.changed = true;
1189
- solved = { kind: "solved", fingerprint, value: () => value };
1258
+ solved = {
1259
+ kind: "solved",
1260
+ fingerprint,
1261
+ value: () => value,
1262
+ inputs,
1263
+ summaries: summariesNow,
1264
+ };
1190
1265
  }
1191
1266
  }
1192
1267
  catch (error) {
@@ -1225,6 +1300,15 @@ function readAnalyses(config, entry, analysisOf, location) {
1225
1300
  const failure = failureFinding(entry, at, found.error);
1226
1301
  missing.push({ ...failure, message: `${failure.message} (in analysis ${id})` });
1227
1302
  }
1303
+ else if (publishes(entry.plugin, id)) {
1304
+ // Its own plugin's rule may read the summaries, so its results hold only while they do.
1305
+ solved.push({
1306
+ id,
1307
+ fingerprint: `${found.fingerprint}\u0000${found.inputs}`,
1308
+ value: found.value,
1309
+ summaries: found.summaries,
1310
+ });
1311
+ }
1228
1312
  else {
1229
1313
  solved.push({ id, fingerprint: found.fingerprint, value: found.value });
1230
1314
  }
@@ -1235,6 +1319,12 @@ function readAnalyses(config, entry, analysisOf, location) {
1235
1319
  kind: "run",
1236
1320
  fingerprints: solved.map((one) => `${one.id}\u0000${one.fingerprint}`),
1237
1321
  values: () => Object.fromEntries(solved.map((one) => [one.id, one.value()])),
1322
+ summaries: (id) => {
1323
+ const summaries = solved.find((one) => one.id === id)?.summaries;
1324
+ if (summaries === undefined)
1325
+ throw new AnalysisSummariesError(entry.id, id);
1326
+ return summaries();
1327
+ },
1238
1328
  };
1239
1329
  }
1240
1330
  /**
@@ -1338,19 +1428,17 @@ function limitPerRuleAndFile(sorted) {
1338
1428
  * cost with the type checker warm (`RuleCost.warmMs`), for benchmarks. In file order, as the check
1339
1429
  * ran them, so a rule's memo of the last file is as cold as it was then.
1340
1430
  */
1341
- function secondPass(units, sets, timing) {
1342
- for (const unit of units) {
1343
- for (const file of unit.files) {
1344
- const sourceFile = unit.sourceFile(file);
1345
- if (sourceFile === undefined)
1346
- continue;
1347
- const same = new Map();
1348
- const types = timing.timedTypes(unit.typesFor(file));
1349
- for (const entry of sets.forFile(file)) {
1350
- timing.warmSide(entry.id, entry.rule.kind, () => {
1351
- runOnFile(entry, sourceFile, types, same, []);
1352
- });
1353
- }
1431
+ function secondPass(unit, sets, timing) {
1432
+ for (const file of unit.files) {
1433
+ const sourceFile = unit.sourceFile(file);
1434
+ if (sourceFile === undefined)
1435
+ continue;
1436
+ const same = new Map();
1437
+ const types = timing.timedTypes(unit.typesFor(file));
1438
+ for (const entry of sets.forFile(file)) {
1439
+ timing.warmSide(entry.id, entry.rule.kind, () => {
1440
+ runOnFile(entry, sourceFile, types, same, []);
1441
+ });
1354
1442
  }
1355
1443
  }
1356
1444
  }
@@ -1462,7 +1550,14 @@ export function silentReasons(config, selection, summaries) {
1462
1550
  const own = summaries.get(entry.id);
1463
1551
  if (own === undefined)
1464
1552
  continue;
1465
- const reason = entry.rule.silentReason?.(own(), { options: entry.options });
1553
+ const reason = entry.rule.silentReason?.(own(), {
1554
+ options: entry.options,
1555
+ analysisSummaries: (id) => {
1556
+ if (!publishes(entry.plugin, id))
1557
+ throw new AnalysisSummariesError(entry.id, id);
1558
+ return summaries.get(id)?.() ?? new Map();
1559
+ },
1560
+ });
1466
1561
  if (reason !== undefined)
1467
1562
  reasons.set(entry.id, reason);
1468
1563
  }
package/dist/index.d.ts CHANGED
@@ -9,6 +9,7 @@ export { check, createChecker } from "./checker.js";
9
9
  export type { CheckInput, Checker } from "./checker.js";
10
10
  export { createPropagationMemo, propagate } from "./graph.js";
11
11
  export type { Propagation, PropagationMemo } from "./graph.js";
12
+ export { summaryHash } from "./cache.js";
12
13
  export { highestUncovered, shortestPath } from "./tree.js";
13
14
  export type { TreeEdge, Uncovered, WalkDown } from "./tree.js";
14
15
  export { describeRelease, describeTraitSource, releaseCandidates, releaseTraitOf, } from "./release.js";
package/dist/index.js CHANGED
@@ -11,6 +11,8 @@ export { lazyRule, moduleLoader } from "./lazy.js";
11
11
  export { check, createChecker } from "./checker.js";
12
12
  // Helpers for project rules that follow calls across files.
13
13
  export { createPropagationMemo, propagate } from "./graph.js";
14
+ // The engine's hash of a summary it handed out: a solver's memo can key by it.
15
+ export { summaryHash } from "./cache.js";
14
16
  export { highestUncovered, shortestPath } from "./tree.js";
15
17
  // The release trait: where a call's result is stated to need releasing (type, facts).
16
18
  export { describeRelease, describeTraitSource, releaseCandidates, releaseTraitOf, } from "./release.js";
@@ -16,7 +16,7 @@ export { advance, buildPlan, describeNotChecked, describeTurnOn, isClean } from
16
16
  export type { Advance, Plan, PlanRow } from "./plan.js";
17
17
  export { findConfigFile, findConfigUpward, loadConfig, loadConfigFile, reloadsLocalImports, } from "./config-file.js";
18
18
  export { LOOSE_NULLS_FIX, MAX_FINDINGS_PER_RULE_PER_FILE, STRICT_NULLS_REMEDY, activeRuleIds, compareFindings, explain, limitFindings, } from "./engine.js";
19
- export type { CheckProgress } from "./engine.js";
19
+ export type { CheckerSlicing, CheckProgress } from "./engine.js";
20
20
  export { SLICE_MS } from "./checker.js";
21
21
  export { counted, describeStatus, guaranteeAt, proveGuarantees } from "./guarantees.js";
22
22
  export { STATED_RULE_ID } from "./stated.js";
@@ -32,11 +32,15 @@ export { NothingToCheckError, TsconfigError, TypeScriptLibMissingError, missingD
32
32
  export { createTimingRecorder } from "./timing.js";
33
33
  export { cacheEntries, dropLeastRecentlyUsed, limitBytes, markUsed } from "./disk-limits.js";
34
34
  export { CACHE_SUBDIR, PROJECT_CACHE_DIR, RESULTS_CACHE_DEFAULT_MB, cleanResultsCache, defaultCacheDir, userCacheDir, openDiskCache, resultsCacheLimit, resultsCacheStats, } from "./disk-cache.js";
35
- export type { DiskCache, ResultsCacheStats } from "./disk-cache.js";
35
+ export type { DiskCache, ResultsCacheStats, SaveOutcome } from "./disk-cache.js";
36
+ export { journalProgress } from "./journal.js";
36
37
  export type { CacheEntry } from "./disk-limits.js";
37
38
  export type { RuleCost, RunTiming, TimingRecorder } from "./timing.js";
38
39
  export { hintLines, hintWithoutExamples, laidOutHint } from "./hint-lines.js";
39
40
  export type { HintLine } from "./hint-lines.js";
40
41
  export { quotedIdLine, removedNotice, removedOf, renameNotice, renamedIdsIn, renamedRule, renamesOf, } from "./renamed.js";
41
42
  export type { Renames } from "./renamed.js";
43
+ export { MemoryBudgetError, describePlan, planMemory } from "./memory-plan.js";
44
+ export type { MemoryPlan, ProjectPlan } from "./memory-plan.js";
45
+ export type { MemoryBudget } from "./checker.js";
42
46
  //# sourceMappingURL=internal.d.ts.map
package/dist/internal.js CHANGED
@@ -27,6 +27,8 @@ export { NothingToCheckError, TsconfigError, TypeScriptLibMissingError, missingD
27
27
  export { createTimingRecorder } from "./timing.js";
28
28
  export { cacheEntries, dropLeastRecentlyUsed, limitBytes, markUsed } from "./disk-limits.js";
29
29
  export { CACHE_SUBDIR, PROJECT_CACHE_DIR, RESULTS_CACHE_DEFAULT_MB, cleanResultsCache, defaultCacheDir, userCacheDir, openDiskCache, resultsCacheLimit, resultsCacheStats, } from "./disk-cache.js";
30
+ export { journalProgress } from "./journal.js";
30
31
  export { hintLines, hintWithoutExamples, laidOutHint } from "./hint-lines.js";
31
32
  export { quotedIdLine, removedNotice, removedOf, renameNotice, renamedIdsIn, renamedRule, renamesOf, } from "./renamed.js";
33
+ export { MemoryBudgetError, describePlan, planMemory } from "./memory-plan.js";
32
34
  //# sourceMappingURL=internal.js.map
@@ -0,0 +1,40 @@
1
+ import type { FileEntry, ResultCache } from "./cache.js";
2
+ /** What a journal belongs to: the cache file's head, and the cache format of its entries. */
3
+ export type JournalOwner = {
4
+ readonly version: string;
5
+ readonly implementation: string;
6
+ readonly project: string;
7
+ };
8
+ /** What a journal holds: the results of finished files, and the file the run was on when it ended. */
9
+ export type JournalContents = {
10
+ readonly entries: ReadonlyMap<string, FileEntry>;
11
+ /** The last file started and not finished; undefined when the run was between files. */
12
+ readonly inProgress: string | undefined;
13
+ };
14
+ /**
15
+ * Reads the journal `file` of `owner`'s cache; undefined when there is none, or its head is
16
+ * another's (another version, implementation, project or cache format).
17
+ */
18
+ export declare function readJournal(file: string, owner: JournalOwner): JournalContents | undefined;
19
+ /**
20
+ * How far the run that wrote the journal `file` got, for a message: the files it finished and the
21
+ * file it was on. Read without its owner (another process asks); undefined when there is none.
22
+ */
23
+ export declare function journalProgress(file: string): {
24
+ readonly finished: number;
25
+ readonly inProgress: string | undefined;
26
+ } | undefined;
27
+ /** An open journal: it appends what `cache.progress` is told, until `close`. */
28
+ export type OpenJournal = {
29
+ close(): void;
30
+ };
31
+ /**
32
+ * Starts appending `cache`'s progress to `file`: after the lines already there when its head is
33
+ * `owner`'s, else in a new journal. A file whose results are the ones the cache already holds is
34
+ * not written again (a warm run writes little more than the `started` lines). A failed write ends
35
+ * the journal (`onError`); the check goes on, and its results are saved at the end as usual.
36
+ */
37
+ export declare function openJournal(file: string, owner: JournalOwner, cache: ResultCache, onError: (error: Error) => void): OpenJournal;
38
+ /** Removes the journal `file`, once the cache holds what it held; a failure leaves it to be read again. */
39
+ export declare function removeJournal(file: string): void;
40
+ //# sourceMappingURL=journal.d.ts.map
@@ -0,0 +1,197 @@
1
+ import { closeSync, existsSync, openSync, readSync, rmSync, writeSync } from "node:fs";
2
+ import { StringDecoder } from "node:string_decoder";
3
+ import { CACHE_FORMAT, fileSnapshot, parseFileEntry } from "./cache.js";
4
+ /**
5
+ * The check's journal: one line per file whose results the run finished, appended as it goes, next
6
+ * to the results cache it belongs to (disk-cache.ts). A run that dies (out of memory) leaves it;
7
+ * the next run that opens the cache folds it in, so it checks again only what was not finished.
8
+ * The cache's own file is written only at the end, never during the check: rewriting a cache of a
9
+ * few hundred MB per batch of files would cost more than the check.
10
+ *
11
+ * Format, one JSON value per line:
12
+ * - first, the head: `{"journal":1,"stateward":…,"implementation":…,"project":…,"format":…}`; a
13
+ * journal with another head is not read;
14
+ * - `{"started":"<file>"}` when the file phase starts a file;
15
+ * - `{"file":"<file>","entry":{…}}` when its results are final (`fileSnapshot`).
16
+ *
17
+ * Each line is read on its own, field by field: a line that does not parse (the last one, torn by
18
+ * the process dying while it wrote) is left out, and the lines after it still count.
19
+ */
20
+ /** Bumped when the lines change. */
21
+ const JOURNAL_FORMAT = 1;
22
+ function headOf(owner) {
23
+ return JSON.stringify({
24
+ journal: JOURNAL_FORMAT,
25
+ stateward: owner.version,
26
+ implementation: owner.implementation,
27
+ project: owner.project,
28
+ format: CACHE_FORMAT,
29
+ });
30
+ }
31
+ /** Each whole line of `file`, in order, without its newline; a last line with no newline is torn. */
32
+ function* linesOf(file) {
33
+ let fd;
34
+ try {
35
+ fd = openSync(file, "r");
36
+ }
37
+ catch {
38
+ // No journal: nothing to read.
39
+ return;
40
+ }
41
+ try {
42
+ const decoder = new StringDecoder("utf8");
43
+ const buffer = Buffer.alloc(1024 * 1024);
44
+ let pending = "";
45
+ for (;;) {
46
+ const read = readSync(fd, buffer, 0, buffer.length, null);
47
+ if (read === 0)
48
+ return;
49
+ pending += decoder.write(buffer.subarray(0, read));
50
+ let end = pending.indexOf("\n");
51
+ while (end !== -1) {
52
+ yield pending.slice(0, end);
53
+ pending = pending.slice(end + 1);
54
+ end = pending.indexOf("\n");
55
+ }
56
+ }
57
+ }
58
+ finally {
59
+ closeSync(fd);
60
+ }
61
+ }
62
+ /** A line's JSON value; undefined when it does not parse (a torn line). */
63
+ function parsedLine(line) {
64
+ try {
65
+ const value = JSON.parse(line);
66
+ return value;
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ }
72
+ /**
73
+ * Reads the journal `file` of `owner`'s cache; undefined when there is none, or its head is
74
+ * another's (another version, implementation, project or cache format).
75
+ */
76
+ export function readJournal(file, owner) {
77
+ const entries = new Map();
78
+ let inProgress;
79
+ let first = true;
80
+ for (const line of linesOf(file)) {
81
+ if (first) {
82
+ if (line !== headOf(owner))
83
+ return undefined;
84
+ first = false;
85
+ continue;
86
+ }
87
+ const value = parsedLine(line);
88
+ if (typeof value !== "object" || value === null)
89
+ continue;
90
+ const started = Reflect.get(value, "started");
91
+ if (typeof started === "string") {
92
+ inProgress = started;
93
+ continue;
94
+ }
95
+ const name = Reflect.get(value, "file");
96
+ const entry = parseFileEntry(Reflect.get(value, "entry"));
97
+ if (typeof name !== "string" || entry === undefined)
98
+ continue;
99
+ entries.set(name, entry);
100
+ if (inProgress === name)
101
+ inProgress = undefined;
102
+ }
103
+ return first ? undefined : { entries, inProgress };
104
+ }
105
+ /**
106
+ * How far the run that wrote the journal `file` got, for a message: the files it finished and the
107
+ * file it was on. Read without its owner (another process asks); undefined when there is none.
108
+ */
109
+ export function journalProgress(file) {
110
+ const finished = new Set();
111
+ let inProgress;
112
+ let lines = 0;
113
+ for (const line of linesOf(file)) {
114
+ lines += 1;
115
+ if (lines === 1)
116
+ continue;
117
+ const value = parsedLine(line);
118
+ if (typeof value !== "object" || value === null)
119
+ continue;
120
+ const started = Reflect.get(value, "started");
121
+ const name = Reflect.get(value, "file");
122
+ if (typeof started === "string")
123
+ inProgress = started;
124
+ else if (typeof name === "string") {
125
+ finished.add(name);
126
+ if (inProgress === name)
127
+ inProgress = undefined;
128
+ }
129
+ }
130
+ return lines === 0 ? undefined : { finished: finished.size, inProgress };
131
+ }
132
+ /** Whether `next` is `before` again: the same fingerprint, the same result objects and reads. */
133
+ function unchanged(before, next) {
134
+ if (before?.fingerprint !== next.fingerprint)
135
+ return false;
136
+ if (before.rules.size !== next.rules.size || before.reads.size !== next.reads.size)
137
+ return false;
138
+ for (const [key, result] of next.rules)
139
+ if (before.rules.get(key) !== result)
140
+ return false;
141
+ for (const [key, hash] of next.reads)
142
+ if (before.reads.get(key) !== hash)
143
+ return false;
144
+ return true;
145
+ }
146
+ /**
147
+ * Starts appending `cache`'s progress to `file`: after the lines already there when its head is
148
+ * `owner`'s, else in a new journal. A file whose results are the ones the cache already holds is
149
+ * not written again (a warm run writes little more than the `started` lines). A failed write ends
150
+ * the journal (`onError`); the check goes on, and its results are saved at the end as usual.
151
+ */
152
+ export function openJournal(file, owner, cache, onError) {
153
+ const head = headOf(owner);
154
+ // Only the head is read: what follows is the earlier start's, kept as it is.
155
+ const [first] = linesOf(file);
156
+ const keep = first === head;
157
+ let fd = openSync(file, keep ? "a" : "w");
158
+ const close = () => {
159
+ if (fd === undefined)
160
+ return;
161
+ cache.progress = undefined;
162
+ closeSync(fd);
163
+ fd = undefined;
164
+ };
165
+ const append = (line) => {
166
+ if (fd === undefined)
167
+ return;
168
+ try {
169
+ writeSync(fd, `${line}\n`);
170
+ }
171
+ catch (error) {
172
+ close();
173
+ onError(error instanceof Error ? error : new Error(String(error)));
174
+ }
175
+ };
176
+ // A new journal starts with its head; a kept one with a line break, which ends a line the
177
+ // earlier start tore (an empty line reads as nothing).
178
+ append(keep ? "" : head);
179
+ const progress = {
180
+ started(name) {
181
+ append(JSON.stringify({ started: name }));
182
+ },
183
+ finished(name, entry) {
184
+ if (unchanged(cache.files.get(name), entry))
185
+ return;
186
+ append(`{"file":${JSON.stringify(name)},"entry":${JSON.stringify(fileSnapshot(entry))}}`);
187
+ },
188
+ };
189
+ cache.progress = progress;
190
+ return { close };
191
+ }
192
+ /** Removes the journal `file`, once the cache holds what it held; a failure leaves it to be read again. */
193
+ export function removeJournal(file) {
194
+ if (existsSync(file))
195
+ rmSync(file, { force: true });
196
+ }
197
+ //# sourceMappingURL=journal.js.map