UNPKG

@grafana/faro-web-sdk

Version:

Faro instrumentations, metas, transports for web.

222 lines 10.9 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import { BaseExtension, BaseTransport, createPromiseBuffer, getTransportBody, noop, VERSION } from '@grafana/faro-core'; import { getSessionManagerByConfig } from '../../instrumentations/session/sessionManager'; import { getUserSessionUpdater } from '../../instrumentations/session/sessionManager/sessionManagerUtils'; const DEFAULT_BUFFER_SIZE = 30; const DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17 const DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000; const BEACON_BODY_SIZE_LIMIT = 60000; const MAX_KEEPALIVE_REQUESTS = 9; const TOO_MANY_REQUESTS = 429; const ACCEPTED = 202; let pendingKeepaliveBodySize = 0; let pendingKeepaliveRequests = 0; export class FetchTransport extends BaseTransport { constructor(options) { var _a, _b, _c, _d, _e; super(); this.options = options; this.name = '@grafana/faro-web-sdk:transport-fetch'; this.version = VERSION; this.disabledUntil = new Date(0); this.rateLimitBackoffMs = (_a = options.defaultRateLimitBackoffMs) !== null && _a !== void 0 ? _a : DEFAULT_RATE_LIMIT_BACKOFF_MS; this.getNow = (_b = options.getNow) !== null && _b !== void 0 ? _b : (() => Date.now()); const requestCompression = (_c = options.requestCompression) !== null && _c !== void 0 ? _c : false; if (requestCompression && typeof CompressionStream === 'undefined') { this.compressionEnabled = false; this.logWarn('requestCompression is enabled but CompressionStream is not available. Falling back to uncompressed.'); } else { this.compressionEnabled = requestCompression; } this.promiseBuffer = createPromiseBuffer({ size: (_d = options.bufferSize) !== null && _d !== void 0 ? _d : DEFAULT_BUFFER_SIZE, concurrency: (_e = options.concurrency) !== null && _e !== void 0 ? _e : DEFAULT_CONCURRENCY, }); } send(items) { return __awaiter(this, void 0, void 0, function* () { try { if (this.disabledUntil > new Date(this.getNow())) { this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`); return Promise.resolve(); } yield this.promiseBuffer.add(() => __awaiter(this, void 0, void 0, function* () { const jsonBody = JSON.stringify(getTransportBody(items)); const { url, requestOptions, apiKey } = this.options; const _a = requestOptions !== null && requestOptions !== void 0 ? requestOptions : {}, { headers = {} } = _a, restOfRequestOptions = __rest(_a, ["headers"]); const { keepalive: configuredKeepalive } = restOfRequestOptions, requestOptionsWithoutKeepalive = __rest(restOfRequestOptions, ["keepalive"]); let sessionId; const sessionMeta = this.metas.value.session; if (sessionMeta != null) { sessionId = sessionMeta.id; } const resolvedHeaders = {}; for (const [key, value] of Object.entries(headers)) { resolvedHeaders[key] = typeof value === 'function' ? yield Promise.resolve(value()) : value; } let body = jsonBody; let bodySize = jsonBody.length; const compressionHeaders = {}; if (this.compressionEnabled) { body = yield this.compress(jsonBody); bodySize = body.size; compressionHeaders['Content-Encoding'] = 'gzip'; } const requestInit = Object.assign({ method: 'POST', headers: Object.assign(Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, compressionHeaders), resolvedHeaders), (apiKey ? { 'x-api-key': apiKey } : {})), (sessionId ? { 'x-faro-session-id': sessionId } : {})), body }, (requestOptionsWithoutKeepalive !== null && requestOptionsWithoutKeepalive !== void 0 ? requestOptionsWithoutKeepalive : {})); return this.fetchWithKeepaliveRetry(url, requestInit, bodySize, configuredKeepalive).catch((err) => { this.logError('Failed sending payload to the receiver\n', JSON.parse(jsonBody), err); }); })); } catch (err) { this.logError(err); } }); } getIgnoreUrls() { var _a; return [this.options.url].concat((_a = this.config.ignoreUrls) !== null && _a !== void 0 ? _a : []); } isBatched() { return true; } getRetryAfterDate(response) { const now = this.getNow(); const retryAfterHeader = response.headers.get('Retry-After'); if (retryAfterHeader) { const delay = Number(retryAfterHeader); if (!isNaN(delay)) { return new Date(delay * 1000 + now); } const date = Date.parse(retryAfterHeader); if (!isNaN(date)) { return new Date(date); } } return new Date(now + this.rateLimitBackoffMs); } reserveKeepalive(bodySize, configuredKeepalive) { if (configuredKeepalive === false) { return { keepalive: false, release: noop, }; } if (bodySize > BEACON_BODY_SIZE_LIMIT || pendingKeepaliveBodySize + bodySize > BEACON_BODY_SIZE_LIMIT || pendingKeepaliveRequests >= MAX_KEEPALIVE_REQUESTS) { this.logDebug('Disabling keepalive because the pending keepalive request budget would be exceeded.'); return { keepalive: false, release: noop, }; } pendingKeepaliveBodySize += bodySize; pendingKeepaliveRequests++; let released = false; return { keepalive: true, release: () => { if (released) { return; } released = true; pendingKeepaliveBodySize = Math.max(0, pendingKeepaliveBodySize - bodySize); pendingKeepaliveRequests = Math.max(0, pendingKeepaliveRequests - 1); }, }; } fetchWithKeepaliveRetry(url, requestInit, bodySize, configuredKeepalive) { return __awaiter(this, void 0, void 0, function* () { const keepaliveReservation = this.reserveKeepalive(bodySize, configuredKeepalive); try { const response = yield fetch(url, Object.assign(Object.assign({}, requestInit), { keepalive: keepaliveReservation.keepalive })); return this.handleResponse(response); } catch (err) { if (keepaliveReservation.keepalive && this.isFetchNetworkError(err)) { this.logDebug('Retrying failed keepalive request with keepalive disabled.'); const response = yield fetch(url, Object.assign(Object.assign({}, requestInit), { keepalive: false })); return this.handleResponse(response); } throw err; } finally { keepaliveReservation.release(); } }); } handleResponse(response) { return __awaiter(this, void 0, void 0, function* () { if (response.status === ACCEPTED) { const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid'; if (sessionExpired) { this.extendFaroSession(this.config, this.logDebug); } } if (response.status === TOO_MANY_REQUESTS) { this.disabledUntil = this.getRetryAfterDate(response); this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`); } // read the body so the connection can be closed response.text().catch(noop); return response; }); } isFetchNetworkError(err) { return err instanceof TypeError; } compress(body) { return __awaiter(this, void 0, void 0, function* () { const stream = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode(body)); controller.close(); }, }).pipeThrough(new CompressionStream('gzip')); const reader = stream.getReader(); const chunks = []; for (;;) { const { done, value } = yield reader.read(); if (done) { break; } chunks.push(value); } return new Blob(chunks); }); } extendFaroSession(config, logDebug) { const SessionExpiredString = `Session expired`; const sessionTrackingConfig = config.sessionTracking; if (sessionTrackingConfig === null || sessionTrackingConfig === void 0 ? void 0 : sessionTrackingConfig.enabled) { const { fetchUserSession, storeUserSession } = getSessionManagerByConfig(sessionTrackingConfig); getUserSessionUpdater({ fetchUserSession, storeUserSession })({ forceSessionExtend: true }); logDebug(`${SessionExpiredString} created new session.`); } else { logDebug(`${SessionExpiredString}.`); } } } //# sourceMappingURL=transport.js.map