Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions src/core/react-query/logging/queries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { useEffect } from 'react';
import { HttpTransportType, HubConnectionBuilder, JsonHubProtocol, LogLevel } from '@microsoft/signalr';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';

import { axios } from '@/core/axios';
import queryClient from '@/core/react-query/queryClient';
import { useSelector } from '@/core/store';

import type { LogEventType, LogReadResultType, LogsSearchParamsType } from '@/core/react-query/logging/types';

const logsQueryKey = ['logs'];

const useLogsSubscription = () => {
const apikey = useSelector(state => state.apiSession.apikey);

useEffect(() => {
const connectionLogHub = '/signalr/logging';
const protocol = new JsonHubProtocol();
// oxlint-disable-next-line no-bitwise
const transport = HttpTransportType.WebSockets | HttpTransportType.LongPolling;
const options = {
transport,
logMessageContent: true,
logger: LogLevel.Warning,
accessTokenFactory: () => apikey,
};

const connectionLog = new HubConnectionBuilder().withUrl(connectionLogHub, options).withHubProtocol(protocol)
.withAutomaticReconnect([5000, 15000, 30000, 60000, 90000])
.build();

connectionLog.onreconnected(() => {
// The server re-sends GetBacklog on every connect; reset the tail so the
// fresh backlog replaces the stale one instead of duplicating entries.
queryClient.setQueryData(logsQueryKey, []);
});

connectionLog.on(
'GetBacklog',
(lines: LogEventType[]) => {
queryClient.setQueryData(
logsQueryKey,
(oldData: LogEventType[] | undefined) => (oldData ? [...oldData, ...lines] : lines),
);
},
);

connectionLog.on(
'Log',
(line: LogEventType) => {
queryClient.setQueryData(
logsQueryKey,
(oldData: LogEventType[] | undefined) => (oldData ? [...oldData, line] : [line]),
);
},
);

connectionLog.start().catch(console.error);

return () => {
connectionLog.stop().catch(console.error);
};
}, [apikey]);
};

export const useLogsQuery = () => {
useLogsSubscription();
return useQuery<LogEventType[]>({
queryKey: logsQueryKey,
queryFn: () => [],
initialData: [],
staleTime: Infinity,
gcTime: Infinity,
});
};

export const useLogsSearchQuery = ({ levels, search }: LogsSearchParamsType) => {
// Sets serialize to {} in the query key hash, so derive a stable, content-sensitive string instead.
// Sorted so any chip-toggle order produces the same key.
const levelKey = [...levels].sort().join(',');
return useInfiniteQuery<LogReadResultType>({
queryKey: ['logs', 'search', { search, levels: levelKey }],
queryFn: ({ pageParam }) =>
axios.get('Logging/Range/Read', {
params: {
offset: pageParam,
limit: 100,
descending: false,
// Server expects a comma-separated list of LogLevel names; omitted params are inactive filters.
level: levelKey || undefined,
message: search || undefined,
},
}),
getNextPageParam: lastPage => lastPage.NextOffset ?? undefined,
initialPageParam: 0,
});
};
23 changes: 23 additions & 0 deletions src/core/react-query/logging/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Mirrors Microsoft.Extensions.Logging.LogLevel as serialized by the server (StringEnumConverter).
export type LogLevelType = 'Trace' | 'Debug' | 'Information' | 'Warning' | 'Error' | 'Critical' | 'None';

export type LogEventType = {
TimeStamp: string;
Level: LogLevelType;
ThreadID?: number;
ProcessID?: number;
Logger?: string;
Caller?: string;
Message: string;
Exception?: string;
};

export type LogReadResultType = {
NextOffset: number | null;
Entries: LogEventType[];
};

export type LogsSearchParamsType = {
search: string;
levels: Set<LogLevelType>;
};
72 changes: 0 additions & 72 deletions src/core/react-query/logs/queries.ts

This file was deleted.

6 changes: 0 additions & 6 deletions src/core/types/api/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,6 @@ export type RatingType = {
Type: 'Permanent' | 'Temporary';
};

export type LogLineType = {
TimeStamp: string;
Message: string;
Level: string;
};

export type DataSourceValues =
| 'Plugin'
| 'LocallyGenerated'
Expand Down
18 changes: 18 additions & 0 deletions src/hooks/useVirtualizerScrollRectWorkaround.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { RefObject } from 'react';

import type { Virtualizer } from '@tanstack/react-virtual';

// Workaround for https://github.com/TanStack/virtual/issues/634: the virtualizer can cache a
// stale/zero-sized scrollRect when the scroll container mounts, breaking item measurement.
// Patching it from the live element on every render fixes virtualization in Firefox and Chrome.
const useVirtualizerScrollRectWorkaround = <TScrollElement extends HTMLElement, TItemElement extends Element>(
rowVirtualizer: Virtualizer<TScrollElement, TItemElement>,
parentRef: RefObject<TScrollElement | null>,
) => {
if (parentRef.current) {
// oxlint-disable-next-line no-param-reassign -- mutating the virtualizer instance is the workaround itself
rowVirtualizer.scrollRect = { height: parentRef.current.clientHeight, width: parentRef.current.clientWidth };
}
};

