@flanksource/clicky-ui 0.3.71 → 0.3.72
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/data/traces/TraceEventStream.cjs +37 -7
- package/dist/data/traces/TraceEventStream.cjs.map +1 -1
- package/dist/data/traces/TraceEventStream.d.ts.map +1 -1
- package/dist/data/traces/TraceEventStream.js +37 -7
- package/dist/data/traces/TraceEventStream.js.map +1 -1
- package/dist/data/traces/TraceFeed.cjs +71 -106
- package/dist/data/traces/TraceFeed.cjs.map +1 -1
- package/dist/data/traces/TraceFeed.d.ts +3 -10
- package/dist/data/traces/TraceFeed.d.ts.map +1 -1
- package/dist/data/traces/TraceFeed.js +72 -107
- package/dist/data/traces/TraceFeed.js.map +1 -1
- package/dist/data/traces/trace-feed.cjs.map +1 -1
- package/dist/data/traces/trace-feed.d.ts +15 -0
- package/dist/data/traces/trace-feed.d.ts.map +1 -1
- package/dist/data/traces/trace-feed.js.map +1 -1
- package/dist/data/traces/use-trace-feed.cjs +100 -0
- package/dist/data/traces/use-trace-feed.cjs.map +1 -0
- package/dist/data/traces/use-trace-feed.d.ts +11 -0
- package/dist/data/traces/use-trace-feed.d.ts.map +1 -0
- package/dist/data/traces/use-trace-feed.js +100 -0
- package/dist/data/traces/use-trace-feed.js.map +1 -0
- package/dist/data/version-info.cjs +3 -3
- package/dist/data/version-info.js +3 -3
- package/dist/hooks/event-hub.cjs +24 -2
- package/dist/hooks/event-hub.cjs.map +1 -1
- package/dist/hooks/event-hub.d.ts +2 -0
- package/dist/hooks/event-hub.d.ts.map +1 -1
- package/dist/hooks/event-hub.js +24 -2
- package/dist/hooks/event-hub.js.map +1 -1
- package/dist/hooks/event-stream.cjs +64 -0
- package/dist/hooks/event-stream.cjs.map +1 -0
- package/dist/hooks/event-stream.d.ts +13 -0
- package/dist/hooks/event-stream.d.ts.map +1 -0
- package/dist/hooks/event-stream.js +64 -0
- package/dist/hooks/event-stream.js.map +1 -0
- package/dist/hooks/log-tail-session.cjs +53 -0
- package/dist/hooks/log-tail-session.cjs.map +1 -0
- package/dist/hooks/log-tail-session.d.ts +31 -0
- package/dist/hooks/log-tail-session.d.ts.map +1 -0
- package/dist/hooks/log-tail-session.js +53 -0
- package/dist/hooks/log-tail-session.js.map +1 -0
- package/dist/hooks/tail-buffer.cjs +15 -0
- package/dist/hooks/tail-buffer.cjs.map +1 -0
- package/dist/hooks/tail-buffer.d.ts +11 -0
- package/dist/hooks/tail-buffer.d.ts.map +1 -0
- package/dist/hooks/tail-buffer.js +15 -0
- package/dist/hooks/tail-buffer.js.map +1 -0
- package/dist/hooks/use-live-snapshot.cjs +60 -0
- package/dist/hooks/use-live-snapshot.cjs.map +1 -0
- package/dist/hooks/use-live-snapshot.d.ts +9 -0
- package/dist/hooks/use-live-snapshot.d.ts.map +1 -0
- package/dist/hooks/use-live-snapshot.js +60 -0
- package/dist/hooks/use-live-snapshot.js.map +1 -0
- package/dist/hooks/use-log-tail.cjs +125 -112
- package/dist/hooks/use-log-tail.cjs.map +1 -1
- package/dist/hooks/use-log-tail.d.ts +2 -24
- package/dist/hooks/use-log-tail.d.ts.map +1 -1
- package/dist/hooks/use-log-tail.js +125 -112
- package/dist/hooks/use-log-tail.js.map +1 -1
- package/dist/hooks.cjs +6 -0
- package/dist/hooks.d.ts +3 -0
- package/dist/hooks.d.ts.map +1 -1
- package/dist/hooks.js +4 -1
- package/dist/index.cjs +6 -0
- package/dist/index.js +4 -1
- package/dist/runtime/barrels.json +6995 -6986
- package/dist/runtime/importmap.json +2120 -2115
- package/dist/styles.css +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-log-tail.cjs","names":["isSessionTerminal","isSessionState","useState","useRef","useEventSourceFactory"],"sources":["../../src/hooks/use-log-tail.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport type { ClickyRow } from \"../data/Clicky\";\nimport { isSessionState, isSessionTerminal, type SessionState } from \"../rpc/sessionTypes\";\nimport { useEventSourceFactory, type EventSourceLike } from \"./event-source\";\n\n// use-log-tail is the clicky-ui client for a *follow* session: the server opens\n// a live source for a query profile and streams rows out of it until someone\n// closes it. The resource underneath is unforgiving. A follow session holds a\n// websocket to Loki, or a log stream to a kubelet, for as long as it exists,\n// and the server caps how many may run at once (ErrMaxSessions, surfaced as\n// HTTP 409). The server owns that slot's release: a view session ends shortly\n// after its last subscriber disconnects, so every exit path — unmount and a\n// parameter change included — only has to abort the start request and close\n// the EventSource.\n//\n// Events travel over SSE only. The events route serves SSE (or ndjson on\n// request) and resumes through Last-Event-ID; there is no JSON-array polling\n// shape to fall back to, so a browser without EventSource fails loudly.\n//\n// Each SSE frame carries an `id:`, so a reconnecting EventSource sends\n// Last-Event-ID and the server resumes from that sequence — re-delivering\n// frames the client may already hold. Sequences are the server's, not a client\n// index: they do not start at 1 and they do not reset, so the accumulator\n// dedupes against the highest sequence it has applied rather than against a\n// position in an array.\n\n/** The sessions API's state, under the name this hook has always exported. */\nexport type LogSessionState = SessionState;\n\n/** SessionInfo as returned by POST /profile/{name}/sessions and the `done` frame. */\nexport interface LogSessionInfo {\n id: string;\n profile: string;\n kind: string;\n state: LogSessionState;\n params?: Record<string, unknown>;\n error?: string;\n eventCount: number;\n startedAt: string;\n stoppedAt?: string;\n}\n\n/**\n * One `event:` frame. It carries either a single `row` or a batch under `rows`\n * — never both — plus an `error` when the source failed mid-stream without the\n * session itself ending.\n *\n * `clickyRow` is the presented row — `{cells, detail?}`, built by the exact\n * function that fills in `node.rows[n]` of the list's own\n * `application/json+clicky` document — riding next to the raw `row` on a\n * trace/follow session's per-row events. A plain log tail (or a top-session\n * snapshot event) never sets it; only a reader that reconciles rows against a\n * presented table, i.e. OperationCatalog's follow mode, depends on it.\n */\nexport interface LogTailEvent {\n sessionId: string;\n sequence: number;\n time?: string;\n row?: Record<string, unknown>;\n rows?: Record<string, unknown>[];\n /** The presented ClickyRow for `row`, when the profile sends one. */\n clickyRow?: ClickyRow;\n error?: string;\n}\n\n/**\n * Where a failure came from, because the three are not interchangeable to a\n * reader: `start` means the session never existed (409 is the cap), `stream`\n * means the session is alive but something in it went wrong, and `session`\n * means the server ended it.\n */\nexport interface LogTailError {\n scope: \"start\" | \"stream\" | \"session\";\n message: string;\n /** HTTP status when a request produced the failure. 409 is the session cap. */\n httpStatus?: number;\n}\n\n/** Renderable transport/session state. The terminal values are the server's own. */\nexport type LogTailStatus =\n | \"idle\"\n | \"starting\"\n | \"streaming\"\n | \"connection lost — retrying\"\n | \"completed\"\n | \"failed\"\n | \"stopped\"\n | \"interrupted\";\n\n/**\n * `stopping` is a stop in flight: the source may still flush rows, so the tail\n * keeps reading until the done frame.\n */\nexport function isTerminalSessionState(state: LogSessionState | undefined): boolean {\n return state !== undefined && isSessionTerminal(state);\n}\n\nfunction isTerminalTailStatus(status: LogTailStatus): boolean {\n return isSessionState(status) && isSessionTerminal(status);\n}\n\nexport interface LogTailBuffer {\n /** Rows in arrival order, oldest first — the order this surface tails in. */\n rows: Record<string, unknown>[];\n /**\n * Each entry's presented ClickyRow, index-aligned with `rows` (same length,\n * same order) — `undefined` where the event carried none. Additive: a plain\n * log tail never reads this and `rows` itself is unchanged, so existing\n * `useLogTail` consumers keep working exactly as before.\n */\n clickyRows: (ClickyRow | undefined)[];\n /** Highest sequence applied, or null before the first frame. Never assumed to start at 1. */\n lastSequence: number | null;\n /** Rows evicted by the cap. Kept so the UI can say so instead of quietly shortening history. */\n dropped: number;\n}\n\nexport const emptyLogTailBuffer: LogTailBuffer = {\n rows: [],\n clickyRows: [],\n lastSequence: null,\n dropped: 0,\n};\n\n/**\n * Renders profile parameters as the tail of a session request's query string,\n * `\"\"` when there are none, and each entry already `&`-prefixed so it appends\n * to a query that always begins with `?follow=true`.\n *\n * Keys are sorted so two callers passing the same parameters in a different\n * order produce the same string — the effect that opens the session depends on\n * it, and an unstable spelling would tear down a live tail and start a new one\n * on a render that changed nothing.\n *\n * A null or undefined value is omitted rather than sent as the text \"null\": the\n * server reads every query key as a supplied parameter, so spelling an absent\n * one out states a filter the caller did not ask for.\n */\nexport function encodeTailParams(params: Record<string, unknown> | undefined): string {\n if (!params) return \"\";\n const query = new URLSearchParams();\n for (const key of Object.keys(params).sort()) {\n const value = params[key];\n if (value === undefined || value === null) continue;\n query.append(key, String(value));\n }\n const encoded = query.toString();\n return encoded === \"\" ? \"\" : `&${encoded}`;\n}\n\n/**\n * Applies one frame to the buffer, dropping anything at or below the highest\n * sequence already seen. A watermark is enough — and cheaper than remembering\n * every id — because SSE is ordered within a connection and the only source of\n * duplicates is a reconnect, whose replay starts at Last-Event-ID and so can\n * only re-deliver frames the buffer has already passed.\n *\n * Returns the buffer unchanged when the frame adds nothing, so React can bail\n * out of the render.\n */\nexport function appendTailEvent(\n buffer: LogTailBuffer,\n event: LogTailEvent,\n maxRows: number,\n): LogTailBuffer {\n if (buffer.lastSequence !== null && event.sequence <= buffer.lastSequence) return buffer;\n const incoming = event.rows ?? (event.row ? [event.row] : []);\n if (incoming.length === 0) return { ...buffer, lastSequence: event.sequence };\n\n // A batched `rows` frame has no per-item clickyRow equivalent — only the\n // single-`row` shape trace/follow sessions use ever carries one — so a\n // batch pads with `undefined` to stay index-aligned with `rows`.\n const incomingClickyRows: (ClickyRow | undefined)[] = event.rows\n ? event.rows.map(() => undefined)\n : [event.clickyRow];\n\n const merged = buffer.rows.concat(incoming);\n const mergedClickyRows = buffer.clickyRows.concat(incomingClickyRows);\n const overflow = Math.max(0, merged.length - Math.max(1, maxRows));\n return {\n rows: overflow > 0 ? merged.slice(overflow) : merged,\n clickyRows: overflow > 0 ? mergedClickyRows.slice(overflow) : mergedClickyRows,\n lastSequence: event.sequence,\n dropped: buffer.dropped + overflow,\n };\n}\n\nexport interface UseLogTailOptions {\n /** Query profile to follow, e.g. \"k8s-pod-logs\". */\n profile: string;\n /** Profile parameters, sent as the session request's query string. */\n params?: Record<string, unknown> | undefined;\n /** Base path of the session API, e.g. \"/api/v1\". */\n basePath?: string | undefined;\n /** Start/stop is the caller's: flipping this to false closes the stream; the server reaps the unsubscribed session. */\n following?: boolean | undefined;\n /** Rows kept in memory; older ones are evicted and counted in `droppedRows`. */\n maxRows?: number | undefined;\n /**\n * Called once per applied `event` frame, in sequence order, before the frame\n * reaches the buffer — so a reducer sees every row even after `maxRows` starts\n * evicting. A replayed sequence is not delivered again, and `done` frames are\n * never delivered. The latest callback is always used; changing its identity\n * does not restart the session. A throw is reported as a `stream` error.\n */\n onEvent?: ((event: LogTailEvent) => void) | undefined;\n}\n\nexport interface UseLogTailResult {\n /** Accumulated rows, oldest first. */\n rows: Record<string, unknown>[];\n /** Each row's presented ClickyRow, index-aligned with `rows`; `undefined`\n * where the event carried none (a plain log tail, or a top-session\n * snapshot event). */\n clickyRows: (ClickyRow | undefined)[];\n status: LogTailStatus;\n error: LogTailError | null;\n sessionId: string | null;\n /** True while the caller wants rows and the session has not reached a terminal state. */\n following: boolean;\n /** Rows the cap evicted; non-zero means the tail no longer holds the whole run. */\n droppedRows: number;\n /** Highest sequence applied — the resume point a reconnect would ask for. */\n lastSequence: number | null;\n /** Latest SessionInfo the server sent, for eventCount / startedAt / state. */\n session: LogSessionInfo | null;\n}\n\nconst DEFAULT_BASE = \"/api/v1\";\nconst DEFAULT_MAX_ROWS = 5_000;\n\nfunction hasEventSource(): boolean {\n return typeof globalThis !== \"undefined\" && typeof globalThis.EventSource !== \"undefined\";\n}\n\nexport function useLogTail(options: UseLogTailOptions): UseLogTailResult {\n const {\n profile,\n params,\n basePath = DEFAULT_BASE,\n following: wantFollow = false,\n maxRows = DEFAULT_MAX_ROWS,\n onEvent,\n } = options;\n\n const [buffer, setBuffer] = useState<LogTailBuffer>(emptyLogTailBuffer);\n const [status, setStatus] = useState<LogTailStatus>(\"idle\");\n const [error, setError] = useState<LogTailError | null>(null);\n const [session, setSession] = useState<LogSessionInfo | null>(null);\n\n // The cap is read when a frame lands rather than closed over, so changing how\n // much history to keep never tears down a live session to do it.\n const maxRowsRef = useRef(maxRows);\n maxRowsRef.current = maxRows;\n const onEventRef = useRef(onEvent);\n onEventRef.current = onEvent;\n\n const eventSourceFactory = useEventSourceFactory();\n const eventSourceFactoryRef = useRef(eventSourceFactory);\n eventSourceFactoryRef.current = eventSourceFactory;\n\n // Profile parameters travel in the query string because that is where the\n // session endpoint reads them from: it builds its params by walking\n // r.URL.Query() and never looks at the body, so a posted body is a filter the\n // server silently ignores — the tail would run the profile's defaults while\n // the reader believed they were following what they had filtered to.\n //\n // Serialized here rather than in the effect so it is also the effect's\n // dependency: two renders with equal parameters must not restart the session.\n const paramsQuery = encodeTailParams(params);\n\n useEffect(() => {\n if (!wantFollow) return;\n\n // Each start is a distinct server session replaying from its own first\n // sequence, so the previous run's rows cannot be continued — carrying them\n // over would interleave two unrelated sequence spaces in one list.\n setBuffer(emptyLogTailBuffer);\n setError(null);\n setSession(null);\n\n // Checked before the session exists: a session nobody can subscribe to\n // would hold a server slot until the reaper noticed.\n if (!hasEventSource()) {\n setStatus(\"failed\");\n setError({\n scope: \"start\",\n message: `cannot follow ${profile}: this browser has no EventSource, and session events are served only as SSE`,\n });\n return;\n }\n setStatus(\"starting\");\n\n let cancelled = false;\n const aborter = new AbortController();\n let source: EventSourceLike | undefined;\n let ended = false;\n // onEvent's own watermark, tracked here rather than read from the buffer:\n // the buffer only dedupes inside a state updater, which React may run twice,\n // so a callback there would double-count. Same rule as appendTailEvent.\n let delivered: number | null = null;\n\n const deliver = (event: LogTailEvent) => {\n if (delivered !== null && event.sequence <= delivered) return;\n delivered = event.sequence;\n try {\n onEventRef.current?.(event);\n } catch (cause) {\n setError({ scope: \"stream\", message: `onEvent threw on sequence ${event.sequence}: ${String(cause)}` });\n }\n };\n\n const apply = (event: LogTailEvent) => {\n // An event-level error does not end the session, so it is reported beside\n // the rows rather than in place of them. Set before delivery so a reducer\n // that throws on the same frame is the error left standing.\n if (event.error) setError({ scope: \"stream\", message: event.error });\n deliver(event);\n setBuffer((prev) => appendTailEvent(prev, event, maxRowsRef.current));\n };\n\n // Unlike the task stream this does not skip what it cannot parse: a tail\n // that silently discards frames is indistinguishable from a quiet log\n // source, which is the one thing a reader must never be left guessing at.\n const readFrame = (label: string, e: MessageEvent): unknown => {\n try {\n return JSON.parse(e.data as string);\n } catch (cause) {\n setError({ scope: \"stream\", message: `unparseable ${label} frame: ${String(cause)}` });\n return undefined;\n }\n };\n\n const settle = (info: LogSessionInfo) => {\n setSession(info);\n if (!isTerminalSessionState(info.state)) return;\n ended = true;\n setStatus(info.state as LogTailStatus);\n if (info.state === \"failed\") {\n setError({\n scope: \"session\",\n message: info.error || `session ${info.id} failed without reporting a reason`,\n });\n }\n };\n\n const subscribe = (id: string) => {\n const es = eventSourceFactoryRef.current(`${basePath}/sessions/${encodeURIComponent(id)}/events`);\n source = es;\n setStatus(\"streaming\");\n es.addEventListener(\"event\", (e) => {\n const frame = readFrame(\"event\", e as MessageEvent);\n if (frame) apply(frame as LogTailEvent);\n });\n es.addEventListener(\"done\", (e) => {\n const info = readFrame(\"done\", e as MessageEvent);\n if (info) settle(info as LogSessionInfo);\n es.close();\n });\n // A dropped connection is not a failure: EventSource reconnects with\n // Last-Event-ID and the server replays. It is reported through `status`\n // only, so a blip never leaves a sticky error the reader has to dismiss —\n // and never after the session ended, where it would overwrite the reason\n // it ended with a reconnect that is not going to happen.\n es.onerror = () => {\n if (!ended) setStatus(\"connection lost — retrying\");\n };\n };\n\n const start = async () => {\n let info: LogSessionInfo;\n try {\n const res = await fetch(\n `${basePath}/profile/${encodeURIComponent(profile)}/sessions?follow=true${paramsQuery}`,\n { method: \"POST\", headers: { Accept: \"application/json\" }, signal: aborter.signal },\n );\n if (cancelled) return;\n if (!res.ok) {\n const detail = (await res.text()).trim() || \"no detail\";\n setStatus(\"failed\");\n setError({\n scope: \"start\",\n httpStatus: res.status,\n message:\n res.status === 409\n ? `the server is already running as many follow sessions as it allows (HTTP 409): ${detail}`\n : `could not start a follow session for ${profile} (HTTP ${res.status}): ${detail}`,\n });\n return;\n }\n info = (await res.json()) as LogSessionInfo;\n } catch (cause) {\n // Our own abort on unmount or a parameter change: nothing is left to report to.\n if (cancelled) return;\n setStatus(\"failed\");\n setError({\n scope: \"start\",\n message: `could not reach ${basePath} to start a follow session for ${profile}: ${String(cause)}`,\n });\n return;\n }\n\n // The caller stopped following while the POST was in flight. If the\n // session was created, nothing ever subscribes, so the server ends it.\n if (cancelled) return;\n setSession(info);\n subscribe(info.id);\n };\n\n void start();\n // Aborting the start and closing the stream is the whole release: a view\n // session without a subscriber ends server-side.\n return () => {\n cancelled = true;\n aborter.abort();\n source?.close();\n };\n }, [profile, paramsQuery, basePath, wantFollow]);\n\n // Stopping returns the surface to idle, but a session that ended on its own\n // keeps its terminal status so the reason it ended stays on screen.\n useEffect(() => {\n if (!wantFollow) setStatus((prev) => (isTerminalTailStatus(prev) ? prev : \"idle\"));\n }, [wantFollow]);\n\n return {\n rows: buffer.rows,\n clickyRows: buffer.clickyRows,\n status,\n error,\n sessionId: session?.id ?? null,\n following: wantFollow && !isTerminalTailStatus(status),\n droppedRows: buffer.dropped,\n lastSequence: buffer.lastSequence,\n session,\n };\n}\n"],"mappings":";;;;;;;;AA6FA,SAAgB,uBAAuB,OAA6C;CAClF,OAAO,UAAU,KAAA,KAAaA,qBAAAA,kBAAkB,KAAK;AACvD;AAEA,SAAS,qBAAqB,QAAgC;CAC5D,OAAOC,qBAAAA,eAAe,MAAM,KAAKD,qBAAAA,kBAAkB,MAAM;AAC3D;AAkBA,IAAa,qBAAoC;CAC/C,MAAM,CAAC;CACP,YAAY,CAAC;CACb,cAAc;CACd,SAAS;AACX;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAiB,QAAqD;CACpF,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,QAAQ,IAAI,gBAAgB;CAClC,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,GAAG;EAC5C,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA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O,KAAK;KACjF,CAAC;KACD;IACF;IACA,OAAQ,MAAM,IAAI,KAAK;GACzB,SAAS,OAAO;IAEd,IAAI,WAAW;IACf,UAAU,QAAQ;IAClB,SAAS;KACP,OAAO;KACP,SAAS,mBAAmB,SAAS,iCAAiC,QAAQ,IAAI,OAAO,KAAK;IAChG,CAAC;IACD;GACF;GAIA,IAAI,WAAW;GACf,WAAW,IAAI;GACf,UAAU,KAAK,EAAE;EACnB;EAEA,MAAW;EAGX,aAAa;GACX,YAAY;GACZ,QAAQ,MAAM;GACd,QAAQ,MAAM;EAChB;CACF,GAAG;EAAC;EAAS;EAAa;EAAU;CAAU,CAAC;CAI/C,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,IAAI,CAAC,YAAY,WAAW,SAAU,qBAAqB,IAAI,IAAI,OAAO,MAAO;CACnF,GAAG,CAAC,UAAU,CAAC;CAEf,OAAO;EACL,MAAM,OAAO;EACb,YAAY,OAAO;EACnB;EACA;EACA,WAAW,SAAS,MAAM;EAC1B,WAAW,cAAc,CAAC,qBAAqB,MAAM;EACrD,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"use-log-tail.cjs","names":["isSessionTerminal","isSessionState","appendTailRows","useState","useEventSourceFactory","useRef","subscribeJSON","openLogTailSession"],"sources":["../../src/hooks/use-log-tail.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport type { ClickyRow } from \"../data/Clicky\";\nimport { isSessionState, isSessionTerminal, type SessionState } from \"../rpc/sessionTypes\";\nimport { useEventSourceFactory } from \"./event-source\";\nimport { subscribeJSON } from \"./event-stream\";\nimport { openLogTailSession, type LogSessionInfo, type LogTailError } from \"./log-tail-session\";\nimport { appendTailRows } from \"./tail-buffer\";\n\nexport type { LogSessionInfo, LogTailError } from \"./log-tail-session\";\n\n// use-log-tail is the clicky-ui client for a *follow* session: the server opens\n// a live source for a query profile and streams rows out of it until someone\n// closes it. The resource underneath is unforgiving. A follow session holds a\n// websocket to Loki, or a log stream to a kubelet, for as long as it exists,\n// and the server caps how many may run at once (ErrMaxSessions, surfaced as\n// HTTP 409). The server owns that slot's release: a view session ends shortly\n// after its last subscriber disconnects, so every exit path — unmount and a\n// parameter change included — only has to abort the start request and close\n// the EventSource.\n//\n// Events travel over SSE only. The events route serves SSE (or ndjson on\n// request) and resumes through Last-Event-ID; there is no JSON-array polling\n// shape to fall back to, so a browser without EventSource fails loudly.\n//\n// Each SSE frame carries an `id:`, so a reconnecting EventSource sends\n// Last-Event-ID and the server resumes from that sequence — re-delivering\n// frames the client may already hold. Sequences are the server's, not a client\n// index: they do not start at 1 and they do not reset, so the accumulator\n// dedupes against the highest sequence it has applied rather than against a\n// position in an array.\n\n/** The sessions API's state, under the name this hook has always exported. */\nexport type LogSessionState = SessionState;\n\n/**\n * One `event:` frame. It carries either a single `row` or a batch under `rows`\n * — never both — plus an `error` when the source failed mid-stream without the\n * session itself ending.\n *\n * `clickyRow` is the presented row — `{cells, detail?}`, built by the exact\n * function that fills in `node.rows[n]` of the list's own\n * `application/json+clicky` document — riding next to the raw `row` on a\n * trace/follow session's per-row events. A plain log tail (or a top-session\n * snapshot event) never sets it; only a reader that reconciles rows against a\n * presented table, i.e. OperationCatalog's follow mode, depends on it.\n */\nexport interface LogTailEvent {\n sessionId: string;\n sequence: number;\n time?: string;\n row?: Record<string, unknown>;\n rows?: Record<string, unknown>[];\n /** The presented ClickyRow for `row`, when the profile sends one. */\n clickyRow?: ClickyRow;\n error?: string;\n}\n\n/** Renderable transport/session state. The terminal values are the server's own. */\nexport type LogTailStatus =\n | \"idle\"\n | \"starting\"\n | \"streaming\"\n | \"connection lost — retrying\"\n | \"completed\"\n | \"failed\"\n | \"stopped\"\n | \"interrupted\";\n\n/**\n * `stopping` is a stop in flight: the source may still flush rows, so the tail\n * keeps reading until the done frame.\n */\nexport function isTerminalSessionState(state: LogSessionState | undefined): boolean {\n return state !== undefined && isSessionTerminal(state);\n}\n\nfunction isTerminalTailStatus(status: LogTailStatus): boolean {\n return isSessionState(status) && isSessionTerminal(status);\n}\n\nexport interface LogTailBuffer {\n /** Rows in arrival order, oldest first — the order this surface tails in. */\n rows: Record<string, unknown>[];\n /**\n * Each entry's presented ClickyRow, index-aligned with `rows` (same length,\n * same order) — `undefined` where the event carried none. Additive: a plain\n * log tail never reads this and `rows` itself is unchanged, so existing\n * `useLogTail` consumers keep working exactly as before.\n */\n clickyRows: (ClickyRow | undefined)[];\n /** Highest sequence applied, or null before the first frame. Never assumed to start at 1. */\n lastSequence: number | null;\n /** Rows evicted by the cap. Kept so the UI can say so instead of quietly shortening history. */\n dropped: number;\n}\n\nexport const emptyLogTailBuffer: LogTailBuffer = {\n rows: [],\n clickyRows: [],\n lastSequence: null,\n dropped: 0,\n};\n\n/**\n * Renders profile parameters as the tail of a session request's query string,\n * `\"\"` when there are none, and each entry already `&`-prefixed so it appends\n * to a query that always begins with `?follow=true`.\n *\n * Keys are sorted so two callers passing the same parameters in a different\n * order produce the same string — the effect that opens the session depends on\n * it, and an unstable spelling would tear down a live tail and start a new one\n * on a render that changed nothing.\n *\n * A null or undefined value is omitted rather than sent as the text \"null\": the\n * server reads every query key as a supplied parameter, so spelling an absent\n * one out states a filter the caller did not ask for.\n */\nexport function encodeTailParams(params: Record<string, unknown> | undefined): string {\n if (!params) return \"\";\n const query = new URLSearchParams();\n for (const key of Object.keys(params).sort()) {\n const value = params[key];\n if (value === undefined || value === null) continue;\n query.append(key, String(value));\n }\n const encoded = query.toString();\n return encoded === \"\" ? \"\" : `&${encoded}`;\n}\n\n/**\n * Applies one frame to the buffer, dropping anything at or below the highest\n * sequence already seen. A watermark is enough — and cheaper than remembering\n * every id — because SSE is ordered within a connection and the only source of\n * duplicates is a reconnect, whose replay starts at Last-Event-ID and so can\n * only re-deliver frames the buffer has already passed.\n *\n * Returns the buffer unchanged when the frame adds nothing, so React can bail\n * out of the render.\n */\nexport function appendTailEvent(\n buffer: LogTailBuffer,\n event: LogTailEvent,\n maxRows: number,\n): LogTailBuffer {\n if (buffer.lastSequence !== null && event.sequence <= buffer.lastSequence) return buffer;\n const incoming = event.rows ?? (event.row ? [event.row] : []);\n if (incoming.length === 0) return { ...buffer, lastSequence: event.sequence };\n\n // A batched `rows` frame has no per-item clickyRow equivalent — only the\n // single-`row` shape trace/follow sessions use ever carries one — so a\n // batch pads with `undefined` to stay index-aligned with `rows`.\n const incomingClickyRows: (ClickyRow | undefined)[] = event.rows\n ? event.rows.map(() => undefined)\n : [event.clickyRow];\n\n const { rows, dropped } = appendTailRows(buffer.rows, incoming, { limit: maxRows });\n return {\n rows,\n clickyRows: buffer.clickyRows.concat(incomingClickyRows).slice(dropped),\n lastSequence: event.sequence,\n dropped: buffer.dropped + dropped,\n };\n}\n\nexport interface UseLogTailOptions {\n /** Query profile to follow, e.g. \"k8s-pod-logs\". */\n profile: string;\n /** Profile parameters, sent as the session request's query string. */\n params?: Record<string, unknown> | undefined;\n /** Base path of the session API, e.g. \"/api/v1\". */\n basePath?: string | undefined;\n /** Start/stop is the caller's: flipping this to false closes the stream; the server reaps the unsubscribed session. */\n following?: boolean | undefined;\n /** Rows kept in memory; older ones are evicted and counted in `droppedRows`. */\n maxRows?: number | undefined;\n /**\n * Called once per applied `event` frame, in sequence order, before the frame\n * reaches the buffer — so a reducer sees every row even after `maxRows` starts\n * evicting. A replayed sequence is not delivered again, and `done` frames are\n * never delivered. The latest callback is always used; changing its identity\n * does not restart the session. A throw is reported as a `stream` error.\n */\n onEvent?: ((event: LogTailEvent) => void) | undefined;\n}\n\nexport interface UseLogTailResult {\n /** Accumulated rows, oldest first. */\n rows: Record<string, unknown>[];\n /** Each row's presented ClickyRow, index-aligned with `rows`; `undefined`\n * where the event carried none (a plain log tail, or a top-session\n * snapshot event). */\n clickyRows: (ClickyRow | undefined)[];\n status: LogTailStatus;\n error: LogTailError | null;\n sessionId: string | null;\n /** True while the caller wants rows and the session has not reached a terminal state. */\n following: boolean;\n /** Rows the cap evicted; non-zero means the tail no longer holds the whole run. */\n droppedRows: number;\n /** Highest sequence applied — the resume point a reconnect would ask for. */\n lastSequence: number | null;\n /** Latest SessionInfo the server sent, for eventCount / startedAt / state. */\n session: LogSessionInfo | null;\n}\n\nconst DEFAULT_BASE = \"/api/v1\";\nconst DEFAULT_MAX_ROWS = 5_000;\n\ninterface LogTailSnapshot {\n request: { key: string; basePath: string; profile: string; paramsQuery: string } | null;\n buffer: LogTailBuffer;\n status: LogTailStatus;\n error: LogTailError | null;\n session: LogSessionInfo | null;\n}\n\nconst emptyLogTailSnapshot: LogTailSnapshot = {\n request: null,\n buffer: emptyLogTailBuffer,\n status: \"idle\",\n error: null,\n session: null,\n};\n\nexport function useLogTail(options: UseLogTailOptions): UseLogTailResult {\n const {\n profile,\n params,\n basePath = DEFAULT_BASE,\n following: wantFollow = false,\n maxRows = DEFAULT_MAX_ROWS,\n onEvent,\n } = options;\n\n const [snapshot, setSnapshot] = useState(emptyLogTailSnapshot);\n\n const eventSourceFactory = useEventSourceFactory();\n const streamOptions = useRef({ maxRows, onEvent, eventSourceFactory });\n useEffect(() => {\n streamOptions.current = { maxRows, onEvent, eventSourceFactory };\n }, [maxRows, onEvent, eventSourceFactory]);\n\n // Profile parameters travel in the query string because that is where the\n // session endpoint reads them from: it builds its params by walking\n // r.URL.Query() and never looks at the body, so a posted body is a filter the\n // server silently ignores — the tail would run the profile's defaults while\n // the reader believed they were following what they had filtered to.\n //\n // Serialized here rather than in the effect so it is also the effect's\n // dependency: two renders with equal parameters must not restart the session.\n const paramsQuery = encodeTailParams(params);\n const key = wantFollow ? JSON.stringify([basePath, profile, paramsQuery]) : null;\n const { request, buffer, error, session } = snapshot;\n if (key !== (request?.key ?? null)) {\n setSnapshot(key === null ? { ...snapshot, request: null } : {\n ...emptyLogTailSnapshot,\n request: { key, basePath, profile, paramsQuery },\n status: \"starting\",\n });\n }\n\n useEffect(() => {\n if (!request) return;\n const update = (fields: Partial<Omit<LogTailSnapshot, \"request\">>) => {\n setSnapshot(current => current.request === request ? { ...current, ...fields } : current);\n };\n\n let ended = false;\n // onEvent's own watermark, tracked here rather than read from the buffer:\n // the buffer only dedupes inside a state updater, which React may run twice,\n // so a callback there would double-count. Same rule as appendTailEvent.\n let delivered: number | null = null;\n\n const deliver = (event: LogTailEvent) => {\n if (delivered !== null && event.sequence <= delivered) return;\n delivered = event.sequence;\n try {\n streamOptions.current.onEvent?.(event);\n } catch (cause) {\n update({ error: { scope: \"stream\", message: `onEvent threw on sequence ${event.sequence}: ${String(cause)}` } });\n }\n };\n\n const apply = (event: LogTailEvent) => {\n const { maxRows: limit } = streamOptions.current;\n // An event-level error does not end the session, so it is reported beside\n // the rows rather than in place of them. Set before delivery so a reducer\n // that throws on the same frame is the error left standing.\n if (event.error) update({ error: { scope: \"stream\", message: event.error } });\n deliver(event);\n setSnapshot(current => {\n if (current.request !== request) return current;\n const next = appendTailEvent(current.buffer, event, limit);\n return next === current.buffer ? current : { ...current, buffer: next };\n });\n };\n\n // Unlike the task stream this does not skip what it cannot parse: a tail\n // that silently discards frames is indistinguishable from a quiet log\n // source, which is the one thing a reader must never be left guessing at.\n const readFrame = (label: string, e: MessageEvent): unknown => {\n try {\n return JSON.parse(e.data as string);\n } catch (cause) {\n update({ error: { scope: \"stream\", message: `unparseable ${label} frame: ${String(cause)}` } });\n return undefined;\n }\n };\n\n const settle = (info: LogSessionInfo) => {\n ended = isTerminalSessionState(info.state);\n if (info.state === \"failed\") {\n update({\n session: info,\n status: info.state,\n error: { scope: \"session\", message: info.error || `session ${info.id} failed without reporting a reason` },\n });\n } else {\n update(ended ? { session: info, status: info.state as LogTailStatus } : { session: info });\n }\n };\n\n const subscribe = (info: LogSessionInfo) => {\n update({ session: info, status: \"streaming\" });\n return subscribeJSON<LogTailEvent>(streamOptions.current.eventSourceFactory, `${request.basePath}/sessions/${encodeURIComponent(info.id)}/events`, {\n messageEvent: \"event\",\n endEvent: \"done\",\n onOpen: () => update({ status: \"streaming\" }),\n onData: apply,\n onInvalidMessage: error => update({ error: { scope: \"stream\", message: error.message } }),\n onEnd: event => {\n const info = readFrame(\"done\", event as MessageEvent);\n if (info) settle(info as LogSessionInfo);\n else update({ status: \"failed\" });\n },\n onError: (error, terminal) => {\n if (ended) return;\n update(terminal ? { status: \"failed\", error: { scope: \"stream\", message: error.message } } : { status: \"connection lost — retrying\" });\n },\n });\n };\n\n return openLogTailSession({\n basePath: request.basePath,\n profile: request.profile,\n paramsQuery: request.paramsQuery,\n onStart: subscribe,\n onError: error => update({ status: \"failed\", error }),\n });\n }, [request]);\n\n // Stopping returns the surface to idle, but a session that ended on its own\n // keeps its terminal status so the reason it ended stays on screen.\n const status = request === null && !isTerminalTailStatus(snapshot.status) ? \"idle\" : snapshot.status;\n\n return {\n rows: buffer.rows,\n clickyRows: buffer.clickyRows,\n status,\n error,\n sessionId: session?.id ?? null,\n following: wantFollow && !isTerminalTailStatus(status),\n droppedRows: buffer.dropped,\n lastSequence: buffer.lastSequence,\n session,\n };\n}\n"],"mappings":";;;;;;;;;;;AAwEA,SAAgB,uBAAuB,OAA6C;CAClF,OAAO,UAAU,KAAA,KAAaA,qBAAAA,kBAAkB,KAAK;AACvD;AAEA,SAAS,qBAAqB,QAAgC;CAC5D,OAAOC,qBAAAA,eAAe,MAAM,KAAKD,qBAAAA,kBAAkB,MAAM;AAC3D;AAkBA,IAAa,qBAAoC;CAC/C,MAAM,CAAC;CACP,YAAY,CAAC;CACb,cAAc;CACd,SAAS;AACX;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAiB,QAAqD;CACpF,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,QAAQ,IAAI,gBAAgB;CAClC,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,GAAG;EAC5C,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM;EAC3C,MAAM,OAAO,KAAK,OAAO,KAAK,CAAC;CACjC;CACA,MAAM,UAAU,MAAM,SAAS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SAAS,YAAY,QAAQ,CAAC,qBAAqB,SAAS,MAAM,IAAI,SAAS,SAAS;CAE9F,OAAO;EACL,MAAM,OAAO;EACb,YAAY,OAAO;EACnB;EACA;EACA,WAAW,SAAS,MAAM;EAC1B,WAAW,cAAc,CAAC,qBAAqB,MAAM;EACrD,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB;CACF;AACF"}
|
|
@@ -1,19 +1,9 @@
|
|
|
1
1
|
import { ClickyRow } from '../data/Clicky.js';
|
|
2
2
|
import { SessionState } from '../rpc/sessionTypes.js';
|
|
3
|
+
import { LogSessionInfo, LogTailError } from './log-tail-session.js';
|
|
4
|
+
export type { LogSessionInfo, LogTailError } from './log-tail-session.js';
|
|
3
5
|
/** The sessions API's state, under the name this hook has always exported. */
|
|
4
6
|
export type LogSessionState = SessionState;
|
|
5
|
-
/** SessionInfo as returned by POST /profile/{name}/sessions and the `done` frame. */
|
|
6
|
-
export interface LogSessionInfo {
|
|
7
|
-
id: string;
|
|
8
|
-
profile: string;
|
|
9
|
-
kind: string;
|
|
10
|
-
state: LogSessionState;
|
|
11
|
-
params?: Record<string, unknown>;
|
|
12
|
-
error?: string;
|
|
13
|
-
eventCount: number;
|
|
14
|
-
startedAt: string;
|
|
15
|
-
stoppedAt?: string;
|
|
16
|
-
}
|
|
17
7
|
/**
|
|
18
8
|
* One `event:` frame. It carries either a single `row` or a batch under `rows`
|
|
19
9
|
* — never both — plus an `error` when the source failed mid-stream without the
|
|
@@ -36,18 +26,6 @@ export interface LogTailEvent {
|
|
|
36
26
|
clickyRow?: ClickyRow;
|
|
37
27
|
error?: string;
|
|
38
28
|
}
|
|
39
|
-
/**
|
|
40
|
-
* Where a failure came from, because the three are not interchangeable to a
|
|
41
|
-
* reader: `start` means the session never existed (409 is the cap), `stream`
|
|
42
|
-
* means the session is alive but something in it went wrong, and `session`
|
|
43
|
-
* means the server ended it.
|
|
44
|
-
*/
|
|
45
|
-
export interface LogTailError {
|
|
46
|
-
scope: "start" | "stream" | "session";
|
|
47
|
-
message: string;
|
|
48
|
-
/** HTTP status when a request produced the failure. 409 is the session cap. */
|
|
49
|
-
httpStatus?: number;
|
|
50
|
-
}
|
|
51
29
|
/** Renderable transport/session state. The terminal values are the server's own. */
|
|
52
30
|
export type LogTailStatus = "idle" | "starting" | "streaming" | "connection lost — retrying" | "completed" | "failed" | "stopped" | "interrupted";
|
|
53
31
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-log-tail.d.ts","sourceRoot":"","sources":["../../src/hooks/use-log-tail.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAqC,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"use-log-tail.d.ts","sourceRoot":"","sources":["../../src/hooks/use-log-tail.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAqC,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAG3F,OAAO,EAAsB,KAAK,cAAc,EAAE,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGhG,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAuBvE,8EAA8E;AAC9E,MAAM,MAAM,eAAe,GAAG,YAAY,CAAC;AAE3C;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IACjC,qEAAqE;IACrE,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,KAAK,CAAC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AAO,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CACvD;AAED,MAAM,WAAW,gBAAgB;IAC/B,sCAAsC;IACtC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IAChC;;2BAEuB;IACvB,UAAU,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC;IACtC,MAAM,EAAE,aAAa,CAAC;IACtB,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;IAC3B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,yFAAyF;IACzF,SAAS,EAAE,OAAO,CAAC;IACnB,mFAAmF;IACnF,WAAW,EAAE,MAAM,CAAC;IACpB,6EAA6E;IAC7E,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,8EAA8E;IAC9E,OAAO,EAAE,cAAc,GAAG,IAAI,CAAC;CAChC;AAqBD,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,CA8IvE"}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { isSessionState, isSessionTerminal } from "../rpc/sessionTypes.js";
|
|
2
2
|
import { useEventSourceFactory } from "./event-source.js";
|
|
3
|
+
import { subscribeJSON } from "./event-stream.js";
|
|
4
|
+
import { openLogTailSession } from "./log-tail-session.js";
|
|
5
|
+
import { appendTailRows } from "./tail-buffer.js";
|
|
3
6
|
import { useEffect, useRef, useState } from "react";
|
|
4
7
|
// src/hooks/use-log-tail.ts
|
|
5
8
|
/**
|
|
@@ -61,160 +64,170 @@ function appendTailEvent(buffer, event, maxRows) {
|
|
|
61
64
|
lastSequence: event.sequence
|
|
62
65
|
};
|
|
63
66
|
const incomingClickyRows = event.rows ? event.rows.map(() => void 0) : [event.clickyRow];
|
|
64
|
-
const
|
|
65
|
-
const mergedClickyRows = buffer.clickyRows.concat(incomingClickyRows);
|
|
66
|
-
const overflow = Math.max(0, merged.length - Math.max(1, maxRows));
|
|
67
|
+
const { rows, dropped } = appendTailRows(buffer.rows, incoming, { limit: maxRows });
|
|
67
68
|
return {
|
|
68
|
-
rows
|
|
69
|
-
clickyRows:
|
|
69
|
+
rows,
|
|
70
|
+
clickyRows: buffer.clickyRows.concat(incomingClickyRows).slice(dropped),
|
|
70
71
|
lastSequence: event.sequence,
|
|
71
|
-
dropped: buffer.dropped +
|
|
72
|
+
dropped: buffer.dropped + dropped
|
|
72
73
|
};
|
|
73
74
|
}
|
|
74
75
|
var DEFAULT_BASE = "/api/v1";
|
|
75
76
|
var DEFAULT_MAX_ROWS = 5e3;
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
77
|
+
var emptyLogTailSnapshot = {
|
|
78
|
+
request: null,
|
|
79
|
+
buffer: emptyLogTailBuffer,
|
|
80
|
+
status: "idle",
|
|
81
|
+
error: null,
|
|
82
|
+
session: null
|
|
83
|
+
};
|
|
79
84
|
function useLogTail(options) {
|
|
80
85
|
const { profile, params, basePath = DEFAULT_BASE, following: wantFollow = false, maxRows = DEFAULT_MAX_ROWS, onEvent } = options;
|
|
81
|
-
const [
|
|
82
|
-
const [status, setStatus] = useState("idle");
|
|
83
|
-
const [error, setError] = useState(null);
|
|
84
|
-
const [session, setSession] = useState(null);
|
|
85
|
-
const maxRowsRef = useRef(maxRows);
|
|
86
|
-
maxRowsRef.current = maxRows;
|
|
87
|
-
const onEventRef = useRef(onEvent);
|
|
88
|
-
onEventRef.current = onEvent;
|
|
86
|
+
const [snapshot, setSnapshot] = useState(emptyLogTailSnapshot);
|
|
89
87
|
const eventSourceFactory = useEventSourceFactory();
|
|
90
|
-
const
|
|
91
|
-
|
|
88
|
+
const streamOptions = useRef({
|
|
89
|
+
maxRows,
|
|
90
|
+
onEvent,
|
|
91
|
+
eventSourceFactory
|
|
92
|
+
});
|
|
93
|
+
useEffect(() => {
|
|
94
|
+
streamOptions.current = {
|
|
95
|
+
maxRows,
|
|
96
|
+
onEvent,
|
|
97
|
+
eventSourceFactory
|
|
98
|
+
};
|
|
99
|
+
}, [
|
|
100
|
+
maxRows,
|
|
101
|
+
onEvent,
|
|
102
|
+
eventSourceFactory
|
|
103
|
+
]);
|
|
92
104
|
const paramsQuery = encodeTailParams(params);
|
|
105
|
+
const key = wantFollow ? JSON.stringify([
|
|
106
|
+
basePath,
|
|
107
|
+
profile,
|
|
108
|
+
paramsQuery
|
|
109
|
+
]) : null;
|
|
110
|
+
const { request, buffer, error, session } = snapshot;
|
|
111
|
+
if (key !== (request?.key ?? null)) setSnapshot(key === null ? {
|
|
112
|
+
...snapshot,
|
|
113
|
+
request: null
|
|
114
|
+
} : {
|
|
115
|
+
...emptyLogTailSnapshot,
|
|
116
|
+
request: {
|
|
117
|
+
key,
|
|
118
|
+
basePath,
|
|
119
|
+
profile,
|
|
120
|
+
paramsQuery
|
|
121
|
+
},
|
|
122
|
+
status: "starting"
|
|
123
|
+
});
|
|
93
124
|
useEffect(() => {
|
|
94
|
-
if (!
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
scope: "start",
|
|
102
|
-
message: `cannot follow ${profile}: this browser has no EventSource, and session events are served only as SSE`
|
|
103
|
-
});
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
setStatus("starting");
|
|
107
|
-
let cancelled = false;
|
|
108
|
-
const aborter = new AbortController();
|
|
109
|
-
let source;
|
|
125
|
+
if (!request) return;
|
|
126
|
+
const update = (fields) => {
|
|
127
|
+
setSnapshot((current) => current.request === request ? {
|
|
128
|
+
...current,
|
|
129
|
+
...fields
|
|
130
|
+
} : current);
|
|
131
|
+
};
|
|
110
132
|
let ended = false;
|
|
111
133
|
let delivered = null;
|
|
112
134
|
const deliver = (event) => {
|
|
113
135
|
if (delivered !== null && event.sequence <= delivered) return;
|
|
114
136
|
delivered = event.sequence;
|
|
115
137
|
try {
|
|
116
|
-
|
|
138
|
+
streamOptions.current.onEvent?.(event);
|
|
117
139
|
} catch (cause) {
|
|
118
|
-
|
|
140
|
+
update({ error: {
|
|
119
141
|
scope: "stream",
|
|
120
142
|
message: `onEvent threw on sequence ${event.sequence}: ${String(cause)}`
|
|
121
|
-
});
|
|
143
|
+
} });
|
|
122
144
|
}
|
|
123
145
|
};
|
|
124
146
|
const apply = (event) => {
|
|
125
|
-
|
|
147
|
+
const { maxRows: limit } = streamOptions.current;
|
|
148
|
+
if (event.error) update({ error: {
|
|
126
149
|
scope: "stream",
|
|
127
150
|
message: event.error
|
|
128
|
-
});
|
|
151
|
+
} });
|
|
129
152
|
deliver(event);
|
|
130
|
-
|
|
153
|
+
setSnapshot((current) => {
|
|
154
|
+
if (current.request !== request) return current;
|
|
155
|
+
const next = appendTailEvent(current.buffer, event, limit);
|
|
156
|
+
return next === current.buffer ? current : {
|
|
157
|
+
...current,
|
|
158
|
+
buffer: next
|
|
159
|
+
};
|
|
160
|
+
});
|
|
131
161
|
};
|
|
132
162
|
const readFrame = (label, e) => {
|
|
133
163
|
try {
|
|
134
164
|
return JSON.parse(e.data);
|
|
135
165
|
} catch (cause) {
|
|
136
|
-
|
|
166
|
+
update({ error: {
|
|
137
167
|
scope: "stream",
|
|
138
168
|
message: `unparseable ${label} frame: ${String(cause)}`
|
|
139
|
-
});
|
|
169
|
+
} });
|
|
140
170
|
return;
|
|
141
171
|
}
|
|
142
172
|
};
|
|
143
173
|
const settle = (info) => {
|
|
144
|
-
|
|
145
|
-
if (
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
174
|
+
ended = isTerminalSessionState(info.state);
|
|
175
|
+
if (info.state === "failed") update({
|
|
176
|
+
session: info,
|
|
177
|
+
status: info.state,
|
|
178
|
+
error: {
|
|
179
|
+
scope: "session",
|
|
180
|
+
message: info.error || `session ${info.id} failed without reporting a reason`
|
|
181
|
+
}
|
|
151
182
|
});
|
|
183
|
+
else update(ended ? {
|
|
184
|
+
session: info,
|
|
185
|
+
status: info.state
|
|
186
|
+
} : { session: info });
|
|
152
187
|
};
|
|
153
|
-
const subscribe = (
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
es.addEventListener("event", (e) => {
|
|
158
|
-
const frame = readFrame("event", e);
|
|
159
|
-
if (frame) apply(frame);
|
|
160
|
-
});
|
|
161
|
-
es.addEventListener("done", (e) => {
|
|
162
|
-
const info = readFrame("done", e);
|
|
163
|
-
if (info) settle(info);
|
|
164
|
-
es.close();
|
|
188
|
+
const subscribe = (info) => {
|
|
189
|
+
update({
|
|
190
|
+
session: info,
|
|
191
|
+
status: "streaming"
|
|
165
192
|
});
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
193
|
+
return subscribeJSON(streamOptions.current.eventSourceFactory, `${request.basePath}/sessions/${encodeURIComponent(info.id)}/events`, {
|
|
194
|
+
messageEvent: "event",
|
|
195
|
+
endEvent: "done",
|
|
196
|
+
onOpen: () => update({ status: "streaming" }),
|
|
197
|
+
onData: apply,
|
|
198
|
+
onInvalidMessage: (error) => update({ error: {
|
|
199
|
+
scope: "stream",
|
|
200
|
+
message: error.message
|
|
201
|
+
} }),
|
|
202
|
+
onEnd: (event) => {
|
|
203
|
+
const info = readFrame("done", event);
|
|
204
|
+
if (info) settle(info);
|
|
205
|
+
else update({ status: "failed" });
|
|
206
|
+
},
|
|
207
|
+
onError: (error, terminal) => {
|
|
208
|
+
if (ended) return;
|
|
209
|
+
update(terminal ? {
|
|
210
|
+
status: "failed",
|
|
211
|
+
error: {
|
|
212
|
+
scope: "stream",
|
|
213
|
+
message: error.message
|
|
214
|
+
}
|
|
215
|
+
} : { status: "connection lost — retrying" });
|
|
188
216
|
}
|
|
189
|
-
|
|
190
|
-
} catch (cause) {
|
|
191
|
-
if (cancelled) return;
|
|
192
|
-
setStatus("failed");
|
|
193
|
-
setError({
|
|
194
|
-
scope: "start",
|
|
195
|
-
message: `could not reach ${basePath} to start a follow session for ${profile}: ${String(cause)}`
|
|
196
|
-
});
|
|
197
|
-
return;
|
|
198
|
-
}
|
|
199
|
-
if (cancelled) return;
|
|
200
|
-
setSession(info);
|
|
201
|
-
subscribe(info.id);
|
|
202
|
-
};
|
|
203
|
-
start();
|
|
204
|
-
return () => {
|
|
205
|
-
cancelled = true;
|
|
206
|
-
aborter.abort();
|
|
207
|
-
source?.close();
|
|
217
|
+
});
|
|
208
218
|
};
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
219
|
+
return openLogTailSession({
|
|
220
|
+
basePath: request.basePath,
|
|
221
|
+
profile: request.profile,
|
|
222
|
+
paramsQuery: request.paramsQuery,
|
|
223
|
+
onStart: subscribe,
|
|
224
|
+
onError: (error) => update({
|
|
225
|
+
status: "failed",
|
|
226
|
+
error
|
|
227
|
+
})
|
|
228
|
+
});
|
|
229
|
+
}, [request]);
|
|
230
|
+
const status = request === null && !isTerminalTailStatus(snapshot.status) ? "idle" : snapshot.status;
|
|
218
231
|
return {
|
|
219
232
|
rows: buffer.rows,
|
|
220
233
|
clickyRows: buffer.clickyRows,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-log-tail.js","names":[],"sources":["../../src/hooks/use-log-tail.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport type { ClickyRow } from \"../data/Clicky\";\nimport { isSessionState, isSessionTerminal, type SessionState } from \"../rpc/sessionTypes\";\nimport { useEventSourceFactory, type EventSourceLike } from \"./event-source\";\n\n// use-log-tail is the clicky-ui client for a *follow* session: the server opens\n// a live source for a query profile and streams rows out of it until someone\n// closes it. The resource underneath is unforgiving. A follow session holds a\n// websocket to Loki, or a log stream to a kubelet, for as long as it exists,\n// and the server caps how many may run at once (ErrMaxSessions, surfaced as\n// HTTP 409). The server owns that slot's release: a view session ends shortly\n// after its last subscriber disconnects, so every exit path — unmount and a\n// parameter change included — only has to abort the start request and close\n// the EventSource.\n//\n// Events travel over SSE only. The events route serves SSE (or ndjson on\n// request) and resumes through Last-Event-ID; there is no JSON-array polling\n// shape to fall back to, so a browser without EventSource fails loudly.\n//\n// Each SSE frame carries an `id:`, so a reconnecting EventSource sends\n// Last-Event-ID and the server resumes from that sequence — re-delivering\n// frames the client may already hold. Sequences are the server's, not a client\n// index: they do not start at 1 and they do not reset, so the accumulator\n// dedupes against the highest sequence it has applied rather than against a\n// position in an array.\n\n/** The sessions API's state, under the name this hook has always exported. */\nexport type LogSessionState = SessionState;\n\n/** SessionInfo as returned by POST /profile/{name}/sessions and the `done` frame. */\nexport interface LogSessionInfo {\n id: string;\n profile: string;\n kind: string;\n state: LogSessionState;\n params?: Record<string, unknown>;\n error?: string;\n eventCount: number;\n startedAt: string;\n stoppedAt?: string;\n}\n\n/**\n * One `event:` frame. It carries either a single `row` or a batch under `rows`\n * — never both — plus an `error` when the source failed mid-stream without the\n * session itself ending.\n *\n * `clickyRow` is the presented row — `{cells, detail?}`, built by the exact\n * function that fills in `node.rows[n]` of the list's own\n * `application/json+clicky` document — riding next to the raw `row` on a\n * trace/follow session's per-row events. A plain log tail (or a top-session\n * snapshot event) never sets it; only a reader that reconciles rows against a\n * presented table, i.e. OperationCatalog's follow mode, depends on it.\n */\nexport interface LogTailEvent {\n sessionId: string;\n sequence: number;\n time?: string;\n row?: Record<string, unknown>;\n rows?: Record<string, unknown>[];\n /** The presented ClickyRow for `row`, when the profile sends one. */\n clickyRow?: ClickyRow;\n error?: string;\n}\n\n/**\n * Where a failure came from, because the three are not interchangeable to a\n * reader: `start` means the session never existed (409 is the cap), `stream`\n * means the session is alive but something in it went wrong, and `session`\n * means the server ended it.\n */\nexport interface LogTailError {\n scope: \"start\" | \"stream\" | \"session\";\n message: string;\n /** HTTP status when a request produced the failure. 409 is the session cap. */\n httpStatus?: number;\n}\n\n/** Renderable transport/session state. The terminal values are the server's own. */\nexport type LogTailStatus =\n | \"idle\"\n | \"starting\"\n | \"streaming\"\n | \"connection lost — retrying\"\n | \"completed\"\n | \"failed\"\n | \"stopped\"\n | \"interrupted\";\n\n/**\n * `stopping` is a stop in flight: the source may still flush rows, so the tail\n * keeps reading until the done frame.\n */\nexport function isTerminalSessionState(state: LogSessionState | undefined): boolean {\n return state !== undefined && isSessionTerminal(state);\n}\n\nfunction isTerminalTailStatus(status: LogTailStatus): boolean {\n return isSessionState(status) && isSessionTerminal(status);\n}\n\nexport interface LogTailBuffer {\n /** Rows in arrival order, oldest first — the order this surface tails in. */\n rows: Record<string, unknown>[];\n /**\n * Each entry's presented ClickyRow, index-aligned with `rows` (same length,\n * same order) — `undefined` where the event carried none. Additive: a plain\n * log tail never reads this and `rows` itself is unchanged, so existing\n * `useLogTail` consumers keep working exactly as before.\n */\n clickyRows: (ClickyRow | undefined)[];\n /** Highest sequence applied, or null before the first frame. Never assumed to start at 1. */\n lastSequence: number | null;\n /** Rows evicted by the cap. Kept so the UI can say so instead of quietly shortening history. */\n dropped: number;\n}\n\nexport const emptyLogTailBuffer: LogTailBuffer = {\n rows: [],\n clickyRows: [],\n lastSequence: null,\n dropped: 0,\n};\n\n/**\n * Renders profile parameters as the tail of a session request's query string,\n * `\"\"` when there are none, and each entry already `&`-prefixed so it appends\n * to a query that always begins with `?follow=true`.\n *\n * Keys are sorted so two callers passing the same parameters in a different\n * order produce the same string — the effect that opens the session depends on\n * it, and an unstable spelling would tear down a live tail and start a new one\n * on a render that changed nothing.\n *\n * A null or undefined value is omitted rather than sent as the text \"null\": the\n * server reads every query key as a supplied parameter, so spelling an absent\n * one out states a filter the caller did not ask for.\n */\nexport function encodeTailParams(params: Record<string, unknown> | undefined): string {\n if (!params) return \"\";\n const query = new URLSearchParams();\n for (const key of Object.keys(params).sort()) {\n const value = params[key];\n if (value === undefined || value === null) continue;\n query.append(key, String(value));\n }\n const encoded = query.toString();\n return encoded === \"\" ? \"\" : `&${encoded}`;\n}\n\n/**\n * Applies one frame to the buffer, dropping anything at or below the highest\n * sequence already seen. A watermark is enough — and cheaper than remembering\n * every id — because SSE is ordered within a connection and the only source of\n * duplicates is a reconnect, whose replay starts at Last-Event-ID and so can\n * only re-deliver frames the buffer has already passed.\n *\n * Returns the buffer unchanged when the frame adds nothing, so React can bail\n * out of the render.\n */\nexport function appendTailEvent(\n buffer: LogTailBuffer,\n event: LogTailEvent,\n maxRows: number,\n): LogTailBuffer {\n if (buffer.lastSequence !== null && event.sequence <= buffer.lastSequence) return buffer;\n const incoming = event.rows ?? (event.row ? [event.row] : []);\n if (incoming.length === 0) return { ...buffer, lastSequence: event.sequence };\n\n // A batched `rows` frame has no per-item clickyRow equivalent — only the\n // single-`row` shape trace/follow sessions use ever carries one — so a\n // batch pads with `undefined` to stay index-aligned with `rows`.\n const incomingClickyRows: (ClickyRow | undefined)[] = event.rows\n ? event.rows.map(() => undefined)\n : [event.clickyRow];\n\n const merged = buffer.rows.concat(incoming);\n const mergedClickyRows = buffer.clickyRows.concat(incomingClickyRows);\n const overflow = Math.max(0, merged.length - Math.max(1, maxRows));\n return {\n rows: overflow > 0 ? merged.slice(overflow) : merged,\n clickyRows: overflow > 0 ? mergedClickyRows.slice(overflow) : mergedClickyRows,\n lastSequence: event.sequence,\n dropped: buffer.dropped + overflow,\n };\n}\n\nexport interface UseLogTailOptions {\n /** Query profile to follow, e.g. \"k8s-pod-logs\". */\n profile: string;\n /** Profile parameters, sent as the session request's query string. */\n params?: Record<string, unknown> | undefined;\n /** Base path of the session API, e.g. \"/api/v1\". */\n basePath?: string | undefined;\n /** Start/stop is the caller's: flipping this to false closes the stream; the server reaps the unsubscribed session. */\n following?: boolean | undefined;\n /** Rows kept in memory; older ones are evicted and counted in `droppedRows`. */\n maxRows?: number | undefined;\n /**\n * Called once per applied `event` frame, in sequence order, before the frame\n * reaches the buffer — so a reducer sees every row even after `maxRows` starts\n * evicting. A replayed sequence is not delivered again, and `done` frames are\n * never delivered. The latest callback is always used; changing its identity\n * does not restart the session. A throw is reported as a `stream` error.\n */\n onEvent?: ((event: LogTailEvent) => void) | undefined;\n}\n\nexport interface UseLogTailResult {\n /** Accumulated rows, oldest first. */\n rows: Record<string, unknown>[];\n /** Each row's presented ClickyRow, index-aligned with `rows`; `undefined`\n * where the event carried none (a plain log tail, or a top-session\n * snapshot event). */\n clickyRows: (ClickyRow | undefined)[];\n status: LogTailStatus;\n error: LogTailError | null;\n sessionId: string | null;\n /** True while the caller wants rows and the session has not reached a terminal state. */\n following: boolean;\n /** Rows the cap evicted; non-zero means the tail no longer holds the whole run. */\n droppedRows: number;\n /** Highest sequence applied — the resume point a reconnect would ask for. */\n lastSequence: number | null;\n /** Latest SessionInfo the server sent, for eventCount / startedAt / state. */\n session: LogSessionInfo | null;\n}\n\nconst DEFAULT_BASE = \"/api/v1\";\nconst DEFAULT_MAX_ROWS = 5_000;\n\nfunction hasEventSource(): boolean {\n return typeof globalThis !== \"undefined\" && typeof globalThis.EventSource !== \"undefined\";\n}\n\nexport function useLogTail(options: UseLogTailOptions): UseLogTailResult {\n const {\n profile,\n params,\n basePath = DEFAULT_BASE,\n following: wantFollow = false,\n maxRows = DEFAULT_MAX_ROWS,\n onEvent,\n } = options;\n\n const [buffer, setBuffer] = useState<LogTailBuffer>(emptyLogTailBuffer);\n const [status, setStatus] = useState<LogTailStatus>(\"idle\");\n const [error, setError] = useState<LogTailError | null>(null);\n const [session, setSession] = useState<LogSessionInfo | null>(null);\n\n // The cap is read when a frame lands rather than closed over, so changing how\n // much history to keep never tears down a live session to do it.\n const maxRowsRef = useRef(maxRows);\n maxRowsRef.current = maxRows;\n const onEventRef = useRef(onEvent);\n onEventRef.current = onEvent;\n\n const eventSourceFactory = useEventSourceFactory();\n const eventSourceFactoryRef = useRef(eventSourceFactory);\n eventSourceFactoryRef.current = eventSourceFactory;\n\n // Profile parameters travel in the query string because that is where the\n // session endpoint reads them from: it builds its params by walking\n // r.URL.Query() and never looks at the body, so a posted body is a filter the\n // server silently ignores — the tail would run the profile's defaults while\n // the reader believed they were following what they had filtered to.\n //\n // Serialized here rather than in the effect so it is also the effect's\n // dependency: two renders with equal parameters must not restart the session.\n const paramsQuery = encodeTailParams(params);\n\n useEffect(() => {\n if (!wantFollow) return;\n\n // Each start is a distinct server session replaying from its own first\n // sequence, so the previous run's rows cannot be continued — carrying them\n // over would interleave two unrelated sequence spaces in one list.\n setBuffer(emptyLogTailBuffer);\n setError(null);\n setSession(null);\n\n // Checked before the session exists: a session nobody can subscribe to\n // would hold a server slot until the reaper noticed.\n if (!hasEventSource()) {\n setStatus(\"failed\");\n setError({\n scope: \"start\",\n message: `cannot follow ${profile}: this browser has no EventSource, and session events are served only as SSE`,\n });\n return;\n }\n setStatus(\"starting\");\n\n let cancelled = false;\n const aborter = new AbortController();\n let source: EventSourceLike | undefined;\n let ended = false;\n // onEvent's own watermark, tracked here rather than read from the buffer:\n // the buffer only dedupes inside a state updater, which React may run twice,\n // so a callback there would double-count. Same rule as appendTailEvent.\n let delivered: number | null = null;\n\n const deliver = (event: LogTailEvent) => {\n if (delivered !== null && event.sequence <= delivered) return;\n delivered = event.sequence;\n try {\n onEventRef.current?.(event);\n } catch (cause) {\n setError({ scope: \"stream\", message: `onEvent threw on sequence ${event.sequence}: ${String(cause)}` });\n }\n };\n\n const apply = (event: LogTailEvent) => {\n // An event-level error does not end the session, so it is reported beside\n // the rows rather than in place of them. Set before delivery so a reducer\n // that throws on the same frame is the error left standing.\n if (event.error) setError({ scope: \"stream\", message: event.error });\n deliver(event);\n setBuffer((prev) => appendTailEvent(prev, event, maxRowsRef.current));\n };\n\n // Unlike the task stream this does not skip what it cannot parse: a tail\n // that silently discards frames is indistinguishable from a quiet log\n // source, which is the one thing a reader must never be left guessing at.\n const readFrame = (label: string, e: MessageEvent): unknown => {\n try {\n return JSON.parse(e.data as string);\n } catch (cause) {\n setError({ scope: \"stream\", message: `unparseable ${label} frame: ${String(cause)}` });\n return undefined;\n }\n };\n\n const settle = (info: LogSessionInfo) => {\n setSession(info);\n if (!isTerminalSessionState(info.state)) return;\n ended = true;\n setStatus(info.state as LogTailStatus);\n if (info.state === \"failed\") {\n setError({\n scope: \"session\",\n message: info.error || `session ${info.id} failed without reporting a reason`,\n });\n }\n };\n\n const subscribe = (id: string) => {\n const es = eventSourceFactoryRef.current(`${basePath}/sessions/${encodeURIComponent(id)}/events`);\n source = es;\n setStatus(\"streaming\");\n es.addEventListener(\"event\", (e) => {\n const frame = readFrame(\"event\", e as MessageEvent);\n if (frame) apply(frame as LogTailEvent);\n });\n es.addEventListener(\"done\", (e) => {\n const info = readFrame(\"done\", e as MessageEvent);\n if (info) settle(info as LogSessionInfo);\n es.close();\n });\n // A dropped connection is not a failure: EventSource reconnects with\n // Last-Event-ID and the server replays. It is reported through `status`\n // only, so a blip never leaves a sticky error the reader has to dismiss —\n // and never after the session ended, where it would overwrite the reason\n // it ended with a reconnect that is not going to happen.\n es.onerror = () => {\n if (!ended) setStatus(\"connection lost — retrying\");\n };\n };\n\n const start = async () => {\n let info: LogSessionInfo;\n try {\n const res = await fetch(\n `${basePath}/profile/${encodeURIComponent(profile)}/sessions?follow=true${paramsQuery}`,\n { method: \"POST\", headers: { Accept: \"application/json\" }, signal: aborter.signal },\n );\n if (cancelled) return;\n if (!res.ok) {\n const detail = (await res.text()).trim() || \"no detail\";\n setStatus(\"failed\");\n setError({\n scope: \"start\",\n httpStatus: res.status,\n message:\n res.status === 409\n ? `the server is already running as many follow sessions as it allows (HTTP 409): ${detail}`\n : `could not start a follow session for ${profile} (HTTP ${res.status}): ${detail}`,\n });\n return;\n }\n info = (await res.json()) as LogSessionInfo;\n } catch (cause) {\n // Our own abort on unmount or a parameter change: nothing is left to report to.\n if (cancelled) return;\n setStatus(\"failed\");\n setError({\n scope: \"start\",\n message: `could not reach ${basePath} to start a follow session for ${profile}: ${String(cause)}`,\n });\n return;\n }\n\n // The caller stopped following while the POST was in flight. If the\n // session was created, nothing ever subscribes, so the server ends it.\n if (cancelled) return;\n setSession(info);\n subscribe(info.id);\n };\n\n void start();\n // Aborting the start and closing the stream is the whole release: a view\n // session without a subscriber ends server-side.\n return () => {\n cancelled = true;\n aborter.abort();\n source?.close();\n };\n }, [profile, paramsQuery, basePath, wantFollow]);\n\n // Stopping returns the surface to idle, but a session that ended on its own\n // keeps its terminal status so the reason it ended stays on screen.\n useEffect(() => {\n if (!wantFollow) setStatus((prev) => (isTerminalTailStatus(prev) ? prev : \"idle\"));\n }, [wantFollow]);\n\n return {\n rows: buffer.rows,\n clickyRows: buffer.clickyRows,\n status,\n error,\n sessionId: session?.id ?? null,\n following: wantFollow && !isTerminalTailStatus(status),\n droppedRows: buffer.dropped,\n lastSequence: buffer.lastSequence,\n session,\n };\n}\n"],"mappings":";;;;;;;;AA6FA,SAAgB,uBAAuB,OAA6C;CAClF,OAAO,UAAU,KAAA,KAAa,kBAAkB,KAAK;AACvD;AAEA,SAAS,qBAAqB,QAAgC;CAC5D,OAAO,eAAe,MAAM,KAAK,kBAAkB,MAAM;AAC3D;AAkBA,IAAa,qBAAoC;CAC/C,MAAM,CAAC;CACP,YAAY,CAAC;CACb,cAAc;CACd,SAAS;AACX;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAiB,QAAqD;CACpF,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,QAAQ,IAAI,gBAAgB;CAClC,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,GAAG;EAC5C,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM;EAC3C,MAAM,OAAO,KAAK,OAAO,KAAK,CAAC;CACjC;CACA,MAAM,UAAU,MAAM,SAAS;CAC/B,OAAO,Y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GX,aAAa;GACX,YAAY;GACZ,QAAQ,MAAM;GACd,QAAQ,MAAM;EAChB;CACF,GAAG;EAAC;EAAS;EAAa;EAAU;CAAU,CAAC;CAI/C,gBAAgB;EACd,IAAI,CAAC,YAAY,WAAW,SAAU,qBAAqB,IAAI,IAAI,OAAO,MAAO;CACnF,GAAG,CAAC,UAAU,CAAC;CAEf,OAAO;EACL,MAAM,OAAO;EACb,YAAY,OAAO;EACnB;EACA;EACA,WAAW,SAAS,MAAM;EAC1B,WAAW,cAAc,CAAC,qBAAqB,MAAM;EACrD,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"use-log-tail.js","names":[],"sources":["../../src/hooks/use-log-tail.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport type { ClickyRow } from \"../data/Clicky\";\nimport { isSessionState, isSessionTerminal, type SessionState } from \"../rpc/sessionTypes\";\nimport { useEventSourceFactory } from \"./event-source\";\nimport { subscribeJSON } from \"./event-stream\";\nimport { openLogTailSession, type LogSessionInfo, type LogTailError } from \"./log-tail-session\";\nimport { appendTailRows } from \"./tail-buffer\";\n\nexport type { LogSessionInfo, LogTailError } from \"./log-tail-session\";\n\n// use-log-tail is the clicky-ui client for a *follow* session: the server opens\n// a live source for a query profile and streams rows out of it until someone\n// closes it. The resource underneath is unforgiving. A follow session holds a\n// websocket to Loki, or a log stream to a kubelet, for as long as it exists,\n// and the server caps how many may run at once (ErrMaxSessions, surfaced as\n// HTTP 409). The server owns that slot's release: a view session ends shortly\n// after its last subscriber disconnects, so every exit path — unmount and a\n// parameter change included — only has to abort the start request and close\n// the EventSource.\n//\n// Events travel over SSE only. The events route serves SSE (or ndjson on\n// request) and resumes through Last-Event-ID; there is no JSON-array polling\n// shape to fall back to, so a browser without EventSource fails loudly.\n//\n// Each SSE frame carries an `id:`, so a reconnecting EventSource sends\n// Last-Event-ID and the server resumes from that sequence — re-delivering\n// frames the client may already hold. Sequences are the server's, not a client\n// index: they do not start at 1 and they do not reset, so the accumulator\n// dedupes against the highest sequence it has applied rather than against a\n// position in an array.\n\n/** The sessions API's state, under the name this hook has always exported. */\nexport type LogSessionState = SessionState;\n\n/**\n * One `event:` frame. It carries either a single `row` or a batch under `rows`\n * — never both — plus an `error` when the source failed mid-stream without the\n * session itself ending.\n *\n * `clickyRow` is the presented row — `{cells, detail?}`, built by the exact\n * function that fills in `node.rows[n]` of the list's own\n * `application/json+clicky` document — riding next to the raw `row` on a\n * trace/follow session's per-row events. A plain log tail (or a top-session\n * snapshot event) never sets it; only a reader that reconciles rows against a\n * presented table, i.e. OperationCatalog's follow mode, depends on it.\n */\nexport interface LogTailEvent {\n sessionId: string;\n sequence: number;\n time?: string;\n row?: Record<string, unknown>;\n rows?: Record<string, unknown>[];\n /** The presented ClickyRow for `row`, when the profile sends one. */\n clickyRow?: ClickyRow;\n error?: string;\n}\n\n/** Renderable transport/session state. The terminal values are the server's own. */\nexport type LogTailStatus =\n | \"idle\"\n | \"starting\"\n | \"streaming\"\n | \"connection lost — retrying\"\n | \"completed\"\n | \"failed\"\n | \"stopped\"\n | \"interrupted\";\n\n/**\n * `stopping` is a stop in flight: the source may still flush rows, so the tail\n * keeps reading until the done frame.\n */\nexport function isTerminalSessionState(state: LogSessionState | undefined): boolean {\n return state !== undefined && isSessionTerminal(state);\n}\n\nfunction isTerminalTailStatus(status: LogTailStatus): boolean {\n return isSessionState(status) && isSessionTerminal(status);\n}\n\nexport interface LogTailBuffer {\n /** Rows in arrival order, oldest first — the order this surface tails in. */\n rows: Record<string, unknown>[];\n /**\n * Each entry's presented ClickyRow, index-aligned with `rows` (same length,\n * same order) — `undefined` where the event carried none. Additive: a plain\n * log tail never reads this and `rows` itself is unchanged, so existing\n * `useLogTail` consumers keep working exactly as before.\n */\n clickyRows: (ClickyRow | undefined)[];\n /** Highest sequence applied, or null before the first frame. Never assumed to start at 1. */\n lastSequence: number | null;\n /** Rows evicted by the cap. Kept so the UI can say so instead of quietly shortening history. */\n dropped: number;\n}\n\nexport const emptyLogTailBuffer: LogTailBuffer = {\n rows: [],\n clickyRows: [],\n lastSequence: null,\n dropped: 0,\n};\n\n/**\n * Renders profile parameters as the tail of a session request's query string,\n * `\"\"` when there are none, and each entry already `&`-prefixed so it appends\n * to a query that always begins with `?follow=true`.\n *\n * Keys are sorted so two callers passing the same parameters in a different\n * order produce the same string — the effect that opens the session depends on\n * it, and an unstable spelling would tear down a live tail and start a new one\n * on a render that changed nothing.\n *\n * A null or undefined value is omitted rather than sent as the text \"null\": the\n * server reads every query key as a supplied parameter, so spelling an absent\n * one out states a filter the caller did not ask for.\n */\nexport function encodeTailParams(params: Record<string, unknown> | undefined): string {\n if (!params) return \"\";\n const query = new URLSearchParams();\n for (const key of Object.keys(params).sort()) {\n const value = params[key];\n if (value === undefined || value === null) continue;\n query.append(key, String(value));\n }\n const encoded = query.toString();\n return encoded === \"\" ? \"\" : `&${encoded}`;\n}\n\n/**\n * Applies one frame to the buffer, dropping anything at or below the highest\n * sequence already seen. A watermark is enough — and cheaper than remembering\n * every id — because SSE is ordered within a connection and the only source of\n * duplicates is a reconnect, whose replay starts at Last-Event-ID and so can\n * only re-deliver frames the buffer has already passed.\n *\n * Returns the buffer unchanged when the frame adds nothing, so React can bail\n * out of the render.\n */\nexport function appendTailEvent(\n buffer: LogTailBuffer,\n event: LogTailEvent,\n maxRows: number,\n): LogTailBuffer {\n if (buffer.lastSequence !== null && event.sequence <= buffer.lastSequence) return buffer;\n const incoming = event.rows ?? (event.row ? [event.row] : []);\n if (incoming.length === 0) return { ...buffer, lastSequence: event.sequence };\n\n // A batched `rows` frame has no per-item clickyRow equivalent — only the\n // single-`row` shape trace/follow sessions use ever carries one — so a\n // batch pads with `undefined` to stay index-aligned with `rows`.\n const incomingClickyRows: (ClickyRow | undefined)[] = event.rows\n ? event.rows.map(() => undefined)\n : [event.clickyRow];\n\n const { rows, dropped } = appendTailRows(buffer.rows, incoming, { limit: maxRows });\n return {\n rows,\n clickyRows: buffer.clickyRows.concat(incomingClickyRows).slice(dropped),\n lastSequence: event.sequence,\n dropped: buffer.dropped + dropped,\n };\n}\n\nexport interface UseLogTailOptions {\n /** Query profile to follow, e.g. \"k8s-pod-logs\". */\n profile: string;\n /** Profile parameters, sent as the session request's query string. */\n params?: Record<string, unknown> | undefined;\n /** Base path of the session API, e.g. \"/api/v1\". */\n basePath?: string | undefined;\n /** Start/stop is the caller's: flipping this to false closes the stream; the server reaps the unsubscribed session. */\n following?: boolean | undefined;\n /** Rows kept in memory; older ones are evicted and counted in `droppedRows`. */\n maxRows?: number | undefined;\n /**\n * Called once per applied `event` frame, in sequence order, before the frame\n * reaches the buffer — so a reducer sees every row even after `maxRows` starts\n * evicting. A replayed sequence is not delivered again, and `done` frames are\n * never delivered. The latest callback is always used; changing its identity\n * does not restart the session. A throw is reported as a `stream` error.\n */\n onEvent?: ((event: LogTailEvent) => void) | undefined;\n}\n\nexport interface UseLogTailResult {\n /** Accumulated rows, oldest first. */\n rows: Record<string, unknown>[];\n /** Each row's presented ClickyRow, index-aligned with `rows`; `undefined`\n * where the event carried none (a plain log tail, or a top-session\n * snapshot event). */\n clickyRows: (ClickyRow | undefined)[];\n status: LogTailStatus;\n error: LogTailError | null;\n sessionId: string | null;\n /** True while the caller wants rows and the session has not reached a terminal state. */\n following: boolean;\n /** Rows the cap evicted; non-zero means the tail no longer holds the whole run. */\n droppedRows: number;\n /** Highest sequence applied — the resume point a reconnect would ask for. */\n lastSequence: number | null;\n /** Latest SessionInfo the server sent, for eventCount / startedAt / state. */\n session: LogSessionInfo | null;\n}\n\nconst DEFAULT_BASE = \"/api/v1\";\nconst DEFAULT_MAX_ROWS = 5_000;\n\ninterface LogTailSnapshot {\n request: { key: string; basePath: string; profile: string; paramsQuery: string } | null;\n buffer: LogTailBuffer;\n status: LogTailStatus;\n error: LogTailError | null;\n session: LogSessionInfo | null;\n}\n\nconst emptyLogTailSnapshot: LogTailSnapshot = {\n request: null,\n buffer: emptyLogTailBuffer,\n status: \"idle\",\n error: null,\n session: null,\n};\n\nexport function useLogTail(options: UseLogTailOptions): UseLogTailResult {\n const {\n profile,\n params,\n basePath = DEFAULT_BASE,\n following: wantFollow = false,\n maxRows = DEFAULT_MAX_ROWS,\n onEvent,\n } = options;\n\n const [snapshot, setSnapshot] = useState(emptyLogTailSnapshot);\n\n const eventSourceFactory = useEventSourceFactory();\n const streamOptions = useRef({ maxRows, onEvent, eventSourceFactory });\n useEffect(() => {\n streamOptions.current = { maxRows, onEvent, eventSourceFactory };\n }, [maxRows, onEvent, eventSourceFactory]);\n\n // Profile parameters travel in the query string because that is where the\n // session endpoint reads them from: it builds its params by walking\n // r.URL.Query() and never looks at the body, so a posted body is a filter the\n // server silently ignores — the tail would run the profile's defaults while\n // the reader believed they were following what they had filtered to.\n //\n // Serialized here rather than in the effect so it is also the effect's\n // dependency: two renders with equal parameters must not restart the session.\n const paramsQuery = encodeTailParams(params);\n const key = wantFollow ? JSON.stringify([basePath, profile, paramsQuery]) : null;\n const { request, buffer, error, session } = snapshot;\n if (key !== (request?.key ?? null)) {\n setSnapshot(key === null ? { ...snapshot, request: null } : {\n ...emptyLogTailSnapshot,\n request: { key, basePath, profile, paramsQuery },\n status: \"starting\",\n });\n }\n\n useEffect(() => {\n if (!request) return;\n const update = (fields: Partial<Omit<LogTailSnapshot, \"request\">>) => {\n setSnapshot(current => current.request === request ? { ...current, ...fields } : current);\n };\n\n let ended = false;\n // onEvent's own watermark, tracked here rather than read from the buffer:\n // the buffer only dedupes inside a state updater, which React may run twice,\n // so a callback there would double-count. Same rule as appendTailEvent.\n let delivered: number | null = null;\n\n const deliver = (event: LogTailEvent) => {\n if (delivered !== null && event.sequence <= delivered) return;\n delivered = event.sequence;\n try {\n streamOptions.current.onEvent?.(event);\n } catch (cause) {\n update({ error: { scope: \"stream\", message: `onEvent threw on sequence ${event.sequence}: ${String(cause)}` } });\n }\n };\n\n const apply = (event: LogTailEvent) => {\n const { maxRows: limit } = streamOptions.current;\n // An event-level error does not end the session, so it is reported beside\n // the rows rather than in place of them. Set before delivery so a reducer\n // that throws on the same frame is the error left standing.\n if (event.error) update({ error: { scope: \"stream\", message: event.error } });\n deliver(event);\n setSnapshot(current => {\n if (current.request !== request) return current;\n const next = appendTailEvent(current.buffer, event, limit);\n return next === current.buffer ? current : { ...current, buffer: next };\n });\n };\n\n // Unlike the task stream this does not skip what it cannot parse: a tail\n // that silently discards frames is indistinguishable from a quiet log\n // source, which is the one thing a reader must never be left guessing at.\n const readFrame = (label: string, e: MessageEvent): unknown => {\n try {\n return JSON.parse(e.data as string);\n } catch (cause) {\n update({ error: { scope: \"stream\", message: `unparseable ${label} frame: ${String(cause)}` } });\n return undefined;\n }\n };\n\n const settle = (info: LogSessionInfo) => {\n ended = isTerminalSessionState(info.state);\n if (info.state === \"failed\") {\n update({\n session: info,\n status: info.state,\n error: { scope: \"session\", message: info.error || `session ${info.id} failed without reporting a reason` },\n });\n } else {\n update(ended ? { session: info, status: info.state as LogTailStatus } : { session: info });\n }\n };\n\n const subscribe = (info: LogSessionInfo) => {\n update({ session: info, status: \"streaming\" });\n return subscribeJSON<LogTailEvent>(streamOptions.current.eventSourceFactory, `${request.basePath}/sessions/${encodeURIComponent(info.id)}/events`, {\n messageEvent: \"event\",\n endEvent: \"done\",\n onOpen: () => update({ status: \"streaming\" }),\n onData: apply,\n onInvalidMessage: error => update({ error: { scope: \"stream\", message: error.message } }),\n onEnd: event => {\n const info = readFrame(\"done\", event as MessageEvent);\n if (info) settle(info as LogSessionInfo);\n else update({ status: \"failed\" });\n },\n onError: (error, terminal) => {\n if (ended) return;\n update(terminal ? { status: \"failed\", error: { scope: \"stream\", message: error.message } } : { status: \"connection lost — retrying\" });\n },\n });\n };\n\n return openLogTailSession({\n basePath: request.basePath,\n profile: request.profile,\n paramsQuery: request.paramsQuery,\n onStart: subscribe,\n onError: error => update({ status: \"failed\", error }),\n });\n }, [request]);\n\n // Stopping returns the surface to idle, but a session that ended on its own\n // keeps its terminal status so the reason it ended stays on screen.\n const status = request === null && !isTerminalTailStatus(snapshot.status) ? \"idle\" : snapshot.status;\n\n return {\n rows: buffer.rows,\n clickyRows: buffer.clickyRows,\n status,\n error,\n sessionId: session?.id ?? null,\n following: wantFollow && !isTerminalTailStatus(status),\n droppedRows: buffer.dropped,\n lastSequence: buffer.lastSequence,\n session,\n };\n}\n"],"mappings":";;;;;;;;;;;AAwEA,SAAgB,uBAAuB,OAA6C;CAClF,OAAO,UAAU,KAAA,KAAa,kBAAkB,KAAK;AACvD;AAEA,SAAS,qBAAqB,QAAgC;CAC5D,OAAO,eAAe,MAAM,KAAK,kBAAkB,MAAM;AAC3D;AAkBA,IAAa,qBAAoC;CAC/C,MAAM,CAAC;CACP,YAAY,CAAC;CACb,cAAc;CACd,SAAS;AACX;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAiB,QAAqD;CACpF,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,QAAQ,IAAI,gBAAgB;CAClC,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,GAAG;EAC5C,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM;EAC3C,MAAM,OAAO,KAAK,OAAO,KAAK,CAAC;CACjC;CACA,MAAM,UAAU,MAAM,SAAS;CAC/B,OAAO,YAAY,KAAK,KAAK,IAAI;AACnC;;;;;;;;;;;AAYA,SAAgB,gBACd,QACA,OACA,SACe;CACf,IAAI,OAAO,iBAAiB,QAAQ,MAAM,YAAY,OAAO,cAAc,OAAO;CAClF,MAAM,WAAW,MAAM,SAAS,MAAM,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;CAC3D,IAAI,SAAS,WAAW,GAAG,OAAO;EAAE,GAAG;EAAQ,cAAc,MAAM;CAAS;CAK5E,MAAM,qBAAgD,MAAM,OACxD,MAAM,KAAK,UAAU,KAAA,CAAS,IAC9B,CAAC,MAAM,SAAS;CAEpB,MAAM,EAAE,MAAM,YA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E,UAAU;IACjJ,cAAc;IACd,UAAU;IACV,cAAc,OAAO,EAAE,QAAQ,YAAY,CAAC;IAC5C,QAAQ;IACR,mBAAkB,UAAS,OAAO,EAAE,OAAO;KAAE,OAAO;KAAU,SAAS,MAAM;IAAQ,EAAE,CAAC;IACxF,QAAO,UAAS;KACd,MAAM,OAAO,UAAU,QAAQ,KAAqB;KACpD,IAAI,MAAM,OAAO,IAAsB;UAClC,OAAO,EAAE,QAAQ,SAAS,CAAC;IAClC;IACA,UAAU,OAAO,aAAa;KAC5B,IAAI,OAAO;KACX,OAAO,WAAW;MAAE,QAAQ;MAAU,OAAO;OAAE,OAAO;OAAU,SAAS,MAAM;MAAQ;KAAE,IAAI,EAAE,QAAQ,6BAA6B,CAAC;IACvI;GACF,CAAC;EACH;EAEA,OAAO,mBAAmB;GACxB,UAAU,QAAQ;GAClB,SAAS,QAAQ;GACjB,aAAa,QAAQ;GACrB,SAAS;GACT,UAAS,UAAS,OAAO;IAAE,QAAQ;IAAU;GAAM,CAAC;EACtD,CAAC;CACH,GAAG,CAAC,OAAO,CAAC;CAIZ,MAAM,SAAS,YAAY,QAAQ,CAAC,qBAAqB,SAAS,MAAM,IAAI,SAAS,SAAS;CAE9F,OAAO;EACL,MAAM,OAAO;EACb,YAAY,OAAO;EACnB;EACA;EACA,WAAW,SAAS,MAAM;EAC1B,WAAW,cAAc,CAAC,qBAAqB,MAAM;EACrD,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB;CACF;AACF"}
|
package/dist/hooks.cjs
CHANGED
|
@@ -10,6 +10,9 @@ const require_use_history_route = require("./hooks/use-history-route.cjs");
|
|
|
10
10
|
const require_event_source = require("./hooks/event-source.cjs");
|
|
11
11
|
const require_event_source_provider = require("./hooks/event-source-provider.cjs");
|
|
12
12
|
const require_event_hub = require("./hooks/event-hub.cjs");
|
|
13
|
+
const require_event_stream = require("./hooks/event-stream.cjs");
|
|
14
|
+
const require_tail_buffer = require("./hooks/tail-buffer.cjs");
|
|
15
|
+
const require_use_live_snapshot = require("./hooks/use-live-snapshot.cjs");
|
|
13
16
|
const require_use_task_run = require("./hooks/use-task-run.cjs");
|
|
14
17
|
const require_use_prompts = require("./hooks/use-prompts.cjs");
|
|
15
18
|
const require_use_hotkey = require("./hooks/use-hotkey.cjs");
|
|
@@ -21,6 +24,7 @@ exports.EventSourceProvider = require_event_source_provider.EventSourceProvider;
|
|
|
21
24
|
exports.ThemeProvider = require_theme_provider.ThemeProvider;
|
|
22
25
|
exports.answerPrompt = require_use_prompts.answerPrompt;
|
|
23
26
|
exports.appendTailEvent = require_use_log_tail.appendTailEvent;
|
|
27
|
+
exports.appendTailRows = require_tail_buffer.appendTailRows;
|
|
24
28
|
exports.createEventHub = require_event_hub.createEventHub;
|
|
25
29
|
exports.emptyLogTailBuffer = require_use_log_tail.emptyLogTailBuffer;
|
|
26
30
|
exports.encodeTailParams = require_use_log_tail.encodeTailParams;
|
|
@@ -31,12 +35,14 @@ exports.isTerminalSessionState = require_use_log_tail.isTerminalSessionState;
|
|
|
31
35
|
exports.mediaMatches = require_use_media_query.mediaMatches;
|
|
32
36
|
exports.onMediaChange = require_use_media_query.onMediaChange;
|
|
33
37
|
exports.parseHotkey = require_use_hotkey.parseHotkey;
|
|
38
|
+
exports.subscribeJSON = require_event_stream.subscribeJSON;
|
|
34
39
|
exports.useContainerWiderThan = require_use_container_width.useContainerWiderThan;
|
|
35
40
|
exports.useDensity = require_use_density.useDensity;
|
|
36
41
|
exports.useDensityValue = require_use_density.useDensityValue;
|
|
37
42
|
exports.useEventSourceFactory = require_event_source.useEventSourceFactory;
|
|
38
43
|
exports.useHistoryRoute = require_use_history_route.useHistoryRoute;
|
|
39
44
|
exports.useHotkey = require_use_hotkey.useHotkey;
|
|
45
|
+
exports.useLiveSnapshot = require_use_live_snapshot.useLiveSnapshot;
|
|
40
46
|
exports.useLogTail = require_use_log_tail.useLogTail;
|
|
41
47
|
exports.useMediaQuery = require_use_media_query.useMediaQuery;
|
|
42
48
|
exports.useOptionalTheme = require_use_theme.useOptionalTheme;
|
package/dist/hooks.d.ts
CHANGED
|
@@ -9,6 +9,9 @@ export { useHistoryRoute, type UseHistoryRouteOptions } from './hooks/use-histor
|
|
|
9
9
|
export { useEventSourceFactory, type EventSourceFactory, type EventSourceLike, } from './hooks/event-source.js';
|
|
10
10
|
export { EventSourceProvider, type EventSourceProviderProps, } from './hooks/event-source-provider.js';
|
|
11
11
|
export { createEventHub, type EventHubOptions } from './hooks/event-hub.js';
|
|
12
|
+
export { subscribeJSON } from './hooks/event-stream.js';
|
|
13
|
+
export { appendTailRows } from './hooks/tail-buffer.js';
|
|
14
|
+
export { useLiveSnapshot } from './hooks/use-live-snapshot.js';
|
|
12
15
|
export { useTaskRun, useTaskRuns, type UseTaskRunOptions, type UseTaskRunResult, type UseTaskRunsOptions, type UseTaskRunsResult, type TaskTransportOptions, } from './hooks/use-task-run.js';
|
|
13
16
|
export { usePrompts, answerPrompt, type PromptSnapshot, type PromptFilter, type UsePromptsOptions, type UsePromptsResult, } from './hooks/use-prompts.js';
|
|
14
17
|
export { useHotkey, parseHotkey, formatHotkey, type UseHotkeyOptions, type ParsedHotkey, } from './hooks/use-hotkey.js';
|
package/dist/hooks.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,QAAQ,EACR,gBAAgB,EAChB,gBAAgB,EAChB,KAAK,KAAK,EACV,KAAK,aAAa,GACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,KAAK,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EACL,YAAY,EACZ,aAAa,EACb,aAAa,GACd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,KAAK,OAAO,EAAE,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