ravensight-playtest 0.8.0 → 0.8.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/README.md +25 -5
- package/package.json +1 -1
- package/src/cli.js +12 -9
- package/src/commands/build.js +3 -1
- package/src/commands/hosted.js +99 -23
- package/src/hosted/archivePreflight.js +65 -2
- package/src/hosted/buildUpload.js +7 -2
- package/src/hosted/recordedRun.js +251 -49
- package/src/hosted/status.js +21 -0
package/README.md
CHANGED
|
@@ -27,9 +27,14 @@ question, and nothing is charged.
|
|
|
27
27
|
| `--build <id>` | Use this build instead of the newest ready one. |
|
|
28
28
|
| `--persona <slug>` | The persona for both runs. Default `curious-kid`. |
|
|
29
29
|
| `--video`, `--transcript` | Save video or transcripts of both sessions in their reports. Priced in the quote. |
|
|
30
|
-
| `--wait` | Stay until the run finishes, printing each phase change, then each mode's outcome. |
|
|
30
|
+
| `--wait` | Stay until the run finishes, printing each phase change and the queue place while it waits, then each mode's outcome. Works with a saved quote file too. |
|
|
31
31
|
| `--game <id>` | Override the linked game. |
|
|
32
32
|
|
|
33
|
+
`hosted run` prints the hosted run id and job id as soon as the run is admitted.
|
|
34
|
+
A run waiting for a hosted machine shows its place, such as "Queued, position 2,
|
|
35
|
+
expected to start in about 14 minutes" or "Queued, starting now", and `--wait`
|
|
36
|
+
prints it again whenever it moves.
|
|
37
|
+
|
|
33
38
|
The phases are the dashboard's: queued, provisioning, running, capturing,
|
|
34
39
|
analyzing, then report ready, failed or canceled. `hosted status <id>` prints
|
|
35
40
|
the current one (`--wait` to follow it) with each mode's state and findings and
|
|
@@ -41,16 +46,26 @@ is refunded during settlement.
|
|
|
41
46
|
To review a quote before paying, save it and confirm it later:
|
|
42
47
|
|
|
43
48
|
```sh
|
|
44
|
-
ravensight-playtest hosted quote --game GAME --build BUILD --
|
|
45
|
-
ravensight-playtest hosted run hosted-quote.json
|
|
49
|
+
ravensight-playtest hosted quote --game GAME --build BUILD --video --output hosted-quote.json
|
|
50
|
+
ravensight-playtest hosted run hosted-quote.json --wait
|
|
46
51
|
```
|
|
47
52
|
|
|
53
|
+
`hosted quote` uses the same default persona as `hosted run`, `curious-kid`, and
|
|
54
|
+
says so; `--persona` names another.
|
|
55
|
+
|
|
48
56
|
`--profile` is needed only when the server advertises more than one build
|
|
49
57
|
profile; the error lists them. The quote names the full Geri then Freki price, prepaid amount, evidence
|
|
50
58
|
options, expiry and refund rules. It charges nothing. `hosted run` confirms
|
|
51
59
|
that saved quote before one admission request. Its durable journal blocks an
|
|
52
60
|
automatic second POST after an uncertain outcome; preserve it for reconciliation.
|
|
53
61
|
Both forms of `hosted run` keep that journal under `.ravensight/hosted-runs/`.
|
|
62
|
+
When the server refuses the run with its own reason (busy capacity, funding,
|
|
63
|
+
an expired quote), no run was started, nothing was charged and the journal is
|
|
64
|
+
cleared, so the same command can be run again; it sends the same idempotency
|
|
65
|
+
key, so the server can never admit it twice. Only an answer that never arrived
|
|
66
|
+
leaves the outcome unknown. Then `hosted status`, with no run id, asks the
|
|
67
|
+
server what happened once the quote has expired (so asking cannot start the
|
|
68
|
+
run), records the run if it was admitted, and clears the journal if it was not.
|
|
54
69
|
A charged-blocked acknowledgement does not prove gameplay or a report. This
|
|
55
70
|
command does not top up funds, change local run/report files or ask for model
|
|
56
71
|
proxy permission on the CLI credential.
|
|
@@ -68,11 +83,16 @@ continues to use its local runner and original API contract.
|
|
|
68
83
|
The hosted build command source adds a local check before a paid upload:
|
|
69
84
|
|
|
70
85
|
```sh
|
|
71
|
-
ravensight-playtest build preflight ./game.zip --format web
|
|
72
|
-
ravensight-playtest build upload ./game.zip --game GAME --
|
|
86
|
+
ravensight-playtest build preflight ./game.zip --format web
|
|
87
|
+
ravensight-playtest build upload ./game.zip --game GAME --dry-run
|
|
73
88
|
ravensight-playtest build status --game GAME
|
|
74
89
|
```
|
|
75
90
|
|
|
91
|
+
`--entrypoint` names the file the game starts from. Without it, an `index.html`
|
|
92
|
+
at the root of the archive (or inside the one folder that holds everything) is
|
|
93
|
+
used, or else the only HTML file, and the command says which. When several
|
|
94
|
+
files could be the entry, it lists them and asks you to choose one.
|
|
95
|
+
|
|
76
96
|
`preflight` seeks through bounded ZIP metadata; it does not load a multi-GB
|
|
77
97
|
archive into memory. A saved server profile can be supplied with `--capacity`
|
|
78
98
|
for its declared limits. Upload uses the server's build profile when it
|
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -161,7 +161,7 @@ export function buildProgram() {
|
|
|
161
161
|
.description('save a full hosted quote without charging or admitting a run')
|
|
162
162
|
.requiredOption('--build <id>', 'an existing validated hosted build')
|
|
163
163
|
.option('--profile <version>', 'hosted profile to quote; optional when the server advertises exactly one, otherwise the error lists the choices')
|
|
164
|
-
.
|
|
164
|
+
.option('--persona <slug>', 'the persona that plays both runs (default: curious-kid, the same as hosted run)')
|
|
165
165
|
.requiredOption('--output <file>', 'save the original quote and immutable consent here')
|
|
166
166
|
.option('--game <id>', 'game id, overriding this repo’s configuration')
|
|
167
167
|
.addOption(new Option('--geri-provider <name>', "Geri's model provider: primary or alternate (ravensight.io/legal/subprocessors names both); unavailable choices are refused").choices(['primary', 'alternate']).conflicts('standardProvider'))
|
|
@@ -180,19 +180,22 @@ export function buildProgram() {
|
|
|
180
180
|
.option('--persona <slug>', 'the persona that plays both runs (default: curious-kid)')
|
|
181
181
|
.option('--game <id>', 'game id, overriding this repo’s configuration')
|
|
182
182
|
.option('--video', 'save video of both game sessions in their reports')
|
|
183
|
-
.option('--wait', 'stay until the report is ready, printing each phase change')
|
|
183
|
+
.option('--wait', 'stay until the report is ready, printing each phase change (with or without a saved quote)')
|
|
184
|
+
// Hidden: the server now queues a funded run instead of refusing it for
|
|
185
|
+
// capacity. Kept so an older server's busy answer can still be waited out.
|
|
186
|
+
.addOption(new Option('--wait-for-capacity [minutes]', 'when hosted capacity is busy, ask again about once a minute and start when there is room, for up to this many minutes (default 60)').hideHelp())
|
|
184
187
|
.action(capture(slot, async (filename, options, command) => {
|
|
185
188
|
const { hostedRun, hostedRunDirect } = await import('./commands/hosted.js');
|
|
186
189
|
if (filename) {
|
|
187
|
-
const extra = ['build', 'persona', 'game', 'video'
|
|
190
|
+
const extra = ['build', 'persona', 'game', 'video'].filter(name => options[name] !== undefined);
|
|
188
191
|
if (extra.length) throw new CliError(`A saved quote already fixes its build, persona and options. Drop --${extra.join(', --')}, or run "hosted run" without a quote file.`);
|
|
189
|
-
return hostedRun(filename, flagsFrom(command.optsWithGlobals()));
|
|
192
|
+
return hostedRun(filename, flagsFrom(command.optsWithGlobals(), { wait: options.wait, waitForCapacity: options.waitForCapacity }));
|
|
190
193
|
}
|
|
191
194
|
return hostedRunDirect(flagsFrom(command.optsWithGlobals(), { build: options.build, persona: options.persona, game: options.game,
|
|
192
|
-
video: options.video, wait: options.wait }));
|
|
195
|
+
video: options.video, wait: options.wait, waitForCapacity: options.waitForCapacity }));
|
|
193
196
|
}));
|
|
194
|
-
common(hosted.command('status
|
|
195
|
-
.description('show the phase of one hosted run (queued, provisioning, running, capturing, analyzing, report ready, failed or canceled), each mode and the report link')
|
|
197
|
+
common(hosted.command('status [run-id]'))
|
|
198
|
+
.description('show the phase of one hosted run (queued, provisioning, running, capturing, analyzing, report ready, failed or canceled), each mode and the report link; with no run id, ask the server about any admission whose outcome is not known yet')
|
|
196
199
|
.option('--game <id>', 'game id, overriding this repo’s configuration')
|
|
197
200
|
.option('--wait', 'stay until the run finishes, printing each phase change')
|
|
198
201
|
.action(capture(slot, async (runId, options, command) => {
|
|
@@ -209,7 +212,7 @@ export function buildProgram() {
|
|
|
209
212
|
const build = common(program.command('build').description('check or upload a self-contained hosted game archive'));
|
|
210
213
|
build.command('preflight <archive>')
|
|
211
214
|
.description('check bounded ZIP metadata locally before any paid upload')
|
|
212
|
-
.
|
|
215
|
+
.option('--entrypoint <path>', 'entry file inside the ZIP (default: index.html at the root, or the only HTML file; several are listed to choose from)')
|
|
213
216
|
.option('--format <name>', 'web or godot-project without a selected capacity profile', 'web')
|
|
214
217
|
.option('--capacity <file>', 'saved profile JSON for a local capacity check; does not establish server readiness')
|
|
215
218
|
.action(capture(slot, async (archive, options, command) => {
|
|
@@ -226,7 +229,7 @@ export function buildProgram() {
|
|
|
226
229
|
build.command('upload <archive>')
|
|
227
230
|
.description('preflight and stream one private build upload after validation-hold consent')
|
|
228
231
|
.option('--profile <version>', 'server build profile to upload under; optional when the server advertises exactly one, otherwise the error lists the choices')
|
|
229
|
-
.
|
|
232
|
+
.option('--entrypoint <path>', 'entry file inside the ZIP (default: index.html at the root, or the only HTML file; several are listed to choose from)')
|
|
230
233
|
.option('--game <id>', 'game id, overriding this repo’s configuration')
|
|
231
234
|
.option('--journal <file>', 'preserve this original upload intent at the specified path')
|
|
232
235
|
.option('--dry-run', 'inspect and hash the archive without requesting a reservation')
|
package/src/commands/build.js
CHANGED
|
@@ -2,7 +2,7 @@ import { readFile, stat } from 'node:fs/promises';
|
|
|
2
2
|
import { createContext } from '../api/index.js';
|
|
3
3
|
import { resolveGameId } from '../config.js';
|
|
4
4
|
import { withAuthHandling } from '../auth/session.js';
|
|
5
|
-
import { preflightBuildArchive, limitsFromProfile } from '../hosted/archivePreflight.js';
|
|
5
|
+
import { preflightBuildArchive, limitsFromProfile, entrypointChoiceLine } from '../hosted/archivePreflight.js';
|
|
6
6
|
import { uploadHostedBuild } from '../hosted/buildUpload.js';
|
|
7
7
|
import { buildStatusLines, readHostedBuilds } from '../hosted/buildStatus.js';
|
|
8
8
|
import { CliError, ExitCode } from '../errors.js';
|
|
@@ -43,6 +43,7 @@ export async function buildPreflight(filename, flags = {}) {
|
|
|
43
43
|
requirements: profile?.capacity?.requirements });
|
|
44
44
|
if (flags.json) ui.json(result);
|
|
45
45
|
else {
|
|
46
|
+
if (result.entrypointChosen) ui.info(entrypointChoiceLine({ entrypoint: result.entrypoint, reason: result.entrypointChosen }));
|
|
46
47
|
ui.ok(`ZIP metadata passed: ${result.entries} entries; ${ui.bytes(result.archiveBytes)} uploaded, ${ui.bytes(result.expandedBytes)} expanded.`);
|
|
47
48
|
ui.info('No wallet charge or upload was requested. Server validation and runtime compatibility checks are still required.');
|
|
48
49
|
}
|
|
@@ -62,6 +63,7 @@ export async function buildUpload(filename, flags = {}, deps = {}) {
|
|
|
62
63
|
onPrepared: prepared => {
|
|
63
64
|
progress.stop();
|
|
64
65
|
if (flags.json) return;
|
|
66
|
+
if (prepared.entrypointChosen) ui.info(entrypointChoiceLine({ entrypoint: prepared.entrypoint, reason: prepared.entrypointChosen }));
|
|
65
67
|
ui.info(`Build profile: ${prepared.profileVersion}${flags.profile ? '' : ', the only one the server advertises'}.`);
|
|
66
68
|
ui.info(`ZIP metadata checked: ${prepared.entries} entries; ${ui.bytes(prepared.archiveBytes)} archive, ${ui.bytes(prepared.expandedBytes)} expanded.`);
|
|
67
69
|
const limit = prepared.limits;
|
package/src/commands/hosted.js
CHANGED
|
@@ -4,21 +4,26 @@ import { withAuthHandling } from '../auth/session.js';
|
|
|
4
4
|
import { CliError, ExitCode } from '../errors.js';
|
|
5
5
|
import { ui } from '../ui/index.js';
|
|
6
6
|
import { quoteHostedRun, runHostedQuote, hostedQuoteLines, prepareHostedRun, admitHostedOffer, confirmQuestion,
|
|
7
|
-
hostedConsentLines, fundingShortfall, readHostedRun, cancelHostedRun, GERI_PROVIDERS
|
|
8
|
-
|
|
7
|
+
hostedConsentLines, fundingShortfall, readHostedRun, cancelHostedRun, GERI_PROVIDERS, admitWithCapacityWait,
|
|
8
|
+
resolveHostedIntents } from '../hosted/recordedRun.js';
|
|
9
|
+
import { hostedPlaytestStatus, modeOutcomes, modeLine, TERMINAL_PHASES, queueInfo, queueLine } from '../hosted/status.js';
|
|
9
10
|
import { jobLink } from '../dashboard.js';
|
|
10
11
|
import { DEFAULT_PERSONAS } from '../runDefaults.js';
|
|
11
12
|
|
|
12
13
|
export async function hostedQuote(flags = {}, deps = {}) {
|
|
13
14
|
const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
|
|
15
|
+
// The same default as "hosted run", so a quote and a run of the same build
|
|
16
|
+
// match unless a persona is named.
|
|
17
|
+
const persona = flags.persona || DEFAULT_PERSONAS[0];
|
|
14
18
|
return withAuthHandling(context, async () => {
|
|
15
19
|
const result = await quoteHostedRun({ api: context.api, apiUrl: context.api.apiUrl,
|
|
16
20
|
gameId: resolveGameId(flags, context.config), buildId: flags.build, profileVersion: flags.profile,
|
|
17
|
-
persona
|
|
21
|
+
persona,
|
|
18
22
|
standardProvider: flags.geriProvider ? GERI_PROVIDERS[flags.geriProvider] : flags.standardProvider, includeVideo: Boolean(flags.video),
|
|
19
23
|
output: flags.output });
|
|
20
|
-
if (flags.json) ui.json(result);
|
|
24
|
+
if (flags.json) ui.json({ ...result, persona, personaDefaulted: !flags.persona });
|
|
21
25
|
else {
|
|
26
|
+
if (!flags.persona) ui.info(`Persona: ${persona}, the default. Choose another with --persona.`);
|
|
22
27
|
hostedQuoteLines(result).forEach(line => ui.info(line));
|
|
23
28
|
ui.ok(`Saved ${result.quoteFile}. No admission or charge was requested.`);
|
|
24
29
|
}
|
|
@@ -28,21 +33,65 @@ export async function hostedQuote(flags = {}, deps = {}) {
|
|
|
28
33
|
|
|
29
34
|
export async function hostedRun(filename, flags = {}, deps = {}) {
|
|
30
35
|
if (flags.json && !flags.yes && !deps.confirm) throw new CliError('Inspect the saved quote, then use --yes with --json. No admission was requested.');
|
|
36
|
+
const maxWaitMs = capacityWaitMs(flags.waitForCapacity);
|
|
31
37
|
const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
|
|
38
|
+
const now = deps.now || Date.now, sleep = deps.sleep || (() => sleepFor(POLL_MS));
|
|
32
39
|
return withAuthHandling(context, async () => {
|
|
33
|
-
const
|
|
40
|
+
const api = context.api, apiUrl = api.apiUrl;
|
|
41
|
+
const result = await runHostedQuote({ filename, api, apiUrl, repoRoot: context.repoRoot, now,
|
|
34
42
|
confirm: deps.confirm || (question => ui.confirm(question, { yes: Boolean(flags.yes) })),
|
|
35
|
-
onPrepared: offer => { if (!flags.json) hostedQuoteLines(offer).forEach(line => ui.info(line)); }
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
43
|
+
onPrepared: offer => { if (!flags.json) hostedQuoteLines(offer).forEach(line => ui.info(line)); },
|
|
44
|
+
admit: admitter(flags, deps, maxWaitMs) });
|
|
45
|
+
if (result.state === 'declined') {
|
|
46
|
+
if (flags.json) ui.json(result); else ui.info('Hosted quote declined. No admission was requested.');
|
|
47
|
+
return ExitCode.CANCELED;
|
|
48
|
+
}
|
|
49
|
+
const { offer: admittedOffer, ...admitted } = result, gameId = admittedOffer.gameId;
|
|
50
|
+
if (!flags.json) {
|
|
51
|
+
ui.ok(`Admission ${admitted.admissionId}; job ${admitted.jobId}. Saved ${admitted.journal}.`);
|
|
52
|
+
admittedLines(admitted, now());
|
|
53
|
+
ui.info(`Check on it with: ravensight-playtest hosted status ${admitted.admissionId}`);
|
|
54
|
+
}
|
|
55
|
+
if (!flags.wait) {
|
|
56
|
+
if (flags.json) ui.json(admitted);
|
|
57
|
+
else ui.info('The server acknowledged charged_blocked. This does not prove a worker started or produced gameplay or reports.');
|
|
58
|
+
return ExitCode.OK;
|
|
41
59
|
}
|
|
42
|
-
|
|
60
|
+
const view = await waitForRun({ api, gameId, admissionId: admitted.admissionId, apiUrl, sleep, now, onPhase: phaseLine(flags) });
|
|
61
|
+
if (flags.json) ui.json({ ...admitted, gameId, status: view });
|
|
62
|
+
else printOutcome(view);
|
|
63
|
+
return exitFor(view);
|
|
43
64
|
});
|
|
44
65
|
}
|
|
45
66
|
|
|
67
|
+
const CAPACITY_WAIT_DEFAULT_MINUTES = 60;
|
|
68
|
+
const CAPACITY_WAIT_MAX_MINUTES = 720;
|
|
69
|
+
|
|
70
|
+
/** --wait-for-capacity [minutes]: true for the default, or whole minutes up to 12 hours. */
|
|
71
|
+
export function capacityWaitMs(value) {
|
|
72
|
+
if (value === undefined || value === false) return null;
|
|
73
|
+
const minutes = value === true ? CAPACITY_WAIT_DEFAULT_MINUTES : Number(value);
|
|
74
|
+
if (!Number.isInteger(minutes) || minutes < 1 || minutes > CAPACITY_WAIT_MAX_MINUTES) {
|
|
75
|
+
throw new CliError(`--wait-for-capacity takes whole minutes from 1 to ${CAPACITY_WAIT_MAX_MINUTES} (default ${CAPACITY_WAIT_DEFAULT_MINUTES}); put a saved quote file before it. Nothing was charged.`);
|
|
76
|
+
}
|
|
77
|
+
return minutes * 60000;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const minutesText = ms => { const m = Math.round(ms / 60000); return m < 1 ? 'under a minute' : `${m} minute${m === 1 ? '' : 's'}`; };
|
|
81
|
+
const delayText = ms => { const s = Math.round(ms / 1000), m = Math.floor(s / 60); return m ? `${m} m ${s % 60} s` : `${s} s`; };
|
|
82
|
+
|
|
83
|
+
/** How an accepted offer is admitted: once, or waiting for capacity when asked. */
|
|
84
|
+
function admitter(flags, deps, maxWaitMs) {
|
|
85
|
+
return async args => {
|
|
86
|
+
if (maxWaitMs === null) return { ...await admitHostedOffer(args), offer: args.offer };
|
|
87
|
+
return admitWithCapacityWait({ ...args, maxWaitMs, sleep: deps.capacitySleep, random: deps.random,
|
|
88
|
+
onBusy: ({ delayMs, waitedMs }) => {
|
|
89
|
+
if (!flags.json) ui.info(`Hosted capacity is busy. No run was started and nothing was charged. Asking again in ${delayText(delayMs)} (waited ${minutesText(waitedMs)} of ${minutesText(maxWaitMs)}).`);
|
|
90
|
+
},
|
|
91
|
+
onRequote: offer => { if (!flags.json) ui.info(`Fresh quote ${offer.quote.quoteId} at the same price, ${dollars(offer.quote.totalPriceCents)}. The earlier attempt charged nothing.`); } });
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
46
95
|
const POLL_MS = 15000;
|
|
47
96
|
const dollars = cents => `$${(cents / 100).toFixed(2)}`;
|
|
48
97
|
const sleepFor = ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); if (timer.unref) timer.unref(); });
|
|
@@ -66,12 +115,13 @@ function statusView(gameId, apiUrl, { admission, job, runs }, now = Date.now())
|
|
|
66
115
|
totalPriceCents: Number.isSafeInteger(admission.totalPriceCents) ? admission.totalPriceCents : null,
|
|
67
116
|
modes: modeOutcomes(runs, Array.isArray(admission.controllers) ? admission.controllers : ['standard', 'jev']),
|
|
68
117
|
summaryReport: job?.summary_report ?? null,
|
|
69
|
-
reportUrl: admission.jobId ? jobLink(gameId, admission.jobId, apiUrl) : null
|
|
118
|
+
reportUrl: admission.jobId ? jobLink(gameId, admission.jobId, apiUrl) : null,
|
|
119
|
+
queue: status.phase === 'queued' ? queueInfo(admission) : null
|
|
70
120
|
};
|
|
71
121
|
}
|
|
72
122
|
|
|
73
|
-
function printOutcome(view) {
|
|
74
|
-
ui.info(`${view.label}. ${view.detail}`);
|
|
123
|
+
function printOutcome(view, now = Date.now()) {
|
|
124
|
+
ui.info(view.queue ? queueLine(view.queue, now) : `${view.label}. ${view.detail}`);
|
|
75
125
|
if (view.failure) ui.info(`Reason: ${view.failure}`);
|
|
76
126
|
if (view.cancelRequested && view.phase !== 'canceled') ui.info('Cancellation was requested.');
|
|
77
127
|
if (TERMINAL_PHASES.includes(view.phase) || view.modes.some(row => row.state !== 'not_started')) view.modes.forEach(row => ui.info(modeLine(row)));
|
|
@@ -85,14 +135,22 @@ const exitFor = view => view.phase === 'canceled' ? ExitCode.CANCELED : view.pha
|
|
|
85
135
|
async function waitForRun({ api, gameId, admissionId, apiUrl, sleep, now, onPhase }) {
|
|
86
136
|
let last = null;
|
|
87
137
|
for (;;) {
|
|
88
|
-
const view = statusView(gameId, apiUrl, await readHostedRun({ api, gameId, admissionId }),
|
|
89
|
-
|
|
138
|
+
const at = now(), view = statusView(gameId, apiUrl, await readHostedRun({ api, gameId, admissionId }), at);
|
|
139
|
+
// In the queue, a new position or estimate is printed too, so the wait is visible.
|
|
140
|
+
const key = view.queue ? queueLine(view.queue, at) : view.phase;
|
|
141
|
+
if (key !== last) { last = key; onPhase(view, at); }
|
|
90
142
|
if (TERMINAL_PHASES.includes(view.phase)) return view;
|
|
91
143
|
await sleep();
|
|
92
144
|
}
|
|
93
145
|
}
|
|
94
146
|
|
|
95
|
-
const phaseLine = flags => row => { if (!flags.json) ui.info(`${row.label}: ${row.detail}`); };
|
|
147
|
+
const phaseLine = flags => (row, at = Date.now()) => { if (!flags.json) ui.info(row.queue ? queueLine(row.queue, at) : `${row.label}: ${row.detail}`); };
|
|
148
|
+
|
|
149
|
+
/** The job id at once, then the queue place when the server gave one. */
|
|
150
|
+
function admittedLines(admitted, now) {
|
|
151
|
+
const line = queueLine(admitted.queue, now);
|
|
152
|
+
if (line) ui.info(line);
|
|
153
|
+
}
|
|
96
154
|
|
|
97
155
|
/**
|
|
98
156
|
* `hosted run` with no saved quote: the newest eligible build (or --build), a
|
|
@@ -101,6 +159,7 @@ const phaseLine = flags => row => { if (!flags.json) ui.info(`${row.label}: ${ro
|
|
|
101
159
|
*/
|
|
102
160
|
export async function hostedRunDirect(flags = {}, deps = {}) {
|
|
103
161
|
if (flags.json && !flags.yes && !deps.confirm) throw new CliError('A hosted run charges prepaid funds. Use --yes with --json. Nothing was charged.');
|
|
162
|
+
const maxWaitMs = capacityWaitMs(flags.waitForCapacity);
|
|
104
163
|
const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
|
|
105
164
|
const now = deps.now || Date.now, sleep = deps.sleep || (() => sleepFor(POLL_MS));
|
|
106
165
|
return withAuthHandling(context, async () => {
|
|
@@ -123,13 +182,14 @@ export async function hostedRunDirect(flags = {}, deps = {}) {
|
|
|
123
182
|
else ui.info('Declined. Nothing was charged.');
|
|
124
183
|
return ExitCode.CANCELED;
|
|
125
184
|
}
|
|
126
|
-
const admitted = await
|
|
185
|
+
const { offer: admittedOffer, ...admitted } = await admitter(flags, deps, maxWaitMs)({ offer, api, apiUrl, repoRoot: context.repoRoot, now });
|
|
127
186
|
const reportUrl = jobLink(gameId, admitted.jobId, apiUrl);
|
|
128
187
|
const result = { state: admitted.state, admissionId: admitted.admissionId, jobId: admitted.jobId, gameId, buildId: build.buildId,
|
|
129
|
-
persona: offer.request.personas[0], totalPriceCents: admitted.totalPriceCents, dueNowCents:
|
|
130
|
-
journal: admitted.journal, reportUrl };
|
|
188
|
+
persona: offer.request.personas[0], totalPriceCents: admitted.totalPriceCents, dueNowCents: admittedOffer.quote.dueNowCents,
|
|
189
|
+
journal: admitted.journal, reportUrl, queue: admitted.queue || null };
|
|
131
190
|
if (!flags.json) {
|
|
132
|
-
ui.ok(`Paid ${dollars(
|
|
191
|
+
ui.ok(`Paid ${dollars(admittedOffer.quote.dueNowCents)}. Hosted run ${admitted.admissionId}, job ${admitted.jobId}.`);
|
|
192
|
+
admittedLines(admitted, now());
|
|
133
193
|
ui.info(`Check on it with: ravensight-playtest hosted status ${admitted.admissionId}`);
|
|
134
194
|
}
|
|
135
195
|
if (!flags.wait) {
|
|
@@ -147,16 +207,32 @@ export async function hostedRunDirect(flags = {}, deps = {}) {
|
|
|
147
207
|
export async function hostedStatus(admissionId, flags = {}, deps = {}) {
|
|
148
208
|
const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
|
|
149
209
|
const now = deps.now || Date.now, sleep = deps.sleep || (() => sleepFor(POLL_MS));
|
|
210
|
+
if (!admissionId) {
|
|
211
|
+
if (flags.wait) throw new CliError('Name the hosted run to wait for: hosted status <run-id> --wait.');
|
|
212
|
+
return withAuthHandling(context, () => resolvePending(context, flags, now));
|
|
213
|
+
}
|
|
150
214
|
return withAuthHandling(context, async () => {
|
|
151
215
|
const api = context.api, apiUrl = api.apiUrl, gameId = resolveGameId(flags, context.config);
|
|
152
216
|
const view = flags.wait
|
|
153
217
|
? await waitForRun({ api, gameId, admissionId, apiUrl, sleep, now, onPhase: phaseLine(flags) })
|
|
154
218
|
: statusView(gameId, apiUrl, await readHostedRun({ api, gameId, admissionId }), now());
|
|
155
|
-
if (flags.json) ui.json(view); else printOutcome(view);
|
|
219
|
+
if (flags.json) ui.json(view); else printOutcome(view, now());
|
|
156
220
|
return flags.wait ? exitFor(view) : ExitCode.OK;
|
|
157
221
|
});
|
|
158
222
|
}
|
|
159
223
|
|
|
224
|
+
/** "hosted status" with no run id: ask the server about every admission whose outcome is not known locally. */
|
|
225
|
+
async function resolvePending(context, flags, now) {
|
|
226
|
+
const results = await resolveHostedIntents({ api: context.api, apiUrl: context.api.apiUrl, repoRoot: context.repoRoot, now });
|
|
227
|
+
if (flags.json) { ui.json({ intents: results.map(({ message, ...row }) => row) }); }
|
|
228
|
+
else if (!results.length) ui.info('No hosted admission is waiting for an answer. Name a run to see it: ravensight-playtest hosted status <run-id>');
|
|
229
|
+
else for (const row of results) {
|
|
230
|
+
ui.info(row.message);
|
|
231
|
+
if (row.state === 'admitted') ui.info(`Check on it with: ravensight-playtest hosted status ${row.admissionId}`);
|
|
232
|
+
}
|
|
233
|
+
return results.some(row => ['unknown', 'unreadable', 'wait', 'other_api'].includes(row.state)) ? ExitCode.ENVIRONMENT : ExitCode.OK;
|
|
234
|
+
}
|
|
235
|
+
|
|
160
236
|
export async function hostedCancel(admissionId, flags = {}, deps = {}) {
|
|
161
237
|
if (flags.json && !flags.yes && !deps.confirm) throw new CliError('Use --yes with --json to cancel a hosted run. Nothing was canceled.');
|
|
162
238
|
const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot: flags.repoRoot, requireAuth: true });
|
|
@@ -279,7 +279,70 @@ export async function inspectBuildArchive(archive, { limits: supplied, format, e
|
|
|
279
279
|
zip64: dir.zip64, metadataVerified: true, nativeBinaryMetadata, contentsVerified: false, serverValidationRequired: true, runtimeCompatibilityProven: false };
|
|
280
280
|
}
|
|
281
281
|
|
|
282
|
-
|
|
282
|
+
// The file names in the central directory, read with the same bounded
|
|
283
|
+
// metadata reads as the full inspection. Only names: inspectBuildArchive still
|
|
284
|
+
// checks every entry once the entry file is chosen.
|
|
285
|
+
async function archiveFileNames(archive, limits) {
|
|
286
|
+
const dir = await directory(archive, limits), names = [];
|
|
287
|
+
let cursor = dir.offset;
|
|
288
|
+
for (let index = 0; index < dir.count; index++) {
|
|
289
|
+
const h = await archive.read(cursor, 46);
|
|
290
|
+
if (h.readUInt32LE(0) !== 0x02014b50) reject('a ZIP directory entry is invalid');
|
|
291
|
+
const nameBytes = h.readUInt16LE(28), extraBytes = h.readUInt16LE(30), commentBytes = h.readUInt16LE(32);
|
|
292
|
+
if (!nameBytes || nameBytes > MAX_PATH_BYTES || cursor + 46 + nameBytes + extraBytes + commentBytes > dir.offset + dir.size) reject('a ZIP directory entry is oversized');
|
|
293
|
+
const name = (await archive.read(cursor + 46, nameBytes)).toString('utf8');
|
|
294
|
+
if (!name.endsWith('/')) names.push(name);
|
|
295
|
+
cursor += 46 + nameBytes + extraBytes + commentBytes;
|
|
296
|
+
}
|
|
297
|
+
return names;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const ENTRY_KINDS = Object.freeze({
|
|
301
|
+
web: { noun: 'HTML file', preferred: 'index.html', match: name => name.endsWith('.html') },
|
|
302
|
+
'godot-project': { noun: 'project.godot file', preferred: 'project.godot', match: name => name.split('/').at(-1) === 'project.godot' },
|
|
303
|
+
'windows-executable': { noun: '.exe file', preferred: null, match: name => name.toLowerCase().endsWith('.exe') }
|
|
304
|
+
});
|
|
305
|
+
const MAX_LISTED = 10;
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* The entry file to use when --entrypoint is not given. An index.html (or
|
|
309
|
+
* project.godot) at the top wins; otherwise the only candidate at the top,
|
|
310
|
+
* looking inside one wrapping folder when everything sits in one; otherwise
|
|
311
|
+
* the only candidate anywhere. With several, the error lists them so the
|
|
312
|
+
* person can choose: nothing is guessed.
|
|
313
|
+
* @returns {Promise<{entrypoint: string, reason: 'root'|'only-top-level'|'wrapped-folder'|'only-one'}>}
|
|
314
|
+
*/
|
|
315
|
+
export async function chooseEntrypoint(archive, { limits: supplied, format } = {}) {
|
|
316
|
+
const kind = ENTRY_KINDS[format];
|
|
317
|
+
if (!kind) throw new CliError('Choose the entry file inside the ZIP with --entrypoint. No upload reservation was requested.');
|
|
318
|
+
const names = await archiveFileNames(archive, buildLimits(supplied));
|
|
319
|
+
const tops = new Set(names.map(name => name.split('/')[0]));
|
|
320
|
+
const wrapped = names.length > 0 && names.every(name => name.includes('/')) && tops.size === 1;
|
|
321
|
+
const base = wrapped ? `${[...tops][0]}/` : '';
|
|
322
|
+
const level = names.filter(name => name.startsWith(base) && !name.slice(base.length).includes('/'));
|
|
323
|
+
if (kind.preferred && level.includes(base + kind.preferred)) return { entrypoint: base + kind.preferred, reason: wrapped ? 'wrapped-folder' : 'root' };
|
|
324
|
+
const top = level.filter(kind.match);
|
|
325
|
+
if (top.length === 1) return { entrypoint: top[0], reason: wrapped ? 'wrapped-folder' : 'only-top-level' };
|
|
326
|
+
const every = top.length ? top : names.filter(kind.match).sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b));
|
|
327
|
+
if (every.length === 1) return { entrypoint: every[0], reason: 'only-one' };
|
|
328
|
+
if (!every.length && format === 'web' && nativeBuildKind(names)) reject(NATIVE_ADVICE[nativeBuildKind(names)]);
|
|
329
|
+
if (!every.length) throw new CliError(`No ${kind.noun} was found in the archive to start the game from. Check the ZIP holds the exported build, or name the entry file with --entrypoint. No upload reservation was requested.`);
|
|
330
|
+
const listed = every.slice(0, MAX_LISTED).join(', ') + (every.length > MAX_LISTED ? `, and ${every.length - MAX_LISTED} more` : '');
|
|
331
|
+
throw new CliError(`Several files could be the entry file: ${listed}. Choose one with --entrypoint. No upload reservation was requested.`);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** One plain sentence saying which entry file was chosen and why. */
|
|
335
|
+
export function entrypointChoiceLine({ entrypoint, reason }) {
|
|
336
|
+
const why = { root: 'found at the root of the archive', 'only-top-level': 'the only one at the top of the archive',
|
|
337
|
+
'wrapped-folder': 'inside the one folder that holds the build', 'only-one': 'the only one in the archive' }[reason];
|
|
338
|
+
return `Entry file: ${entrypoint}, ${why}. Pass --entrypoint to choose another.`;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export async function preflightBuildArchive(filename, options = {}) {
|
|
283
342
|
const archive = await openBuildArchive(filename, options);
|
|
284
|
-
try {
|
|
343
|
+
try {
|
|
344
|
+
if (options.entrypoint) return await inspectBuildArchive(archive, options);
|
|
345
|
+
const chosen = await chooseEntrypoint(archive, options);
|
|
346
|
+
return { ...await inspectBuildArchive(archive, { ...options, entrypoint: chosen.entrypoint }), entrypointChosen: chosen.reason };
|
|
347
|
+
} finally { await archive.close(); }
|
|
285
348
|
}
|
|
@@ -6,7 +6,7 @@ import { CliError } from '../errors.js';
|
|
|
6
6
|
import { ApiError } from '../api/errors.js';
|
|
7
7
|
import { writeJson } from '../fsutil.js';
|
|
8
8
|
import { printable } from '../ui/index.js';
|
|
9
|
-
import { openBuildArchive, inspectBuildArchive, buildLimits, limitsFromProfile } from './archivePreflight.js';
|
|
9
|
+
import { openBuildArchive, inspectBuildArchive, buildLimits, limitsFromProfile, chooseEntrypoint } from './archivePreflight.js';
|
|
10
10
|
|
|
11
11
|
const fail = message => { throw new CliError(message); };
|
|
12
12
|
const base = game => `/api/v1/games/${encodeURIComponent(game)}/playtest/hosted`;
|
|
@@ -102,11 +102,16 @@ export async function uploadHostedBuild({ filename, gameId, profileVersion, entr
|
|
|
102
102
|
const archive = await openBuildArchive(filename, { signal });
|
|
103
103
|
try {
|
|
104
104
|
onProgress({ phase: 'preflight' });
|
|
105
|
+
// No --entrypoint: an index.html at the root, or the only candidate, is
|
|
106
|
+
// used and said so; several candidates are listed, never guessed.
|
|
107
|
+
const chosen = entrypoint ? null : await chooseEntrypoint(archive, { limits, format: profile.format });
|
|
108
|
+
if (chosen) entrypoint = chosen.entrypoint;
|
|
105
109
|
const measurement = await inspectBuildArchive(archive, { limits, format: profile.format, entrypoint, requirements: profile.capacity?.requirements });
|
|
106
110
|
onProgress({ phase: 'hash', completedBytes: 0, totalBytes: archive.size });
|
|
107
111
|
const sha256 = await archive.sha256({ onProgress: (completedBytes, totalBytes) => onProgress({ phase: 'hash', completedBytes, totalBytes }) });
|
|
108
112
|
const prepared = { ...measurement, sha256, profileVersion, limits, capacity: profile.capacity || null,
|
|
109
|
-
validationHoldCents: offer.amountCents, funding: caps.funding || null, gameplayQuoteRequired: true
|
|
113
|
+
validationHoldCents: offer.amountCents, funding: caps.funding || null, gameplayQuoteRequired: true,
|
|
114
|
+
...(chosen ? { entrypointChosen: chosen.reason } : {}) };
|
|
110
115
|
await onPrepared(prepared);
|
|
111
116
|
if (dryRun) return { state: 'preflight_only', ...prepared, walletMutationRequested: false };
|
|
112
117
|
if (!await confirm(`Reserve ${money(offer.amountCents)} from prepaid funds for this build’s static validation? It is returned after safe cleanup and is separate from the gameplay quote.`)) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { mkdir, open, access, rename } from 'node:fs/promises';
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, open, access, rename, readFile, readdir, rm } from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { CliError, ExitCode } from '../errors.js';
|
|
5
5
|
import { ApiError } from '../api/errors.js';
|
|
@@ -7,6 +7,7 @@ import { stableStringify } from '../fsutil.js';
|
|
|
7
7
|
import { printable } from '../ui/index.js';
|
|
8
8
|
import { chooseProfile } from './buildUpload.js';
|
|
9
9
|
import { displayName } from '../run/controllers.js';
|
|
10
|
+
import { queueInfo } from './status.js';
|
|
10
11
|
|
|
11
12
|
const MAX_QUOTE_BYTES = 1024 * 1024;
|
|
12
13
|
const CONSENT_KEYS = ['quoteId', 'planHash', 'profileVersion', 'controllers', 'includeVideo', 'includeTranscript',
|
|
@@ -155,85 +156,286 @@ export function hostedQuoteLines(offer) {
|
|
|
155
156
|
`Quote expires ${new Date(q.expiresAt).toISOString()}.`];
|
|
156
157
|
}
|
|
157
158
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
159
|
+
const journalDir = repoRoot => path.join(repoRoot, '.ravensight', 'hosted-runs');
|
|
160
|
+
const journalFor = (repoRoot, { apiUrl, gameId, planHash }) => path.join(journalDir(repoRoot), `${digest({ apiUrl, gameId, planHash })}.json`);
|
|
161
|
+
const offerJournal = (repoRoot, offer) => journalFor(repoRoot, { apiUrl: offer.apiUrl, gameId: offer.gameId, planHash: offer.quote.planHash });
|
|
162
|
+
// The longest a server quote lives (recordedPlan QUOTE_MS). An older journal
|
|
163
|
+
// without the quote's own expiry is resolved after this much time.
|
|
164
|
+
const QUOTE_LIFETIME_MS = 300000;
|
|
165
|
+
const SERVER_CLOCK_MARGIN_MS = 15000;
|
|
166
|
+
|
|
167
|
+
async function readJournal(filename) {
|
|
168
|
+
try { return JSON.parse(await readFile(filename, 'utf8')); }
|
|
169
|
+
catch (error) { if (error.code === 'ENOENT') return null; return { unreadable: true }; }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Removes the intent and every response captured for it. Only called when the
|
|
173
|
+
// server said for certain that nothing was admitted. The idempotency key is
|
|
174
|
+
// derived from the plan, so a later attempt with the same quote sends the same
|
|
175
|
+
// key and the server still deduplicates it.
|
|
176
|
+
async function clearIntent(journal) {
|
|
177
|
+
const dir = path.dirname(journal), name = path.basename(journal);
|
|
178
|
+
let names = [];
|
|
179
|
+
try { names = await readdir(dir); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
180
|
+
await Promise.all(names.filter(row => row === name || row.startsWith(name + '.')).map(row => rm(path.join(dir, row), { force: true })));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// A saved durable intent whose outcome is unknown is never retried here; only
|
|
184
|
+
// "hosted status" asks the server about it. The server receives a stable key.
|
|
185
|
+
export async function runHostedQuote({ filename, api, apiUrl, repoRoot, confirm, onPrepared = () => {}, now = Date.now, admit = admitHostedOffer }) {
|
|
161
186
|
const offer = validateHostedOffer(await readHostedQuote(filename), apiUrl, now());
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
187
|
+
const journal = offerJournal(repoRoot, offer), prior = await readJournal(journal);
|
|
188
|
+
if (prior?.phase === 'charged_blocked' && admissionPattern.test(prior.admission?.admissionId || '')) {
|
|
189
|
+
fail(`This quote already started hosted run ${prior.admission.admissionId}. Check it with: ravensight-playtest hosted status ${prior.admission.admissionId}`);
|
|
190
|
+
}
|
|
191
|
+
if (prior) fail(`This quote's earlier admission has no known outcome yet (${journal}). Ask the server what happened with: ravensight-playtest hosted status. No request was repeated.`);
|
|
166
192
|
const { profile, funding } = await available(api, offer.gameId, offer.request.profileVersion, offer.request.standardProvider);
|
|
167
193
|
if (profile.driver !== offer.request.driver || funding?.eligible === false || offer.quote.funding?.eligible === false) fail('The server no longer advertises this profile or sufficient prepaid funding. Nothing was charged.');
|
|
168
194
|
await onPrepared(offer);
|
|
169
195
|
if (typeof confirm !== 'function') fail('The full hosted quote must be confirmed before admission.');
|
|
170
196
|
if (!await confirm(confirmQuestion(offer))) return { state: 'declined', walletMutationRequested: false };
|
|
171
|
-
return
|
|
197
|
+
return admit({ offer, api, apiUrl, repoRoot, now });
|
|
172
198
|
}
|
|
173
199
|
|
|
174
200
|
export const confirmQuestion = offer => `Pay ${money(offer.quote.dueNowCents)} now (${money(offer.quote.totalPriceCents)} total) for the quoted Geri then Freki runs and the evidence options shown?`;
|
|
175
201
|
|
|
176
|
-
// Refusals the server makes before any charge: the
|
|
177
|
-
//
|
|
178
|
-
// intent is
|
|
179
|
-
|
|
202
|
+
// Refusals the server makes with its own code, before any charge: the request
|
|
203
|
+
// failed inside the admission's transaction, which rolled back, or before it.
|
|
204
|
+
// These are certain, so the local intent is cleared and the same quote can be
|
|
205
|
+
// tried again. A 5xx or a status the server did not explain is not certain.
|
|
206
|
+
const CERTAIN_REFUSALS = new Set(['hosted_funding_required', 'quote_not_accepted', 'not_found',
|
|
180
207
|
'recorded_setup_required', 'hosted_global_capacity', 'too_many_active_hosted_runs', 'hosted_daily_capacity',
|
|
181
|
-
'hosted_build_too_large', 'hosted_build_safety_hold'
|
|
208
|
+
'hosted_build_too_large', 'hosted_build_safety_hold', 'quote_expired', 'recorded_quote_changed',
|
|
209
|
+
'hosted_game_unavailable', 'hosted_studio_unavailable']);
|
|
210
|
+
// Refused by the server with its own code, but a 5xx: reported plainly, intent kept for "hosted status".
|
|
211
|
+
const EXPLAINED_UNAVAILABLE = new Set(['recorded_unavailable', 'hosted_execution_budget_unconfigured']);
|
|
212
|
+
export const CAPACITY_CODES = Object.freeze(['hosted_global_capacity', 'too_many_active_hosted_runs']);
|
|
213
|
+
// The server keeps an attempt it refused under the plan's key and answers a
|
|
214
|
+
// repeat with this, so that quote cannot start a run. Nothing was charged.
|
|
215
|
+
export const REFUSED_EARLIER = 'hosted_quote_refused_earlier';
|
|
216
|
+
|
|
217
|
+
export const certainRefusal = error => error instanceof ApiError
|
|
218
|
+
&& (error.status === 401 || error.status >= 400 && error.status < 500 && CERTAIN_REFUSALS.has(error.code));
|
|
182
219
|
|
|
183
220
|
export function hostedRefusalMessage(error) {
|
|
184
221
|
const code = error?.code;
|
|
185
222
|
if (code === 'hosted_funding_required') {
|
|
186
223
|
const f = error.body?.funding;
|
|
187
224
|
const topUp = Number.isSafeInteger(f?.requiredTopUpCents) && f.requiredTopUpCents > 0 ? ` Add at least ${money(f.requiredTopUpCents)} of prepaid funds, then request a new quote.` : ' Add prepaid funds, then request a new quote.';
|
|
188
|
-
return `The server refused the run for funding.
|
|
225
|
+
return `The server refused the run for funding. No run was started and nothing was charged.${topUp}`;
|
|
189
226
|
}
|
|
190
227
|
if (code === 'quote_not_accepted') return 'The server did not accept this consent for the quote. Nothing was charged; request a new quote.';
|
|
191
|
-
if (
|
|
192
|
-
if (code === 'hosted_daily_capacity') return 'Today\'s hosted run allowance is used up.
|
|
228
|
+
if (CAPACITY_CODES.includes(code)) return 'Hosted capacity is busy, so no run was started and nothing was charged. Run the same command again with --wait-for-capacity to wait for room and start then; it never charges twice. Adding funds does not increase capacity.';
|
|
229
|
+
if (code === 'hosted_daily_capacity') return 'Today\'s hosted run allowance is used up. No run was started and nothing was charged. Try again after the daily limit resets at 00:00 UTC.';
|
|
193
230
|
if (code === 'recorded_setup_required') return `${error.message || 'Complete the playtest brief and choose an available persona.'} Nothing was charged.`;
|
|
194
231
|
if (code === 'not_found') return 'The quote is no longer available. Nothing was charged; request a new quote.';
|
|
232
|
+
if (code === 'quote_expired' || code === 'recorded_quote_changed') return 'The quote expired before the run was admitted. No run was started and nothing was charged; request a new quote.';
|
|
195
233
|
if (code === 'hosted_build_too_large') return 'This build is too large to play on a hosted machine: hosted playtests play builds up to 300 MiB unpacked. Make the build smaller and upload it again. Nothing was charged.';
|
|
196
234
|
if (code === 'hosted_build_safety_hold') return 'This build was stopped for safety during a hosted playtest and cannot run again until an admin reviews and clears it in the dashboard. Nothing was charged.';
|
|
235
|
+
if (code === REFUSED_EARLIER) return 'The server already refused an earlier attempt with this quote, so it will not start a run from it. No run was started and nothing was charged; request a new quote, or use "hosted run" without a quote file.';
|
|
197
236
|
return 'Hosted playtests are not available right now. Nothing was charged.';
|
|
198
237
|
}
|
|
199
238
|
|
|
200
|
-
|
|
201
|
-
|
|
239
|
+
const refusalError = (code, error = { code }) => Object.assign(new CliError(hostedRefusalMessage(error), ExitCode.ENVIRONMENT),
|
|
240
|
+
{ refusal: { code, certain: true, retryAfter: Number.isFinite(error.retryAfter) ? error.retryAfter : null } });
|
|
241
|
+
|
|
242
|
+
// What a 202 from POST /runs says: the acknowledgement of a new or replayed
|
|
243
|
+
// admission, the server's record that this key's attempt was refused, or an
|
|
244
|
+
// outcome the server itself cannot yet state.
|
|
245
|
+
function readAdmissionAnswer(answer, totalPriceCents) {
|
|
246
|
+
if (answer.status !== 202 || answer.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json'
|
|
247
|
+
|| typeof answer.body !== 'string' || Buffer.byteLength(answer.body) > MAX_QUOTE_BYTES) return { kind: 'unknown' };
|
|
248
|
+
let ack;
|
|
249
|
+
try { ack = JSON.parse(answer.body); } catch { return { kind: 'unknown' }; }
|
|
250
|
+
if (ack && same(ack, { state: 'failed', dispatchAllowed: false })) return { kind: 'refused_earlier' };
|
|
251
|
+
// A queued admission also carries its queue place; it is read through queueInfo, never trusted as money.
|
|
252
|
+
const keys = ack && typeof ack === 'object' ? Object.keys(ack).filter(key => key !== 'queue').sort() : [];
|
|
253
|
+
if (Object.hasOwn(ack || {}, 'queue') && !queueInfo(ack)) return { kind: 'unknown' };
|
|
254
|
+
if (!ack || !same(keys, ['admissionId', 'dispatchAllowed', 'jobId', 'state', 'totalPriceCents'])
|
|
255
|
+
|| ack.state !== 'charged_blocked' || ack.dispatchAllowed !== false || ack.totalPriceCents !== totalPriceCents
|
|
256
|
+
|| !admissionPattern.test(ack.admissionId || '') || !/^pt_job_[a-f0-9]{20}$/.test(ack.jobId || '')) return { kind: 'unknown' };
|
|
257
|
+
return { kind: 'admitted', ack };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function postAdmission(api, { gameId, consent, idempotencyKey }, captureFile) {
|
|
261
|
+
let responseCaptured = false;
|
|
262
|
+
const answer = await api.request('POST', `${base(gameId)}/runs`, { body: consent,
|
|
263
|
+
headers: { 'Idempotency-Key': idempotencyKey }, idempotent: false, raw: true,
|
|
264
|
+
onResponseRaw: async ({ status, contentType, bytes, bodyComplete }) => {
|
|
265
|
+
await exclusiveJson(captureFile, { status, contentType, bodyComplete,
|
|
266
|
+
bodyBase64: bytes.toString('base64'), bodyBytes: bytes.length,
|
|
267
|
+
bodySha256: createHash('sha256').update(bytes).digest('hex') });
|
|
268
|
+
responseCaptured = true;
|
|
269
|
+
} });
|
|
270
|
+
return responseCaptured ? answer : null;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async function recordAdmitted(journal, state, ack) {
|
|
274
|
+
state.phase = 'charged_blocked'; state.admission = ack; state.resolvedAt = new Date().toISOString();
|
|
275
|
+
await rm(journal + '.acknowledged.json', { force: true });
|
|
276
|
+
await exclusiveJson(journal + '.acknowledged.json', state);
|
|
277
|
+
await rename(journal + '.acknowledged.json', journal);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// The journal is fsynced before the only wallet-mutating POST and the server
|
|
281
|
+
// receives a stable key for the plan. A certain refusal clears the journal;
|
|
282
|
+
// anything else keeps it as admission_unknown for "hosted status" to resolve.
|
|
202
283
|
export async function admitHostedOffer({ offer, api, apiUrl, repoRoot, now = Date.now }) {
|
|
203
284
|
validateHostedOffer(offer, apiUrl, now());
|
|
204
|
-
const
|
|
205
|
-
const journal = path.join(repoRoot, '.ravensight', 'hosted-runs', `${identity}.json`);
|
|
285
|
+
const journal = offerJournal(repoRoot, offer);
|
|
206
286
|
const state = { schema: 'ravensight-hosted-admission-journal/v1', apiUrl: offer.apiUrl, gameId: offer.gameId,
|
|
207
287
|
quoteId: offer.quote.quoteId, planHash: offer.quote.planHash, consent: offer.consent,
|
|
208
|
-
idempotencyKey: `hosted-${offer.quote.planHash}`,
|
|
288
|
+
idempotencyKey: `hosted-${offer.quote.planHash}`, quoteExpiresAt: offer.quote.expiresAt,
|
|
289
|
+
phase: 'admission_unknown', createdAt: new Date(now()).toISOString() };
|
|
209
290
|
await exclusiveJson(journal, state); // fsync BEFORE the only wallet-mutating POST
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
291
|
+
let answer;
|
|
292
|
+
try { answer = await postAdmission(api, state, journal + '.response.json'); }
|
|
293
|
+
catch (error) {
|
|
294
|
+
if (certainRefusal(error)) {
|
|
295
|
+
await clearIntent(journal);
|
|
296
|
+
if (error.status === 401) throw error;
|
|
297
|
+
throw refusalError(error.code, error);
|
|
298
|
+
}
|
|
299
|
+
if (error instanceof ApiError && EXPLAINED_UNAVAILABLE.has(error.code)) {
|
|
300
|
+
throw new CliError(`${hostedRefusalMessage(error)} To confirm and free this quote, run: ravensight-playtest hosted status`, ExitCode.ENVIRONMENT);
|
|
301
|
+
}
|
|
302
|
+
fail(`The admission's outcome is not known: ${unknownAdvice(journal)}`);
|
|
303
|
+
}
|
|
304
|
+
const read = answer ? readAdmissionAnswer(answer, offer.quote.totalPriceCents) : { kind: 'unknown' };
|
|
305
|
+
if (read.kind === 'refused_earlier') { await clearIntent(journal); throw refusalError(REFUSED_EARLIER); }
|
|
306
|
+
if (read.kind !== 'admitted') fail(`The admission acknowledgement needs reconciliation: ${unknownAdvice(journal)}`);
|
|
307
|
+
await recordAdmitted(journal, state, read.ack);
|
|
308
|
+
return { state: 'charged_blocked', ...read.ack, queue: queueInfo(read.ack), journal, replayAuthorized: false, gameplayProven: false };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const unknownAdvice = journal => `the run may or may not have started. Preserve ${journal}; nothing was retried. Ask the server what happened with: ravensight-playtest hosted status`;
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Settle every saved admission intent whose outcome is unknown by asking the
|
|
315
|
+
* server, which answers from its own record under the same idempotency key.
|
|
316
|
+
* The question is only sent once the quote has expired, so it can report an
|
|
317
|
+
* admission but never start one. A certain answer that nothing was admitted
|
|
318
|
+
* clears the intent; an admission is recorded; anything else is kept.
|
|
319
|
+
*/
|
|
320
|
+
export async function resolveHostedIntents({ api, apiUrl, repoRoot, now = Date.now }) {
|
|
321
|
+
const dir = journalDir(repoRoot), here = origin(apiUrl), results = [];
|
|
322
|
+
let names = [];
|
|
323
|
+
try { names = (await readdir(dir)).filter(name => /^[a-f0-9]{64}\.json$/.test(name)).sort(); }
|
|
324
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
325
|
+
for (const name of names) {
|
|
326
|
+
const journal = path.join(dir, name), state = await readJournal(journal);
|
|
327
|
+
if (!state || state.phase !== 'admission_unknown') continue;
|
|
328
|
+
if (state.unreadable || state.schema !== 'ravensight-hosted-admission-journal/v1' || !id(state.gameId) || !hex(state.planHash)
|
|
329
|
+
|| state.idempotencyKey !== `hosted-${state.planHash}` || !state.consent || typeof state.consent !== 'object'
|
|
330
|
+
|| journalFor(repoRoot, state) !== journal) {
|
|
331
|
+
results.push({ journal, state: 'unreadable', message: `${journal} is not a hosted admission record this version can read. Nothing was sent.` });
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (state.apiUrl !== here) {
|
|
335
|
+
results.push({ journal, gameId: state.gameId, state: 'other_api', message: `${journal} belongs to ${state.apiUrl}. Run this with --api-url ${state.apiUrl} to resolve it.` });
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
const created = Date.parse(state.createdAt);
|
|
339
|
+
const expiresAt = Number.isSafeInteger(state.quoteExpiresAt) ? state.quoteExpiresAt : (Number.isFinite(created) ? created + QUOTE_LIFETIME_MS : null);
|
|
340
|
+
const askAt = expiresAt === null ? null : expiresAt + SERVER_CLOCK_MARGIN_MS;
|
|
341
|
+
if (askAt === null || now() < askAt) {
|
|
342
|
+
results.push({ journal, gameId: state.gameId, state: 'wait', askAt,
|
|
343
|
+
message: askAt === null ? `${journal} has no readable time. Nothing was sent.`
|
|
344
|
+
: `Game ${state.gameId}: asking before ${new Date(askAt).toISOString()} could still start the run, so nothing was sent. Run "hosted status" again after that time.` });
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
let answer;
|
|
348
|
+
try { answer = await postAdmission(api, state, `${journal}.reconcile-${now()}-${randomUUID().slice(0, 8)}.json`); }
|
|
349
|
+
catch (error) {
|
|
350
|
+
if (certainRefusal(error) && error.status !== 401) {
|
|
351
|
+
await clearIntent(journal);
|
|
352
|
+
results.push({ journal, gameId: state.gameId, state: 'not_admitted', code: error.code,
|
|
353
|
+
message: `Game ${state.gameId}: the server has no run for this quote. No run was started and nothing was charged. The record is cleared.` });
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
if (error instanceof ApiError && error.status === 401) throw error;
|
|
357
|
+
results.push({ journal, gameId: state.gameId, state: 'unknown', message: `Game ${state.gameId}: the server did not answer clearly (${error.code || error.message}). The record is kept; try again later.` });
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
const read = answer ? readAdmissionAnswer(answer, state.consent.totalPriceCents) : { kind: 'unknown' };
|
|
361
|
+
if (read.kind === 'refused_earlier') {
|
|
362
|
+
await clearIntent(journal);
|
|
363
|
+
results.push({ journal, gameId: state.gameId, state: 'not_admitted', code: REFUSED_EARLIER,
|
|
364
|
+
message: `Game ${state.gameId}: the server refused that attempt. No run was started and nothing was charged. The record is cleared.` });
|
|
365
|
+
} else if (read.kind === 'admitted') {
|
|
366
|
+
await recordAdmitted(journal, state, read.ack);
|
|
367
|
+
results.push({ journal, gameId: state.gameId, state: 'admitted', admissionId: read.ack.admissionId, jobId: read.ack.jobId,
|
|
368
|
+
totalPriceCents: read.ack.totalPriceCents, message: `Game ${state.gameId}: the run was admitted as ${read.ack.admissionId} and charged ${money(read.ack.totalPriceCents)}.` });
|
|
369
|
+
} else {
|
|
370
|
+
results.push({ journal, gameId: state.gameId, state: 'unknown',
|
|
371
|
+
message: `Game ${state.gameId}: the server cannot state the outcome yet. The record is kept; nothing was retried. If this persists, write to support@realityse.com with ${path.basename(journal)}.` });
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return results;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// The terms a person accepted. A fresh quote taken while waiting for capacity
|
|
378
|
+
// must match them exactly, or nothing is admitted without asking again.
|
|
379
|
+
const TERMS = ['buildId', 'profileVersion', 'driver', 'controllers', 'includeVideo', 'includeTranscript', 'currency',
|
|
380
|
+
'localPriceCents', 'computePriceCents', 'totalPriceCents', 'dueNowCents', 'alreadyReservedCents', 'localBreakdown',
|
|
381
|
+
'computeBreakdown', 'priceVersion', 'policyVersion', 'customerFailure', 'cancelAfterStart', 'standardProvider',
|
|
382
|
+
'standardProviderPolicyHash'];
|
|
383
|
+
const sameTerms = (a, b) => TERMS.every(key => same(a[key] ?? null, b[key] ?? null));
|
|
384
|
+
|
|
385
|
+
/** A fresh quote for exactly the request of an accepted offer. Charges nothing. */
|
|
386
|
+
export async function requoteOffer({ api, apiUrl, offer, now = Date.now }) {
|
|
387
|
+
const { profile, funding } = await available(api, offer.gameId, offer.request.profileVersion, offer.request.standardProvider);
|
|
388
|
+
if (profile.driver !== offer.request.driver) fail('The server no longer advertises this build profile. No run was started and nothing was charged.');
|
|
389
|
+
const response = await api.request('POST', `${base(offer.gameId)}/quotes`, { body: offer.request, idempotent: false });
|
|
390
|
+
if (response.status !== 200) fail('The server did not return a hosted quote. No run was started and nothing was charged.');
|
|
391
|
+
const quote = response.body, consent = hostedConsent(quote, offer.request, now());
|
|
392
|
+
if (fundingShortfall(quote, funding)) fail('The balance no longer meets this hosted run\'s funding requirement. No run was started and nothing was charged. Add prepaid funds, then run the command again.');
|
|
393
|
+
if (!sameTerms(offer.quote, quote)) fail(`The price or terms changed while waiting for capacity, so no run was started and nothing was charged. Run the command again to see the new quote (it was ${money(offer.quote.totalPriceCents)}, now ${money(quote.totalPriceCents)}).`);
|
|
394
|
+
const value = { apiUrl: origin(apiUrl), gameId: offer.gameId, request: offer.request, quote, consent };
|
|
395
|
+
return { schema: 'ravensight-hosted-recorded-quote/v1', ...value, integrity: digest(value) };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export const CAPACITY_POLL_MS = 60000;
|
|
399
|
+
export const CAPACITY_JITTER_MS = 30000;
|
|
400
|
+
const CAPACITY_RETRY_AFTER_MAX_MS = 15 * 60000;
|
|
401
|
+
|
|
402
|
+
/** The wait before asking again: at least a minute, longer if the server says so, plus jitter. */
|
|
403
|
+
export function capacityDelay(error, random = Math.random) {
|
|
404
|
+
const server = Number.isFinite(error?.retryAfter) && error.retryAfter > 0 ? Math.min(error.retryAfter * 1000, CAPACITY_RETRY_AFTER_MAX_MS) : 0;
|
|
405
|
+
return Math.max(CAPACITY_POLL_MS, server) + Math.floor(random() * CAPACITY_JITTER_MS);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Admit an accepted offer, and while the server answers that hosted capacity
|
|
410
|
+
* is busy, ask again about once a minute until there is room or maxWaitMs
|
|
411
|
+
* passes. Every busy answer is a certain refusal that charged nothing and
|
|
412
|
+
* cleared its intent; any other outcome ends the wait, so an unknown outcome
|
|
413
|
+
* is never retried. Quotes last minutes, so each new attempt takes a fresh
|
|
414
|
+
* quote and refuses unless its terms equal the accepted ones exactly.
|
|
415
|
+
*/
|
|
416
|
+
export async function admitWithCapacityWait({ offer, api, apiUrl, repoRoot, maxWaitMs, now = Date.now,
|
|
417
|
+
sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), random = Math.random, onBusy = () => {}, onRequote = () => {} }) {
|
|
418
|
+
if (!Number.isSafeInteger(maxWaitMs) || maxWaitMs < 1) fail('Choose how long to wait for capacity.');
|
|
419
|
+
const started = now(), deadline = started + maxWaitMs;
|
|
420
|
+
let current = offer, requoteNext = false, busy = 0;
|
|
421
|
+
for (;;) {
|
|
422
|
+
if (requoteNext) { current = await requoteOffer({ api, apiUrl, offer, now }); onRequote(current); }
|
|
423
|
+
try { return { ...await admitHostedOffer({ offer: current, api, apiUrl, repoRoot, now }), offer: current, busyAnswers: busy }; }
|
|
424
|
+
catch (error) {
|
|
425
|
+
const code = error?.refusal?.code;
|
|
426
|
+
// The server will not admit this quote again: take a fresh one straight away, once.
|
|
427
|
+
if (!requoteNext && [REFUSED_EARLIER, 'quote_expired', 'recorded_quote_changed'].includes(code)) { requoteNext = true; continue; }
|
|
428
|
+
if (!CAPACITY_CODES.includes(code)) throw error;
|
|
429
|
+
busy += 1;
|
|
430
|
+
const delay = capacityDelay(error.refusal, random);
|
|
431
|
+
if (now() + delay > deadline) {
|
|
432
|
+
const waited = Math.max(1, Math.round((now() - started) / 60000));
|
|
433
|
+
throw Object.assign(new CliError(`Hosted capacity stayed busy for ${waited} minute${waited === 1 ? '' : 's'}, so no run was started and nothing was charged. Run the command again later, or with a longer --wait-for-capacity.`, ExitCode.ENVIRONMENT), { refusal: error.refusal });
|
|
434
|
+
}
|
|
435
|
+
onBusy({ attempt: busy, delayMs: delay, waitedMs: now() - started, maxWaitMs });
|
|
436
|
+
await sleep(delay);
|
|
437
|
+
requoteNext = true;
|
|
235
438
|
}
|
|
236
|
-
fail(`The original admission outcome needs reconciliation. Preserve ${journal}; no retry or replacement admission was requested.`);
|
|
237
439
|
}
|
|
238
440
|
}
|
|
239
441
|
|
package/src/hosted/status.js
CHANGED
|
@@ -107,3 +107,24 @@ export function modeLine(row) {
|
|
|
107
107
|
if (row.reason) parts.push(row.reason);
|
|
108
108
|
return `${row.name}: ${parts.join(', ')}.`;
|
|
109
109
|
}
|
|
110
|
+
|
|
111
|
+
// The server's FIFO queue for hosted runs (game_tracker fix/hosted-capacity-and-reaper).
|
|
112
|
+
// ASSUMED field names, read in this one place until that branch's contract lands:
|
|
113
|
+
// `queue: { position: <whole number, 1 is next>, estimatedStartAt: <ISO time or null> }`
|
|
114
|
+
// on the admission acknowledgement and on GET /hosted/runs/:admissionId.
|
|
115
|
+
// Position 0, or an estimate already past, reads as starting now.
|
|
116
|
+
export function queueInfo(source) {
|
|
117
|
+
const q = source?.queue;
|
|
118
|
+
if (!q || typeof q !== 'object' || !Number.isSafeInteger(q.position) || q.position < 0) return null;
|
|
119
|
+
const at = typeof q.estimatedStartAt === 'string' ? Date.parse(q.estimatedStartAt) : NaN;
|
|
120
|
+
return { position: q.position, estimatedStartAt: Number.isFinite(at) ? new Date(at).toISOString() : null };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** "Queued, position 2, expected to start in about 14 minutes." or "Queued, starting now." */
|
|
124
|
+
export function queueLine(queue, now = Date.now()) {
|
|
125
|
+
if (!queue) return null;
|
|
126
|
+
const minutes = queue.estimatedStartAt === null ? null : Math.ceil((Date.parse(queue.estimatedStartAt) - Number(now)) / 60000);
|
|
127
|
+
if (queue.position === 0 || minutes !== null && minutes <= 0) return 'Queued, starting now.';
|
|
128
|
+
const eta = minutes === null ? '' : `, expected to start in about ${minutes} minute${minutes === 1 ? '' : 's'}`;
|
|
129
|
+
return `Queued, position ${queue.position}${eta}.`;
|
|
130
|
+
}
|