Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/submit-records-submission.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@reactivapp/cli': minor
---

`reactiv app submit` now records the published version with Reactiv and shows where to follow it.

After the publish, the CLI sends the version to Reactiv, which records it as a submission. The receipt keeps its seven lines and adds two: `submission <id>` and `dashboard <link>`, the submission's page in the Reactiv Dashboard; the link is printed once more on a line of its own so it can be opened in one piece. A network or server error is tried three times in all; a refusal is not retried.

If the version cannot be recorded, it stays published and the CLI does not publish it again: it prints why, the version and `reactiv app submit --record <version>` on a line of its own, and exits with an error. The new `--record <version>` flag checks that it was given a draft version and then sends only that record call, with no checks, pack or publish, so it can be run once the cause is fixed.
4 changes: 4 additions & 0 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,19 @@ Validates and packs the library at the project root and publishes it as a draft

```
reactiv app submit [--dry-run] [--max-size-mb <n>]
reactiv app submit --record <version>
```

| Flag | Effect |
| --- | --- |
| `--dry-run` | Run every check and pack the library, but publish nothing. The token service and the registry are still contacted, and the project's `.npmrc` token may be refreshed. |
| `--max-size-mb` | Maximum unpacked size in MB. Default 5. |
| `--record <version>` | Record a version that is already published as a submission, and do nothing else: no checks, no pack, no publish. Use the version and command a failed submit printed; a value that is not a draft version (`<x.y.z>-draft.<N>`) is refused before anything is sent. Cannot be combined with `--dry-run`; `--max-size-mb` has no effect with it. |

