Files
cypress/packages/server/lib/api.js
Brian Mann 29841f32b9 feat: redesign server errors (#20072)
* chore: rename errors.js -> errors.ts

* refactor: type safety on errors

* refactor: add err_template for consistent error formatting

* fix a few system tests

* fix tests; update snapshots

* Fix types

* normalize snapshot - remove chalk ansi colors

* more unit test fixes

* more system test fixes

* circleci build

* backtick always in stdout, fix error formatting and failing snapshots

* refactor: create @packages/errors

* fix import

* fix import

* fixing build / tests

* remove extraneous file

* move warnIfExplicitCiBuildId

* fix build / tests

* Fix

* error, type fixes, documentation, standardize child process error serialization

* fix import

* build errors on install

* wrote specs generating visual images of all errors

* remove unused dep

* sanitize stack traces

* add image diffing

- if base images don't exist, create them
- if base images don't match and local, overwrite them, if in CI throw
- if base images are stale and local, delete them, if in CI throw

* remove Courier New + MesloLGS NF font

* type fixes, remove Bluebird, general cleanup

* TS Cleanup

* skip typecheck on tests for now

* yarn.lock

* fix @types/chai version

* fix yarn.lock

* Different version of mocha types so it isnt patched

* errors spec snapshot

* CI fix

* fixes

* store snapshot images in circle artifacts

* dont change artifact destination prefix

* use Courier Prime

* antialias the text

* decrease pixelmatch threshold, fail in CI only when changed pixels > 100

* increase timeout

* overflow: hidden, remove new Promise, add debug logging

Co-Authored-By: Tim Griesser <tgriesser@gmail.com>

* run unit tests w/ concurrency=1

* unique window per file

* disable app hardware acceleration + use in process gpu + single process

* do not do image diffing

- conditionally convert html to images
- store html snapshots
- do not store images in git

* store snapshot html

* Merge branch 'tgriesser/chore/refactor-errors' of https://github.com/cypress-io/cypress into tgriesser/chore/refactor-errors

* remove concurrency

* fix assertion

* fixing ci

* Link in readme

* pass the browsers to listItems

* fix: build @packages/errors in CI, defer import to prevent errors locally

* Merge branch 'develop' into tgriesser/chore/refactor-errors

* develop:
  chore: fix cypress npm package artifact upload path (#20023)
  chore(driver): move cy.within logic into it's own file (#20036)
  chore: update automerge workflows (#19982)
  fix(selectFile): use target window's File/DataTransfer classes (#20003)
  chore: Update Chrome (stable) to 98.0.4758.80 and Chrome (beta) to 98.0.4758.80 (#19995)
  fix: Adjust ffmpeg CLI args for performance (#19983)
  build: allow unified to run cypress on Apple Silicon (arm64) (backport #19067 to 9.x) (#19968)

* fix run-if-ci.sh

* remove dead code

* Mark the .html files as generated in gitattributes

* fix running single error case, slice out more of the brittle stack

* remove additional brittle stack line

* firefox web security error

* nest inside of describe

* reformat and redesign errors

* more error cleanup and standardization

* additional formatting of errors, code cleanup, refactoring

* update ansi colors to match terminal colors

* cleanup remaining loose ends, update several errors, compact excess formatters

* fix types

* additional formatting, remove TODO's, ensure no [object Object] in output

* add test for 412 server response on invalid schema

* update unknown dashboard error on creating run

* use fs.access instead of fs.stat for perf

* added PLUGINS_FILE_NOT_FOUND error

- separated out from PLUGINS_FILE_ERROR
- add system tests for both cases
- update snapshots
- remove stack trace from PLUGINS_FILE_NOT_FOUND fka PLUGINS_FILE_ERROR

* add plugins system test around plugins synchronously throwing on require

* remove forcing process.cwd() to be packages/server, update affected code

- this was a long needed hangover from very old code that was doing unnecessary things due to respawning electron from node and handling various entrypoints into booting cypress
- this also makes the root yarn dev and dev-debug work correctly because options.cwd is set correctly now

* perf: lazy load chalk

* remove excessive line since the file exists but is invalid

* fix types

* add system test when plugins function throws a synchronous error

* create new PLUGINS_INVALID_EVENT_ERROR, wire it up correctly for error template use

- properly pass error instance from child to ensure proper user stack frames
- move error display code into the right place

* only show a single stack trace, either originalError or internal cypressError

* push error html snapshots

* fix tests, types

* fix test

* fix failing tests

* fix tests

* fixes lots of broken tests

* more test fixes

* fixes more tests

* fix type checking

* wip: consistent handling of interpolated values

* feat: fixing up errors, added simple error comparison tool

* wrapping up error formatting

* Fixes for unit tests

* fix PLUGINS_VALIDATION_ERROR

* fix fs.readdir bug, show rows even if there's only markdown formatting [SKIP CI]

* when in base-list, show full width of errors

* Fix type errors

* added searching and filtering for files based on error name

* fix: system tests

* updated NO_SPECS_FOUND error to properly join searched folder + pattern

- join patterns off of process.cwd, not projectRoot
- highlight original specPattern in yellow, baseDir in blue
- add tests

* fixes failing tests

* fix test

* preserve original spec pattern, display relative to projectRoot for terminal banner

* make the nodeVersion path display in gray, not white

* fix tests, pass right variables

* fix chrome:canary snapshots

* update snapshots

* update snapshot

* strip newlines caused by "Still waiting to connect to {browser}..."

* don't remove the snapshotHtmlFolder in CI, add additional verification snapshots match to error keys symmetrically

* update snapshot

* update snapshot

* update snapshot

* update snapshot

* update snapshot

* update snapshot

* update gitignore

* fix snapshot

* update snapshot html

* update logic for parsing the resolve pattern matching, add tests

* update snapshots

* update snapshot

* update snapshot

* update snapshot

* fix failing test

* fix: error_message_spec

* fix snapshot

* run each variant through an it(...) so multiple failures are received

* add newlines to multiline formatters, add fmt.stringify, allow format overrides

* stringify invalid return values from plugins

* move config validation errors into packages/errors, properly highlight and stringify values

* add component testing yarn commands

* fix the arrow not showing on details

* fix typescript error

* fixed lots of poorly written tests that weren't actually testing anything. created settings validation error when given a string validation result.

* fixes tests

* fixes tests, adds new error template for validating within an array list (for browser validation)

* remove dupe line

* fix copy for consistency, update snapshots

* remove redundant errors, standardize formatting and phrasing

* more formatting

* remove excess snapshots

* prune out excessive error snapshot html files when not in CI

* add missing tests, add case for when config validation fails without a fileType

* fixes test

* update snapshot

* update snapshot

* update snapshot

* sort uniqErrors + errorKeys prior to assertion - assert one by one

* add system test for binding to an event with the wrong handler

* fixes tests

* set more descriptive errors when setting invalid plugin events, or during plugin event validation

* remove duplicate PLUGINS_EVENT_ERROR, collapse into existing error

* use the same multiline formatting as @packages/errors

* standardize verbiage and highlighting for consistency

* fix incorrect error path

* fixes tests, standardized and condensed more language

* Update packages/errors/src/errors.ts

Co-authored-by: Ryan Manuel <ryanm@cypress.io>

* Update guides/error-handling.md

Co-authored-by: Ryan Manuel <ryanm@cypress.io>

* Update guides/error-handling.md

Co-authored-by: Ryan Manuel <ryanm@cypress.io>

* added some final todo's

* fix types

Co-authored-by: Tim Griesser <tgriesser10@gmail.com>
Co-authored-by: Tim Griesser <tgriesser@gmail.com>
Co-authored-by: Ryan Manuel <ryanm@cypress.io>
2022-02-11 02:06:07 -05:00

479 lines
11 KiB
JavaScript

const _ = require('lodash')
const os = require('os')
const debug = require('debug')('cypress:server:api')
const request = require('@cypress/request-promise')
const RequestErrors = require('@cypress/request-promise/errors')
const Promise = require('bluebird')
const humanInterval = require('human-interval')
const { agent } = require('@packages/network')
const pkg = require('@packages/root')
const machineId = require('./util/machine_id')
const errors = require('./errors')
const { apiRoutes, onRoutes } = require('./util/routes')
const THIRTY_SECONDS = humanInterval('30 seconds')
const SIXTY_SECONDS = humanInterval('60 seconds')
const TWO_MINUTES = humanInterval('2 minutes')
let intervals
let DELAYS = [
THIRTY_SECONDS,
SIXTY_SECONDS,
TWO_MINUTES,
]
const runnerCapabilities = {
'dynamicSpecsInSerialMode': true,
'skipSpecAction': true,
}
let responseCache = {}
intervals = process.env.API_RETRY_INTERVALS
if (intervals) {
DELAYS = _
.chain(intervals)
.split(',')
.map(_.toNumber)
.value()
}
const rp = request.defaults((params = {}, callback) => {
let resp
if (params.cacheable && (resp = getCachedResponse(params))) {
debug('resolving with cached response for ', params.url)
return Promise.resolve(resp)
}
_.defaults(params, {
agent,
proxy: null,
gzip: true,
cacheable: false,
})
const headers = params.headers != null ? params.headers : (params.headers = {})
_.defaults(headers, {
'x-os-name': os.platform(),
'x-cypress-version': pkg.version,
})
const method = params.method.toLowerCase()
// use %j argument to ensure deep nested properties are serialized
debug(
'request to url: %s with params: %j and token: %s',
`${params.method} ${params.url}`,
_.pick(params, 'body', 'headers'),
params.auth && params.auth.bearer,
)
return request[method](params, callback)
.promise()
.tap((resp) => {
if (params.cacheable) {
debug('caching response for ', params.url)
cacheResponse(resp, params)
}
return debug('response %o', resp)
})
})
const cacheResponse = (resp, params) => {
return responseCache[params.url] = resp
}
const getCachedResponse = (params) => {
return responseCache[params.url]
}
const retryWithBackoff = (fn) => {
// for e2e testing purposes
let attempt
if (process.env.DISABLE_API_RETRIES) {
debug('api retries disabled')
return Promise.try(() => fn(0))
}
return (attempt = (retryIndex) => {
return Promise
.try(() => fn(retryIndex))
.catch(isRetriableError, (err) => {
if (retryIndex > DELAYS.length) {
throw err
}
const delay = DELAYS[retryIndex]
errors.warning(
'DASHBOARD_API_RESPONSE_FAILED_RETRYING', {
delay,
tries: DELAYS.length - retryIndex,
response: err,
},
)
retryIndex++
return Promise
.delay(delay)
.then(() => {
debug(`retry #${retryIndex} after ${delay}ms`)
return attempt(retryIndex)
})
})
})(0)
}
const formatResponseBody = function (err) {
// if the body is JSON object
if (_.isObject(err.error)) {
// transform the error message to include the
// stringified body (represented as the 'error' property)
const body = JSON.stringify(err.error, null, 2)
err.message = [err.statusCode, body].join('\n\n')
}
throw err
}
const tagError = function (err) {
err.isApiError = true
throw err
}
// retry on timeouts, 5xx errors, or any error without a status code
const isRetriableError = (err) => {
return (err instanceof Promise.TimeoutError) ||
(500 <= err.statusCode && err.statusCode < 600) ||
(err.statusCode == null)
}
module.exports = {
rp,
ping () {
return rp.get(apiRoutes.ping())
.catch(tagError)
},
getMe (authToken) {
return rp.get({
url: apiRoutes.me(),
json: true,
auth: {
bearer: authToken,
},
})
},
getAuthUrls () {
return rp.get({
url: apiRoutes.auth(),
json: true,
cacheable: true,
headers: {
'x-route-version': '2',
},
})
.catch(tagError)
},
getOrgs (authToken) {
return rp.get({
url: apiRoutes.orgs(),
json: true,
auth: {
bearer: authToken,
},
})
.catch(tagError)
},
getProjects (authToken) {
return rp.get({
url: apiRoutes.projects(),
json: true,
auth: {
bearer: authToken,
},
})
.catch(tagError)
},
getProject (projectId, authToken) {
return rp.get({
url: apiRoutes.project(projectId),
json: true,
auth: {
bearer: authToken,
},
headers: {
'x-route-version': '2',
},
})
.catch(tagError)
},
getProjectRuns (projectId, authToken, options = {}) {
if (options.page == null) {
options.page = 1
}
return rp.get({
url: apiRoutes.projectRuns(projectId),
json: true,
timeout: options.timeout != null ? options.timeout : 10000,
auth: {
bearer: authToken,
},
headers: {
'x-route-version': '3',
},
})
.catch(RequestErrors.StatusCodeError, formatResponseBody)
.catch(tagError)
},
createRun (options = {}) {
return retryWithBackoff((attemptIndex) => {
const body = {
..._.pick(options, [
'ci',
'specs',
'commit',
'group',
'platform',
'parallel',
'ciBuildId',
'projectId',
'recordKey',
'specPattern',
'tags',
'testingType',
]),
runnerCapabilities,
}
return rp.post({
body,
url: apiRoutes.runs(),
json: true,
timeout: options.timeout != null ? options.timeout : SIXTY_SECONDS,
headers: {
'x-route-version': '4',
'x-cypress-request-attempt': attemptIndex,
},
})
.catch(RequestErrors.StatusCodeError, formatResponseBody)
.catch(tagError)
})
},
createInstance (options = {}) {
const { runId, timeout } = options
const body = _.pick(options, [
'spec',
'groupId',
'machineId',
'platform',
])
return retryWithBackoff((attemptIndex) => {
return rp.post({
body,
url: apiRoutes.instances(runId),
json: true,
timeout: timeout != null ? timeout : SIXTY_SECONDS,
headers: {
'x-route-version': '5',
'x-cypress-run-id': runId,
'x-cypress-request-attempt': attemptIndex,
},
})
.catch(RequestErrors.StatusCodeError, formatResponseBody)
.catch(tagError)
})
},
postInstanceTests (options = {}) {
const { instanceId, runId, timeout, ...body } = options
return retryWithBackoff((attemptIndex) => {
return rp.post({
url: apiRoutes.instanceTests(instanceId),
json: true,
timeout: timeout || SIXTY_SECONDS,
headers: {
'x-route-version': '1',
'x-cypress-run-id': runId,
'x-cypress-request-attempt': attemptIndex,
},
body,
})
.catch(RequestErrors.StatusCodeError, formatResponseBody)
.catch(tagError)
})
},
updateInstanceStdout (options = {}) {
return retryWithBackoff((attemptIndex) => {
return rp.put({
url: apiRoutes.instanceStdout(options.instanceId),
json: true,
timeout: options.timeout != null ? options.timeout : SIXTY_SECONDS,
body: {
stdout: options.stdout,
},
headers: {
'x-cypress-run-id': options.runId,
'x-cypress-request-attempt': attemptIndex,
},
})
.catch(RequestErrors.StatusCodeError, formatResponseBody)
.catch(tagError)
})
},
postInstanceResults (options = {}) {
return retryWithBackoff((attemptIndex) => {
return rp.post({
url: apiRoutes.instanceResults(options.instanceId),
json: true,
timeout: options.timeout != null ? options.timeout : SIXTY_SECONDS,
headers: {
'x-route-version': '1',
'x-cypress-run-id': options.runId,
'x-cypress-request-attempt': attemptIndex,
},
body: _.pick(options, [
'stats',
'tests',
'exception',
'video',
'screenshots',
'reporterStats',
'metadata',
]),
})
.catch(RequestErrors.StatusCodeError, formatResponseBody)
.catch(tagError)
})
},
createCrashReport (body, authToken, timeout = 3000) {
return rp.post({
url: apiRoutes.exceptions(),
json: true,
body,
auth: {
bearer: authToken,
},
})
.timeout(timeout)
.catch(tagError)
},
postLogout (authToken) {
return Promise.join(
this.getAuthUrls(),
machineId.machineId(),
(urls, machineId) => {
return rp.post({
url: urls.dashboardLogoutUrl,
json: true,
auth: {
bearer: authToken,
},
headers: {
'x-machine-id': machineId,
},
})
.catch({ statusCode: 401 }, () => {}) // do nothing on 401
.catch(tagError)
},
)
},
createProject (projectDetails, remoteOrigin, authToken) {
debug('create project with args %o', {
projectDetails,
remoteOrigin,
authToken,
})
return rp.post({
url: apiRoutes.projects(),
json: true,
auth: {
bearer: authToken,
},
headers: {
'x-route-version': '2',
},
body: {
name: projectDetails.projectName,
orgId: projectDetails.orgId,
public: projectDetails.public,
remoteOrigin,
},
})
.catch(RequestErrors.StatusCodeError, formatResponseBody)
.catch(tagError)
},
getProjectRecordKeys (projectId, authToken) {
return rp.get({
url: apiRoutes.projectRecordKeys(projectId),
json: true,
auth: {
bearer: authToken,
},
})
.catch(tagError)
},
requestAccess (projectId, authToken) {
return rp.post({
url: apiRoutes.membershipRequests(projectId),
json: true,
auth: {
bearer: authToken,
},
})
.catch(RequestErrors.StatusCodeError, formatResponseBody)
.catch(tagError)
},
getReleaseNotes (version) {
return rp.get({
url: onRoutes.releaseNotes(version),
json: true,
})
.catch((err) => {
// log and ignore by sending an empty response if there's an error
debug('error getting release notes for version %s: %s', version, err.stack || err.message || err)
return {}
})
},
clearCache () {
responseCache = {}
},
retryWithBackoff,
}