logixia 1.12.5 → 1.12.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -14
- package/dist/.tsbuildinfo +1 -1
- package/dist/async-context-CSHWoHMB.js +88 -0
- package/dist/async-context-CSHWoHMB.js.map +1 -0
- package/dist/async-context-CwBNMm2E.mjs +68 -0
- package/dist/async-context-CwBNMm2E.mjs.map +1 -0
- package/dist/azure-monitor.transport-CG7ClkYj.d.ts +62 -0
- package/dist/azure-monitor.transport-CG7ClkYj.d.ts.map +1 -0
- package/dist/azure-monitor.transport-CHnjVRF-.mjs +152 -0
- package/dist/azure-monitor.transport-CHnjVRF-.mjs.map +1 -0
- package/dist/azure-monitor.transport-Cm74kXZS.d.mts +62 -0
- package/dist/azure-monitor.transport-Cm74kXZS.d.mts.map +1 -0
- package/dist/azure-monitor.transport-CrvfHd9C.js +157 -0
- package/dist/azure-monitor.transport-CrvfHd9C.js.map +1 -0
- package/dist/azure.d.mts +3 -0
- package/dist/azure.d.ts +3 -0
- package/dist/azure.js +6 -0
- package/dist/azure.mjs +6 -0
- package/dist/batch-buffer-BY-mRWIK.js +170 -0
- package/dist/batch-buffer-BY-mRWIK.js.map +1 -0
- package/dist/batch-buffer-PGvSgbmd.mjs +132 -0
- package/dist/batch-buffer-PGvSgbmd.mjs.map +1 -0
- package/dist/browser.d.mts +427 -0
- package/dist/browser.d.mts.map +1 -0
- package/dist/browser.d.ts +427 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +590 -0
- package/dist/browser.js.map +1 -0
- package/dist/browser.mjs +586 -0
- package/dist/browser.mjs.map +1 -0
- package/dist/chunk-DLSkYcPk.mjs +7 -0
- package/dist/chunk-nOFOJqeH.js +30 -0
- package/dist/cloudwatch.d.mts +3 -0
- package/dist/cloudwatch.d.ts +3 -0
- package/dist/cloudwatch.js +6 -0
- package/dist/cloudwatch.mjs +6 -0
- package/dist/cloudwatch.transport-CGHY4buE.d.mts +81 -0
- package/dist/cloudwatch.transport-CGHY4buE.d.mts.map +1 -0
- package/dist/cloudwatch.transport-DK_8cKd3.d.ts +81 -0
- package/dist/cloudwatch.transport-DK_8cKd3.d.ts.map +1 -0
- package/dist/cloudwatch.transport-pNBNWJLt.js +370 -0
- package/dist/cloudwatch.transport-pNBNWJLt.js.map +1 -0
- package/dist/cloudwatch.transport-yBwm4OeO.mjs +360 -0
- package/dist/cloudwatch.transport-yBwm4OeO.mjs.map +1 -0
- package/dist/coerce.utils-BN980Y9V.js +44 -0
- package/dist/coerce.utils-BN980Y9V.js.map +1 -0
- package/dist/coerce.utils-Dxv4_ikC.mjs +38 -0
- package/dist/coerce.utils-Dxv4_ikC.mjs.map +1 -0
- package/dist/correlation.d.mts +238 -0
- package/dist/correlation.d.mts.map +1 -0
- package/dist/correlation.d.ts +238 -0
- package/dist/correlation.d.ts.map +1 -0
- package/dist/correlation.js +272 -0
- package/dist/correlation.js.map +1 -0
- package/dist/correlation.mjs +261 -0
- package/dist/correlation.mjs.map +1 -0
- package/dist/gcp.d.mts +3 -0
- package/dist/gcp.d.ts +3 -0
- package/dist/gcp.js +6 -0
- package/dist/gcp.mjs +6 -0
- package/dist/gcp.transport-BJuNRFe_.mjs +192 -0
- package/dist/gcp.transport-BJuNRFe_.mjs.map +1 -0
- package/dist/gcp.transport-BOhkVKlI.d.ts +71 -0
- package/dist/gcp.transport-BOhkVKlI.d.ts.map +1 -0
- package/dist/gcp.transport-Bi6CUqZR.d.mts +71 -0
- package/dist/gcp.transport-Bi6CUqZR.d.mts.map +1 -0
- package/dist/gcp.transport-SHdtc1n0.js +198 -0
- package/dist/gcp.transport-SHdtc1n0.js.map +1 -0
- package/dist/{index-CwFww7VC.d.ts → index-BPKwwERo.d.mts} +18 -174
- package/dist/index-BPKwwERo.d.mts.map +1 -0
- package/dist/{index-DnyeaoZU.d.mts → index-C1X-TE5I.d.ts} +18 -174
- package/dist/index-C1X-TE5I.d.ts.map +1 -0
- package/dist/index.d.mts +41 -11
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +40 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +87 -147
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +62 -132
- package/dist/index.mjs.map +1 -1
- package/dist/internal-log-BUJYMZbE.js +70 -0
- package/dist/internal-log-BUJYMZbE.js.map +1 -0
- package/dist/internal-log-Cm8SOWSV.mjs +52 -0
- package/dist/internal-log-Cm8SOWSV.mjs.map +1 -0
- package/dist/{logitron-logger.module-BIGTm2V6.mjs → logitron-logger.module-Bs3XYZgF.mjs} +266 -166
- package/dist/logitron-logger.module-Bs3XYZgF.mjs.map +1 -0
- package/dist/{logitron-logger.module-BTxDpK6u.js → logitron-logger.module-BsDZR5BH.js} +297 -203
- package/dist/logitron-logger.module-BsDZR5BH.js.map +1 -0
- package/dist/{logitron-logger.module-DvqtI43C.d.ts → logitron-logger.module-CxT1F6Cm.d.ts} +25 -12
- package/dist/logitron-logger.module-CxT1F6Cm.d.ts.map +1 -0
- package/dist/{logitron-logger.module-CpffEHec.d.mts → logitron-logger.module-zDKVd_o0.d.mts} +25 -12
- package/dist/logitron-logger.module-zDKVd_o0.d.mts.map +1 -0
- package/dist/middleware.d.mts +5 -2
- package/dist/middleware.d.mts.map +1 -1
- package/dist/middleware.d.ts +5 -2
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +13 -4
- package/dist/middleware.js.map +1 -1
- package/dist/middleware.mjs +14 -4
- package/dist/middleware.mjs.map +1 -1
- package/dist/nest.d.mts +3 -2
- package/dist/nest.d.mts.map +1 -1
- package/dist/nest.d.ts +3 -2
- package/dist/nest.d.ts.map +1 -1
- package/dist/nest.js +6 -2
- package/dist/nest.mjs +6 -2
- package/dist/safe-stringify-DJ66tW5I.mjs +118 -0
- package/dist/safe-stringify-DJ66tW5I.mjs.map +1 -0
- package/dist/safe-stringify-DWo3aZp_.js +142 -0
- package/dist/safe-stringify-DWo3aZp_.js.map +1 -0
- package/dist/search-CFQRISUv.mjs +1596 -0
- package/dist/search-CFQRISUv.mjs.map +1 -0
- package/dist/search-CQOo-Iq6.d.mts +816 -0
- package/dist/search-CQOo-Iq6.d.mts.map +1 -0
- package/dist/search-DujhR94O.d.ts +816 -0
- package/dist/search-DujhR94O.d.ts.map +1 -0
- package/dist/search-njTI2hdo.js +1631 -0
- package/dist/search-njTI2hdo.js.map +1 -0
- package/dist/search.d.mts +4 -1
- package/dist/search.d.ts +4 -1
- package/dist/search.js +9 -1
- package/dist/search.mjs +3 -2
- package/dist/testing.d.mts +2 -1
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.d.ts +2 -1
- package/dist/testing.d.ts.map +1 -1
- package/dist/{transport.manager-ciG4r5uz.js → transport.manager-BivyUTtU.js} +497 -437
- package/dist/transport.manager-BivyUTtU.js.map +1 -0
- package/dist/{transport.manager-DETpXuaY.mjs → transport.manager-D6KL3t9V.mjs} +473 -364
- package/dist/transport.manager-D6KL3t9V.mjs.map +1 -0
- package/dist/transport.types-B5vcyv2k.d.mts +187 -0
- package/dist/transport.types-B5vcyv2k.d.mts.map +1 -0
- package/dist/transport.types-BuY84TwO.d.ts +187 -0
- package/dist/transport.types-BuY84TwO.d.ts.map +1 -0
- package/dist/transports.d.mts +90 -29
- package/dist/transports.d.mts.map +1 -1
- package/dist/transports.d.ts +90 -29
- package/dist/transports.d.ts.map +1 -1
- package/dist/transports.js +14 -2
- package/dist/transports.mjs +10 -2
- package/dist/worker-entry.js +1241 -0
- package/dist/worker.d.mts +3 -0
- package/dist/worker.d.ts +3 -0
- package/dist/worker.js +4 -0
- package/dist/worker.mjs +4 -0
- package/dist/worker.transport-BP8Q28Z2.d.mts +76 -0
- package/dist/worker.transport-BP8Q28Z2.d.mts.map +1 -0
- package/dist/worker.transport-BhMyvqQ2.mjs +167 -0
- package/dist/worker.transport-BhMyvqQ2.mjs.map +1 -0
- package/dist/worker.transport-CfH6z37Z.js +168 -0
- package/dist/worker.transport-CfH6z37Z.js.map +1 -0
- package/dist/worker.transport-mKXgNK0L.d.ts +76 -0
- package/dist/worker.transport-mKXgNK0L.d.ts.map +1 -0
- package/package.json +23 -18
- package/dist/index-CwFww7VC.d.ts.map +0 -1
- package/dist/index-DnyeaoZU.d.mts.map +0 -1
- package/dist/logitron-logger.module-BIGTm2V6.mjs.map +0 -1
- package/dist/logitron-logger.module-BTxDpK6u.js.map +0 -1
- package/dist/logitron-logger.module-CpffEHec.d.mts.map +0 -1
- package/dist/logitron-logger.module-DvqtI43C.d.ts.map +0 -1
- package/dist/search-Cg_OasF-.d.ts +0 -1
- package/dist/search-DN676Dnz.d.mts +0 -1
- package/dist/search-DOvSI-mb.mjs +0 -1
- package/dist/search-DoZF3RZj.js +0 -0
- package/dist/transport.manager-DETpXuaY.mjs.map +0 -1
- package/dist/transport.manager-ciG4r5uz.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"azure-monitor.transport-CrvfHd9C.js","names":["SEVERITY_MAP: Record<string, number>","DEFAULT_REQUEST_TIMEOUT_MS","BatchBuffer","DEFAULT_MAX_BUFFER_SIZE","stringifyForLog","httpRequest","reqUrl: URL"],"sources":["../src/transports/azure-monitor.transport.ts"],"sourcesContent":["/**\n * logixia — Azure Monitor / Application Insights transport\n *\n * Sends log entries to Azure Monitor via the Data Collection Rules (DCR) API\n * using the Logs Ingestion API (the modern replacement for the legacy HTTP\n * Data Collector API).\n *\n * Maps logixia levels to Application Insights severity levels:\n * verbose → 0, debug → 1, info → 1, warn → 2, error → 3, critical → 4\n *\n * @example\n * ```ts\n * import { AzureMonitorTransport } from 'logixia';\n *\n * const logger = createLogger({\n * transports: {\n * azure: new AzureMonitorTransport({\n * // Logs Ingestion API endpoint (from your DCR)\n * endpoint: 'https://<dce>.ingest.monitor.azure.com',\n * ruleId: 'dcr-xxxxxxxxxxxxxxxx',\n * streamName: 'Custom-LogixiaLogs',\n * // Client credentials (or managed identity via no-credential mode)\n * tenantId: process.env.AZURE_TENANT_ID,\n * clientId: process.env.AZURE_CLIENT_ID,\n * clientSecret: process.env.AZURE_CLIENT_SECRET,\n * }),\n * },\n * });\n * ```\n */\n\nimport type { IAsyncTransport, TransportLogEntry } from '../types/transport.types';\nimport { internalError, internalWarn } from '../utils/internal-log';\nimport { stringifyForLog } from '../utils/safe-stringify';\nimport {\n BatchBuffer,\n DEFAULT_MAX_BUFFER_SIZE,\n DEFAULT_REQUEST_TIMEOUT_MS,\n httpRequest,\n} from './batch-buffer';\n\n/**\n * Azure AD tenant IDs are either a GUID or a verified domain (e.g. `contoso.onmicrosoft.com`).\n * This pattern is deliberately permissive on structure but strict on character\n * set — it rejects the breakout characters (`/`, `@`, `:`, `?`, `#`, whitespace)\n * that would let a hostile config smuggle a different host, path, or query into\n * the OAuth token URL.\n */\nconst AZURE_TENANT_RE = /^[a-z0-9][a-z0-9.-]{1,253}$/i;\n\nexport interface AzureMonitorTransportConfig {\n /** DCE (Data Collection Endpoint) URL, e.g. `https://<name>.ingest.monitor.azure.com`. */\n endpoint: string;\n /** Data Collection Rule immutable ID (from Azure portal). */\n ruleId: string;\n /** Stream name defined in the DCR, e.g. `'Custom-LogixiaLogs_CL'`. */\n streamName: string;\n /** Azure AD tenant ID for OAuth2 client-credentials flow. */\n tenantId?: string;\n /** Azure AD app (service principal) client ID. */\n clientId?: string;\n /** Azure AD app client secret. */\n clientSecret?: string;\n /** Number of entries to batch. @default 200 */\n batchSize?: number;\n /** Flush interval in ms. @default 5000 */\n flushIntervalMs?: number;\n /** Abort a request that has not finished after this many ms. @default 10000 */\n requestTimeoutMs?: number;\n /** Max buffered entries; the oldest are dropped past this. @default 10000 */\n maxBufferSize?: number;\n level?: string;\n}\n\nconst SEVERITY_MAP: Record<string, number> = {\n verbose: 0,\n trace: 0,\n debug: 1,\n info: 1,\n log: 1,\n warn: 2,\n warning: 2,\n error: 3,\n critical: 4,\n fatal: 4,\n};\n\n/**\n * Azure Monitor Logs Ingestion transport.\n */\nexport class AzureMonitorTransport implements IAsyncTransport {\n public readonly name = 'azure-monitor';\n public readonly batchSize: number;\n public readonly flushInterval: number;\n public readonly level: string | undefined;\n\n private readonly buffer: BatchBuffer<TransportLogEntry>;\n private readonly requestTimeoutMs: number;\n private flushTimer: NodeJS.Timeout | null = null;\n private accessToken: string | null = null;\n private tokenExpiry = 0;\n\n private readonly endpoint: string;\n private readonly ruleId: string;\n private readonly streamName: string;\n private readonly tenantId: string | undefined;\n private readonly clientId: string | undefined;\n private readonly clientSecret: string | undefined;\n\n constructor(config: AzureMonitorTransportConfig) {\n this.endpoint = config.endpoint.replace(/\\/$/, '');\n this.ruleId = config.ruleId;\n this.streamName = config.streamName;\n this.tenantId = config.tenantId ?? process.env['AZURE_TENANT_ID'];\n this.clientId = config.clientId ?? process.env['AZURE_CLIENT_ID'];\n this.clientSecret = config.clientSecret ?? process.env['AZURE_CLIENT_SECRET'];\n this.batchSize = config.batchSize ?? 200;\n this.flushInterval = config.flushIntervalMs ?? 5000;\n this.level = config.level;\n this.requestTimeoutMs = config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.buffer = new BatchBuffer<TransportLogEntry>({\n name: 'AzureMonitorTransport',\n batchSize: this.batchSize,\n maxBufferSize: config.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE,\n send: (entries) => this.sendEntries(entries),\n });\n\n this.flushTimer = setInterval(() => {\n this.flush().catch(() => {});\n }, this.flushInterval);\n if (this.flushTimer.unref) this.flushTimer.unref();\n }\n\n write(entry: TransportLogEntry): void {\n this.buffer.push(entry);\n this.buffer.flushIfFull();\n }\n\n flush(): Promise<void> {\n return this.buffer.flush();\n }\n\n /**\n * Flush remaining entries and stop the interval timer on shutdown. Without\n * this the manager's close() skipped the transport (close was undefined) and\n * buffered entries were lost on deploy. Waits for any in-flight send first.\n */\n async close(): Promise<void> {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n await this.buffer.close();\n }\n\n private toAzureRecord(entry: TransportLogEntry): Record<string, unknown> {\n return {\n TimeGenerated: entry.timestamp ?? new Date().toISOString(),\n SeverityLevel: SEVERITY_MAP[entry.level.toLowerCase()] ?? 1,\n Message: entry.message,\n AppName: entry.appName,\n Context: entry.context ?? '',\n TraceId: entry.traceId ?? '',\n Properties: stringifyForLog(entry.data ?? {}),\n };\n }\n\n private async getAccessToken(): Promise<string | null> {\n if (this.accessToken && Date.now() < this.tokenExpiry) return this.accessToken;\n\n if (!this.tenantId || !this.clientId || !this.clientSecret) {\n internalWarn(\n 'AzureMonitorTransport: missing credentials — set tenantId, clientId, clientSecret'\n );\n return null;\n }\n\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret,\n scope: 'https://monitor.azure.com/.default',\n }).toString();\n\n const tenantId = this.tenantId;\n if (!AZURE_TENANT_RE.test(tenantId)) {\n internalWarn(\n `AzureMonitorTransport: refusing to request token — tenantId \"${tenantId}\" is not a valid GUID or domain`\n );\n return null;\n }\n\n const reqUrl = new URL(\n `https://login.microsoftonline.com/${encodeURIComponent(tenantId)}/oauth2/v2.0/token`\n );\n try {\n const res = await httpRequest({\n url: reqUrl,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure token request',\n });\n const parsed = JSON.parse(res.body) as { access_token?: string; expires_in?: number };\n if (!parsed.access_token) return null;\n this.accessToken = parsed.access_token;\n this.tokenExpiry = Date.now() + (parsed.expires_in ?? 3600) * 1000 - 60_000;\n return this.accessToken;\n } catch (err) {\n internalError('AzureMonitorTransport token request failed', err);\n return null;\n }\n }\n\n private async sendEntries(entries: TransportLogEntry[]): Promise<void> {\n const token = await this.getAccessToken();\n if (!token) throw new Error('AzureMonitorTransport: no access token available');\n\n const records = entries.map((e) => this.toAzureRecord(e));\n const body = stringifyForLog(records);\n let reqUrl: URL;\n try {\n // Build from the user-configured DCE endpoint; encodeURIComponent-ing the\n // ruleId/streamName stops a hostile config from smuggling extra path\n // segments or query params into the request.\n reqUrl = new URL(\n `dataCollectionRules/${encodeURIComponent(this.ruleId)}/streams/${encodeURIComponent(this.streamName)}?api-version=2023-01-01`,\n this.endpoint.endsWith('/') ? this.endpoint : `${this.endpoint}/`\n );\n } catch (error) {\n internalError(`AzureMonitorTransport: invalid endpoint \"${this.endpoint}\"`, error);\n return;\n }\n if (reqUrl.protocol !== 'https:') {\n internalError(`AzureMonitorTransport: endpoint must use https (got ${reqUrl.protocol})`);\n return;\n }\n\n await httpRequest({\n url: reqUrl,\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body,\n timeoutMs: this.requestTimeoutMs,\n label: 'Azure Monitor API',\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAgDA,MAAM,kBAAkB;AA0BxB,MAAMA,eAAuC;CAC3C,SAAS;CACT,OAAO;CACP,OAAO;CACP,MAAM;CACN,KAAK;CACL,MAAM;CACN,SAAS;CACT,OAAO;CACP,UAAU;CACV,OAAO;CACR;;;;AAKD,IAAa,wBAAb,MAA8D;CAmB5D,YAAY,QAAqC;cAlB1B;oBAOqB;qBACP;qBACf;AAUpB,OAAK,WAAW,OAAO,SAAS,QAAQ,OAAO,GAAG;AAClD,OAAK,SAAS,OAAO;AACrB,OAAK,aAAa,OAAO;AACzB,OAAK,WAAW,OAAO,YAAY,QAAQ,IAAI;AAC/C,OAAK,WAAW,OAAO,YAAY,QAAQ,IAAI;AAC/C,OAAK,eAAe,OAAO,gBAAgB,QAAQ,IAAI;AACvD,OAAK,YAAY,OAAO,aAAa;AACrC,OAAK,gBAAgB,OAAO,mBAAmB;AAC/C,OAAK,QAAQ,OAAO;AACpB,OAAK,mBAAmB,OAAO,oBAAoBC;AACnD,OAAK,SAAS,IAAIC,iCAA+B;GAC/C,MAAM;GACN,WAAW,KAAK;GAChB,eAAe,OAAO,iBAAiBC;GACvC,OAAO,YAAY,KAAK,YAAY,QAAQ;GAC7C,CAAC;AAEF,OAAK,aAAa,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;IAChB,OAAO;IACR,CAAC;GACF,MAAM,SAAS,KAAK,MAAM,IAAI,KAAK;AACnC,OAAI,CAAC,OAAO,aAAc,QAAO;AACjC,QAAK,cAAc,OAAO;AAC1B,QAAK,cAAc,KAAK,KAAK,IAAI,OAAO,cAAc,QAAQ,MAAO;AACrE,UAAO,KAAK;WACL,KAAK;AACZ,sCAAc,8CAA8C,IAAI;AAChE,UAAO;;;CAIX,MAAc,YAAY,SAA6C;EACrE,MAAM,QAAQ,MAAM,KAAK,gBAAgB;AACzC,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,mDAAmD;EAG/E,MAAM,OAAOD,uCADG,QAAQ,KAAK,MAAM,KAAK,cAAc,EAAE,CAAC,CACpB;EACrC,IAAIE;AACJ,MAAI;AAIF,YAAS,IAAI,IACX,uBAAuB,mBAAmB,KAAK,OAAO,CAAC,WAAW,mBAAmB,KAAK,WAAW,CAAC,0BACtG,KAAK,SAAS,SAAS,IAAI,GAAG,KAAK,WAAW,GAAG,KAAK,SAAS,GAChE;WACM,OAAO;AACd,sCAAc,4CAA4C,KAAK,SAAS,IAAI,MAAM;AAClF;;AAEF,MAAI,OAAO,aAAa,UAAU;AAChC,sCAAc,uDAAuD,OAAO,SAAS,GAAG;AACxF;;AAGF,QAAMD,iCAAY;GAChB,KAAK;GACL,SAAS;IAAE,eAAe,UAAU;IAAS,gBAAgB;IAAoB;GACjF;GACA,WAAW,KAAK;GAChB,OAAO;GACR,CAAC"}
|
package/dist/azure.d.mts
ADDED
package/dist/azure.d.ts
ADDED
package/dist/azure.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
require('./internal-log-BUJYMZbE.js');
|
|
2
|
+
require('./safe-stringify-DWo3aZp_.js');
|
|
3
|
+
require('./batch-buffer-BY-mRWIK.js');
|
|
4
|
+
const require_azure_monitor_transport = require('./azure-monitor.transport-CrvfHd9C.js');
|
|
5
|
+
|
|
6
|
+
exports.AzureMonitorTransport = require_azure_monitor_transport.AzureMonitorTransport;
|
package/dist/azure.mjs
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
const require_chunk = require('./chunk-nOFOJqeH.js');
|
|
2
|
+
const require_internal_log = require('./internal-log-BUJYMZbE.js');
|
|
3
|
+
let node_http = require("node:http");
|
|
4
|
+
node_http = require_chunk.__toESM(node_http);
|
|
5
|
+
let node_https = require("node:https");
|
|
6
|
+
node_https = require_chunk.__toESM(node_https);
|
|
7
|
+
|
|
8
|
+
//#region src/transports/batch-buffer.ts
|
|
9
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 1e4;
|
|
10
|
+
const DEFAULT_MAX_BUFFER_SIZE = 1e4;
|
|
11
|
+
const WARN_INTERVAL_MS = 1e4;
|
|
12
|
+
const MAX_ERROR_BODY = 500;
|
|
13
|
+
const MAX_BACKOFF_MS = 3e4;
|
|
14
|
+
var HttpError = class extends Error {
|
|
15
|
+
constructor(status, body, label) {
|
|
16
|
+
const detail = body ? `: ${body.slice(0, MAX_ERROR_BODY)}` : "";
|
|
17
|
+
super(`${label} returned HTTP ${status}${detail}`);
|
|
18
|
+
this.status = status;
|
|
19
|
+
this.body = body;
|
|
20
|
+
this.name = "HttpError";
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
function isPermanentHttpError(err) {
|
|
24
|
+
return err instanceof HttpError && err.status >= 400 && err.status < 500 && err.status !== 429;
|
|
25
|
+
}
|
|
26
|
+
/** One request with a hard timeout. Rejects with HttpError on any non-2xx status. */
|
|
27
|
+
function httpRequest(opts) {
|
|
28
|
+
const { url, method = "POST", headers = {}, body, timeoutMs, label } = opts;
|
|
29
|
+
const transport = url.protocol === "http:" ? node_http : node_https;
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const req = transport.request({
|
|
32
|
+
protocol: url.protocol,
|
|
33
|
+
hostname: url.hostname,
|
|
34
|
+
port: url.port || void 0,
|
|
35
|
+
path: `${url.pathname}${url.search}`,
|
|
36
|
+
method,
|
|
37
|
+
headers: body === void 0 ? headers : {
|
|
38
|
+
...headers,
|
|
39
|
+
"Content-Length": Buffer.byteLength(body)
|
|
40
|
+
}
|
|
41
|
+
}, (res) => {
|
|
42
|
+
let raw = "";
|
|
43
|
+
res.on("data", (c) => raw += c.toString());
|
|
44
|
+
res.on("end", () => {
|
|
45
|
+
const status = res.statusCode ?? 0;
|
|
46
|
+
if (status >= 200 && status < 300) resolve({
|
|
47
|
+
status,
|
|
48
|
+
body: raw
|
|
49
|
+
});
|
|
50
|
+
else reject(new HttpError(status, raw, label));
|
|
51
|
+
});
|
|
52
|
+
res.on("error", reject);
|
|
53
|
+
});
|
|
54
|
+
req.setTimeout(timeoutMs, () => {
|
|
55
|
+
req.destroy(/* @__PURE__ */ new Error(`${label} timed out after ${timeoutMs}ms`));
|
|
56
|
+
});
|
|
57
|
+
req.on("error", reject);
|
|
58
|
+
if (body !== void 0) req.write(body);
|
|
59
|
+
req.end();
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
var BatchBuffer = class {
|
|
63
|
+
constructor(opts) {
|
|
64
|
+
this.opts = opts;
|
|
65
|
+
this.items = [];
|
|
66
|
+
this.dropped = 0;
|
|
67
|
+
this.lastDropWarn = 0;
|
|
68
|
+
this.failures = 0;
|
|
69
|
+
this.retryAfter = 0;
|
|
70
|
+
}
|
|
71
|
+
get length() {
|
|
72
|
+
return this.items.length;
|
|
73
|
+
}
|
|
74
|
+
get batchSize() {
|
|
75
|
+
return this.opts.batchSize;
|
|
76
|
+
}
|
|
77
|
+
push(item) {
|
|
78
|
+
this.items.push(item);
|
|
79
|
+
this.enforceCap();
|
|
80
|
+
}
|
|
81
|
+
/** Threshold flush for write(): skipped while a send is running or the endpoint is backing off. */
|
|
82
|
+
flushIfFull() {
|
|
83
|
+
if (this.items.length < this.opts.batchSize || this.inFlight || Date.now() < this.retryAfter) return;
|
|
84
|
+
this.flush().catch(() => {});
|
|
85
|
+
}
|
|
86
|
+
flush() {
|
|
87
|
+
if (!this.inFlight) this.inFlight = this.drain().finally(() => {
|
|
88
|
+
this.inFlight = void 0;
|
|
89
|
+
});
|
|
90
|
+
return this.inFlight;
|
|
91
|
+
}
|
|
92
|
+
/** Flush up to `attempts` times, then report whatever is still undelivered. */
|
|
93
|
+
async close(attempts = 3) {
|
|
94
|
+
await this.inFlight;
|
|
95
|
+
for (let i = 0; i < attempts && this.items.length > 0; i += 1) await this.flush();
|
|
96
|
+
if (this.items.length > 0) require_internal_log.internalError(`${this.opts.name} closing with ${this.items.length} undelivered entr${this.items.length === 1 ? "y" : "ies"}`);
|
|
97
|
+
}
|
|
98
|
+
async drain() {
|
|
99
|
+
while (this.items.length > 0) {
|
|
100
|
+
const batch = this.items.splice(0, this.opts.batchSize);
|
|
101
|
+
try {
|
|
102
|
+
await this.opts.send(batch);
|
|
103
|
+
this.failures = 0;
|
|
104
|
+
} catch (err) {
|
|
105
|
+
if (!(this.opts.shouldRetry ? this.opts.shouldRetry(err) : !isPermanentHttpError(err))) {
|
|
106
|
+
require_internal_log.internalWarn(`${this.opts.name}: dropping ${batch.length} entr${batch.length === 1 ? "y" : "ies"} the server rejected (${err instanceof Error ? err.message : String(err)})`);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
require_internal_log.internalError(`${this.opts.name} flush error`, err);
|
|
110
|
+
this.items.unshift(...batch);
|
|
111
|
+
this.enforceCap();
|
|
112
|
+
this.failures += 1;
|
|
113
|
+
this.retryAfter = Date.now() + Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.failures - 1));
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
enforceCap() {
|
|
119
|
+
const max = this.opts.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;
|
|
120
|
+
const excess = this.items.length - max;
|
|
121
|
+
if (excess <= 0) return;
|
|
122
|
+
this.items.splice(0, excess);
|
|
123
|
+
this.dropped += excess;
|
|
124
|
+
const now = Date.now();
|
|
125
|
+
if (now - this.lastDropWarn >= WARN_INTERVAL_MS) {
|
|
126
|
+
require_internal_log.internalWarn(`${this.opts.name}: buffer full (${max}), dropped ${this.dropped} oldest entr${this.dropped === 1 ? "y" : "ies"}`);
|
|
127
|
+
this.dropped = 0;
|
|
128
|
+
this.lastDropWarn = now;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
//#endregion
|
|
134
|
+
Object.defineProperty(exports, 'BatchBuffer', {
|
|
135
|
+
enumerable: true,
|
|
136
|
+
get: function () {
|
|
137
|
+
return BatchBuffer;
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
Object.defineProperty(exports, 'DEFAULT_MAX_BUFFER_SIZE', {
|
|
141
|
+
enumerable: true,
|
|
142
|
+
get: function () {
|
|
143
|
+
return DEFAULT_MAX_BUFFER_SIZE;
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
Object.defineProperty(exports, 'DEFAULT_REQUEST_TIMEOUT_MS', {
|
|
147
|
+
enumerable: true,
|
|
148
|
+
get: function () {
|
|
149
|
+
return DEFAULT_REQUEST_TIMEOUT_MS;
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
Object.defineProperty(exports, 'HttpError', {
|
|
153
|
+
enumerable: true,
|
|
154
|
+
get: function () {
|
|
155
|
+
return HttpError;
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
Object.defineProperty(exports, 'httpRequest', {
|
|
159
|
+
enumerable: true,
|
|
160
|
+
get: function () {
|
|
161
|
+
return httpRequest;
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
Object.defineProperty(exports, 'isPermanentHttpError', {
|
|
165
|
+
enumerable: true,
|
|
166
|
+
get: function () {
|
|
167
|
+
return isPermanentHttpError;
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
//# sourceMappingURL=batch-buffer-BY-mRWIK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batch-buffer-BY-mRWIK.js","names":["status: number","body: string","http","https","opts: BatchBufferOptions<T>"],"sources":["../src/transports/batch-buffer.ts"],"sourcesContent":["/**\n * Shared batching core for the network transports (OTLP, CloudWatch, GCP, Azure).\n *\n * - one send in flight at a time; flush() and close() join it instead of\n * racing it, so close() cannot return while a request is still on the wire\n * - a failed batch goes back to the front in its original order\n * - 4xx responses other than 429 drop the batch with a warning instead of\n * retrying a request the server will never accept\n * - the buffer is capped; when full the oldest entries are dropped\n */\n\nimport * as http from 'node:http';\nimport * as https from 'node:https';\n\nimport { internalError, internalWarn } from '../utils/internal-log';\n\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\nexport const DEFAULT_MAX_BUFFER_SIZE = 10_000;\nconst WARN_INTERVAL_MS = 10_000;\nconst MAX_ERROR_BODY = 500;\nconst MAX_BACKOFF_MS = 30_000;\n\nexport class HttpError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string,\n label: string\n ) {\n const detail = body ? `: ${body.slice(0, MAX_ERROR_BODY)}` : '';\n super(`${label} returned HTTP ${status}${detail}`);\n this.name = 'HttpError';\n }\n}\n\nexport function isPermanentHttpError(err: unknown): boolean {\n return err instanceof HttpError && err.status >= 400 && err.status < 500 && err.status !== 429;\n}\n\nexport interface HttpRequestOptions {\n url: URL;\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n timeoutMs: number;\n label: string;\n}\n\nexport interface HttpResult {\n status: number;\n body: string;\n}\n\n/** One request with a hard timeout. Rejects with HttpError on any non-2xx status. */\nexport function httpRequest(opts: HttpRequestOptions): Promise<HttpResult> {\n const { url, method = 'POST', headers = {}, body, timeoutMs, label } = opts;\n const transport = url.protocol === 'http:' ? http : https;\n return new Promise<HttpResult>((resolve, reject) => {\n const req = transport.request(\n {\n protocol: url.protocol,\n hostname: url.hostname,\n port: url.port || undefined,\n path: `${url.pathname}${url.search}`,\n method,\n headers:\n body === undefined ? headers : { ...headers, 'Content-Length': Buffer.byteLength(body) },\n },\n (res) => {\n let raw = '';\n res.on('data', (c: Buffer) => (raw += c.toString()));\n res.on('end', () => {\n const status = res.statusCode ?? 0;\n if (status >= 200 && status < 300) resolve({ status, body: raw });\n else reject(new HttpError(status, raw, label));\n });\n res.on('error', reject);\n }\n );\n req.setTimeout(timeoutMs, () => {\n req.destroy(new Error(`${label} timed out after ${timeoutMs}ms`));\n });\n req.on('error', reject);\n if (body !== undefined) req.write(body);\n req.end();\n });\n}\n\nexport interface BatchBufferOptions<T> {\n name: string;\n batchSize: number;\n maxBufferSize?: number;\n send: (items: T[]) => Promise<void>;\n /** Overrides the default drop-on-4xx rule. Return true to keep and retry the batch. */\n shouldRetry?: (err: unknown) => boolean;\n}\n\nexport class BatchBuffer<T> {\n private items: T[] = [];\n private inFlight: Promise<void> | undefined;\n private dropped = 0;\n private lastDropWarn = 0;\n private failures = 0;\n private retryAfter = 0;\n\n constructor(private readonly opts: BatchBufferOptions<T>) {}\n\n get length(): number {\n return this.items.length;\n }\n\n get batchSize(): number {\n return this.opts.batchSize;\n }\n\n push(item: T): void {\n this.items.push(item);\n this.enforceCap();\n }\n\n /** Threshold flush for write(): skipped while a send is running or the endpoint is backing off. */\n flushIfFull(): void {\n if (this.items.length < this.opts.batchSize || this.inFlight || Date.now() < this.retryAfter) {\n return;\n }\n this.flush().catch(() => {});\n }\n\n flush(): Promise<void> {\n if (!this.inFlight) {\n this.inFlight = this.drain().finally(() => {\n this.inFlight = undefined;\n });\n }\n return this.inFlight;\n }\n\n /** Flush up to `attempts` times, then report whatever is still undelivered. */\n async close(attempts = 3): Promise<void> {\n await this.inFlight;\n for (let i = 0; i < attempts && this.items.length > 0; i += 1) {\n await this.flush();\n }\n if (this.items.length > 0) {\n internalError(\n `${this.opts.name} closing with ${this.items.length} undelivered entr${this.items.length === 1 ? 'y' : 'ies'}`\n );\n }\n }\n\n private async drain(): Promise<void> {\n while (this.items.length > 0) {\n const batch = this.items.splice(0, this.opts.batchSize);\n try {\n await this.opts.send(batch);\n this.failures = 0;\n } catch (err) {\n const retry = this.opts.shouldRetry\n ? this.opts.shouldRetry(err)\n : !isPermanentHttpError(err);\n if (!retry) {\n internalWarn(\n `${this.opts.name}: dropping ${batch.length} entr${batch.length === 1 ? 'y' : 'ies'} the server rejected (${err instanceof Error ? err.message : String(err)})`\n );\n continue;\n }\n internalError(`${this.opts.name} flush error`, err);\n this.items.unshift(...batch);\n this.enforceCap();\n this.failures += 1;\n this.retryAfter = Date.now() + Math.min(MAX_BACKOFF_MS, 1000 * 2 ** (this.failures - 1));\n return;\n }\n }\n }\n\n private enforceCap(): void {\n const max = this.opts.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n const excess = this.items.length - max;\n if (excess <= 0) return;\n this.items.splice(0, excess);\n this.dropped += excess;\n const now = Date.now();\n if (now - this.lastDropWarn >= WARN_INTERVAL_MS) {\n internalWarn(\n `${this.opts.name}: buffer full (${max}), dropped ${this.dropped} oldest entr${this.dropped === 1 ? 'y' : 'ies'}`\n );\n this.dropped = 0;\n this.lastDropWarn = now;\n }\n }\n}\n"],"mappings":";;;;;;;;AAgBA,MAAa,6BAA6B;AAC1C,MAAa,0BAA0B;AACvC,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,IAAa,YAAb,cAA+B,MAAM;CACnC,YACE,AAAgBA,QAChB,AAAgBC,MAChB,OACA;EACA,MAAM,SAAS,OAAO,KAAK,KAAK,MAAM,GAAG,eAAe,KAAK;AAC7D,QAAM,GAAG,MAAM,iBAAiB,SAAS,SAAS;EALlC;EACA;AAKhB,OAAK,OAAO;;;AAIhB,SAAgB,qBAAqB,KAAuB;AAC1D,QAAO,eAAe,aAAa,IAAI,UAAU,OAAO,IAAI,SAAS,OAAO,IAAI,WAAW;;;AAkB7F,SAAgB,YAAY,MAA+C;CACzE,MAAM,EAAE,KAAK,SAAS,QAAQ,UAAU,EAAE,EAAE,MAAM,WAAW,UAAU;CACvE,MAAM,YAAY,IAAI,aAAa,UAAUC,YAAO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K,gBAAgB,kBAAkB;AAC/C,qCACE,GAAG,KAAK,KAAK,KAAK,iBAAiB,IAAI,aAAa,KAAK,QAAQ,cAAc,KAAK,YAAY,IAAI,MAAM,QAC3G;AACD,QAAK,UAAU;AACf,QAAK,eAAe"}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { r as internalWarn, t as internalError } from "./internal-log-Cm8SOWSV.mjs";
|
|
2
|
+
import * as http from "node:http";
|
|
3
|
+
import * as https from "node:https";
|
|
4
|
+
|
|
5
|
+
//#region src/transports/batch-buffer.ts
|
|
6
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 1e4;
|
|
7
|
+
const DEFAULT_MAX_BUFFER_SIZE = 1e4;
|
|
8
|
+
const WARN_INTERVAL_MS = 1e4;
|
|
9
|
+
const MAX_ERROR_BODY = 500;
|
|
10
|
+
const MAX_BACKOFF_MS = 3e4;
|
|
11
|
+
var HttpError = class extends Error {
|
|
12
|
+
constructor(status, body, label) {
|
|
13
|
+
const detail = body ? `: ${body.slice(0, MAX_ERROR_BODY)}` : "";
|
|
14
|
+
super(`${label} returned HTTP ${status}${detail}`);
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.body = body;
|
|
17
|
+
this.name = "HttpError";
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
function isPermanentHttpError(err) {
|
|
21
|
+
return err instanceof HttpError && err.status >= 400 && err.status < 500 && err.status !== 429;
|
|
22
|
+
}
|
|
23
|
+
/** One request with a hard timeout. Rejects with HttpError on any non-2xx status. */
|
|
24
|
+
function httpRequest(opts) {
|
|
25
|
+
const { url, method = "POST", headers = {}, body, timeoutMs, label } = opts;
|
|
26
|
+
const transport = url.protocol === "http:" ? http : https;
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
const req = transport.request({
|
|
29
|
+
protocol: url.protocol,
|
|
30
|
+
hostname: url.hostname,
|
|
31
|
+
port: url.port || void 0,
|
|
32
|
+
path: `${url.pathname}${url.search}`,
|
|
33
|
+
method,
|
|
34
|
+
headers: body === void 0 ? headers : {
|
|
35
|
+
...headers,
|
|
36
|
+
"Content-Length": Buffer.byteLength(body)
|
|
37
|
+
}
|
|
38
|
+
}, (res) => {
|
|
39
|
+
let raw = "";
|
|
40
|
+
res.on("data", (c) => raw += c.toString());
|
|
41
|
+
res.on("end", () => {
|
|
42
|
+
const status = res.statusCode ?? 0;
|
|
43
|
+
if (status >= 200 && status < 300) resolve({
|
|
44
|
+
status,
|
|
45
|
+
body: raw
|
|
46
|
+
});
|
|
47
|
+
else reject(new HttpError(status, raw, label));
|
|
48
|
+
});
|
|
49
|
+
res.on("error", reject);
|
|
50
|
+
});
|
|
51
|
+
req.setTimeout(timeoutMs, () => {
|
|
52
|
+
req.destroy(/* @__PURE__ */ new Error(`${label} timed out after ${timeoutMs}ms`));
|
|
53
|
+
});
|
|
54
|
+
req.on("error", reject);
|
|
55
|
+
if (body !== void 0) req.write(body);
|
|
56
|
+
req.end();
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
var BatchBuffer = class {
|
|
60
|
+
constructor(opts) {
|
|
61
|
+
this.opts = opts;
|
|
62
|
+
this.items = [];
|
|
63
|
+
this.dropped = 0;
|
|
64
|
+
this.lastDropWarn = 0;
|
|
65
|
+
this.failures = 0;
|
|
66
|
+
this.retryAfter = 0;
|
|
67
|
+
}
|
|
68
|
+
get length() {
|
|
69
|
+
return this.items.length;
|
|
70
|
+
}
|
|
71
|
+
get batchSize() {
|
|
72
|
+
return this.opts.batchSize;
|
|
73
|
+
}
|
|
74
|
+
push(item) {
|
|
75
|
+
this.items.push(item);
|
|
76
|
+
this.enforceCap();
|
|
77
|
+
}
|
|
78
|
+
/** Threshold flush for write(): skipped while a send is running or the endpoint is backing off. */
|
|
79
|
+
flushIfFull() {
|
|
80
|
+
if (this.items.length < this.opts.batchSize || this.inFlight || Date.now() < this.retryAfter) return;
|
|
81
|
+
this.flush().catch(() => {});
|
|
82
|
+
}
|
|
83
|
+
flush() {
|
|
84
|
+
if (!this.inFlight) this.inFlight = this.drain().finally(() => {
|
|
85
|
+
this.inFlight = void 0;
|
|
86
|
+
});
|
|
87
|
+
return this.inFlight;
|
|
88
|
+
}
|
|
89
|
+
/** Flush up to `attempts` times, then report whatever is still undelivered. */
|
|
90
|
+
async close(attempts = 3) {
|
|
91
|
+
await this.inFlight;
|
|
92
|
+
for (let i = 0; i < attempts && this.items.length > 0; i += 1) await this.flush();
|
|
93
|
+
if (this.items.length > 0) internalError(`${this.opts.name} closing with ${this.items.length} undelivered entr${this.items.length === 1 ? "y" : "ies"}`);
|
|
94
|
+
}
|
|
95
|
+
async drain() {
|
|
96
|
+
while (this.items.length > 0) {
|
|
97
|
+
const batch = this.items.splice(0, this.opts.batchSize);
|
|
98
|
+
try {
|
|
99
|
+
await this.opts.send(batch);
|
|
100
|
+
this.failures = 0;
|
|
101
|
+
} catch (err) {
|
|
102
|
+
if (!(this.opts.shouldRetry ? this.opts.shouldRetry(err) : !isPermanentHttpError(err))) {
|
|
103
|
+
internalWarn(`${this.opts.name}: dropping ${batch.length} entr${batch.length === 1 ? "y" : "ies"} the server rejected (${err instanceof Error ? err.message : String(err)})`);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
internalError(`${this.opts.name} flush error`, err);
|
|
107
|
+
this.items.unshift(...batch);
|
|
108
|
+
this.enforceCap();
|
|
109
|
+
this.failures += 1;
|
|
110
|
+
this.retryAfter = Date.now() + Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.failures - 1));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
enforceCap() {
|
|
116
|
+
const max = this.opts.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;
|
|
117
|
+
const excess = this.items.length - max;
|
|
118
|
+
if (excess <= 0) return;
|
|
119
|
+
this.items.splice(0, excess);
|
|
120
|
+
this.dropped += excess;
|
|
121
|
+
const now = Date.now();
|
|
122
|
+
if (now - this.lastDropWarn >= WARN_INTERVAL_MS) {
|
|
123
|
+
internalWarn(`${this.opts.name}: buffer full (${max}), dropped ${this.dropped} oldest entr${this.dropped === 1 ? "y" : "ies"}`);
|
|
124
|
+
this.dropped = 0;
|
|
125
|
+
this.lastDropWarn = now;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
//#endregion
|
|
131
|
+
export { httpRequest as a, HttpError as i, DEFAULT_MAX_BUFFER_SIZE as n, isPermanentHttpError as o, DEFAULT_REQUEST_TIMEOUT_MS as r, BatchBuffer as t };
|
|
132
|
+
//# sourceMappingURL=batch-buffer-PGvSgbmd.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batch-buffer-PGvSgbmd.mjs","names":["status: number","body: string","opts: BatchBufferOptions<T>"],"sources":["../src/transports/batch-buffer.ts"],"sourcesContent":["/**\n * Shared batching core for the network transports (OTLP, CloudWatch, GCP, Azure).\n *\n * - one send in flight at a time; flush() and close() join it instead of\n * racing it, so close() cannot return while a request is still on the wire\n * - a failed batch goes back to the front in its original order\n * - 4xx responses other than 429 drop the batch with a warning instead of\n * retrying a request the server will never accept\n * - the buffer is capped; when full the oldest entries are dropped\n */\n\nimport * as http from 'node:http';\nimport * as https from 'node:https';\n\nimport { internalError, internalWarn } from '../utils/internal-log';\n\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\nexport const DEFAULT_MAX_BUFFER_SIZE = 10_000;\nconst WARN_INTERVAL_MS = 10_000;\nconst MAX_ERROR_BODY = 500;\nconst MAX_BACKOFF_MS = 30_000;\n\nexport class HttpError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string,\n label: string\n ) {\n const detail = body ? `: ${body.slice(0, MAX_ERROR_BODY)}` : '';\n super(`${label} returned HTTP ${status}${detail}`);\n this.name = 'HttpError';\n }\n}\n\nexport function isPermanentHttpError(err: unknown): boolean {\n return err instanceof HttpError && err.status >= 400 && err.status < 500 && err.status !== 429;\n}\n\nexport interface HttpRequestOptions {\n url: URL;\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n timeoutMs: number;\n label: string;\n}\n\nexport interface HttpResult {\n status: number;\n body: string;\n}\n\n/** One request with a hard timeout. Rejects with HttpError on any non-2xx status. */\nexport function httpRequest(opts: HttpRequestOptions): Promise<HttpResult> {\n const { url, method = 'POST', headers = {}, body, timeoutMs, label } = opts;\n const transport = url.protocol === 'http:' ? http : https;\n return new Promise<HttpResult>((resolve, reject) => {\n const req = transport.request(\n {\n protocol: url.protocol,\n hostname: url.hostname,\n port: url.port || undefined,\n path: `${url.pathname}${url.search}`,\n method,\n headers:\n body === undefined ? headers : { ...headers, 'Content-Length': Buffer.byteLength(body) },\n },\n (res) => {\n let raw = '';\n res.on('data', (c: Buffer) => (raw += c.toString()));\n res.on('end', () => {\n const status = res.statusCode ?? 0;\n if (status >= 200 && status < 300) resolve({ status, body: raw });\n else reject(new HttpError(status, raw, label));\n });\n res.on('error', reject);\n }\n );\n req.setTimeout(timeoutMs, () => {\n req.destroy(new Error(`${label} timed out after ${timeoutMs}ms`));\n });\n req.on('error', reject);\n if (body !== undefined) req.write(body);\n req.end();\n });\n}\n\nexport interface BatchBufferOptions<T> {\n name: string;\n batchSize: number;\n maxBufferSize?: number;\n send: (items: T[]) => Promise<void>;\n /** Overrides the default drop-on-4xx rule. Return true to keep and retry the batch. */\n shouldRetry?: (err: unknown) => boolean;\n}\n\nexport class BatchBuffer<T> {\n private items: T[] = [];\n private inFlight: Promise<void> | undefined;\n private dropped = 0;\n private lastDropWarn = 0;\n private failures = 0;\n private retryAfter = 0;\n\n constructor(private readonly opts: BatchBufferOptions<T>) {}\n\n get length(): number {\n return this.items.length;\n }\n\n get batchSize(): number {\n return this.opts.batchSize;\n }\n\n push(item: T): void {\n this.items.push(item);\n this.enforceCap();\n }\n\n /** Threshold flush for write(): skipped while a send is running or the endpoint is backing off. */\n flushIfFull(): void {\n if (this.items.length < this.opts.batchSize || this.inFlight || Date.now() < this.retryAfter) {\n return;\n }\n this.flush().catch(() => {});\n }\n\n flush(): Promise<void> {\n if (!this.inFlight) {\n this.inFlight = this.drain().finally(() => {\n this.inFlight = undefined;\n });\n }\n return this.inFlight;\n }\n\n /** Flush up to `attempts` times, then report whatever is still undelivered. */\n async close(attempts = 3): Promise<void> {\n await this.inFlight;\n for (let i = 0; i < attempts && this.items.length > 0; i += 1) {\n await this.flush();\n }\n if (this.items.length > 0) {\n internalError(\n `${this.opts.name} closing with ${this.items.length} undelivered entr${this.items.length === 1 ? 'y' : 'ies'}`\n );\n }\n }\n\n private async drain(): Promise<void> {\n while (this.items.length > 0) {\n const batch = this.items.splice(0, this.opts.batchSize);\n try {\n await this.opts.send(batch);\n this.failures = 0;\n } catch (err) {\n const retry = this.opts.shouldRetry\n ? this.opts.shouldRetry(err)\n : !isPermanentHttpError(err);\n if (!retry) {\n internalWarn(\n `${this.opts.name}: dropping ${batch.length} entr${batch.length === 1 ? 'y' : 'ies'} the server rejected (${err instanceof Error ? err.message : String(err)})`\n );\n continue;\n }\n internalError(`${this.opts.name} flush error`, err);\n this.items.unshift(...batch);\n this.enforceCap();\n this.failures += 1;\n this.retryAfter = Date.now() + Math.min(MAX_BACKOFF_MS, 1000 * 2 ** (this.failures - 1));\n return;\n }\n }\n }\n\n private enforceCap(): void {\n const max = this.opts.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n const excess = this.items.length - max;\n if (excess <= 0) return;\n this.items.splice(0, excess);\n this.dropped += excess;\n const now = Date.now();\n if (now - this.lastDropWarn >= WARN_INTERVAL_MS) {\n internalWarn(\n `${this.opts.name}: buffer full (${max}), dropped ${this.dropped} oldest entr${this.dropped === 1 ? 'y' : 'ies'}`\n );\n this.dropped = 0;\n this.lastDropWarn = now;\n }\n }\n}\n"],"mappings":";;;;;AAgBA,MAAa,6BAA6B;AAC1C,MAAa,0BAA0B;AACvC,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBA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