The checks are listed in [Project layout](project-layout.md#what-reactiv-app-submit-checks). The local ones run first; the CLI then contacts Reactiv's token service for a registry token and the submissions registry for the next draft version, scans the staged copy for credentials, packs `src/` and a generated `package.json` into a tarball, verifies the tarball's contents, and publishes it as `@reactiv-submissions/<slug>@<x.y.z>-draft.<N>` with the dist-tag `draft`. The receipt shows the version, the review-cycle base version, the app UUID, the declared dependencies, the registry and the tarball's sha256.

After the publish the CLI records the version with Reactiv as a submission, sending only the version; Reactiv works out the store from your API key. The receipt then ends with two more lines: `submission <id>` and `dashboard <link>`, the submission's page in the Reactiv Dashboard. The link is printed once more on a line of its own below the receipt, so it can be opened or copied in one piece. A network error or a server error is tried three times in all, one and then two seconds apart; a refusal, including "too many submissions", is not retried. If recording still fails, the published version is kept and the CLI does not publish it again: it prints why, the version, and `reactiv app submit --record <version>` on a line of its own, and exits with an error. Run that command once the cause is fixed. Recording the same version twice is harmless, because Reactiv records each version of a store only once. When `--record` itself fails, it offers to run the same command again only if the failure can pass (Reactiv unreachable, too many submissions, or Reactiv not finding or not answering the record request); a refusal such as a revoked key needs its cause fixed first.

## Environment variables

| Variable | Effect |
Expand Down
4 changes: 4 additions & 0 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ Another Metro is running on this machine. Stop it, then run `reactiv app run ios

Try again in a few minutes. When the service answered, the message includes a request id; include it when you report the problem.

## `Version … is published but not recorded`

`reactiv app submit` published your version, but Reactiv did not record it as a submission, so it does not appear in the Dashboard yet. The first line says why: Reactiv could not be reached (try again in a few minutes), too many submissions (try again later), or a refusal such as a revoked or expired key (fix that first, for example with `reactiv login`). Then run the command the CLI printed on a line of its own, `reactiv app submit --record <version>`. It sends only the record call; it does not pack or publish again, so the version Reactiv reviews is the one already published. Do not run a plain `reactiv app submit` instead: that publishes a new draft version.

## `Reactiv's token service no longer serves this CLI's API version`

Update the CLI: `npm install -g @reactivapp/cli@latest`.
Expand Down
60 changes: 58 additions & 2 deletions packages/cli/src/commands/app/submit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import * as path from 'node:path'

import {createAuthContext, reportAuthError} from '../../lib/auth/context.js'
import {SUBMISSIONS_SCOPE} from '../../lib/auth/npmrc.js'
import {ensureRegistryAuth, refreshAfterRegistryAuthError, type RegistryAuth, takeRegistryRetry} from '../../lib/auth/token.js'
import type {SubmitResponse} from '../../lib/auth/contract/submit.js'
import {type AuthContext, ensureRegistryAuth, refreshAfterRegistryAuthError, type RegistryAuth, takeRegistryRetry} from '../../lib/auth/token.js'
import {describeRecordFailure, isRetryable, publishedNotRecorded, recordCommand, recordSubmission} from '../../lib/devtools-submit.js'
import {assertImportsDeclared, type DeclaredPackages, readDeclaredPackages} from '../../lib/imports.js'
import {
assertDependenciesInSync,
Expand All @@ -18,6 +20,7 @@ import {
} from '../../lib/layout.js'
import {assertNoAppNativeIntegration} from '../../lib/native-integration.js'
import {capture, captureAll, isRegistryAuthError, NPM_LOGLEVEL, npmEnv, runTee} from '../../lib/npm.js'
import {sanitizeForOutput} from '../../lib/auth/errors.js'
import {loadProjectIdentity, type ProjectIdentity} from '../../lib/project.js'
import {findSecretsInDirectory, formatSecretFindings} from '../../lib/secret-scan.js'
import {
Expand All @@ -28,6 +31,7 @@ import {
assertTarballContents,
checkSizeCap,
computeSha256,
DRAFT_VERSION_PATTERN,
draftBaseVersion,
findEntryInTarball,
findForbiddenPaths,
Expand Down Expand Up @@ -56,11 +60,17 @@ export class AppSubmit extends Command {
static override flags = {
'max-size-mb': Flags.integer({description: 'maximum unpacked size in MB', default: DEFAULT_SIZE_CAP_MB, min: 1}),
'dry-run': Flags.boolean({description: 'run everything including pack but skip the actual publish', default: false}),
record: Flags.string({
description: 'record an already published version as a submission, without packing or publishing again',
helpValue: '<version>',
exclusive: ['dry-run'],
}),
}

async run(): Promise<void> {
const {renderSuccess, renderInfo} = await import('@reactivapp/cli-ui')
const {flags} = await this.parse(AppSubmit)
if (flags.record !== undefined) return this.recordOnly(flags.record)
const projectRoot = process.cwd()

if (!fs.existsSync(path.join(projectRoot, 'reactiv.conf.js'))) {
Expand Down Expand Up @@ -250,14 +260,60 @@ export class AppSubmit extends Command {
this.error(`the registry rejected the publish — npm publish exited with ${publish.status}`)
}

// The version is published from here on: a failure below never publishes again.
let record: SubmitResponse
try {
record = await this.record(ctx, version)
} catch (error) {
const reason = await describeRecordFailure(ctx, error)
const {renderWarning} = await import('@reactivapp/cli-ui')
renderWarning({headline: 'Submission published, not recorded', body: receipt})
this.fail([reason, publishedNotRecorded(version), ` ${recordCommand(version)}`])
}

renderSuccess({
headline: 'Submission published',
body: receipt,
body: [...receipt, ...recordLines(record)],
})
this.log(sanitizeForOutput(record.dashboardUrl))
} catch (error) {
reportAuthError(this, error)
} finally {
fs.rmSync(stagingDir, {recursive: true, force: true})
}
}

private async record(ctx: AuthContext, version: string): Promise<SubmitResponse> {
this.log('Recording the submission with Reactiv…')
return recordSubmission(ctx, version)
}

// Plain lines: oclif's error gutter would wrap the command to run.
private fail(lines: string[]): never {
for (const line of lines) this.logToStderr(line)
return this.exit(2)
}

private async recordOnly(version: string): Promise<void> {
if (!DRAFT_VERSION_PATTERN.test(version)) {
this.error(`--record takes the version a failed submit printed, such as 0.1.8-draft.2; "${sanitizeForOutput(version)}" is not one.`)
}
const {renderSuccess} = await import('@reactivapp/cli-ui')
const ctx = createAuthContext(this)
let record: SubmitResponse
try {
record = await this.record(ctx, version)
} catch (error) {
const reason = await describeRecordFailure(ctx, error)
// A refusal (a 4xx other than 429) is not fixed by running the same call again.
this.fail(isRetryable(error) ? [reason, 'Then run:', ` ${recordCommand(version)}`] : [reason])
}
renderSuccess({headline: 'Submission recorded', body: recordLines(record)})
this.log(sanitizeForOutput(record.dashboardUrl))
}
}

const recordLines = (record: SubmitResponse): string[] => [
`submission ${sanitizeForOutput(record.submissionId)}`,
`dashboard ${sanitizeForOutput(record.dashboardUrl)}`,
]
12 changes: 12 additions & 0 deletions packages/cli/src/lib/auth/contract/submit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Wire types of POST /v1/submissions; responses are wrapped in {data}. Update
// this copy in the same change as the service's published submissions contract.

export interface SubmitRequest {
version: string
}

export interface SubmitResponse {
submissionId: string
status: string
dashboardUrl: string
}
2 changes: 1 addition & 1 deletion packages/cli/src/lib/auth/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const vendingUnreachable = (requestId: string | undefined, cachedTokenExp
export const registryRefreshFailed = (vendingMessage: string): string =>
`Registry token could not be refreshed: ${vendingMessage}`

const withRequestId = (message: string, requestId: string | undefined): string =>
export const withRequestId = (message: string, requestId: string | undefined): string =>
requestId ? `${message}\nRequest id: ${sanitizeForOutput(requestId)}` : message

export const describeVendingError = (error: VendingError, cachedTokenExpiresAt?: string): string => {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/lib/auth/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ const deleteFileLogin = async (ctx: AuthContext, keyId: string): Promise<void> =
}, ctx.lockOptions)
}

const vendingFailure = async (ctx: AuthContext, identity: Identity | undefined, error: unknown): Promise<never> => {
export const vendingFailure = async (ctx: AuthContext, identity: Identity | undefined, error: unknown): Promise<never> => {
if (!(error instanceof VendingError)) throw error
if ((error.code === 'key_revoked' || error.code === 'key_expired') && identity?.source === 'file') {
await deleteFileLogin(ctx, identity.keyId)
Expand Down
20 changes: 18 additions & 2 deletions packages/cli/src/lib/auth/vending-client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type {ApiKey} from './credentials'
import type {ErrorCode, ErrorResponse, MeResponse, TermsAcceptRequest, TermsAcceptResponse, TermsResponse, TokenResponse} from './contract'
import type {SubmitRequest, SubmitResponse} from './contract/submit'
import {AuthError} from './errors'

export const DEFAULT_VENDING_API_URL = 'https://plus-devtools-staging.dev.reactivapp.com'
Expand Down Expand Up @@ -71,6 +72,7 @@ export interface VendingClient {
terms(): Promise<TermsResponse>
acceptTerms(key: ApiKey, request: TermsAcceptRequest): Promise<TermsAcceptResponse>
mint(key: ApiKey): Promise<TokenResponse>
submit(key: ApiKey, request: SubmitRequest): Promise<{data: SubmitResponse}>
}

export interface VendingClientOptions {
Expand Down Expand Up @@ -130,6 +132,9 @@ export const isErrorResponse = (value: unknown): value is Pick<ErrorResponse, 'c
(value.requestId === undefined || isString(value.requestId)) &&
(value.details === undefined || isRecord(value.details))

export const isSubmitEnvelope: Guard<{data: SubmitResponse}> = (value): value is {data: SubmitResponse} =>
isRecord(value) && isRecord(value.data) && isString(value.data.submissionId) && isString(value.data.dashboardUrl)

const parseJson = (text: string): unknown => {
try {
return JSON.parse(text) as unknown
Expand Down Expand Up @@ -168,7 +173,15 @@ export const createVendingClient = (options: VendingClientOptions): VendingClien
const timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS
const userAgent = `reactiv-cli/${options.cliVersion} (${options.platform ?? process.platform})`

const call = async <T>(method: 'GET' | 'POST', path: string, guard: Guard<T>, key?: ApiKey, body?: unknown): Promise<T> => {
// waitOnRateLimit false: a 429 fails at once.
const call = async <T>(
method: 'GET' | 'POST',
path: string,
guard: Guard<T>,
key?: ApiKey,
body?: unknown,
{waitOnRateLimit = true}: {waitOnRateLimit?: boolean} = {},
): Promise<T> => {
const headers: Record<string, string> = {'User-Agent': userAgent, Accept: 'application/json'}
if (key) headers.Authorization = `Bearer ${key.reveal()}`
if (body !== undefined) headers['Content-Type'] = 'application/json'
Expand Down Expand Up @@ -214,7 +227,7 @@ export const createVendingClient = (options: VendingClientOptions): VendingClien
const retryAfter = parseRetryAfter(retryAfterHeader, now())
const waitSeconds = retryAfter ?? FALLBACK_RATE_LIMIT_WAIT_S
// Beyond setTimeout's range the timer would fire at once instead of waiting.
if (!rateLimitRetried && waitSeconds * 1000 <= MAX_TIMER_MS) {
if (waitOnRateLimit && !rateLimitRetried && waitSeconds * 1000 <= MAX_TIMER_MS) {
rateLimitRetried = true
options.onWait?.(`Reactiv's token service is rate limiting; retrying in ${waitSeconds} s.`)
await sleep(waitSeconds * 1000)
Expand Down Expand Up @@ -250,5 +263,8 @@ export const createVendingClient = (options: VendingClientOptions): VendingClien
terms: () => call('GET', '/v1/terms', isTermsResponse),
acceptTerms: (key, request) => call('POST', '/v1/terms/accept', isTermsAcceptResponse, key, request),
mint: key => call('POST', '/v1/tokens', isTokenResponse, key),
// Submits are limited per hour and a published version can be recorded later, so a 429 is not waited out.
submit: (key, request) =>
call('POST', '/v1/submissions', isSubmitEnvelope, key, request, {waitOnRateLimit: false}),
}
}
52 changes: 52 additions & 0 deletions packages/cli/src/lib/devtools-submit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type {SubmitResponse} from './auth/contract/submit'
import {AuthError, sanitizeForOutput} from './auth/errors'
import {withRequestId} from './auth/messages'
import {type AuthContext, resolveIdentity, vendingFailure} from './auth/token'
import {VendingError} from './auth/vending-client'