export default useVirtualizerScrollRectWorkaround;
46 changes: 46 additions & 0 deletions src/pages/logs/LogLevelChip.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import cx from 'classnames';

import type { LogLevelType } from '@/core/react-query/logging/types';

const logLevelStyles: Record<LogLevelType, string> = {
Trace: 'bg-panel-text/25 text-panel-text/90',
Debug: 'bg-panel-text-other/15 text-panel-text-other',
Information: 'bg-panel-text-important/15 text-panel-text-important',
Warning: 'bg-panel-text-warning/15 text-panel-text-warning',
Error: 'bg-panel-text-danger/20 text-panel-text-danger',
Critical: 'bg-panel-text-danger text-button-danger-text',
None: 'bg-panel-text/25 text-panel-text/90',
};

const logLevelHoverStyles: Record<LogLevelType, string> = {
Trace: 'hover:bg-panel-text/25 hover:text-panel-text/90',
Debug: 'hover:bg-panel-text-other/15 hover:text-panel-text-other',
Information: 'hover:bg-panel-text-important/15 hover:text-panel-text-important',
Warning: 'hover:bg-panel-text-warning/15 hover:text-panel-text-warning',
Error: 'hover:bg-panel-text-danger/20 hover:text-panel-text-danger',
Critical: 'hover:bg-panel-text-danger hover:text-button-danger-text',
None: 'hover:bg-panel-text/25 hover:text-panel-text/90',
};

type Props = {
level: LogLevelType;
active?: boolean;
};

const LogLevelChip = ({ active = true, level }: Props) => (
<div
className={cx(
'rounded-md px-2 py-0.5 text-xs transition-colors',
active
? logLevelStyles[level]
: cx(
'bg-panel-input/50 text-panel-text/85 ring-1 ring-panel-text/25 ring-inset hover:ring-0',
logLevelHoverStyles[level],
),
)}
>
{level}
</div>
);

export default LogLevelChip;
79 changes: 79 additions & 0 deletions src/pages/logs/LogLiveView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { useEffect, useRef } from 'react';
import { mdiLoading } from '@mdi/js';
import { Icon } from '@mdi/react';
import { useVirtualizer } from '@tanstack/react-virtual';

import useVirtualizerScrollRectWorkaround from '@/hooks/useVirtualizerScrollRectWorkaround';
import LogRow from '@/pages/logs/LogRow';

import type { LogEventType } from '@/core/react-query/logging/types';

type Props = {
logLines: LogEventType[];
scrollToBottom: boolean;
setScrollToBottom: (value: boolean) => void;
};

const LogLiveView = ({ logLines, scrollToBottom, setScrollToBottom }: Props) => {
const parentRef = useRef<HTMLDivElement>(null);
const rowVirtualizer = useVirtualizer({
count: logLines.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 36,
useFlushSync: false,
});
const virtualItems = rowVirtualizer.getVirtualItems();
useVirtualizerScrollRectWorkaround(rowVirtualizer, parentRef);

useEffect(() => {
if (!scrollToBottom || logLines.length === 0) return;
rowVirtualizer.scrollToIndex(logLines.length - 1);
}, [logLines, scrollToBottom, rowVirtualizer]);

// Disables auto scroll when the user scrolls up. While locked, the only way the
// container stops being at the bottom is a user scroll — the programmatic
// scrollToIndex always lands at the bottom, and the virtualizer's measurement
// corrections keep it there.
const handleScroll = () => {
const container = parentRef.current;
if (!scrollToBottom || !container) return;
if (container.scrollHeight - container.scrollTop - container.clientHeight > 1) setScrollToBottom(false);
};

return (
<div
className="w-full overflow-y-auto rounded-lg border-16 border-panel-input bg-panel-input font-mono text-sm contain-strict"
ref={parentRef}
onScroll={handleScroll}
>
{logLines.length === 0 && (
<div className="flex h-full items-center justify-center text-panel-text-primary">
<Icon path={mdiLoading} size={4} spin />
</div>
)}

{logLines.length > 0 && (
<div
className="relative w-full"
style={{ height: rowVirtualizer.getTotalSize() }}
>
<div
className="absolute inset-x-4 top-0"
style={{ transform: `translateY(${virtualItems[0]?.start ?? 0}px)` }}
>
{virtualItems.map(virtualRow => (
<LogRow
key={virtualRow.key}
dataIndex={virtualRow.index}
event={logLines[virtualRow.index]}
measureRef={rowVirtualizer.measureElement}
/>
))}
</div>
</div>
)}
</div>
);
};

export default LogLiveView;
Loading