@ultimat3/cli 31.48.0 → 31.49.0
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/CLAUDE.md +30 -23
- package/README.md +96 -4
- package/package.json +29 -29
- package/src/api-registration.ts +28 -14
- package/src/app-load.ts +6 -1
- package/src/app-root.ts +7 -1
- package/src/clean-services.ts +142 -0
- package/src/cmd-auth.ts +3 -0
- package/src/cmd-clean-spec.ts +10 -3
- package/src/cmd-clean.ts +23 -9
- package/src/cmd-db-backfill.ts +6 -0
- package/src/cmd-db-branch.ts +10 -4
- package/src/cmd-db-recount.ts +5 -12
- package/src/cmd-db-rollback.ts +77 -0
- package/src/cmd-db-spec.ts +18 -2
- package/src/cmd-db-status.ts +5 -10
- package/src/cmd-db.ts +105 -33
- package/src/cmd-deploy-verify.ts +14 -6
- package/src/cmd-docs-topic.ts +94 -0
- package/src/cmd-docs.ts +15 -1
- package/src/cmd-doctor.ts +109 -41
- package/src/cmd-drill.ts +80 -18
- package/src/cmd-env.ts +30 -8
- package/src/cmd-errors-app.ts +63 -0
- package/src/cmd-errors.ts +50 -14
- package/src/cmd-generate.ts +17 -4
- package/src/cmd-heavy-spec.ts +9 -1
- package/src/cmd-heavy.ts +111 -27
- package/src/cmd-jobs.ts +27 -1
- package/src/cmd-merge-driver-spec.ts +12 -0
- package/src/cmd-merge-driver.ts +95 -0
- package/src/cmd-new.ts +23 -3
- package/src/cmd-policy-spec.ts +9 -1
- package/src/cmd-policy.ts +72 -17
- package/src/cmd-stop.ts +18 -4
- package/src/cmd-tasks-run.ts +87 -0
- package/src/cmd-tasks-spec.ts +10 -3
- package/src/cmd-tasks.ts +8 -5
- package/src/cmd-test.ts +2 -1
- package/src/cmd-upgrade-spec.ts +8 -1
- package/src/cmd-upgrade.ts +15 -1
- package/src/cmd-verify.ts +9 -41
- package/src/codemods/agents-doc-row.ts +73 -0
- package/src/codemods/define-error-leaf.ts +37 -12
- package/src/codemods/docs-many-agents.ts +11 -15
- package/src/codemods/docs-worker-commands.ts +26 -0
- package/src/codemods/index.ts +4 -0
- package/src/codemods/merge-drivers.ts +66 -0
- package/src/command.ts +3 -0
- package/src/db-applied-edits.ts +117 -0
- package/src/db-dev-wire.ts +18 -0
- package/src/db-diagnostics.ts +5 -10
- package/src/db-generate.ts +82 -7
- package/src/db-migrate-pass.ts +51 -0
- package/src/db-migrate-through-dev.ts +209 -0
- package/src/db-rollback-consent.ts +128 -0
- package/src/db-rollback-pass.ts +76 -0
- package/src/db-seed-generate.ts +5 -1
- package/src/db-seed.ts +7 -1
- package/src/deploy-verify-findings.ts +3 -0
- package/src/deploy-verify-grade.ts +3 -0
- package/src/deploy-verify-processes.ts +32 -0
- package/src/dev-boot.ts +3 -0
- package/src/dev-db-migrate.ts +155 -0
- package/src/dev-db-rollback.ts +33 -0
- package/src/dev-db-settled.ts +22 -0
- package/src/dev-lock-errors.ts +78 -0
- package/src/dev-lock-holder-dir.ts +64 -0
- package/src/dev-lock-live.ts +44 -0
- package/src/dev-lock.ts +59 -84
- package/src/dev-policy.ts +11 -8
- package/src/dev-rebuild-schema.ts +116 -13
- package/src/dev-rebuild.ts +13 -4
- package/src/dev-route-table.ts +7 -0
- package/src/dispatch.ts +21 -1
- package/src/doctor-api-listing.ts +114 -0
- package/src/doctor-guarded.ts +41 -0
- package/src/doctor-port.ts +90 -17
- package/src/doctor-probe.ts +36 -5
- package/src/doctor-processes-probe.ts +127 -0
- package/src/doctor-processes.ts +136 -0
- package/src/doctor-warnings.ts +17 -0
- package/src/error-codes-agents.ts +35 -0
- package/src/error-codes-processes.ts +30 -0
- package/src/error-codes-tooling.ts +2 -0
- package/src/error-codes.ts +12 -13
- package/src/errors-suite.ts +27 -0
- package/src/errors.ts +18 -22
- package/src/exercise-registration.ts +4 -3
- package/src/framework-env.ts +7 -3
- package/src/generate-files.ts +1 -0
- package/src/generate-grant-findings.ts +7 -5
- package/src/generate-grants.ts +9 -8
- package/src/generate-kinds.ts +30 -6
- package/src/generate-roles-file.ts +30 -0
- package/src/generate-slice-policy.ts +3 -3
- package/src/guards.ts +2 -2
- package/src/heavy-env.ts +2 -0
- package/src/heavy-errors.ts +18 -0
- package/src/heavy-holders.ts +78 -0
- package/src/heavy-ledger.ts +56 -14
- package/src/heavy-pressure.ts +104 -0
- package/src/heavy.ts +31 -13
- package/src/i18n-registration.ts +22 -2
- package/src/island-harness.ts +2 -2
- package/src/job-budget.ts +4 -2
- package/src/job-registration.ts +64 -8
- package/src/jobs-queue-known.ts +43 -0
- package/src/mcp-errors-agents.ts +20 -0
- package/src/mcp-errors-doctor.ts +27 -0
- package/src/mcp-errors-processes.ts +23 -0
- package/src/mcp-errors.ts +15 -29
- package/src/mcp-host.ts +2 -2
- package/src/merge-driver-catalog.ts +58 -0
- package/src/merge-driver-config.ts +43 -0
- package/src/merge-driver-lines.ts +140 -0
- package/src/merge-state.ts +105 -0
- package/src/messages-db.ts +22 -1
- package/src/messages-processes.ts +13 -0
- package/src/messages-upgrade.ts +6 -0
- package/src/messages.ts +54 -4
- package/src/output-findings.ts +48 -21
- package/src/parse.ts +37 -6
- package/src/policy-facts.ts +38 -21
- package/src/policy-row.ts +99 -0
- package/src/port-pair-free.ts +28 -0
- package/src/registry-lines.ts +110 -0
- package/src/registry.ts +2 -0
- package/src/retain-sweep.ts +1 -1
- package/src/role-replicator.ts +4 -1
- package/src/role-select.ts +86 -0
- package/src/role-start.ts +13 -55
- package/src/role-sync.ts +10 -5
- package/src/runtime-cache-frame.ts +46 -0
- package/src/runtime-cache-ttl.ts +23 -0
- package/src/runtime-cache.ts +33 -16
- package/src/runtime-database-ssl.ts +84 -0
- package/src/runtime-idempotency-scope.ts +16 -2
- package/src/runtime-jobs-share.ts +52 -0
- package/src/runtime-jobs.ts +43 -12
- package/src/runtime-queue.ts +18 -3
- package/src/runtime-services.ts +8 -1
- package/src/schema-drift.ts +19 -2
- package/src/schema-dump-drift.ts +4 -1
- package/src/serve-boot-probe.ts +30 -2
- package/src/serve-boot.ts +11 -1
- package/src/serve-env.ts +39 -3
- package/src/serve.ts +61 -10
- package/src/stop-run-start.ts +12 -0
- package/src/supervise-boot.ts +61 -0
- package/src/supervise-cgroup.ts +84 -0
- package/src/supervise-child.ts +206 -0
- package/src/supervise-count.ts +244 -0
- package/src/supervise-errors.ts +83 -0
- package/src/supervise-facts.ts +40 -0
- package/src/supervise-messages.ts +84 -0
- package/src/supervise-policy.ts +46 -0
- package/src/supervise-pool.ts +10 -0
- package/src/supervise-probe.ts +158 -0
- package/src/supervise-run.ts +54 -0
- package/src/supervise.ts +383 -0
- package/src/templates/generate-purge.ts +6 -6
- package/src/templates/guard-animated-layout-property.ts +2 -2
- package/src/templates/guard-bare-error.ts +1 -1
- package/src/templates/guard-error-declared.ts +2 -2
- package/src/templates/guard-focus-visible.ts +1 -1
- package/src/templates/guard-image-dimensions.ts +2 -2
- package/src/templates/guard-island-mount-clears.ts +1 -1
- package/src/templates/guard-native-confirm.ts +1 -1
- package/src/templates/guard-raw-breakpoint.ts +2 -2
- package/src/templates/guard-raw-colour.ts +2 -2
- package/src/templates/guard-raw-fetch.ts +1 -1
- package/src/templates/guard-raw-interval.ts +1 -1
- package/src/templates/guard-raw-length.ts +3 -3
- package/src/templates/guard-raw-motion.ts +1 -1
- package/src/templates/guard-raw-shadow.ts +1 -1
- package/src/templates/guard-raw-z-index.ts +1 -1
- package/src/templates/guard-released-forms.ts +54 -8
- package/src/templates/guard-repo-await-in-loop.ts +1 -1
- package/src/templates/guard-repo-raw-sql.ts +4 -4
- package/src/templates/guard-repo-unbounded.ts +1 -1
- package/src/templates/guard-runtime-pin.ts +1 -1
- package/src/templates/guard-semantic-interactive.ts +2 -2
- package/src/templates/guard-unbounded-fanout.ts +1 -1
- package/src/templates/guard-undeclared-custom-property.ts +3 -3
- package/src/templates/guard-undefined-style-class.ts +3 -3
- package/src/templates/guard-unzoned-date.ts +3 -3
- package/src/templates/query-slice.ts +82 -0
- package/src/templates/query.ts +76 -30
- package/src/templates/resource-page.ts +3 -2
- package/src/templates/scaffold-bin.ts +2 -0
- package/src/templates/scaffold-claude-commands.ts +6 -0
- package/src/templates/scaffold-claude.ts +4 -4
- package/src/templates/scaffold-container-compose.ts +47 -7
- package/src/templates/scaffold-docs.ts +7 -3
- package/src/templates/scaffold-gitattributes.ts +18 -1
- package/src/templates/scaffold-helm-templates.ts +9 -0
- package/src/templates/scaffold-repo.ts +4 -1
- package/src/templates/scaffold-test-services.ts +33 -11
- package/src/templates/shapes/offline.ts +0 -7
- package/src/templates/shapes/realtime.ts +2 -6
- package/src/templates/sign-in-action-tests.ts +6 -4
- package/src/templates/sign-in-challenge.ts +62 -0
- package/src/templates/sign-in-oidc-mfa.ts +31 -0
- package/src/templates/sign-in-oidc.ts +11 -3
- package/src/templates/sign-in-password.ts +18 -56
- package/src/test-shards.ts +114 -34
- package/src/test-verdict.ts +79 -0
- package/src/test-workers.ts +15 -0
- package/src/upgrade-gate-codemods.ts +5 -3
- package/src/upgrade-gate.ts +19 -1
- package/src/upgrade-merge-drivers.ts +25 -0
- package/src/upgrade-report.ts +18 -4
- package/src/upgrade-scope.ts +62 -0
- package/src/verify-checks.ts +2 -8
- package/src/verify-coverage-run.ts +4 -1
- package/src/verify-live.ts +38 -14
- package/src/verify-only.ts +67 -0
- package/src/verify-progress.ts +7 -3
- package/src/verify-run.ts +20 -2
- package/src/verify-services-stack.ts +165 -0
- package/src/verify-services.ts +84 -2
- package/src/verify-test-run.ts +6 -7
- package/src/verify-tests.ts +8 -2
- package/src/verify-typecheck.ts +25 -2
- package/wiki/Actions.md +2 -1
- package/wiki/Admin-Dashboard.md +2 -2
- package/wiki/Agents.md +5 -5
- package/wiki/Auth.md +15 -5
- package/wiki/Bare-VM.md +1 -1
- package/wiki/CI-Parallel-Gate.md +2 -1
- package/wiki/CLI-Reference.md +107 -40
- package/wiki/Caching-And-Invalidation.md +1 -1
- package/wiki/Client-Navigation.md +1 -1
- package/wiki/Configuration.md +10 -9
- package/wiki/Deployment.md +44 -4
- package/wiki/Entities-And-Migrations.md +5 -1
- package/wiki/FAQ.md +1 -1
- package/wiki/Getting-Started.md +2 -2
- package/wiki/Home.md +1 -1
- package/wiki/I18n.md +5 -3
- package/wiki/Installation.md +12 -11
- package/wiki/Jobs-And-Workflows.md +24 -4
- package/wiki/Known-Gaps.md +1 -1
- package/wiki/MCP-And-AI.md +8 -5
- package/wiki/Many-Agents.md +69 -2
- package/wiki/Migrations-And-Backfills.md +18 -0
- package/wiki/Notify.md +1 -1
- package/wiki/Observability.md +13 -0
- package/wiki/Queries-And-Live-Queries.md +2 -2
- package/wiki/Realtime.md +10 -1
- package/wiki/Routes-And-Render-Modes.md +1 -1
- package/wiki/Scheduled-Tasks.md +4 -1
- package/wiki/Testing.md +7 -4
- package/wiki/Timezones-And-Dates.md +5 -1
- package/wiki/Troubleshooting.md +1 -0
- package/wiki/Tutorial-01-First-App.md +3 -3
- package/wiki/Tutorial-02-First-Feature.md +1 -1
- package/wiki/Tutorial-03-Auth-And-Admin.md +7 -6
- package/wiki/Upgrading.md +37 -0
package/src/errors.ts
CHANGED
|
@@ -5,6 +5,20 @@ import { UltimateError } from '@ultimat3/core';
|
|
|
5
5
|
import type { Finding } from './output';
|
|
6
6
|
import { quoteArg } from './shell-quote';
|
|
7
7
|
|
|
8
|
+
/** Commands whose bare form runs everything. */
|
|
9
|
+
const WHOLE_RUN: ReadonlySet<string> = new Set(['test', 'verify']);
|
|
10
|
+
|
|
11
|
+
/** Commands that act when run bare (stop, delete, roll out, rewrite, re-pin, inject a fault). */
|
|
12
|
+
const ACTS_BARE = new Set('stop clean deploy fix upgrade drill'.split(' '));
|
|
13
|
+
|
|
14
|
+
/** The suggested command as a fix: its help when bare it starts a whole suite or changes state. */
|
|
15
|
+
const suggestedCommandFix = (suggestion: string): string =>
|
|
16
|
+
WHOLE_RUN.has(suggestion)
|
|
17
|
+
? `x ${suggestion} --help # the nearest command; bare, it runs every suite`
|
|
18
|
+
: ACTS_BARE.has(suggestion)
|
|
19
|
+
? `x ${suggestion} --help # the nearest command; bare, it acts at once`
|
|
20
|
+
: `x ${quoteArg(suggestion.split(' '))}`;
|
|
21
|
+
|
|
8
22
|
/** An unknown command or subcommand. Carries a suggestion so the retry is one keystroke away. */
|
|
9
23
|
export class UnknownCommandError extends UltimateError {
|
|
10
24
|
/** `why`: the decision behind a name that is deliberately not a command, said after the list. */
|
|
@@ -17,7 +31,7 @@ export class UnknownCommandError extends UltimateError {
|
|
|
17
31
|
super({
|
|
18
32
|
code: 'X_CLI_UNKNOWN_COMMAND',
|
|
19
33
|
cause: `"x ${input.path}" is not a command (known: ${input.known.join(', ')})${input.why === undefined ? '' : ` — ${input.why}`}`,
|
|
20
|
-
fix: input.suggestion === undefined ? 'x help' :
|
|
34
|
+
fix: input.suggestion === undefined ? 'x help' : suggestedCommandFix(input.suggestion),
|
|
21
35
|
});
|
|
22
36
|
}
|
|
23
37
|
}
|
|
@@ -138,12 +152,14 @@ export class NotInAppError extends UltimateError {
|
|
|
138
152
|
adopter?: boolean;
|
|
139
153
|
/** `from`'s `package.json` has an `x` script (the framework repo): `bun run x -- … --cwd`. */
|
|
140
154
|
xScript?: boolean;
|
|
155
|
+
/** The words as typed — subcommand, positionals, flags — less the two the fix writes itself. */
|
|
156
|
+
typed?: readonly string[];
|
|
141
157
|
}) {
|
|
142
158
|
const [first] = input.below ?? [];
|
|
143
159
|
const found = (input.below ?? []).join(', ');
|
|
144
160
|
// Word by word: `'vapid create'` pasted as one quoted token is a command `x` does not have.
|
|
145
161
|
// Assembled from arrays of screened words, so no value is spliced where a shell runs it.
|
|
146
|
-
const argv = input.command.split(' ').map(quoteArg);
|
|
162
|
+
const argv = (input.typed ?? input.command.split(' ')).map(quoteArg);
|
|
147
163
|
const words = argv.join(' ');
|
|
148
164
|
super({
|
|
149
165
|
code: 'X_NOT_IN_APP',
|
|
@@ -178,26 +194,6 @@ export class BunVersionError extends UltimateError {
|
|
|
178
194
|
}
|
|
179
195
|
}
|
|
180
196
|
|
|
181
|
-
/**
|
|
182
|
-
* `x test` discovered nothing. A green run over zero files is the most expensive false pass, so
|
|
183
|
-
* the selection that found nothing is named in full — a caller that cannot see whether the type
|
|
184
|
-
* or the filter emptied the set has to guess which one to drop.
|
|
185
|
-
*/
|
|
186
|
-
export class NoTestFilesError extends UltimateError {
|
|
187
|
-
constructor(input: { root: string; type?: string; filter?: string }) {
|
|
188
|
-
const parts = [
|
|
189
|
-
input.type === undefined ? undefined : `of type ${input.type}`,
|
|
190
|
-
input.filter === undefined ? undefined : `matching "${input.filter}"`,
|
|
191
|
-
].filter((part): part is string => part !== undefined);
|
|
192
|
-
const where = parts.length === 0 ? '' : ` ${parts.join(' ')}`;
|
|
193
|
-
super({
|
|
194
|
-
code: 'X_TEST_NO_FILES',
|
|
195
|
-
cause: `no *.test.ts files${where} under ${input.root}`,
|
|
196
|
-
fix: parts.length === 0 ? 'x test --json # run it from the repo root' : 'x test',
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
197
|
/**
|
|
202
198
|
* A generated path resolves outside the directory it is being written into — the scaffold gate's
|
|
203
199
|
* sandbox, the app root `x g` writes into, or the catalog root a `--locales` segment names. `..`
|
|
@@ -8,8 +8,9 @@ import { exerciseFiles } from './templates/scaffold-exercise';
|
|
|
8
8
|
export const EXERCISE_FILE = 'apps/web/exercise.ts';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
|
-
* The
|
|
12
|
-
* each in the app's file, inside Biome's 100 columns: `login()` refuses the drawn
|
|
11
|
+
* The sign-in actions the pass cannot drive, by the file that declares each; the second leg is both
|
|
12
|
+
* shapes'. One line each in the app's file, inside Biome's 100 columns: `login()` refuses the drawn
|
|
13
|
+
* address and password.
|
|
13
14
|
*/
|
|
14
15
|
const SIGN_IN_OFF: ReadonlyMap<string, readonly [string, string]> = new Map([
|
|
15
16
|
[
|
|
@@ -18,7 +19,7 @@ const SIGN_IN_OFF: ReadonlyMap<string, readonly [string, string]> = new Map([
|
|
|
18
19
|
],
|
|
19
20
|
[
|
|
20
21
|
'apps/web/app/auth/actions/confirm-session.ts',
|
|
21
|
-
['confirmSession', 'answers the challenge
|
|
22
|
+
['confirmSession', 'answers the challenge the first leg holds; the pass holds none'],
|
|
22
23
|
],
|
|
23
24
|
]);
|
|
24
25
|
|
package/src/framework-env.ts
CHANGED
|
@@ -32,8 +32,9 @@ export const deployed = (env: EnvTable): boolean => devSecretsRefused({ env });
|
|
|
32
32
|
/**
|
|
33
33
|
* Does `env` NAME a deployed environment — `ULTIMATE_ENV`, else `NODE_ENV`, resolving to
|
|
34
34
|
* `staging` or `production`? `x doctor`'s gate, and deliberately not `deployed`: the two commands
|
|
35
|
-
* answer different questions. `x env check` asks what a
|
|
36
|
-
*
|
|
35
|
+
* answer different questions. `x env check` asks what a boot does with a table: an unnamed one is
|
|
36
|
+
* checked as `x dev` runs it (development), except under `CI`, where the boot fails closed and it
|
|
37
|
+
* is a deploy (`cmd-env.ts`'s `checkedAsDev`). `x doctor` asks about THIS machine,
|
|
37
38
|
* and a developer shell that names nothing is not a deploy — reporting the shipped keys there would
|
|
38
39
|
* put two findings in front of every developer on day one. An unknown `ULTIMATE_ENV` names
|
|
39
40
|
* nothing (`tryResolveEnvironment`): the boot refuses it first, and doctor must not crash on it.
|
|
@@ -43,7 +44,10 @@ export const namedDeployed = (env: EnvTable): boolean => {
|
|
|
43
44
|
return environment === 'staging' || environment === 'production';
|
|
44
45
|
};
|
|
45
46
|
|
|
46
|
-
/**
|
|
47
|
+
/**
|
|
48
|
+
* Does `env` name no environment? The boot then reads it as production; `x env check` checks it so
|
|
49
|
+
* under `CI` only, and as development elsewhere — and says which.
|
|
50
|
+
*/
|
|
47
51
|
export const namesNoEnvironment = (env: EnvTable): boolean =>
|
|
48
52
|
// Core's reading, twice: only a table that names nothing answers with whichever fallback it got.
|
|
49
53
|
tryResolveEnvironment({ env, fallback: 'production' }) !==
|
package/src/generate-files.ts
CHANGED
|
@@ -240,6 +240,7 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
|
|
|
240
240
|
...target,
|
|
241
241
|
live: options.live === true,
|
|
242
242
|
...(options.locales === undefined ? {} : { locales: options.locales }),
|
|
243
|
+
...(options.slicePolicy === undefined ? {} : { slicePolicy: options.slicePolicy }),
|
|
243
244
|
...(options.sliceEntity === undefined ? {} : { sliceEntity: options.sliceEntity }),
|
|
244
245
|
...(options.sliceRepo === undefined ? {} : { sliceRepo: options.sliceRepo }),
|
|
245
246
|
}),
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
policyGrantsFor,
|
|
14
14
|
writtenTables,
|
|
15
15
|
} from './generate-grants';
|
|
16
|
+
import { rolesFileOf } from './generate-roles-file';
|
|
16
17
|
import type { Finding } from './output';
|
|
17
18
|
import { ROLES_FILE } from './permission-grants';
|
|
18
19
|
|
|
@@ -61,11 +62,12 @@ export async function ungrantedByGenerator(
|
|
|
61
62
|
const admin = (await writtenTables(root, written, disk)).flatMap(adminGrantsFor);
|
|
62
63
|
const grants = [...(await policyGrantsFor(root, written, disk)), ...admin];
|
|
63
64
|
if (grants.length === 0) return [];
|
|
64
|
-
const
|
|
65
|
+
const rolesFile = await rolesFileOf(root, disk);
|
|
66
|
+
const source = rolesFile === undefined ? undefined : await disk.read(rolesFile);
|
|
65
67
|
// The file whose declarations nobody granted: where a reader starts when the map is not ours.
|
|
66
68
|
const declaredIn =
|
|
67
69
|
written.find((path) => path.endsWith('/policy.ts')) ?? written[0] ?? ROLES_FILE;
|
|
68
|
-
if (source === undefined) {
|
|
70
|
+
if (rolesFile === undefined || source === undefined) {
|
|
69
71
|
return [
|
|
70
72
|
{
|
|
71
73
|
code: 'X_PERMISSION_UNGRANTED',
|
|
@@ -80,9 +82,9 @@ export async function ungrantedByGenerator(
|
|
|
80
82
|
return [
|
|
81
83
|
{
|
|
82
84
|
code: 'X_PERMISSION_UNGRANTED',
|
|
83
|
-
cause: `${
|
|
84
|
-
fix: `{ ${roleEntries(missing)} } // merge into the role map in ${
|
|
85
|
-
at:
|
|
85
|
+
cause: `${rolesFile} has no role, no "grants: [...]" list or no definePermissions([...]) these could be safely added to, so nothing granted: ${linesFor(missing)}`,
|
|
86
|
+
fix: `{ ${roleEntries(missing)} } // merge into the role map in ${rolesFile}, declaring any the map does not know in definePermissions([...]) — then x verify --only policy`,
|
|
87
|
+
at: rolesFile,
|
|
86
88
|
},
|
|
87
89
|
];
|
|
88
90
|
}
|
package/src/generate-grants.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// `x g policy` / `x g resource` grant what they declare. A generated `policy.ts` declares
|
|
2
2
|
// `<feature>:read` and `<feature>:write`; nothing granted them, so every generated endpoint
|
|
3
|
-
// answered 403 to every actor a role mints. The edit lands in the
|
|
4
|
-
// `
|
|
3
|
+
// answered 403 to every actor a role mints. The edit lands in the app's one role map
|
|
4
|
+
// (`generate-roles-file.ts`): `:read` to `member`, `:write` to `admin` (which inherits member).
|
|
5
5
|
//
|
|
6
6
|
// And a generated ENTITY is a screen at `/admin/<table>`, behind `<table>:read|write|delete` —
|
|
7
7
|
// three permissions `defineAdmin()` derives from the table's own name. They are declared in the
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import type { GenerateDisk } from './generate-disk';
|
|
11
11
|
import { appDisk } from './generate-disk';
|
|
12
|
-
import {
|
|
12
|
+
import { rolesFileOf } from './generate-roles-file';
|
|
13
13
|
import { absentFrom, appendToList, maskOf, readList, readProperties } from './source-list-edit';
|
|
14
14
|
import { isEntityModule } from './templates/entity-module';
|
|
15
15
|
|
|
@@ -155,7 +155,7 @@ export function insertGrants(
|
|
|
155
155
|
}
|
|
156
156
|
|
|
157
157
|
/** Every `definePermissions([` in the masked text: the index of each call's opening `[`. */
|
|
158
|
-
const declarationLists = (masked: string): readonly number[] =>
|
|
158
|
+
export const declarationLists = (masked: string): readonly number[] =>
|
|
159
159
|
[...masked.matchAll(/\bdefinePermissions\(\s*\[/g)].map(
|
|
160
160
|
(found) => found.index + found[0].length - 1,
|
|
161
161
|
);
|
|
@@ -216,8 +216,9 @@ export async function grantGeneratedPermissions(
|
|
|
216
216
|
): Promise<readonly string[]> {
|
|
217
217
|
const admin = (await writtenTables(root, written, disk)).flatMap(adminGrantsFor);
|
|
218
218
|
const grants = [...(await policyGrantsFor(root, written, disk)), ...admin];
|
|
219
|
-
const
|
|
220
|
-
|
|
219
|
+
const file = grants.length === 0 ? undefined : await rolesFileOf(root, disk);
|
|
220
|
+
const before = file === undefined ? undefined : await disk.read(file);
|
|
221
|
+
if (file === undefined || before === undefined) return [];
|
|
221
222
|
const unplaced = insertGrants(before, grants).skipped;
|
|
222
223
|
const placeable = grants.filter((grant) => !unplaced.includes(grant));
|
|
223
224
|
const declared = insertPermissions(
|
|
@@ -228,6 +229,6 @@ export async function grantGeneratedPermissions(
|
|
|
228
229
|
const grantable = placeable.filter((grant) => !declared.skipped.includes(grant.permission));
|
|
229
230
|
const { source } = insertGrants(declared.source, grantable);
|
|
230
231
|
if (source === before) return [];
|
|
231
|
-
await disk.write(
|
|
232
|
-
return [
|
|
232
|
+
await disk.write(file, source);
|
|
233
|
+
return [file];
|
|
233
234
|
}
|
package/src/generate-kinds.ts
CHANGED
|
@@ -83,6 +83,26 @@ export function assertLiveSupported(kind: Generator, live: boolean, name: string
|
|
|
83
83
|
});
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
/** What the caller typed after the generator: its `<name>` and `--feature`, when given. */
|
|
87
|
+
export interface TypedRest {
|
|
88
|
+
readonly name?: string | undefined;
|
|
89
|
+
readonly feature?: string | undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** One shell word, unquoted: a name or slice that would need quoting is not reused as typed. */
|
|
93
|
+
const ONE_WORD = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The rest of the near-miss's line: the caller's own name (and slice) when they paste as one word,
|
|
97
|
+
* else the generator's example. `x g acton foo` answered `x g action publish-post --feature post`,
|
|
98
|
+
* which in a scaffold holding `post` writes an action nobody asked for.
|
|
99
|
+
*/
|
|
100
|
+
const retyped = (kind: Generator, typed: TypedRest): string => {
|
|
101
|
+
if (typed.name === undefined || !ONE_WORD.test(typed.name)) return exampleName(kind);
|
|
102
|
+
const feature = typed.feature !== undefined && ONE_WORD.test(typed.feature);
|
|
103
|
+
return feature ? `${typed.name} --feature ${typed.feature}` : typed.name;
|
|
104
|
+
};
|
|
105
|
+
|
|
86
106
|
/**
|
|
87
107
|
* The generator a spelling reaches, or a refusal that leads with the one it is nearest.
|
|
88
108
|
*
|
|
@@ -91,8 +111,9 @@ export function assertLiveSupported(kind: Generator, live: boolean, name: string
|
|
|
91
111
|
* because it carries no `<name>`. `nearestName` is what `parse.ts` already does with a mistyped
|
|
92
112
|
* command, over this file's own list.
|
|
93
113
|
*
|
|
94
|
-
* Two rules hold the fix line to a command that runs. A near miss is completed with
|
|
95
|
-
* generator's own `EXAMPLE_NAME
|
|
114
|
+
* Two rules hold the fix line to a command that runs. A near miss is completed with the name the
|
|
115
|
+
* caller typed (`retyped`), else that generator's own `EXAMPLE_NAME` — never a `<name>`, because
|
|
116
|
+
* `x g route <name>` pasted into a shell is a redirect.
|
|
96
117
|
* A word near NOTHING gets `x help g` rather than an invented lead — the same rule `parse.test.ts`
|
|
97
118
|
* pins for a command that resembles nothing, and the reason `nearestName` is never asked about an
|
|
98
119
|
* ABSENT kind: the empty string is within the cutoff of `job`, so `x g` would "suggest" a
|
|
@@ -101,7 +122,7 @@ export function assertLiveSupported(kind: Generator, live: boolean, name: string
|
|
|
101
122
|
* And a THIRD rule, for the word that is not there at all: no generator is a missing subcommand,
|
|
102
123
|
* never an unknown command — see the branch below.
|
|
103
124
|
*/
|
|
104
|
-
export function readKind(raw: string | undefined): Generator {
|
|
125
|
+
export function readKind(raw: string | undefined, typed: TypedRest = {}): Generator {
|
|
105
126
|
const kinds: readonly string[] = GENERATORS;
|
|
106
127
|
if (raw !== undefined && kinds.includes(raw)) return raw as Generator;
|
|
107
128
|
// A MISSING generator is not an unknown command. `x g --json` answered `X_CLI_UNKNOWN_COMMAND:
|
|
@@ -119,7 +140,8 @@ export function readKind(raw: string | undefined): Generator {
|
|
|
119
140
|
throw new UnknownCommandError({
|
|
120
141
|
path: `g ${raw}`.trim(),
|
|
121
142
|
known: GENERATORS,
|
|
122
|
-
suggestion:
|
|
143
|
+
suggestion:
|
|
144
|
+
suggestion === undefined ? 'help g' : `g ${suggestion} ${retyped(suggestion, typed)}`,
|
|
123
145
|
...(decided === undefined
|
|
124
146
|
? {}
|
|
125
147
|
: { why: `${decided.factory}() has no generator: ${decided.none}` }),
|
|
@@ -273,8 +295,10 @@ function refuseBadIdentifier(raw: string, kind: Generator): void {
|
|
|
273
295
|
* a `Record` object literal answers an `Object.prototype` member for a key nobody declared, and
|
|
274
296
|
* this string is pasted into a shell. Two callers, one read.
|
|
275
297
|
*/
|
|
276
|
-
const
|
|
277
|
-
|
|
298
|
+
const exampleName = (kind: Generator): string =>
|
|
299
|
+
Object.hasOwn(EXAMPLE_NAME, kind) ? EXAMPLE_NAME[kind] : '<name>';
|
|
300
|
+
|
|
301
|
+
const exampleFor = (kind: Generator): string => `x g ${kind} ${exampleName(kind)}`;
|
|
278
302
|
|
|
279
303
|
/**
|
|
280
304
|
* `resource:verb`, or nothing is written. `--permission` reaches the generated page in three
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Which file `x g` edits the role map in. The scaffold's `apps/web/shared/roles.ts` when it is
|
|
2
|
+
// there; otherwise the ONE module beside it that calls `defineRoles(` — the reference app keeps
|
|
3
|
+
// its map in `shared/policies.ts`, and a fixed path granted nothing there on every run.
|
|
4
|
+
|
|
5
|
+
import { stripComments } from '@ultimat3/core';
|
|
6
|
+
import type { GenerateDisk } from './generate-disk';
|
|
7
|
+
import { ROLES_FILE } from './permission-grants';
|
|
8
|
+
import { isTest } from './source-files';
|
|
9
|
+
|
|
10
|
+
/** Where an app's role map can live without the app being loaded: the shared leaf, one level. */
|
|
11
|
+
const SHARED_GLOB = 'apps/web/shared/*.ts';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* `undefined` when no file, or more than one, declares the map: a generator never picks between
|
|
15
|
+
* two, and the finding then says what nobody granted. Read off disk, not the registry — `x g` does
|
|
16
|
+
* not load the app, and the edit that follows is of this source text in either case.
|
|
17
|
+
*/
|
|
18
|
+
export async function rolesFileOf(root: string, disk: GenerateDisk): Promise<string | undefined> {
|
|
19
|
+
if ((await disk.read(ROLES_FILE)) !== undefined) return ROLES_FILE;
|
|
20
|
+
const declaring: string[] = [];
|
|
21
|
+
for await (const path of new Bun.Glob(SHARED_GLOB).scan({ cwd: root })) {
|
|
22
|
+
const file = path.replaceAll('\\', '/');
|
|
23
|
+
if (isTest(file)) continue;
|
|
24
|
+
const source = await disk.read(file);
|
|
25
|
+
if (source !== undefined && /\bdefineRoles\s*\(/.test(stripComments(source))) {
|
|
26
|
+
declaring.push(file);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return declaring.length === 1 ? declaring[0] : undefined;
|
|
30
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Single responsibility: the refusal `x g action` / `x g mutator` raise when the slice they were
|
|
1
|
+
// Single responsibility: the refusal `x g action` / `x g mutator` / `x g query` raise when the slice they were
|
|
2
2
|
// pointed at has a hand-written `policy.ts` without the exports the generated file imports.
|
|
3
3
|
// Declared outside `templates/` (source the CLI emits) and beside nothing else, as
|
|
4
4
|
// `generate-feature.ts`'s `FeatureUnknownError` is: `errors.ts` sits at its line ceiling.
|
|
@@ -11,7 +11,7 @@ export class SlicePolicyIncompleteError extends UltimateError {
|
|
|
11
11
|
readonly policy: string;
|
|
12
12
|
readonly feature: string;
|
|
13
13
|
readonly missing: readonly string[];
|
|
14
|
-
readonly kind: 'action' | 'mutator';
|
|
14
|
+
readonly kind: 'action' | 'mutator' | 'query';
|
|
15
15
|
}) {
|
|
16
16
|
super({
|
|
17
17
|
code: 'X_SLICE_POLICY_INCOMPLETE',
|
|
@@ -26,4 +26,4 @@ export class SlicePolicyIncompleteError extends UltimateError {
|
|
|
26
26
|
const exportLine = (name: string, feature: string): string =>
|
|
27
27
|
name.endsWith('Tag')
|
|
28
28
|
? `export const ${name} = tag('${feature}');`
|
|
29
|
-
: `export const ${name} = can('${feature}:write');`;
|
|
29
|
+
: `export const ${name} = can('${feature}:${name.endsWith('Read') ? 'read' : 'write'}');`;
|
package/src/guards.ts
CHANGED
|
@@ -124,7 +124,7 @@ const failed = (path: string, cause: string): Finding => ({
|
|
|
124
124
|
const invalid = (path: string, cause: string): Finding => ({
|
|
125
125
|
code: 'X_GUARD_INVALID',
|
|
126
126
|
cause,
|
|
127
|
-
fix: `export a \`guard\` object — { summary, check } — from ${path}, then: x verify`,
|
|
127
|
+
fix: `export a \`guard\` object — { summary, check } — from ${path}, then: x verify --only boundaries --json`,
|
|
128
128
|
docs: ERROR_DOCS_URL,
|
|
129
129
|
at: path,
|
|
130
130
|
});
|
|
@@ -157,7 +157,7 @@ const notADirectory: Finding = {
|
|
|
157
157
|
const findingInvalid = (path: string, cause: string): Finding => ({
|
|
158
158
|
code: 'X_GUARD_FINDING_INVALID',
|
|
159
159
|
cause: `${path} returned a finding that is not one: ${cause}`,
|
|
160
|
-
fix: `{ code: 'X_<YOURS>', cause: '<what is wrong>', fix: '<a command or a file>' } // what ${path} returns, then: x verify`,
|
|
160
|
+
fix: `{ code: 'X_<YOURS>', cause: '<what is wrong>', fix: '<a command or a file>' } // what ${path} returns, then: x verify --only boundaries --json`,
|
|
161
161
|
docs: ERROR_DOCS_URL,
|
|
162
162
|
at: path,
|
|
163
163
|
});
|
package/src/heavy-env.ts
CHANGED
|
@@ -9,6 +9,8 @@ export const HEAVY_DIR_ENV = 'ULTIMATE_HEAVY_DIR';
|
|
|
9
9
|
export const HEAVY_MEMORY_ENV = 'ULTIMATE_HEAVY_MEMORY';
|
|
10
10
|
/** The local core ceiling, replacing `LOCAL_CORE_CAP`. */
|
|
11
11
|
export const HEAVY_CORES_ENV = 'ULTIMATE_HEAVY_CORES';
|
|
12
|
+
/** `0` turns the CPU half of admission off (`heavy-pressure.ts`); memory still applies. */
|
|
13
|
+
export const HEAVY_CPU_ENV = 'ULTIMATE_HEAVY_CPU';
|
|
12
14
|
/** Set on a holder's children: the reservation file they run inside. A protocol, not a knob. */
|
|
13
15
|
export const HEAVY_HOLD_ENV = 'ULTIMATE_HEAVY_HOLD';
|
|
14
16
|
|
package/src/heavy-errors.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import { UltimateError } from '@ultimat3/core';
|
|
5
5
|
import { HEAVY_MEMORY_ENV } from './heavy-env';
|
|
6
|
+
import type { LedgerWait } from './heavy-ledger';
|
|
6
7
|
import { quoteArg } from './shell-quote';
|
|
7
8
|
|
|
8
9
|
export class HeavyLedgerUnavailableError extends UltimateError {
|
|
@@ -34,3 +35,20 @@ export class HeavyCommandNotFoundError extends UltimateError {
|
|
|
34
35
|
});
|
|
35
36
|
}
|
|
36
37
|
}
|
|
38
|
+
|
|
39
|
+
/** `--max-wait` ran out in the queue. The one refusal admission makes, and only when asked to. */
|
|
40
|
+
export class HeavyWaitExpiredError extends UltimateError {
|
|
41
|
+
constructor(input: {
|
|
42
|
+
readonly label: string;
|
|
43
|
+
readonly maxWaitMs: number;
|
|
44
|
+
readonly wait: LedgerWait;
|
|
45
|
+
}) {
|
|
46
|
+
const { wait } = input;
|
|
47
|
+
const holders = wait.holds.map((entry) => entry.label).join(', ') || 'an admission in progress';
|
|
48
|
+
super({
|
|
49
|
+
code: 'X_HEAVY_WAIT_EXPIRED',
|
|
50
|
+
cause: `${JSON.stringify(input.label)} was not admitted within --max-wait ${String(input.maxWaitMs / 1000)}s and did not start: it needs ${String(wait.needMb)} MB, was ${String(wait.position)} of ${String(wait.queued)} in the queue, and ${String(wait.usedMb)} of ${String(wait.capacityMb)} MB are held by ${holders}${wait.cpu === undefined ? '' : ', and the CPU was saturated'}; run it again later or with a longer --max-wait`,
|
|
51
|
+
fix: 'x heavy status --json',
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Which processes keep a reservation alive: every process with its lock file open, as the OS sees
|
|
2
|
+
// it. The ledger records only the wrapper's pid, and after `kill -9` of the wrapper the memory is
|
|
3
|
+
// held by the command it started, so a recorded pid cannot say what would free it.
|
|
4
|
+
|
|
5
|
+
// why: Bun ships no directory listing, readlink or realpath primitive.
|
|
6
|
+
import { existsSync, readdirSync, readlinkSync, realpathSync } from 'node:fs';
|
|
7
|
+
// why: Bun ships no path-join primitive.
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import type { Runner } from './exec';
|
|
10
|
+
|
|
11
|
+
const PROC = '/proc';
|
|
12
|
+
|
|
13
|
+
function realOrSame(path: string): string {
|
|
14
|
+
try {
|
|
15
|
+
return realpathSync(path);
|
|
16
|
+
} catch {
|
|
17
|
+
return path; // Released while being asked about: nothing will match it, which is the answer.
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function hasOpen(procRoot: string, pid: string, target: string): boolean {
|
|
22
|
+
const fds = join(procRoot, pid, 'fd');
|
|
23
|
+
try {
|
|
24
|
+
return readdirSync(fds).some((fd) => {
|
|
25
|
+
try {
|
|
26
|
+
return readlinkSync(join(fds, fd)) === target;
|
|
27
|
+
} catch {
|
|
28
|
+
return false; // The descriptor closed between the listing and the read.
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
} catch {
|
|
32
|
+
return false; // The process exited, or belongs to another user.
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const parsePids = (text: string): readonly number[] =>
|
|
37
|
+
text
|
|
38
|
+
.split('\n')
|
|
39
|
+
.map((line) => line.trim())
|
|
40
|
+
.filter((line) => /^\d+$/.test(line))
|
|
41
|
+
.map(Number);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The pids with `file` open, this process excepted, or `undefined` when the OS will not say: `/proc`
|
|
45
|
+
* where it exists, `lsof` elsewhere (macOS; Windows has no ledger).
|
|
46
|
+
*/
|
|
47
|
+
export async function holderPids(
|
|
48
|
+
file: string,
|
|
49
|
+
runner: Runner,
|
|
50
|
+
cwd: string,
|
|
51
|
+
procRoot: string = PROC,
|
|
52
|
+
): Promise<readonly number[] | undefined> {
|
|
53
|
+
if (existsSync(join(procRoot, 'self', 'fd'))) {
|
|
54
|
+
const target = realOrSame(file);
|
|
55
|
+
return readdirSync(procRoot)
|
|
56
|
+
.filter((name) => /^\d+$/.test(name) && Number(name) !== process.pid)
|
|
57
|
+
.filter((pid) => hasOpen(procRoot, pid, target))
|
|
58
|
+
.map(Number)
|
|
59
|
+
.sort((a, b) => a - b);
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
// `lsof` exits 1 for "nobody has it open", so its stdout is read whatever the status.
|
|
63
|
+
const result = await runner(['lsof', '-t', file], { cwd });
|
|
64
|
+
return parsePids(result.stdout).filter((pid) => pid !== process.pid);
|
|
65
|
+
} catch {
|
|
66
|
+
return undefined; // No `lsof` on this machine.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The fallback when no holder list exists. Signal 0 delivers nothing; it only asks. */
|
|
71
|
+
export function isProcessRunning(pid: number): boolean {
|
|
72
|
+
try {
|
|
73
|
+
process.kill(pid, 0);
|
|
74
|
+
return true;
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
package/src/heavy-ledger.ts
CHANGED
|
@@ -24,8 +24,10 @@ import {
|
|
|
24
24
|
} from 'node:fs';
|
|
25
25
|
// why: Bun ships no path-join primitive.
|
|
26
26
|
import { join } from 'node:path';
|
|
27
|
-
import { HeavyLedgerUnavailableError } from './heavy-errors';
|
|
27
|
+
import { HeavyLedgerUnavailableError, HeavyWaitExpiredError } from './heavy-errors';
|
|
28
28
|
import type { TryLock } from './heavy-flock';
|
|
29
|
+
import type { CpuReading } from './heavy-pressure';
|
|
30
|
+
import { cpuAdmission } from './heavy-pressure';
|
|
29
31
|
|
|
30
32
|
export const LEDGER_POLL_MS = 100;
|
|
31
33
|
/** A temp file this old lost its creator: creating one takes microseconds. */
|
|
@@ -39,8 +41,13 @@ export interface LedgerEntry {
|
|
|
39
41
|
readonly at: number;
|
|
40
42
|
}
|
|
41
43
|
|
|
44
|
+
/** An admitted reservation, and the file whose lock it is. */
|
|
45
|
+
export interface LedgerHold extends LedgerEntry {
|
|
46
|
+
readonly file: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
42
49
|
export interface LedgerView {
|
|
43
|
-
readonly holds: readonly
|
|
50
|
+
readonly holds: readonly LedgerHold[];
|
|
44
51
|
/** Oldest first: index 0 is the next admission. */
|
|
45
52
|
readonly queue: readonly LedgerEntry[];
|
|
46
53
|
}
|
|
@@ -72,6 +79,10 @@ export interface ReserveInput {
|
|
|
72
79
|
readonly cwd: string;
|
|
73
80
|
readonly tryLock: TryLock;
|
|
74
81
|
readonly pollMs?: number;
|
|
82
|
+
/** Give up after this long in the queue. `0` is one attempt; unset waits for as long as it takes. */
|
|
83
|
+
readonly maxWaitMs?: number;
|
|
84
|
+
/** The CPU reading the head is judged by (`heavy-pressure.ts`); absent, CPU never holds it. */
|
|
85
|
+
readonly cpu?: () => CpuReading;
|
|
75
86
|
readonly onWait?: (wait: LedgerWait) => void;
|
|
76
87
|
}
|
|
77
88
|
|
|
@@ -82,6 +93,8 @@ export interface LedgerWait {
|
|
|
82
93
|
readonly position: number;
|
|
83
94
|
readonly queued: number;
|
|
84
95
|
readonly holds: readonly LedgerEntry[];
|
|
96
|
+
/** Set when memory fits and the CPU is what holds the head back. */
|
|
97
|
+
readonly cpu?: CpuReading;
|
|
85
98
|
}
|
|
86
99
|
|
|
87
100
|
const codeOf = (error: unknown): unknown =>
|
|
@@ -164,7 +177,10 @@ function liveEntries(dir: string, tryLock: TryLock, sweep: boolean): Live[] {
|
|
|
164
177
|
}
|
|
165
178
|
|
|
166
179
|
export const readLedger = (dir: string, tryLock: TryLock): LedgerView => ({
|
|
167
|
-
holds: liveEntries(join(dir, 'holds'), tryLock, false).map((one) =>
|
|
180
|
+
holds: liveEntries(join(dir, 'holds'), tryLock, false).map((one) => ({
|
|
181
|
+
...one.entry,
|
|
182
|
+
file: join(dir, 'holds', one.name),
|
|
183
|
+
})),
|
|
168
184
|
queue: liveEntries(join(dir, 'queue'), tryLock, false).map((one) => one.entry),
|
|
169
185
|
});
|
|
170
186
|
|
|
@@ -298,8 +314,11 @@ export async function reserve(input: ReserveInput): Promise<Reservation> {
|
|
|
298
314
|
if (ticket === undefined) throw new HeavyLedgerUnavailableError('a new queue file was locked');
|
|
299
315
|
const minUnits = input.minUnits ?? 1;
|
|
300
316
|
let said = '';
|
|
317
|
+
/** When the head started waiting on CPU alone: `CPU_WAIT_LIMIT_MS` is counted from here. */
|
|
318
|
+
let cpuBlockedAt: number | undefined;
|
|
301
319
|
try {
|
|
302
320
|
for (;;) {
|
|
321
|
+
let cpu: CpuReading | undefined;
|
|
303
322
|
const queue = liveEntries(join(dir, 'queue'), tryLock, true);
|
|
304
323
|
const position = queue.findIndex((one) => one.name === name);
|
|
305
324
|
if (position === -1) throw new HeavyLedgerUnavailableError(`${dir} was removed mid-wait`);
|
|
@@ -313,7 +332,18 @@ export async function reserve(input: ReserveInput): Promise<Reservation> {
|
|
|
313
332
|
holds = liveEntries(join(dir, 'holds'), tryLock, true);
|
|
314
333
|
const usedMb = holds.reduce((sum, one) => sum + one.entry.mb, 0);
|
|
315
334
|
const granted = unitsThatFit({ capacityMb, usedMb, unitMb, units, minUnits, baseMb });
|
|
316
|
-
|
|
335
|
+
const reading = granted > 0 ? input.cpu?.() : undefined;
|
|
336
|
+
const now = performance.now();
|
|
337
|
+
const verdict = cpuAdmission({
|
|
338
|
+
reading,
|
|
339
|
+
running: holds.length,
|
|
340
|
+
blockedMs: cpuBlockedAt === undefined ? 0 : now - cpuBlockedAt,
|
|
341
|
+
});
|
|
342
|
+
if (granted > 0 && verdict === 'wait') {
|
|
343
|
+
cpuBlockedAt ??= now;
|
|
344
|
+
cpu = reading;
|
|
345
|
+
} else cpuBlockedAt = undefined;
|
|
346
|
+
if (granted > 0 && verdict === 'admit') {
|
|
317
347
|
const mb = baseMb + granted * unitMb;
|
|
318
348
|
const hold = createEntry(
|
|
319
349
|
dir,
|
|
@@ -338,19 +368,31 @@ export async function reserve(input: ReserveInput): Promise<Reservation> {
|
|
|
338
368
|
}
|
|
339
369
|
}
|
|
340
370
|
const usedMb = holds.reduce((sum, one) => sum + one.entry.mb, 0);
|
|
341
|
-
|
|
371
|
+
// Behind the head, the queue is held by whatever holds the head: say CPU when that is it.
|
|
372
|
+
if (cpu === undefined && position > 0 && holds.length > 0) {
|
|
373
|
+
const reading = input.cpu?.();
|
|
374
|
+
if (reading?.busy === true) cpu = reading;
|
|
375
|
+
}
|
|
376
|
+
const wait: LedgerWait = {
|
|
377
|
+
needMb: Math.min(baseMb + units * unitMb, capacityMb),
|
|
378
|
+
usedMb,
|
|
379
|
+
capacityMb,
|
|
380
|
+
position: position + 1,
|
|
381
|
+
queued: queue.length,
|
|
382
|
+
holds: holds.map((one) => one.entry),
|
|
383
|
+
...(cpu === undefined ? {} : { cpu }),
|
|
384
|
+
};
|
|
385
|
+
const key = `${String(position)}|${cpu === undefined ? '' : 'cpu'}|${holds.map((one) => one.name).join(',')}`;
|
|
342
386
|
if (key !== said) {
|
|
343
387
|
said = key;
|
|
344
|
-
input.onWait?.(
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
holds: holds.map((one) => one.entry),
|
|
351
|
-
});
|
|
388
|
+
input.onWait?.(wait);
|
|
389
|
+
}
|
|
390
|
+
const { maxWaitMs } = input;
|
|
391
|
+
const left = (maxWaitMs ?? Number.POSITIVE_INFINITY) - (performance.now() - started);
|
|
392
|
+
if (maxWaitMs !== undefined && left <= 0) {
|
|
393
|
+
throw new HeavyWaitExpiredError({ label: input.label, maxWaitMs, wait });
|
|
352
394
|
}
|
|
353
|
-
await Bun.sleep(pollMs);
|
|
395
|
+
await Bun.sleep(Math.min(pollMs, left));
|
|
354
396
|
}
|
|
355
397
|
} finally {
|
|
356
398
|
ticket.release();
|