export const recordSubmission = async (ctx: AuthContext, version: string): Promise<SubmitResponse> => {
const identity = await resolveIdentity(ctx)
return (await ctx.vending.submit(identity.apiKey, {version})).data
}

// The submissions route answered 404, or answered 2xx without a submission.
const isUnservedRecord = (error: VendingError): boolean =>
error.kind === 'api' && (error.code === 'not_found' || error.status === 404 || (error.status !== undefined && error.status < 300))

/** True when running the same record call again later can succeed. */
export const isRetryable = (error: unknown): boolean =>
error instanceof VendingError && (error.kind === 'unreachable' || error.kind === 'rate_limited' || isUnservedRecord(error))

/**
* The reason to print for a failed record call. Key and store refusals get the
* same text and stored-login cleanup as every other call. The cases where that
* text would speak of the token service, the token cache or updating the CLI
* have their own sentence here.
*/
export const describeRecordFailure = async (ctx: AuthContext, error: unknown): Promise<string> => {
if (error instanceof VendingError && error.kind === 'rate_limited') {
return withRequestId('Too many submissions — try again later.', error.requestId)
}
if (error instanceof VendingError && error.kind === 'unreachable') {
return withRequestId('Reactiv could not be reached to record the submission.', error.requestId)
}
if (error instanceof VendingError && isUnservedRecord(error)) {
const sentence =
error.status === 404 || error.code === 'not_found'
? 'Reactiv could not find the submissions service (HTTP 404). Contact Reactiv if this continues.'
: `Reactiv's answer did not contain the submission (HTTP ${error.status}). Contact Reactiv if this continues.`
return withRequestId(sentence, error.requestId)
}
try {
await vendingFailure(ctx, ctx.memo?.identity, error)
} catch (failure) {
if (failure instanceof AuthError) return failure.message
if (failure instanceof Error) return `The submission could not be recorded: ${sanitizeForOutput(failure.message)}`
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return 'The submission could not be recorded.'
}

export const recordCommand = (version: string): string => `reactiv app submit --record ${sanitizeForOutput(version)}`

export const publishedNotRecorded = (version: string): string =>
`Version ${sanitizeForOutput(version)} is published but not recorded. Once the cause is fixed, record it without publishing again:`
Loading
Loading