Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(cli): improve error message in case sanity telemetry enable fails #5416

Merged
merged 1 commit into from
Dec 21, 2023
Merged
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
106 changes: 16 additions & 90 deletions packages/@sanity/cli/src/actions/telemetry/setTelemetryConsent.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import {type ConsentStatus} from '@sanity/telemetry'
import {ClientError, ServerError} from '@sanity/client'
import {type CliCommandAction} from '../../types'
import {debug} from '../../debug'
import {getUserConfig} from '../../util/getUserConfig'
import {
ConsentInformation,
TELEMETRY_CONSENT_CONFIG_KEY,
resolveConsent,
TELEMETRY_CONSENT_CONFIG_KEY,
} from '../../util/createTelemetryStore'
import {
telemetryLearnMoreMessage,
Expand All @@ -15,17 +14,6 @@ import {

type SettableConsentStatus = Extract<ConsentStatus, 'granted' | 'denied'>

const MOCK_MODES = ['success', 'failure:server', 'failure:msa'] as const
type MockMode = (typeof MOCK_MODES)[number]

interface SetConsentResponse<Type = string> {
type: Type
status: ConsentStatus
updatedAt: string
}

type Mock = () => Promise<SetConsentResponse<'telemetry'>>

interface ResultMessage {
success: () => string
failure: (message?: string) => string
Expand Down Expand Up @@ -56,66 +44,6 @@ const resultMessages: Record<SettableConsentStatus, ResultMessage> = {
},
}

const mocks: Record<MockMode, Mock> = {
success: () =>
Promise.resolve({
type: 'telemetry',
status: 'granted',
updatedAt: '2023-08-08T13:40:30.801847Z',
}),
'failure:server': () => {
throw new ServerError({
statusCode: 500,
headers: {},
body: {},
})
},
'failure:msa': () => {
throw new ClientError({
statusCode: 403,
headers: {},
body: {
message: 'User cannot give consent',
},
})
},
}

function isMockMode(mode?: string): mode is MockMode {
return MOCK_MODES.includes(mode as MockMode)
}

function validateMockMode() {
// eslint-disable-next-line no-process-env
if (process.env.MOCK_TELEMETRY_CONSENT_MODE) {
// eslint-disable-next-line no-process-env
const mode = process.env.MOCK_TELEMETRY_CONSENT_MODE.toLowerCase()

if (!isMockMode(mode)) {
const validModes = new Intl.ListFormat('en-US', {
style: 'long',
type: 'disjunction',
}).format(MOCK_MODES.map((name) => `"${name}"`))

throw new Error(
`Invalid value provided for environment variable MOCK_TELEMETRY_CONSENT_MODE. Must be either ${validModes}`,
)
}
}
}

// eslint-disable-next-line consistent-return
function getMock(): Mock | undefined {
validateMockMode()

// eslint-disable-next-line no-process-env
const mode = process.env.MOCK_TELEMETRY_CONSENT_MODE?.toLowerCase()

if (isMockMode(mode)) {
return mocks[mode]
}
}

export function createSetTelemetryConsentAction(status: SettableConsentStatus): CliCommandAction {
return async function setTelemetryConsentAction(_, context) {
const {apiClient, output} = context
Expand All @@ -128,9 +56,6 @@ export function createSetTelemetryConsentAction(status: SettableConsentStatus):
apiVersion: '2023-12-18',
useProjectHostname: false,
})

const mock = getMock()

// eslint-disable-next-line no-process-env
const currentInformation = await resolveConsent({env: process.env})
const isChanged = currentInformation.status !== status
Expand All @@ -144,28 +69,29 @@ export function createSetTelemetryConsentAction(status: SettableConsentStatus):
if (isChanged) {
debug('Setting telemetry consent to "%s"', status)
try {
if (mock) {
debug('Mocking telemetry consent request')
await mock()
} else {
// TODO: Finalise API request.
const uri = `/users/me/consents/telemetry/status/${status}`
debug('Sending telemetry consent status to %s', uri)
const uri = `/users/me/consents/telemetry/status/${status}`
debug('Sending telemetry consent status to %s', uri)

await client.request({
method: 'PUT',
uri,
})
}
await client.request({
method: 'PUT',
uri,
})

// Clear cached telemetry consent
config.delete(TELEMETRY_CONSENT_CONFIG_KEY)

output.print(`${telemetryStatusMessage(status, context)}\n`)
output.print(resultMessages[status].success())
} catch (err) {
err.message = resultMessages[status].failure(err?.responseBody?.message)
throw err
const errorMessage = resultMessages[status].failure(err.response?.body?.message)
if (err.statusCode === 403) {
// throw without stack trace from original error
throw new Error(errorMessage)
} else {
// if not 403, throw original error
err.message = errorMessage
throw err
}
}
}

Expand Down
Loading