diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 18b8566..90b40f7 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -31,6 +31,7 @@ jobs: tests.test_label \ tests.test_observability \ tests.test_secrets -v + node tests/observability_web_test.mjs sh -n infra/lock_dependencies.sh integration: diff --git a/tests/observability_web_test.mjs b/tests/observability_web_test.mjs new file mode 100644 index 0000000..48619a5 --- /dev/null +++ b/tests/observability_web_test.mjs @@ -0,0 +1,50 @@ +// The browser's API error grouping (note Sentry): one issue per kind of error. +// Dependency-free: Node loads web/observability.js with a stub Sentry. +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import vm from 'node:vm'; + +let captured; +globalThis.window = globalThis; +globalThis.location = {pathname: '/carrinho'}; +globalThis.Sentry = { + init() {}, + setTag() {}, + captureMessage(message, options) { captured = {message, options}; }, +}; +vm.runInThisContext(readFileSync('web/observability.js', 'utf8')); +window.dtfObservability.start('https://key@o1.ingest.sentry.io/1', 'site'); + +const apiError = (path, status, message) => { + captured = null; + window.dtfObservability.apiError(path, status, message); + assert.ok(captured, 'apiError sends one event'); + return captured; +}; + +const expired = 'Este arquivo expirou. Escolha o arquivo de novo.'; +const first = apiError('/uploads/ba39b432-b0d1-4b1b-8971-09123e067067', 410, expired); +const second = apiError('/uploads/5f2be7e0-1111-2222-3333-444455556666', 410, expired); +assert.deepEqual(first.options.fingerprint, second.options.fingerprint); +assert.equal(first.message, 'API 410 /uploads/:id: ' + expired); +assert.deepEqual(first.options.fingerprint, ['api-error', '410', '/uploads/:id', expired]); + +const otherMessage = apiError('/uploads/ba39b432-b0d1-4b1b-8971-09123e067067', 410, + 'Arquivo não encontrado. Escolha o arquivo de novo.'); +assert.notDeepEqual(first.options.fingerprint, otherMessage.options.fingerprint); + +// The numbers and the file names in the server message change per occurrence; +// the kind does not. +const png = apiError('/quotes', 422, 'Item 1: layout.png abaixo do mínimo de 96 DPI.'); +const jpg = apiError('/quotes', 422, 'Item 2: final.jpg abaixo do mínimo de 300 DPI.'); +assert.deepEqual(png.options.fingerprint, jpg.options.fingerprint); +assert.equal(png.message, 'API 422 /quotes: Item :id: :arquivo abaixo do mínimo de :id DPI.'); + +// The status and the path are part of the kind. +assert.notDeepEqual(png.options.fingerprint, + apiError('/quotes', 500, 'Item 1: layout.png abaixo do mínimo de 96 DPI.').options.fingerprint); +assert.notDeepEqual( + apiError('/quotes/ba39b432-b0d1-4b1b-8971-09123e067067', 422, expired).options.fingerprint, + apiError('/orders/ba39b432-b0d1-4b1b-8971-09123e067067', 422, expired).options.fingerprint); + +console.log('observability web checks passed'); diff --git a/web/checkout.js b/web/checkout.js index 61b274b..97fd19f 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -37,7 +37,7 @@ localStorage.removeItem(key); } function clearDraft() { forgetDraft(); actions.replaceChildren(); } - const api = async (path, body) => { + const api = async (path, body, options = {}) => { const response = await fetch('/api'+path, { credentials: 'same-origin', headers: {'Content-Type':'application/json'}, ...(body === undefined ? {} : {method:'POST', body:JSON.stringify(body)}) @@ -55,7 +55,10 @@ const error=new Error(text);error.status=response.status; const retry=response.headers.get('Retry-After'); if(retry!=null)error.retryAfter=retry; - window.dtfObservability?.apiError?.(path,response.status,error.message,data.detail); + // A status the caller expects (a resumed upload that expired) is handled + // there, not reported. + if(!(options.expected||[]).includes(response.status)) + window.dtfObservability?.apiError?.(path,response.status,error.message,data.detail); throw error; } return data; diff --git a/web/observability.js b/web/observability.js index 47fdc0a..c893fa5 100644 --- a/web/observability.js +++ b/web/observability.js @@ -8,6 +8,11 @@ (function () { const EMAIL = /[^\s@]+@[^\s@]+\.[A-Za-z]{2,}/g; const DOCUMENT = /(?:,;()[\]{}]+\.(?:png|jpe?g|pdf|tiff?|psd|psb|ai|cdr|webp|zip)\b/gi; + const NUMBER = /\d+/g; const SENSITIVE_PARAM = /token|signature|x-amz/i; const SENSITIVE_HEADER = /^(cookie|authorization|x-.*token.*)$/i; const REDACTED = '[removido]'; @@ -104,13 +109,24 @@ } } + const normalizedPath = value => clean(String(value == null ? '' : value) + .replace(UUID, ':id').replace(NUMBER, ':id')); + const normalizedMessage = value => clean(String(value == null ? '' : value) + .replace(UUID, ':id').replace(FILE_NAME, ':arquivo').replace(NUMBER, ':id')); + function apiError(path, status, message, detail) { if (!started || status === 401 || typeof Sentry === 'undefined') return; try { + // One issue per kind of API error: without this Sentry groups them all + // by apiError and DTF-WEB-1 mixes a 422 for 66 files with a 422 for + // 96 DPI. The title names the same kind as the fingerprint. + const kindPath = normalizedPath(path); + const kindMessage = normalizedMessage(message); const extra = {path, status, page: location.pathname}; if (status === 422 && detail) extra.detail = detail; - Sentry.captureMessage(clean('API ' + status + ' ' + path + ': ' + (message || '')), - {level: 'error', tags: {app}, extra}); + Sentry.captureMessage('API ' + status + ' ' + kindPath + ': ' + kindMessage, + {level: 'error', tags: {app}, extra, + fingerprint: ['api-error', String(status), kindPath, kindMessage]}); } catch (error) { // Reporting an error must never break the page. } diff --git a/web/upload.js b/web/upload.js index 11c436e..53eb65e 100644 --- a/web/upload.js +++ b/web/upload.js @@ -36,11 +36,12 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr }; let id=resume?localStorage.getItem(key):null,state; if(id){ - try{state=await api(prefix+'/'+id);} + try{state=await api(prefix+'/'+id,undefined,{expected:[403,404,410]});} catch(error){ - // The id was started under another session (a sign-in changes the scope): - // the new session does not own it, so this file starts again as a new - // upload. A 403/404/410 must never keep the retry on the old id. + // The id is only a hint from the last visit. When the upload expired or + // was started under another session (a sign-in changes the scope), this + // file starts again as a new upload, silently, and its id is replaced. + // These refusals are expected here and never reach Sentry. if(![403,404,410].includes(error.status))throw error; id=null; if(resume)localStorage.removeItem(key);