@rebasepro/server 0.31.0 → 0.32.0
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/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
- package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
- package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
- package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
- package/dist/{access-Dtu87BMj.js → access-BxkEYQh1.js} +5 -5
- package/dist/{access-Dtu87BMj.js.map → access-BxkEYQh1.js.map} +1 -1
- package/dist/api/errors.d.ts +4 -0
- package/dist/api/rest/api-generator.d.ts +8 -0
- package/dist/{auth-BOz84vIr.js → auth-Bfwjg4Bg.js} +37 -13
- package/dist/auth-Bfwjg4Bg.js.map +1 -0
- package/dist/backend/create-backend.d.ts +6 -0
- package/dist/backend/options.d.ts +10 -0
- package/dist/backend/services.d.ts +9 -0
- package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
- package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
- package/dist/boot/bundle.d.ts +11 -1
- package/dist/boot/env.d.ts +5 -0
- package/dist/boot/security-headers.d.ts +15 -5
- package/dist/boot/static-routing.d.ts +58 -0
- package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
- package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
- package/dist/{contract-routes-o5oqNhfc.js → contract-routes-CZTlAP7p.js} +3 -3
- package/dist/{contract-routes-o5oqNhfc.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
- package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
- package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
- package/dist/{cron-routes-BOu-bY7I.js → cron-routes-Du03uJ7K.js} +5 -5
- package/dist/{cron-routes-BOu-bY7I.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
- package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
- package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
- package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
- package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
- package/dist/dist-C1vNURUy.js +19354 -0
- package/dist/dist-C1vNURUy.js.map +1 -0
- package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
- package/dist/errors-NVbAQU25.js.map +1 -0
- package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
- package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
- package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
- package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
- package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
- package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
- package/dist/functions/index.d.ts +2 -0
- package/dist/functions/index.js +162 -1
- package/dist/functions/index.js.map +1 -1
- package/dist/functions/rate-limit.d.ts +71 -0
- package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
- package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
- package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
- package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.es.js +1241 -213
- package/dist/index.es.js.map +1 -1
- package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
- package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
- package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
- package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
- package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
- package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
- package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
- package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
- package/dist/{load-schema-Cv5XLVjW.js → load-schema-B4Nv1mwq.js} +32 -4
- package/dist/{load-schema-Cv5XLVjW.js.map → load-schema-B4Nv1mwq.js.map} +1 -1
- package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
- package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
- package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
- package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
- package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
- package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
- package/dist/{openapi-generator-CoAFACMx.js → openapi-generator-CAhJiwBm.js} +3 -3
- package/dist/{openapi-generator-CoAFACMx.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
- package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
- package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
- package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
- package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
- package/dist/push/push-options.d.ts +26 -0
- package/dist/push/push-routes.d.ts +30 -0
- package/dist/push/push-service.d.ts +13 -0
- package/dist/push/push-store.d.ts +45 -0
- package/dist/push/set-up.d.ts +25 -0
- package/dist/push/subscription-input.d.ts +26 -0
- package/dist/push/vapid-config.d.ts +35 -0
- package/dist/push/web-push-crypto.d.ts +44 -0
- package/dist/push/web-push-sender.d.ts +10 -0
- package/dist/{query-parser-D9Uf8aha.js → query-parser-Cd70kZO8.js} +5 -5
- package/dist/{query-parser-D9Uf8aha.js.map → query-parser-Cd70kZO8.js.map} +1 -1
- package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
- package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
- package/dist/{rls-simulator-routes-BvH6wI64.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
- package/dist/{rls-simulator-routes-BvH6wI64.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
- package/dist/{schema-editor-routes-CzITcAgt.js → schema-editor-routes-DEGwyQmx.js} +5 -5
- package/dist/{schema-editor-routes-CzITcAgt.js.map → schema-editor-routes-DEGwyQmx.js.map} +1 -1
- package/dist/{schema-tables-lJHnyqj4.js → schema-tables-DKFg6vMV.js} +3 -3
- package/dist/{schema-tables-lJHnyqj4.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
- package/dist/{schema-tables-routes-Uss-ljon.js → schema-tables-routes-BfsNG4c4.js} +5 -5
- package/dist/{schema-tables-routes-Uss-ljon.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
- package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
- package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
- package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
- package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
- package/dist/serve-spa.d.ts +12 -0
- package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
- package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
- package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
- package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
- package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
- package/dist/src-CNZB3fuE.js.map +1 -0
- package/dist/{table-source-editor-qmyi5vxX.js → table-source-editor-D_zNDhEU.js} +3 -3
- package/dist/{table-source-editor-qmyi5vxX.js.map → table-source-editor-D_zNDhEU.js.map} +1 -1
- package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
- package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
- package/package.json +5 -5
- package/dist/auth-BOz84vIr.js.map +0 -1
- package/dist/dist-fBcYxf4h.js +0 -19354
- package/dist/dist-fBcYxf4h.js.map +0 -1
- package/dist/errors-DpTMfX77.js.map +0 -1
- package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
- package/dist/src-DLIb1O9l.js.map +0 -1
|
@@ -2,9 +2,9 @@ import { createRequire as __rebaseCreateRequire } from "module";
|
|
|
2
2
|
import __rebaseProcess from "process";
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
|
-
import {
|
|
5
|
+
import { Rn as __exportAll } from "./src-CNZB3fuE.js";
|
|
6
6
|
import { n as addLogSink } from "./logger-SigQ2oZJ.js";
|
|
7
|
-
import { i as errorHandler, t as ApiError } from "./errors-
|
|
7
|
+
import { i as errorHandler, t as ApiError } from "./errors-NVbAQU25.js";
|
|
8
8
|
import { Hono } from "hono";
|
|
9
9
|
import { streamSSE } from "hono/streaming";
|
|
10
10
|
//#region src/api/logs-routes.ts
|
|
@@ -380,4 +380,4 @@ createLogsRoutes();
|
|
|
380
380
|
//#endregion
|
|
381
381
|
export { logs_routes_exports as n, logMiddleware as t };
|
|
382
382
|
|
|
383
|
-
//# sourceMappingURL=logs-routes-
|
|
383
|
+
//# sourceMappingURL=logs-routes-C3CLYP-n.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logs-routes-BT4af1Or.js","names":[],"sources":["../src/api/logs-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { MiddlewareHandler } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport type { HonoEnv } from \"./types\";\nimport { ApiError, errorHandler } from \"./errors\";\nimport { addLogSink } from \"../utils/logger\";\n\nexport interface LogEntry {\n id: string;\n timestamp: string;\n level: \"debug\" | \"info\" | \"warn\" | \"error\";\n source: \"api\" | \"auth\" | \"storage\" | \"realtime\" | \"system\";\n message: string;\n metadata?: Record<string, unknown>;\n}\n\n/** What a caller can narrow the log by, in either direction (query or stream). */\nexport interface LogFilterOptions {\n level?: string;\n source?: string;\n search?: string;\n since?: string;\n}\n\n/**\n * A filter with the search term already lowercased.\n *\n * The distinction matters on the stream path: `query()` lowercases once and then\n * scans, but a subscriber tests one entry at a time and would otherwise redo the\n * same `toLowerCase()` on every request the server handles.\n */\ntype NormalizedFilter = LogFilterOptions;\n\nfunction normalizeFilter(options: LogFilterOptions): NormalizedFilter {\n return { ...options,\n search: options.search?.toLowerCase() };\n}\n\n/**\n * Whether one entry belongs in a filtered view.\n *\n * Shared by the query and the stream on purpose: two copies of this would drift,\n * and the failure that produces is invisible — a tail that quietly shows a\n * different set of lines than the snapshot it started from.\n */\nfunction matchesFilter(entry: LogEntry, filter: NormalizedFilter): boolean {\n if (filter.level && entry.level !== filter.level) return false;\n if (filter.source && entry.source !== filter.source) return false;\n if (filter.search && !entry.message.toLowerCase().includes(filter.search)) return false;\n if (filter.since && entry.timestamp < filter.since) return false;\n return true;\n}\n\n/** Notified for every entry pushed, in push order. */\nexport type LogListener = (entry: LogEntry) => void;\n\nclass LogRingBuffer {\n private buffer: LogEntry[] = [];\n private maxSize: number;\n private idCounter = 0;\n private listeners = new Set<LogListener>();\n\n constructor(maxSize = 10000) {\n this.maxSize = maxSize;\n }\n\n push(entry: Omit<LogEntry, \"id\">): void {\n const id = `log_${++this.idCounter}`;\n const stored: LogEntry = { ...entry,\n id };\n this.buffer.push(stored);\n if (this.buffer.length > this.maxSize) {\n this.buffer.shift();\n }\n // This runs on the request hot path, so a listener must never be able to\n // take the request down with it: a tail that throws loses its own tail,\n // not the response the log line was describing.\n for (const listener of this.listeners) {\n try {\n listener(stored);\n } catch {\n /* a broken tail is not the request's problem */\n }\n }\n }\n\n /**\n * Follow the buffer. Returns the unsubscribe — call it, always: a listener\n * left behind holds its whole closure, and on this class that closure is a\n * pending-entry array.\n *\n * A listener must not log. It is called from inside `push`, so anything that\n * reaches `addLog` from here recurses until the stack gives out.\n */\n subscribe(listener: LogListener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n query(options: LogFilterOptions & {\n limit?: number;\n offset?: number;\n }): { entries: LogEntry[]; total: number } {\n const filter = normalizeFilter(options);\n const filtered = this.buffer.filter(e => matchesFilter(e, filter));\n\n // Newest first\n const sorted = [...filtered].reverse();\n const total = sorted.length;\n const limit = options.limit || 100;\n const offset = options.offset || 0;\n\n return {\n entries: sorted.slice(offset, offset + limit),\n total\n };\n }\n\n getLatest(count = 50): LogEntry[] {\n return this.buffer.slice(-count).reverse();\n }\n}\n\n// Global singleton\nexport const logBuffer = new LogRingBuffer();\n\n/**\n * Which process this log belongs to.\n *\n * The ring is this process's memory, and nothing gathers the rings of a\n * deployment's other replicas or of its split runtime roles. So a reader is\n * told whose log it is: `HOSTNAME` is the pod name on Kubernetes and the\n * container id under Docker; the pid tells two local processes apart.\n */\nexport function logInstanceName(): string {\n return process.env.HOSTNAME?.trim() || `pid-${process.pid}`;\n}\n\n/** Add a log entry */\nexport function addLog(\n level: LogEntry[\"level\"],\n source: LogEntry[\"source\"],\n message: string,\n metadata?: Record<string, unknown>\n): void {\n logBuffer.push({\n timestamp: new Date().toISOString(),\n level,\n source,\n message,\n metadata\n });\n}\n\nexport interface LogMiddlewareOptions {\n /**\n * Paths this sink ignores, matched exactly against `c.req.path`.\n *\n * For requests whose only reason to exist is to read the log. Recording\n * those makes the reader the loudest thing in its own output, and on a quiet\n * server it is also the thing evicting real entries out of the ring.\n */\n ignorePaths?: string[];\n /**\n * Where the API is mounted (`/api`). The segment after it names the\n * subsystem a request is filed under — see {@link sourceForRequestPath}.\n * Unset, the first segment of the path is read.\n */\n basePath?: string;\n}\n\n/** The first path segment under the base path that files a request under a source other than `api`. */\nconst SOURCE_BY_SEGMENT: Readonly<Record<string, LogEntry[\"source\"]>> = {\n auth: \"auth\",\n oauth: \"auth\",\n storage: \"storage\"\n};\n\n/**\n * The `source` of a request entry: the subsystem its path addresses.\n *\n * `/api/auth/*` and the MCP authorization server under `/api/oauth/*` are\n * `auth`, `/api/storage/*` is `storage`, and everything else is `api`. The\n * Logs Explorer's Source filter matches this field, so a sign-in filed as\n * `api` was invisible under Auth. The realtime socket is not an HTTP request\n * and is not recorded here.\n *\n * Exported for its test.\n */\nexport function sourceForRequestPath(path: string, basePath = \"\"): LogEntry[\"source\"] {\n const base = basePath.replace(/\\/+$/, \"\");\n if (base && path !== base && !path.startsWith(`${base}/`)) return \"api\";\n const segment = path.slice(base.length).split(\"/\").find(part => part !== \"\")?.toLowerCase();\n return (segment !== undefined && Object.prototype.hasOwnProperty.call(SOURCE_BY_SEGMENT, segment))\n ? SOURCE_BY_SEGMENT[segment]\n : \"api\";\n}\n\n/** Hono middleware to log API requests */\nexport function logMiddleware(options: LogMiddlewareOptions = {}): MiddlewareHandler<HonoEnv> {\n const ignored = new Set(options.ignorePaths ?? []);\n return async (c, next) => {\n const start = Date.now();\n await next();\n if (ignored.has(c.req.path)) return;\n const duration = Date.now() - start;\n const reqId = c.get(\"requestId\");\n // Every request used to be recorded at `info`, whatever it answered, so\n // the Logs Explorer's level filter could not find a single failure: a\n // 500 sat at the same level as the 200 above it, in a wall of them.\n const status = c.res.status;\n const level: LogEntry[\"level\"] = status >= 500 ? \"error\" : status >= 400 ? \"warn\" : \"info\";\n // What the error handler answered, so the failure is on the entry\n // rather than in a stdout line the panel cannot see. See\n // `HonoEnv.Variables.errorSummary`.\n const failure = c.get(\"errorSummary\");\n addLog(\n level,\n sourceForRequestPath(c.req.path, options.basePath),\n `${c.req.method} ${c.req.path} ${status} ${duration}ms`\n + (failure ? ` — ${failure.code}: ${failure.message}` : \"\"),\n {\n method: c.req.method,\n path: c.req.path,\n status,\n duration,\n ...(reqId && { requestId: reqId }),\n ...(c.get(\"collection\") && { collection: c.get(\"collection\") }),\n ...(failure && { errorCode: failure.code, errorMessage: failure.message })\n }\n );\n };\n}\n\n/**\n * Prefixes the server writes at the head of a log message, and the `source`\n * each one belongs to.\n *\n * The ring's `source` is a closed set the Studio filters on, and the messages\n * carry their origin as a bracketed prefix — `[API]`, `[Auth]`, `[functions]`,\n * `[schema]`. Matching them is what makes a teed line filterable beside the\n * request entries rather than a heap under \"system\".\n */\nconst SOURCE_BY_PREFIX: Array<[RegExp, LogEntry[\"source\"]]> = [\n [/^\\[?(api|rest)\\b/i, \"api\"],\n [/^\\[?auth\\b/i, \"auth\"],\n [/^\\[?(storage|s3|gcs)\\b/i, \"storage\"],\n [/^\\[?(realtime|ws|websocket|cdc)\\b/i, \"realtime\"]\n];\n\n/**\n * The `source` for a teed line, from whatever prefix it carries.\n *\n * Exported for its test: the mapping is a string match on wording somebody else\n * writes, which is the shape of check that stops working without failing.\n */\nexport function sourceForMessage(message: string): LogEntry[\"source\"] {\n // The level emoji comes first on several call sites (`⚠️ [API] …`), so the\n // prefix is whatever is inside the first bracket, wherever that is.\n const bracketed = message.match(/\\[([^\\]]{1,32})\\]/);\n const candidate = bracketed?.[1] ?? message;\n for (const [pattern, source] of SOURCE_BY_PREFIX) {\n if (pattern.test(candidate)) return source;\n }\n return \"system\";\n}\n\n/**\n * Feed the Logs Explorer everything the server says at warn and above.\n *\n * The ring used to be filled by `logMiddleware` alone, so the panel showed a\n * wall of `GET /api/data/posts 200 4ms` and not one of the errors, warnings or\n * boot diagnoses being written to stdout at the same moment. A function that\n * threw was the sharpest case: the request entry said `500` and the reason\n * existed only in a terminal the person looking at the panel does not have.\n *\n * Warn and above, deliberately. `info` is where the steady-state chatter lives,\n * and a 10,000-entry ring filled with it evicts the lines somebody opened the\n * panel to find.\n *\n * Idempotent: called from `createLogsRoutes`, which a split deployment may\n * reach more than once.\n */\nlet detachLoggerTee: (() => void) | undefined;\nexport function teeLoggerIntoLogBuffer(): () => void {\n if (detachLoggerTee) return detachLoggerTee;\n const detach = addLogSink((level, message, data) => {\n if (level !== \"warn\" && level !== \"error\") return;\n // `requestLogger` writes this one to stdout for every request, and\n // `logMiddleware` has already recorded the same request here with the\n // fields this panel renders. Teeing it too would double every failure.\n if (message === \"request\") return;\n addLog(level, sourceForMessage(message), message, Object.keys(data).length > 0 ? data : undefined);\n });\n detachLoggerTee = () => {\n detach();\n detachLoggerTee = undefined;\n };\n return detachLoggerTee;\n}\n\n/**\n * How long entries accumulate before a batch goes out.\n *\n * Not zero, and that is the point. A busy server logs faster than a browser can\n * render, and one SSE frame per line would hand the client a re-render per\n * request served — worse than the 3s poll this replaces, precisely when the logs\n * are worth watching. Coalescing keeps the frame rate bounded by the window\n * rather than by traffic, and 250ms still reads as \"live\" to a person.\n */\nconst STREAM_FLUSH_MS = 250;\n\n/**\n * Idle gap after which the stream sends a comment line.\n *\n * A silent SSE connection is indistinguishable from a dead one to everything in\n * between — proxies, load balancers and laptop NICs all reap idle sockets, and a\n * server with nothing to say is the normal state here.\n */\nconst STREAM_HEARTBEAT_MS = 25_000;\n\n/**\n * Entries a single connection will hold between flushes.\n *\n * This is a *rate* ceiling, not just a memory bound, and that is easy to get\n * wrong: nothing drains `pending` between flushes, so the most a connection can\n * carry losslessly is `maxPending` per `flushMs` — here 2000 per 250ms, or 8000\n * entries a second. Above that the oldest pending entries go and the client is\n * told how many, whatever speed it is reading at.\n *\n * It was 500, which put that ceiling at 2000/s. A healthy reader on a loopback\n * socket lost 85% of a 20k burst to it — the cap fired on the server's own\n * coalescing window rather than on any slowness at the client, which is a drop\n * notice that says nothing true about why. 8000/s is past what one Node process\n * serves, so reaching it now means genuinely more log than a person can be shown.\n *\n * The memory this bounds is the copy a *stalled* reader causes: roughly 2000\n * entries, a few MB, per stuck connection.\n */\nconst STREAM_MAX_PENDING = 2000;\n\n/**\n * The largest window any of these routes will hand back.\n *\n * The ring buffer holds 10,000 entries, so asking for more than all of it is a\n * mistake worth naming rather than silently clamping — and a clamped answer is\n * indistinguishable from \"that is all there is\".\n */\nconst LOG_WINDOW_MAX = 10_000;\n\n/**\n * The stream's timings, injectable only so they can be tested.\n *\n * The defaults above are the contract and nothing in production passes this. A\n * heartbeat is a 25-second wait to observe, and a suite that cannot observe it is\n * a suite where the keepalive can rot — which surfaces as \"the tail dies after a\n * few minutes behind the load balancer\", months later, on someone else's cluster.\n */\nexport interface LogStreamTiming {\n flushMs?: number;\n heartbeatMs?: number;\n maxPending?: number;\n}\n\n/** What ends the stream from the server's side. */\nexport interface LogsRoutesOptions {\n /**\n * Aborted when the backend shuts down. Every open stream ends then, rather\n * than when its client happens to leave: `server.close()` waits on every\n * open connection, so one Studio → Logs tab held a SIGTERM for the whole\n * force timeout — longer than Cloud Run's or `docker stop`'s grace period,\n * which killed the process before the pool was closed.\n */\n closeSignal?: AbortSignal;\n}\n\nexport function createLogsRoutes(timing: LogStreamTiming = {}, options: LogsRoutesOptions = {}): Hono<HonoEnv> {\n // Here rather than at module load: the ring exists whether or not anything\n // reads it, but there is no reason to fill it on a process that serves no\n // logs surface. Idempotent, so the repeated calls a split deployment makes\n // do not stack up sinks.\n teeLoggerIntoLogBuffer();\n\n const flushMs = timing.flushMs ?? STREAM_FLUSH_MS;\n const heartbeatMs = timing.heartbeatMs ?? STREAM_HEARTBEAT_MS;\n const maxPending = timing.maxPending ?? STREAM_MAX_PENDING;\n\n const app = new Hono<HonoEnv>();\n // Its own, like every other router here: nothing registers one on the host\n // app — not `boot.ts`, not the scaffolded backend, not the eject template —\n // so a router that throws without this answers Hono's default 500 in plain\n // text, outside the `{ error: { code, message } }` envelope the rest of the\n // API keeps to.\n app.onError(errorHandler);\n\n /**\n * A window into the ring buffer, or a 400 saying why not.\n *\n * `parseInt` was the whole of it before, and every malformed value failed\n * differently and silently: `?limit=abc` fell through to the default,\n * `?limit=-5` sliced an empty window and answered 200 with no entries, and\n * `?count=abc` made `slice(-NaN)` return the *entire* buffer. Three ways to\n * be wrong, none of them visible to the caller. The data plane refuses the\n * same input with a 400 — see `resolveListLimitParam`.\n *\n * `min` is 1 for a size and 0 for an offset: `?offset=0` is the first page,\n * which is where every pager starts, and it was a 400.\n */\n const window = (raw: string | undefined, what: string, max: number, min = 1): number | undefined => {\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const parsed = Number(raw.trim());\n if (!Number.isInteger(parsed) || parsed < min || parsed > max) {\n throw new ApiError(\n 400,\n \"INVALID_PARAM\",\n `Invalid \\`${what}\\`: ${raw}. Expected a whole number between ${min} and ${max}.`,\n undefined,\n true\n );\n }\n return parsed;\n };\n\n // GET /api/logs — Query logs\n app.get(\"/\", (c) => {\n const query = c.req.query();\n const result = logBuffer.query({\n level: query.level,\n source: query.source,\n search: query.search,\n limit: window(query.limit, \"limit\", LOG_WINDOW_MAX),\n offset: window(query.offset, \"offset\", Number.MAX_SAFE_INTEGER, 0),\n since: query.since\n });\n return c.json(result);\n });\n\n // GET /api/logs/latest — Get latest logs (for real-time)\n app.get(\"/latest\", (c) => {\n const count = window(c.req.query(\"count\"), \"count\", LOG_WINDOW_MAX) ?? 50;\n return c.json({ entries: logBuffer.getLatest(count) });\n });\n\n // GET /api/logs/stream — tail the buffer over SSE.\n //\n // The Logs Explorer used to poll this router every 3 seconds, which cost a\n // request per client per 3s to say \"nothing happened\" and still showed each\n // line up to 3s late. Here the buffer pushes instead, so an idle server is an\n // idle socket.\n //\n // Events:\n // snapshot {entries, total, instance}\n // the filtered window, oldest-first, at open,\n // and the process whose ring it is\n // append {entries, dropped} entries since the last frame, oldest-first\n // `: ping` comment, keepalive only\n //\n // Snapshot and appends come down the same connection deliberately. A client\n // that fetched its backlog separately would race the subscription — entries\n // logged between the two calls belong to neither — and closing that race from\n // the outside needs an id cursor and dedupe on every frame.\n app.get(\"/stream\", (c) => {\n const query = c.req.query();\n const filter = normalizeFilter({\n level: query.level,\n source: query.source,\n search: query.search\n });\n const limit = window(query.limit, \"limit\", LOG_WINDOW_MAX) ?? 200;\n\n // Reverse proxies buffer text responses by default, which turns a live\n // tail into nothing at all until the buffer fills. nginx (and the ingress\n // in front of the managed runtime) reads this header; everything else\n // ignores it. The rest of the SSE headers are set by `streamSSE`.\n c.header(\"X-Accel-Buffering\", \"no\");\n\n return streamSSE(c, async (stream) => {\n let pending: LogEntry[] = [];\n let dropped = 0;\n\n // Subscribe *before* reading the backlog, with nothing awaited\n // between the two. Both are synchronous, so the two halves meet\n // exactly: an entry logged after the query but before the\n // subscription would otherwise be in neither, and that gap is the one\n // thing this route exists to close.\n const unsubscribe = logBuffer.subscribe(entry => {\n if (!matchesFilter(entry, filter)) return;\n if (pending.length >= maxPending) {\n pending.shift();\n dropped++;\n }\n pending.push(entry);\n });\n const snapshot = logBuffer.query({ ...filter,\n limit });\n\n // A client that goes away has to end this handler, or the\n // subscription outlives the socket. `streamSSE` only wires the\n // request signal through on old Bun, so do it here and let\n // `stream.aborted` be the one condition the loop tests.\n //\n // The `aborted` check is not belt-and-braces. A listener added to an\n // already-aborted signal is never called, so a client that leaves\n // during the snapshot write — a fast navigation, or a reconnect storm\n // against a restarting server — would leave this handler with no way\n // to learn it had gone: a subscriber and a flush loop, per attempt,\n // for the life of the process.\n const abortOnDisconnect = () => {\n if (!stream.closed) stream.abort();\n };\n c.req.raw.signal.addEventListener(\"abort\", abortOnDisconnect, { once: true });\n if (c.req.raw.signal.aborted) abortOnDisconnect();\n // The server going away ends it the same way, for the same reason\n // the client going away does — and a stream opened after shutdown\n // began still sends its snapshot, then ends.\n const closeSignal = options.closeSignal;\n closeSignal?.addEventListener(\"abort\", abortOnDisconnect, { once: true });\n if (closeSignal?.aborted) abortOnDisconnect();\n\n try {\n await stream.writeSSE({\n event: \"snapshot\",\n // The view tails like a terminal; both frames are oldest-first\n // so the client only ever appends.\n data: JSON.stringify({\n entries: snapshot.entries.slice().reverse(),\n total: snapshot.total,\n instance: logInstanceName()\n })\n });\n\n let idleMs = 0;\n while (!stream.aborted && !stream.closed) {\n await stream.sleep(flushMs);\n if (stream.aborted || stream.closed) break;\n\n if (pending.length === 0) {\n idleMs += flushMs;\n if (idleMs >= heartbeatMs) {\n await stream.write(\": ping\\n\\n\");\n idleMs = 0;\n }\n continue;\n }\n\n const entries = pending;\n const lost = dropped;\n pending = [];\n dropped = 0;\n idleMs = 0;\n await stream.writeSSE({\n event: \"append\",\n data: JSON.stringify(lost > 0 ? { entries,\n dropped: lost } : { entries })\n });\n }\n } finally {\n unsubscribe();\n c.req.raw.signal.removeEventListener(\"abort\", abortOnDisconnect);\n closeSignal?.removeEventListener(\"abort\", abortOnDisconnect);\n }\n });\n });\n\n return app;\n}\n\nexport default createLogsRoutes();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,gBAAgB,SAA6C;CAClE,OAAO;EAAE,GAAG;EACR,QAAQ,QAAQ,QAAQ,YAAY;CAAE;AAC9C;;;;;;;;AASA,SAAS,cAAc,OAAiB,QAAmC;CACvE,IAAI,OAAO,SAAS,MAAM,UAAU,OAAO,OAAO,OAAO;CACzD,IAAI,OAAO,UAAU,MAAM,WAAW,OAAO,QAAQ,OAAO;CAC5D,IAAI,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AAC;KACrC,CAAC;IACL;GACJ,UAAU;IACN,YAAY;IACZ,EAAE,IAAI,IAAI,OAAO,oBAAoB,SAAS,iBAAiB;IAC/D,aAAa,oBAAoB,SAAS,iBAAiB;GAC/D;EACJ,CAAC;CACL,CAAC;CAED,OAAO;AACX;AAEe,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"logs-routes-C3CLYP-n.js","names":[],"sources":["../src/api/logs-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { MiddlewareHandler } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport type { HonoEnv } from \"./types\";\nimport { ApiError, errorHandler } from \"./errors\";\nimport { addLogSink } from \"../utils/logger\";\n\nexport interface LogEntry {\n id: string;\n timestamp: string;\n level: \"debug\" | \"info\" | \"warn\" | \"error\";\n source: \"api\" | \"auth\" | \"storage\" | \"realtime\" | \"system\";\n message: string;\n metadata?: Record<string, unknown>;\n}\n\n/** What a caller can narrow the log by, in either direction (query or stream). */\nexport interface LogFilterOptions {\n level?: string;\n source?: string;\n search?: string;\n since?: string;\n}\n\n/**\n * A filter with the search term already lowercased.\n *\n * The distinction matters on the stream path: `query()` lowercases once and then\n * scans, but a subscriber tests one entry at a time and would otherwise redo the\n * same `toLowerCase()` on every request the server handles.\n */\ntype NormalizedFilter = LogFilterOptions;\n\nfunction normalizeFilter(options: LogFilterOptions): NormalizedFilter {\n return { ...options,\n search: options.search?.toLowerCase() };\n}\n\n/**\n * Whether one entry belongs in a filtered view.\n *\n * Shared by the query and the stream on purpose: two copies of this would drift,\n * and the failure that produces is invisible — a tail that quietly shows a\n * different set of lines than the snapshot it started from.\n */\nfunction matchesFilter(entry: LogEntry, filter: NormalizedFilter): boolean {\n if (filter.level && entry.level !== filter.level) return false;\n if (filter.source && entry.source !== filter.source) return false;\n if (filter.search && !entry.message.toLowerCase().includes(filter.search)) return false;\n if (filter.since && entry.timestamp < filter.since) return false;\n return true;\n}\n\n/** Notified for every entry pushed, in push order. */\nexport type LogListener = (entry: LogEntry) => void;\n\nclass LogRingBuffer {\n private buffer: LogEntry[] = [];\n private maxSize: number;\n private idCounter = 0;\n private listeners = new Set<LogListener>();\n\n constructor(maxSize = 10000) {\n this.maxSize = maxSize;\n }\n\n push(entry: Omit<LogEntry, \"id\">): void {\n const id = `log_${++this.idCounter}`;\n const stored: LogEntry = { ...entry,\n id };\n this.buffer.push(stored);\n if (this.buffer.length > this.maxSize) {\n this.buffer.shift();\n }\n // This runs on the request hot path, so a listener must never be able to\n // take the request down with it: a tail that throws loses its own tail,\n // not the response the log line was describing.\n for (const listener of this.listeners) {\n try {\n listener(stored);\n } catch {\n /* a broken tail is not the request's problem */\n }\n }\n }\n\n /**\n * Follow the buffer. Returns the unsubscribe — call it, always: a listener\n * left behind holds its whole closure, and on this class that closure is a\n * pending-entry array.\n *\n * A listener must not log. It is called from inside `push`, so anything that\n * reaches `addLog` from here recurses until the stack gives out.\n */\n subscribe(listener: LogListener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n query(options: LogFilterOptions & {\n limit?: number;\n offset?: number;\n }): { entries: LogEntry[]; total: number } {\n const filter = normalizeFilter(options);\n const filtered = this.buffer.filter(e => matchesFilter(e, filter));\n\n // Newest first\n const sorted = [...filtered].reverse();\n const total = sorted.length;\n const limit = options.limit || 100;\n const offset = options.offset || 0;\n\n return {\n entries: sorted.slice(offset, offset + limit),\n total\n };\n }\n\n getLatest(count = 50): LogEntry[] {\n return this.buffer.slice(-count).reverse();\n }\n}\n\n// Global singleton\nexport const logBuffer = new LogRingBuffer();\n\n/**\n * Which process this log belongs to.\n *\n * The ring is this process's memory, and nothing gathers the rings of a\n * deployment's other replicas or of its split runtime roles. So a reader is\n * told whose log it is: `HOSTNAME` is the pod name on Kubernetes and the\n * container id under Docker; the pid tells two local processes apart.\n */\nexport function logInstanceName(): string {\n return process.env.HOSTNAME?.trim() || `pid-${process.pid}`;\n}\n\n/** Add a log entry */\nexport function addLog(\n level: LogEntry[\"level\"],\n source: LogEntry[\"source\"],\n message: string,\n metadata?: Record<string, unknown>\n): void {\n logBuffer.push({\n timestamp: new Date().toISOString(),\n level,\n source,\n message,\n metadata\n });\n}\n\nexport interface LogMiddlewareOptions {\n /**\n * Paths this sink ignores, matched exactly against `c.req.path`.\n *\n * For requests whose only reason to exist is to read the log. Recording\n * those makes the reader the loudest thing in its own output, and on a quiet\n * server it is also the thing evicting real entries out of the ring.\n */\n ignorePaths?: string[];\n /**\n * Where the API is mounted (`/api`). The segment after it names the\n * subsystem a request is filed under — see {@link sourceForRequestPath}.\n * Unset, the first segment of the path is read.\n */\n basePath?: string;\n}\n\n/** The first path segment under the base path that files a request under a source other than `api`. */\nconst SOURCE_BY_SEGMENT: Readonly<Record<string, LogEntry[\"source\"]>> = {\n auth: \"auth\",\n oauth: \"auth\",\n storage: \"storage\"\n};\n\n/**\n * The `source` of a request entry: the subsystem its path addresses.\n *\n * `/api/auth/*` and the MCP authorization server under `/api/oauth/*` are\n * `auth`, `/api/storage/*` is `storage`, and everything else is `api`. The\n * Logs Explorer's Source filter matches this field, so a sign-in filed as\n * `api` was invisible under Auth. The realtime socket is not an HTTP request\n * and is not recorded here.\n *\n * Exported for its test.\n */\nexport function sourceForRequestPath(path: string, basePath = \"\"): LogEntry[\"source\"] {\n const base = basePath.replace(/\\/+$/, \"\");\n if (base && path !== base && !path.startsWith(`${base}/`)) return \"api\";\n const segment = path.slice(base.length).split(\"/\").find(part => part !== \"\")?.toLowerCase();\n return (segment !== undefined && Object.prototype.hasOwnProperty.call(SOURCE_BY_SEGMENT, segment))\n ? SOURCE_BY_SEGMENT[segment]\n : \"api\";\n}\n\n/** Hono middleware to log API requests */\nexport function logMiddleware(options: LogMiddlewareOptions = {}): MiddlewareHandler<HonoEnv> {\n const ignored = new Set(options.ignorePaths ?? []);\n return async (c, next) => {\n const start = Date.now();\n await next();\n if (ignored.has(c.req.path)) return;\n const duration = Date.now() - start;\n const reqId = c.get(\"requestId\");\n // Every request used to be recorded at `info`, whatever it answered, so\n // the Logs Explorer's level filter could not find a single failure: a\n // 500 sat at the same level as the 200 above it, in a wall of them.\n const status = c.res.status;\n const level: LogEntry[\"level\"] = status >= 500 ? \"error\" : status >= 400 ? \"warn\" : \"info\";\n // What the error handler answered, so the failure is on the entry\n // rather than in a stdout line the panel cannot see. See\n // `HonoEnv.Variables.errorSummary`.\n const failure = c.get(\"errorSummary\");\n addLog(\n level,\n sourceForRequestPath(c.req.path, options.basePath),\n `${c.req.method} ${c.req.path} ${status} ${duration}ms`\n + (failure ? ` — ${failure.code}: ${failure.message}` : \"\"),\n {\n method: c.req.method,\n path: c.req.path,\n status,\n duration,\n ...(reqId && { requestId: reqId }),\n ...(c.get(\"collection\") && { collection: c.get(\"collection\") }),\n ...(failure && { errorCode: failure.code, errorMessage: failure.message })\n }\n );\n };\n}\n\n/**\n * Prefixes the server writes at the head of a log message, and the `source`\n * each one belongs to.\n *\n * The ring's `source` is a closed set the Studio filters on, and the messages\n * carry their origin as a bracketed prefix — `[API]`, `[Auth]`, `[functions]`,\n * `[schema]`. Matching them is what makes a teed line filterable beside the\n * request entries rather than a heap under \"system\".\n */\nconst SOURCE_BY_PREFIX: Array<[RegExp, LogEntry[\"source\"]]> = [\n [/^\\[?(api|rest)\\b/i, \"api\"],\n [/^\\[?auth\\b/i, \"auth\"],\n [/^\\[?(storage|s3|gcs)\\b/i, \"storage\"],\n [/^\\[?(realtime|ws|websocket|cdc)\\b/i, \"realtime\"]\n];\n\n/**\n * The `source` for a teed line, from whatever prefix it carries.\n *\n * Exported for its test: the mapping is a string match on wording somebody else\n * writes, which is the shape of check that stops working without failing.\n */\nexport function sourceForMessage(message: string): LogEntry[\"source\"] {\n // The level emoji comes first on several call sites (`⚠️ [API] …`), so the\n // prefix is whatever is inside the first bracket, wherever that is.\n const bracketed = message.match(/\\[([^\\]]{1,32})\\]/);\n const candidate = bracketed?.[1] ?? message;\n for (const [pattern, source] of SOURCE_BY_PREFIX) {\n if (pattern.test(candidate)) return source;\n }\n return \"system\";\n}\n\n/**\n * Feed the Logs Explorer everything the server says at warn and above.\n *\n * The ring used to be filled by `logMiddleware` alone, so the panel showed a\n * wall of `GET /api/data/posts 200 4ms` and not one of the errors, warnings or\n * boot diagnoses being written to stdout at the same moment. A function that\n * threw was the sharpest case: the request entry said `500` and the reason\n * existed only in a terminal the person looking at the panel does not have.\n *\n * Warn and above, deliberately. `info` is where the steady-state chatter lives,\n * and a 10,000-entry ring filled with it evicts the lines somebody opened the\n * panel to find.\n *\n * Idempotent: called from `createLogsRoutes`, which a split deployment may\n * reach more than once.\n */\nlet detachLoggerTee: (() => void) | undefined;\nexport function teeLoggerIntoLogBuffer(): () => void {\n if (detachLoggerTee) return detachLoggerTee;\n const detach = addLogSink((level, message, data) => {\n if (level !== \"warn\" && level !== \"error\") return;\n // `requestLogger` writes this one to stdout for every request, and\n // `logMiddleware` has already recorded the same request here with the\n // fields this panel renders. Teeing it too would double every failure.\n if (message === \"request\") return;\n addLog(level, sourceForMessage(message), message, Object.keys(data).length > 0 ? data : undefined);\n });\n detachLoggerTee = () => {\n detach();\n detachLoggerTee = undefined;\n };\n return detachLoggerTee;\n}\n\n/**\n * How long entries accumulate before a batch goes out.\n *\n * Not zero, and that is the point. A busy server logs faster than a browser can\n * render, and one SSE frame per line would hand the client a re-render per\n * request served — worse than the 3s poll this replaces, precisely when the logs\n * are worth watching. Coalescing keeps the frame rate bounded by the window\n * rather than by traffic, and 250ms still reads as \"live\" to a person.\n */\nconst STREAM_FLUSH_MS = 250;\n\n/**\n * Idle gap after which the stream sends a comment line.\n *\n * A silent SSE connection is indistinguishable from a dead one to everything in\n * between — proxies, load balancers and laptop NICs all reap idle sockets, and a\n * server with nothing to say is the normal state here.\n */\nconst STREAM_HEARTBEAT_MS = 25_000;\n\n/**\n * Entries a single connection will hold between flushes.\n *\n * This is a *rate* ceiling, not just a memory bound, and that is easy to get\n * wrong: nothing drains `pending` between flushes, so the most a connection can\n * carry losslessly is `maxPending` per `flushMs` — here 2000 per 250ms, or 8000\n * entries a second. Above that the oldest pending entries go and the client is\n * told how many, whatever speed it is reading at.\n *\n * It was 500, which put that ceiling at 2000/s. A healthy reader on a loopback\n * socket lost 85% of a 20k burst to it — the cap fired on the server's own\n * coalescing window rather than on any slowness at the client, which is a drop\n * notice that says nothing true about why. 8000/s is past what one Node process\n * serves, so reaching it now means genuinely more log than a person can be shown.\n *\n * The memory this bounds is the copy a *stalled* reader causes: roughly 2000\n * entries, a few MB, per stuck connection.\n */\nconst STREAM_MAX_PENDING = 2000;\n\n/**\n * The largest window any of these routes will hand back.\n *\n * The ring buffer holds 10,000 entries, so asking for more than all of it is a\n * mistake worth naming rather than silently clamping — and a clamped answer is\n * indistinguishable from \"that is all there is\".\n */\nconst LOG_WINDOW_MAX = 10_000;\n\n/**\n * The stream's timings, injectable only so they can be tested.\n *\n * The defaults above are the contract and nothing in production passes this. A\n * heartbeat is a 25-second wait to observe, and a suite that cannot observe it is\n * a suite where the keepalive can rot — which surfaces as \"the tail dies after a\n * few minutes behind the load balancer\", months later, on someone else's cluster.\n */\nexport interface LogStreamTiming {\n flushMs?: number;\n heartbeatMs?: number;\n maxPending?: number;\n}\n\n/** What ends the stream from the server's side. */\nexport interface LogsRoutesOptions {\n /**\n * Aborted when the backend shuts down. Every open stream ends then, rather\n * than when its client happens to leave: `server.close()` waits on every\n * open connection, so one Studio → Logs tab held a SIGTERM for the whole\n * force timeout — longer than Cloud Run's or `docker stop`'s grace period,\n * which killed the process before the pool was closed.\n */\n closeSignal?: AbortSignal;\n}\n\nexport function createLogsRoutes(timing: LogStreamTiming = {}, options: LogsRoutesOptions = {}): Hono<HonoEnv> {\n // Here rather than at module load: the ring exists whether or not anything\n // reads it, but there is no reason to fill it on a process that serves no\n // logs surface. Idempotent, so the repeated calls a split deployment makes\n // do not stack up sinks.\n teeLoggerIntoLogBuffer();\n\n const flushMs = timing.flushMs ?? STREAM_FLUSH_MS;\n const heartbeatMs = timing.heartbeatMs ?? STREAM_HEARTBEAT_MS;\n const maxPending = timing.maxPending ?? STREAM_MAX_PENDING;\n\n const app = new Hono<HonoEnv>();\n // Its own, like every other router here: nothing registers one on the host\n // app — not `boot.ts`, not the scaffolded backend, not the eject template —\n // so a router that throws without this answers Hono's default 500 in plain\n // text, outside the `{ error: { code, message } }` envelope the rest of the\n // API keeps to.\n app.onError(errorHandler);\n\n /**\n * A window into the ring buffer, or a 400 saying why not.\n *\n * `parseInt` was the whole of it before, and every malformed value failed\n * differently and silently: `?limit=abc` fell through to the default,\n * `?limit=-5` sliced an empty window and answered 200 with no entries, and\n * `?count=abc` made `slice(-NaN)` return the *entire* buffer. Three ways to\n * be wrong, none of them visible to the caller. The data plane refuses the\n * same input with a 400 — see `resolveListLimitParam`.\n *\n * `min` is 1 for a size and 0 for an offset: `?offset=0` is the first page,\n * which is where every pager starts, and it was a 400.\n */\n const window = (raw: string | undefined, what: string, max: number, min = 1): number | undefined => {\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const parsed = Number(raw.trim());\n if (!Number.isInteger(parsed) || parsed < min || parsed > max) {\n throw new ApiError(\n 400,\n \"INVALID_PARAM\",\n `Invalid \\`${what}\\`: ${raw}. Expected a whole number between ${min} and ${max}.`,\n undefined,\n true\n );\n }\n return parsed;\n };\n\n // GET /api/logs — Query logs\n app.get(\"/\", (c) => {\n const query = c.req.query();\n const result = logBuffer.query({\n level: query.level,\n source: query.source,\n search: query.search,\n limit: window(query.limit, \"limit\", LOG_WINDOW_MAX),\n offset: window(query.offset, \"offset\", Number.MAX_SAFE_INTEGER, 0),\n since: query.since\n });\n return c.json(result);\n });\n\n // GET /api/logs/latest — Get latest logs (for real-time)\n app.get(\"/latest\", (c) => {\n const count = window(c.req.query(\"count\"), \"count\", LOG_WINDOW_MAX) ?? 50;\n return c.json({ entries: logBuffer.getLatest(count) });\n });\n\n // GET /api/logs/stream — tail the buffer over SSE.\n //\n // The Logs Explorer used to poll this router every 3 seconds, which cost a\n // request per client per 3s to say \"nothing happened\" and still showed each\n // line up to 3s late. Here the buffer pushes instead, so an idle server is an\n // idle socket.\n //\n // Events:\n // snapshot {entries, total, instance}\n // the filtered window, oldest-first, at open,\n // and the process whose ring it is\n // append {entries, dropped} entries since the last frame, oldest-first\n // `: ping` comment, keepalive only\n //\n // Snapshot and appends come down the same connection deliberately. A client\n // that fetched its backlog separately would race the subscription — entries\n // logged between the two calls belong to neither — and closing that race from\n // the outside needs an id cursor and dedupe on every frame.\n app.get(\"/stream\", (c) => {\n const query = c.req.query();\n const filter = normalizeFilter({\n level: query.level,\n source: query.source,\n search: query.search\n });\n const limit = window(query.limit, \"limit\", LOG_WINDOW_MAX) ?? 200;\n\n // Reverse proxies buffer text responses by default, which turns a live\n // tail into nothing at all until the buffer fills. nginx (and the ingress\n // in front of the managed runtime) reads this header; everything else\n // ignores it. The rest of the SSE headers are set by `streamSSE`.\n c.header(\"X-Accel-Buffering\", \"no\");\n\n return streamSSE(c, async (stream) => {\n let pending: LogEntry[] = [];\n let dropped = 0;\n\n // Subscribe *before* reading the backlog, with nothing awaited\n // between the two. Both are synchronous, so the two halves meet\n // exactly: an entry logged after the query but before the\n // subscription would otherwise be in neither, and that gap is the one\n // thing this route exists to close.\n const unsubscribe = logBuffer.subscribe(entry => {\n if (!matchesFilter(entry, filter)) return;\n if (pending.length >= maxPending) {\n pending.shift();\n dropped++;\n }\n pending.push(entry);\n });\n const snapshot = logBuffer.query({ ...filter,\n limit });\n\n // A client that goes away has to end this handler, or the\n // subscription outlives the socket. `streamSSE` only wires the\n // request signal through on old Bun, so do it here and let\n // `stream.aborted` be the one condition the loop tests.\n //\n // The `aborted` check is not belt-and-braces. A listener added to an\n // already-aborted signal is never called, so a client that leaves\n // during the snapshot write — a fast navigation, or a reconnect storm\n // against a restarting server — would leave this handler with no way\n // to learn it had gone: a subscriber and a flush loop, per attempt,\n // for the life of the process.\n const abortOnDisconnect = () => {\n if (!stream.closed) stream.abort();\n };\n c.req.raw.signal.addEventListener(\"abort\", abortOnDisconnect, { once: true });\n if (c.req.raw.signal.aborted) abortOnDisconnect();\n // The server going away ends it the same way, for the same reason\n // the client going away does — and a stream opened after shutdown\n // began still sends its snapshot, then ends.\n const closeSignal = options.closeSignal;\n closeSignal?.addEventListener(\"abort\", abortOnDisconnect, { once: true });\n if (closeSignal?.aborted) abortOnDisconnect();\n\n try {\n await stream.writeSSE({\n event: \"snapshot\",\n // The view tails like a terminal; both frames are oldest-first\n // so the client only ever appends.\n data: JSON.stringify({\n entries: snapshot.entries.slice().reverse(),\n total: snapshot.total,\n instance: logInstanceName()\n })\n });\n\n let idleMs = 0;\n while (!stream.aborted && !stream.closed) {\n await stream.sleep(flushMs);\n if (stream.aborted || stream.closed) break;\n\n if (pending.length === 0) {\n idleMs += flushMs;\n if (idleMs >= heartbeatMs) {\n await stream.write(\": ping\\n\\n\");\n idleMs = 0;\n }\n continue;\n }\n\n const entries = pending;\n const lost = dropped;\n pending = [];\n dropped = 0;\n idleMs = 0;\n await stream.writeSSE({\n event: \"append\",\n data: JSON.stringify(lost > 0 ? { entries,\n dropped: lost } : { entries })\n });\n }\n } finally {\n unsubscribe();\n c.req.raw.signal.removeEventListener(\"abort\", abortOnDisconnect);\n closeSignal?.removeEventListener(\"abort\", abortOnDisconnect);\n }\n });\n });\n\n return app;\n}\n\nexport default createLogsRoutes();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,gBAAgB,SAA6C;CAClE,OAAO;EAAE,GAAG;EACR,QAAQ,QAAQ,QAAQ,YAAY;CAAE;AAC9C;;;;;;;;AASA,SAAS,cAAc,OAAiB,QAAmC;CACvE,IAAI,OAAO,SAAS,MAAM,UAAU,OAAO,OAAO,OAAO;CACzD,IAAI,OAAO,UAAU,MAAM,WAAW,OAAO,QAAQ,OAAO;CAC5D,IAAI,OAAO,UAAU,CAAC,MAAM,QAAQ,YAAY,CAAC,CAAC,SAAS,OAAO,MAAM,GAAG,OAAO;CAClF,IAAI,OAAO,SAAS,MAAM,YAAY,O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B,SAAS,iBAAiB;GAC/D;EACJ,CAAC;CACL,CAAC;CAED,OAAO;AACX;AAEe,iBAAiB"}
|
|
@@ -2,11 +2,11 @@ import { createRequire as __rebaseCreateRequire } from "module";
|
|
|
2
2
|
import __rebaseProcess from "process";
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
|
-
import { An as
|
|
5
|
+
import { An as parseRelationAggregateSort, Fn as isUnsupported, Mn as toCanonicalOp, Nn as RebaseApiError, Pn as RebaseClientError, U as hasFieldOperation, kn as parseCaseFoldedFieldPath } from "./src-CNZB3fuE.js";
|
|
6
6
|
import { n as splitSearchTerms } from "./strings.es-k0kjzQBh.js";
|
|
7
|
-
import { a as byIdRead, d as etagOf, f as withETag, i as buildQueryString, n as MemoryOfflineStore, o as createMutationId, p as unref, r as SDKQueryBuilder, t as IndexedDBOfflineStore, u as invalidBulkBody } from "./offline-store-DtmBwmKE-
|
|
8
|
-
import { _ as normalizeOrderBy, c as collectAllPages, l as paginateFind, u as resolveFindWindow } from "./filter-dialect-
|
|
9
|
-
//#region ../client/dist/offline-
|
|
7
|
+
import { a as byIdRead, d as etagOf, f as withETag, i as buildQueryString, n as MemoryOfflineStore, o as createMutationId, p as unref, r as SDKQueryBuilder, t as IndexedDBOfflineStore, u as invalidBulkBody } from "./offline-store-DtmBwmKE-C9ba2NJv.js";
|
|
8
|
+
import { _ as normalizeOrderBy, c as collectAllPages, l as paginateFind, u as resolveFindWindow } from "./filter-dialect-XtPJOCbD.js";
|
|
9
|
+
//#region ../client/dist/offline-ET6xI1ZO.js
|
|
10
10
|
/**
|
|
11
11
|
* Rows and queued writes through the offline store.
|
|
12
12
|
*
|
|
@@ -851,6 +851,113 @@ function runLocalQuery(rows, params) {
|
|
|
851
851
|
}
|
|
852
852
|
};
|
|
853
853
|
}
|
|
854
|
+
/**
|
|
855
|
+
* A cross-tab mutex over `localStorage`, for the browsers that have no Web
|
|
856
|
+
* Locks: Safari before 15.4, pages served over plain http from anything but
|
|
857
|
+
* localhost (Web Locks is secure-context only), and embedded webviews.
|
|
858
|
+
*
|
|
859
|
+
* Without it two tabs on such a browser each replayed the whole offline queue,
|
|
860
|
+
* so every queued write reached the server twice. Creates survived that (the
|
|
861
|
+
* idempotency key dedups them) and deletes did too (a second delete's 404 is
|
|
862
|
+
* taken as done), but an update with `If-Match` came back `412` from its own
|
|
863
|
+
* twin and was reported as a conflict nobody caused.
|
|
864
|
+
*
|
|
865
|
+
* The lease is a `{ holder, until }` record under one key. A tab takes it by
|
|
866
|
+
* writing its own record when the key is empty, expired or already its own,
|
|
867
|
+
* then reading it back after `settleMs`: `localStorage` has no compare-and-set,
|
|
868
|
+
* but every tab reads and writes in one synchronous step, so two tabs can only
|
|
869
|
+
* both write within the time a write takes to reach the other process — far
|
|
870
|
+
* under `settleMs` — and the read-back sees whichever write landed last. Only
|
|
871
|
+
* that tab proceeds. The holder renews the record while it works and removes it
|
|
872
|
+
* when done; a tab that died holding it is outlived by `ttlMs`.
|
|
873
|
+
*
|
|
874
|
+
* It is a weaker guarantee than Web Locks, on purpose kept to what it can
|
|
875
|
+
* promise: a holder whose timers the browser throttles hard enough (a hidden
|
|
876
|
+
* tab can be held to one timer a minute) may see its lease expire mid-replay,
|
|
877
|
+
* and the next tab then replays what is still queued. That costs at most the
|
|
878
|
+
* one write in flight, not the whole queue.
|
|
879
|
+
*/
|
|
880
|
+
var DEFAULT_TTL_MS = 3e4;
|
|
881
|
+
var DEFAULT_SETTLE_MS = 50;
|
|
882
|
+
var DEFAULT_POLL_MS = 200;
|
|
883
|
+
function readRecord(storage, key) {
|
|
884
|
+
let raw;
|
|
885
|
+
try {
|
|
886
|
+
raw = storage.getItem(key);
|
|
887
|
+
} catch {
|
|
888
|
+
return null;
|
|
889
|
+
}
|
|
890
|
+
if (!raw) return null;
|
|
891
|
+
try {
|
|
892
|
+
const parsed = JSON.parse(raw);
|
|
893
|
+
if (parsed !== null && typeof parsed === "object" && "holder" in parsed && typeof parsed.holder === "string" && "until" in parsed && typeof parsed.until === "number") return {
|
|
894
|
+
holder: parsed.holder,
|
|
895
|
+
until: parsed.until
|
|
896
|
+
};
|
|
897
|
+
} catch {}
|
|
898
|
+
return null;
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* `localStorage` when this page can use it, or `undefined` — a worker has none,
|
|
902
|
+
* and a browser with storage blocked throws on the mere access.
|
|
903
|
+
*/
|
|
904
|
+
function browserLeaseStorage() {
|
|
905
|
+
try {
|
|
906
|
+
if (typeof localStorage === "undefined") return void 0;
|
|
907
|
+
const storage = localStorage;
|
|
908
|
+
const probe = "rebase-lease-probe";
|
|
909
|
+
storage.setItem(probe, "1");
|
|
910
|
+
storage.removeItem(probe);
|
|
911
|
+
return storage;
|
|
912
|
+
} catch {
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Run `fn` while holding the lease named `key`, waiting for another holder to
|
|
918
|
+
* finish first. Storage that fails mid-protocol makes the lease unenforceable,
|
|
919
|
+
* and then `fn` runs anyway: a queue that never drains is worse than one that
|
|
920
|
+
* might drain twice.
|
|
921
|
+
*/
|
|
922
|
+
async function withStorageLease(storage, key, holder, fn, options = {}) {
|
|
923
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
924
|
+
const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
|
|
925
|
+
const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
|
|
926
|
+
const now = options.now ?? Date.now;
|
|
927
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
928
|
+
const write = () => {
|
|
929
|
+
try {
|
|
930
|
+
storage.setItem(key, JSON.stringify({
|
|
931
|
+
holder,
|
|
932
|
+
until: now() + ttlMs
|
|
933
|
+
}));
|
|
934
|
+
return true;
|
|
935
|
+
} catch {
|
|
936
|
+
return false;
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
for (;;) {
|
|
940
|
+
const current = readRecord(storage, key);
|
|
941
|
+
if (!current || current.until <= now() || current.holder === holder) {
|
|
942
|
+
if (!write()) return fn();
|
|
943
|
+
await sleep(settleMs);
|
|
944
|
+
if (readRecord(storage, key)?.holder === holder) break;
|
|
945
|
+
}
|
|
946
|
+
await sleep(pollMs);
|
|
947
|
+
}
|
|
948
|
+
const renew = setInterval(() => {
|
|
949
|
+
if (readRecord(storage, key)?.holder === holder) write();
|
|
950
|
+
}, Math.max(1, Math.floor(ttlMs / 3)));
|
|
951
|
+
unref(renew);
|
|
952
|
+
try {
|
|
953
|
+
return await fn();
|
|
954
|
+
} finally {
|
|
955
|
+
clearInterval(renew);
|
|
956
|
+
try {
|
|
957
|
+
if (readRecord(storage, key)?.holder === holder) storage.removeItem(key);
|
|
958
|
+
} catch {}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
854
961
|
function offlineError(message) {
|
|
855
962
|
return new RebaseApiError(message, {
|
|
856
963
|
status: 0,
|
|
@@ -3360,7 +3467,7 @@ var OfflineManager = class {
|
|
|
3360
3467
|
}
|
|
3361
3468
|
async withLock(fn) {
|
|
3362
3469
|
const locks = globalThis.navigator?.locks;
|
|
3363
|
-
if (!locks?.request) return fn
|
|
3470
|
+
if (!locks?.request) return this.withLeaseFallback(fn);
|
|
3364
3471
|
let started = false;
|
|
3365
3472
|
try {
|
|
3366
3473
|
return await locks.request(`rebase-offline-sync:${this.scope}`, () => {
|
|
@@ -3369,9 +3476,19 @@ var OfflineManager = class {
|
|
|
3369
3476
|
});
|
|
3370
3477
|
} catch (error) {
|
|
3371
3478
|
if (started) throw error;
|
|
3372
|
-
return fn
|
|
3479
|
+
return this.withLeaseFallback(fn);
|
|
3373
3480
|
}
|
|
3374
3481
|
}
|
|
3482
|
+
/**
|
|
3483
|
+
* Serialise replay across tabs without Web Locks — see `offline-lease.ts`.
|
|
3484
|
+
* Where there is no `localStorage` either (a worker), there is no other
|
|
3485
|
+
* tab sharing this queue through it to guard against.
|
|
3486
|
+
*/
|
|
3487
|
+
withLeaseFallback(fn) {
|
|
3488
|
+
const storage = browserLeaseStorage();
|
|
3489
|
+
if (!storage) return fn();
|
|
3490
|
+
return withStorageLease(storage, `rebase-offline-sync:${this.scope}`, this.tabId, fn);
|
|
3491
|
+
}
|
|
3375
3492
|
broadcast(message, scope = this.scope) {
|
|
3376
3493
|
if (!this.channel) return;
|
|
3377
3494
|
try {
|
|
@@ -3494,4 +3611,4 @@ var OfflineManager = class {
|
|
|
3494
3611
|
//#endregion
|
|
3495
3612
|
export { OfflineManager };
|
|
3496
3613
|
|
|
3497
|
-
//# sourceMappingURL=offline-
|
|
3614
|
+
//# sourceMappingURL=offline-ET6xI1ZO-BQpLQ7wh.js.map
|