diff --git a/packages/insomnia-data/src/models/project.ts b/packages/insomnia-data/src/models/project.ts index 122c6bbba20..8356b945c0a 100644 --- a/packages/insomnia-data/src/models/project.ts +++ b/packages/insomnia-data/src/models/project.ts @@ -114,12 +114,28 @@ export interface GitProject extends BaseModel, CommonProject { remoteId: null; } +export interface KonnectProject extends LocalProject { + konnectControlPlaneId: string | null; + konnectClusterType: string | null; + konnectDeploymentType: KonnectDeploymentType | null; + konnectRegion: string | null; + // Latest Kong Debugger session id for this project (control plane) + konnectDebugSessionId?: string | null; +} + export type Project = LocalProject | RemoteProject | GitProject; export const isProject = (model: Pick): model is Project => model.type === type; export const isProjectId = (id: string | null) => id?.startsWith(`${prefix}_`); +export const isKonnectProject = (project: Project): project is KonnectProject => + isProject(project) && + 'konnectControlPlaneId' in project && + 'konnectRegion' in project && + 'konnectClusterType' in project && + 'konnectDeploymentType' in project; + export const optionalKeys: (keyof CommonProject)[] = [ 'konnectControlPlaneId', 'konnectClusterType', diff --git a/packages/insomnia-data/src/models/types.ts b/packages/insomnia-data/src/models/types.ts index 5f85692a692..e872566e474 100644 --- a/packages/insomnia-data/src/models/types.ts +++ b/packages/insomnia-data/src/models/types.ts @@ -81,7 +81,14 @@ export type { ResponseInfo, RunnerResultPerRequestPerIteration, } from './runner-test-result'; -export type { Project, LocalProject, RemoteProject, GitProject, KonnectDeploymentType } from './project'; +export type { + Project, + LocalProject, + RemoteProject, + GitProject, + KonnectProject, + KonnectDeploymentType, +} from './project'; export type { ProjectLintRuleset } from './project-lint-ruleset'; export type { Settings, ThemeSettings } from './settings'; export type { Stats } from './stats'; diff --git a/packages/insomnia/src/konnect/__tests__/debug-trace-helper.test.ts b/packages/insomnia/src/konnect/__tests__/debug-trace-helper.test.ts index b1550316aca..6872f2955b6 100644 --- a/packages/insomnia/src/konnect/__tests__/debug-trace-helper.test.ts +++ b/packages/insomnia/src/konnect/__tests__/debug-trace-helper.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import type { DebugTraceDetail } from '../debug-session-api'; -import { findTraceIdsByRouteId, getRouteIdFromKonnectRouteKey } from '../debug-trace-helper'; +import { getRouteIdFromKonnectRouteKey, type SpanTree, summarizeTrace } from '../debug-trace-helper'; const detail = (traceId: string, attributes: Record[]): DebugTraceDetail => ({ traceId, @@ -30,18 +30,36 @@ describe('getRouteIdFromKonnectRouteKey', () => { }); }); -describe('findTraceIdsByRouteId', () => { - const details = new Map([ - ['t1', detail('t1', [{ 'http.route': '/a' }, { 'proxy.kong.route.id': 'route-1' }])], - ['t2', detail('t2', [{ 'proxy.kong.route.id': 'route-2' }])], - ['t3', detail('t3', [{}])], - ]); +describe('summarizeTrace', () => { + const treeWith = (attributes: Record): SpanTree => ({ + roots: [ + { + span: { ...detail('t1', [attributes]).spans[0] }, + name: 'span', + depth: 0, + startOffsetMs: 0, + durationMs: 1, + children: [], + }, + ], + totalMs: 1, + }); - it('matches traces having a span with the same proxy.kong.route.id', () => { - expect([...findTraceIdsByRouteId(details, 'route-1')]).toEqual(['t1']); + it('reads the route id, method, protocol and url scheme from the latency span', () => { + const summary = summarizeTrace( + treeWith({ + 'proxy.kong.latency.total': 10, + 'proxy.kong.route.id': 'route-1', + 'http.request.method': 'GET', + 'network.protocol.name': 'http', + 'url.scheme': 'https', + }), + ); + expect(summary).toMatchObject({ routeId: 'route-1', method: 'GET', protocol: 'http', urlScheme: 'https' }); }); - it('matches nothing without a route id', () => { - expect(findTraceIdsByRouteId(details, null).size).toBe(0); + it('defaults the route fields to empty strings when absent', () => { + const summary = summarizeTrace(treeWith({ 'proxy.kong.latency.total': 10 })); + expect(summary).toMatchObject({ routeId: '', method: '', protocol: '', urlScheme: '' }); }); }); diff --git a/packages/insomnia/src/konnect/debug-session-api.ts b/packages/insomnia/src/konnect/debug-session-api.ts index 73de0510b07..c66518ddfa6 100644 --- a/packages/insomnia/src/konnect/debug-session-api.ts +++ b/packages/insomnia/src/konnect/debug-session-api.ts @@ -52,11 +52,13 @@ export type DebugErrorKind = 'unauthorized' | 'forbidden' | 'not_found' | 'rate_ export class DebugApiError extends Error { kind: DebugErrorKind; retryAfterMs?: number; - constructor(kind: DebugErrorKind, message: string, retryAfterMs?: number) { + responseText: string; + constructor(kind: DebugErrorKind, message: string, responseText: string, retryAfterMs?: number) { super(message); this.name = 'DebugApiError'; this.kind = kind; this.retryAfterMs = retryAfterMs; + this.responseText = responseText; } } @@ -67,28 +69,29 @@ export async function toDebugApiError(err: unknown): Promise { if (isApiError(err)) { const status = err.response.status; const response = err.response; + const responseText = response.bodyUsed ? err.message || `HTTP ${status}` : await response.text(); if (status === 401) { - return new DebugApiError('unauthorized', 'Personal access token is invalid or expired.'); + return new DebugApiError('unauthorized', 'Personal access token is invalid or expired.', responseText); } if (status === 403) { - return new DebugApiError('forbidden', 'Personal access token lacks permission for the debugger.'); + return new DebugApiError('forbidden', 'Personal access token lacks permission for the debugger.', responseText); } if (status === 404) { - return new DebugApiError('not_found', 'Not found.'); + return new DebugApiError('not_found', 'Not found.', responseText); } if (status === 429) { const retryAfter = Number.parseInt(err.response.headers.get('Retry-After') ?? '', 10); return new DebugApiError( 'rate_limited', 'Konnect rate limit reached.', + responseText, Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : undefined, ); } - const responseText = response.bodyUsed ? err.message || `HTTP ${status}` : await response.text(); - throw new DebugApiError('unknown', `Konnect error: ${responseText}`); + throw new DebugApiError('unknown', `${responseText}`, responseText); } const message = err instanceof Error ? err.message : 'Could not reach Konnect.'; - return new DebugApiError('network', message); + return new DebugApiError('network', message, ''); } async function request( diff --git a/packages/insomnia/src/konnect/debug-session-query.ts b/packages/insomnia/src/konnect/debug-session-query.ts index 6440989477e..2f37df74e51 100644 --- a/packages/insomnia/src/konnect/debug-session-query.ts +++ b/packages/insomnia/src/konnect/debug-session-query.ts @@ -194,7 +194,7 @@ export async function startOrAdoptDebugSession( ): Promise { const nodeIds = await listNodeIds(ctx); if (nodeIds.length === 0) { - throw new DebugApiError('unknown', 'No data plane nodes are connected to this control plane.'); + throw new DebugApiError('unknown', 'No data plane nodes are connected to this control plane.', ''); } return createDebugSession(ctx, durationSecs, nodeIds); } diff --git a/packages/insomnia/src/konnect/debug-trace-helper.ts b/packages/insomnia/src/konnect/debug-trace-helper.ts index 942288f3abb..5e529fc2cff 100644 --- a/packages/insomnia/src/konnect/debug-trace-helper.ts +++ b/packages/insomnia/src/konnect/debug-trace-helper.ts @@ -1,6 +1,19 @@ import type { DebugSession, DebugSpan, DebugTraceDetail, DebugTraceSummary } from './debug-session-api'; export type DebugSessionState = 'active' | 'cancelled' | 'completed' | 'completing' | 'timed_out'; +// Attribute names used in debug traces +export const TRACE_ATTRIBUTE_NAMES = { + HTTP_REQUEST_METHOD: 'http.request.method', + URL_FULL: 'url.full', + HTTP_ROUTE: 'http.route', + HTTP_RESPONSE_STATUS_CODE: 'http.response.status_code', + HTTP_REQUEST_SIZE: 'http.request.size', + HTTP_RESPONSE_SIZE: 'http.response.size', + PROTOCOL: 'network.protocol.name', + ROUTE_ID: 'proxy.kong.route.id', + URL_SCHEME: 'url.scheme', +}; + // Derive the state of a debug session from its response export function deriveSessionState(session: DebugSession): DebugSessionState { if (session.stoppedAt) { @@ -59,7 +72,7 @@ export interface SpanTree { const NANOS_PER_MS = 1_000_000n; // Span timestamps are unix nanoseconds as strings: too large for a JS number to hold exactly. -function toBigInt(value: string): bigint { +export function toBigInt(value: string): bigint { try { return BigInt(value); } catch { @@ -110,7 +123,6 @@ export function buildSpanTree(detail: DebugTraceDetail): SpanTree { } } - // Depth, owner and self time depend on the parent, so fill them in top-down once the tree is linked. const finalize = (node: SpanNode, depth: number) => { node.depth = depth; node.children.sort((a, b) => a.startOffsetMs - b.startOffsetMs); @@ -123,7 +135,7 @@ export function buildSpanTree(detail: DebugTraceDetail): SpanTree { return { roots, totalMs }; } -/** Depth-first rows for the waterfall, skipping the children of collapsed spans. */ +// Depth-first rows for the waterfall, skipping the children of collapsed spans. export function flattenVisible(roots: SpanNode[], collapsed: ReadonlySet): SpanNode[] { const result: SpanNode[] = []; const visit = (node: SpanNode) => { @@ -137,6 +149,10 @@ export function flattenVisible(roots: SpanNode[], collapsed: ReadonlySet } export interface TraceSummaryBreakdown { + routeId: string; + protocol: string; + method: string; + urlScheme: string; totalMs: number; kongMs: number; upstreamMs: number; @@ -145,6 +161,8 @@ export interface TraceSummaryBreakdown { kongPct: number; upstreamPct: number; clientPct: number; + requestSize: number; + responseSize: number; thirdPartyPct: number; } @@ -155,6 +173,7 @@ const LATENCY_ATTRIBUTES = { upstream: 'proxy.kong.latency.upstream', client: 'proxy.kong.latency.client', thirdParty: 'proxy.kong.latency.3p.total_io', + protocol: 'network.protocol.name', }; // Some numeric attributes come back as strings (e.g. `proxy.kong.http.response.body.size`). @@ -189,6 +208,12 @@ export function summarizeTrace(tree: SpanTree): TraceSummaryBreakdown | null { const thirdPartyMs = readMs(span.attributes, LATENCY_ATTRIBUTES.thirdParty) ?? 0; const sum = kongMs + upstreamMs + clientMs + thirdPartyMs; const pct = (value: number) => (sum > 0 ? (value / sum) * 100 : 0); + const requestSize = span.attributes[TRACE_ATTRIBUTE_NAMES.HTTP_REQUEST_SIZE] || 0; + const responseSize = span.attributes[TRACE_ATTRIBUTE_NAMES.HTTP_RESPONSE_SIZE] || 0; + const protocol = span.attributes[TRACE_ATTRIBUTE_NAMES.PROTOCOL] || ''; + const method = span.attributes[TRACE_ATTRIBUTE_NAMES.HTTP_REQUEST_METHOD] || ''; + const routeId = span.attributes[TRACE_ATTRIBUTE_NAMES.ROUTE_ID] || ''; + const urlScheme = span.attributes[TRACE_ATTRIBUTE_NAMES.URL_SCHEME] || ''; return { totalMs: readMs(span.attributes, LATENCY_ATTRIBUTES.total) ?? tree.totalMs, kongMs, @@ -199,6 +224,12 @@ export function summarizeTrace(tree: SpanTree): TraceSummaryBreakdown | null { upstreamPct: pct(upstreamMs), clientPct: pct(clientMs), thirdPartyPct: pct(thirdPartyMs), + requestSize, + responseSize, + protocol, + method, + routeId, + urlScheme, }; } @@ -219,8 +250,6 @@ export function getTracePath(trace: Pick): s return trace.route ? normalizePath(trace.route) : null; } -const ROUTE_ID_ATTRIBUTE = 'proxy.kong.route.id'; - // konnectRouteKey is `${route.id}:${method}:${pathSegment}:${protocol}` export function getRouteIdFromKonnectRouteKey(konnectRouteKey: string | null | undefined): string | null { if (!konnectRouteKey) { @@ -230,16 +259,28 @@ export function getRouteIdFromKonnectRouteKey(konnectRouteKey: string | null | u return routeId; } -/** Ids of the traces having a span served by the Kong route `routeId`. */ -export function findTraceIdsByRouteId(details: Map, routeId: string | null): Set { - const matching = new Set(); - if (!routeId) { - return matching; - } - for (const [traceId, detail] of details) { - if (detail.spans.some(span => span.attributes[ROUTE_ID_ATTRIBUTE] === routeId)) { - matching.add(traceId); +interface ParsedKonnectError { + title?: string; + detail?: string; + traceId?: string; + raw: string; +} + +// Parse Konnect JSON error message +export const parseKonnectError = (message: string): ParsedKonnectError | null => { + try { + const json = JSON.parse(message); + if (!json || typeof json !== 'object' || Array.isArray(json)) { + return null; + } + const title = typeof json.title === 'string' ? json.title : ''; + const detail = typeof json.detail === 'string' ? json.detail : ''; + if (!title && !detail) { + return null; } + const instance = typeof json.instance === 'string' ? json.instance : undefined; + return { title, detail, traceId: instance, raw: JSON.stringify(json, null, 2) }; + } catch { + return null; } - return matching; -} +}; diff --git a/packages/insomnia/src/konnect/links.ts b/packages/insomnia/src/konnect/links.ts index 97128b29f17..024f7fe0ff7 100644 --- a/packages/insomnia/src/konnect/links.ts +++ b/packages/insomnia/src/konnect/links.ts @@ -3,6 +3,7 @@ import { getKongDocsOrigin, getKonnectCloudOrigin } from '../common/constants'; export const getPluginHubUrl = () => `${getKongDocsOrigin()}/plugins/`; export const getPluginPriorityDocsUrl = () => `${getKongDocsOrigin()}/gateway/entities/plugin/#plugin-priority`; export const getDeckApplyDocsUrl = () => `${getKongDocsOrigin()}/deck/gateway/apply/`; +export const getDebugSessionsUrl = () => `${getKongDocsOrigin()}/observability/debugger/`; const encodePathSegment = (value: string) => encodeURIComponent(value); diff --git a/packages/insomnia/src/konnect/route-request-lookup.ts b/packages/insomnia/src/konnect/route-request-lookup.ts new file mode 100644 index 00000000000..6171dca9f0b --- /dev/null +++ b/packages/insomnia/src/konnect/route-request-lookup.ts @@ -0,0 +1,57 @@ +import type { GrpcRequest, Request, WebSocketRequest, Workspace, WorkspaceChildrenForScope } from 'insomnia-data'; +import { models } from 'insomnia-data'; + +import { getRouteIdFromKonnectRouteKey, type TraceSummaryBreakdown } from './debug-trace-helper'; + +export interface KonnectRouteRequest { + request: Request | WebSocketRequest | GrpcRequest; + workspaceId: string; + workspaceName: string; + routeId: string; + /** Method and protocol segments of the konnectRouteKey. */ + method: string; + protocol: string; +} + +// Local requests of the given workspaces that were synced from a Konnect route. +export function listKonnectRouteRequests( + workspaces: Pick[], + childrenByWorkspaceId: ReadonlyMap>, +): KonnectRouteRequest[] { + return workspaces.flatMap(workspace => + (childrenByWorkspaceId.get(workspace._id)?.data.requestsAndGroups ?? []).flatMap(doc => { + if ( + !models.request.isRequest(doc) && + !models.webSocketRequest.isWebSocketRequest(doc) && + !models.grpcRequest.isGrpcRequest(doc) + ) { + return []; + } + const routeId = getRouteIdFromKonnectRouteKey(doc.konnectRouteKey); + if (!routeId) { + return []; + } + // konnectRouteKey is `${route.id}:${method}:${pathSegment}:${protocol}`; the path may contain ':'. + const segments = doc.konnectRouteKey!.split(':'); + const method = (segments[1] ?? '').toUpperCase(); + const protocol = (segments.at(-1) ?? '').toUpperCase(); + return [{ request: doc, workspaceId: workspace._id, workspaceName: workspace.name, routeId, method, protocol }]; + }), + ); +} + +// Picks the local request for a trace: same Kong route, and the same HTTP method and protocol as the trace. +export function findRouteRequestForTrace( + routeRequests: KonnectRouteRequest[], + trace: Pick, +): KonnectRouteRequest | null { + const method = trace.method?.toUpperCase(); + return ( + routeRequests.find( + candidate => + trace.routeId === candidate.routeId && + candidate.method.toUpperCase() === method && + candidate.protocol.toUpperCase() === trace.urlScheme?.toUpperCase(), + ) ?? null + ); +} diff --git a/packages/insomnia/src/routes/organization.$organizationId.project.$projectId.konnect-debugger.tsx b/packages/insomnia/src/routes/organization.$organizationId.project.$projectId.konnect-debugger.tsx new file mode 100644 index 00000000000..097fea86f91 --- /dev/null +++ b/packages/insomnia/src/routes/organization.$organizationId.project.$projectId.konnect-debugger.tsx @@ -0,0 +1,39 @@ +import { models, services } from 'insomnia-data'; +import { href, redirect } from 'react-router'; + +import { ErrorBoundary } from '~/ui/components/error-boundary'; +import { KonnectDebuggerPane } from '~/ui/components/panes/konnect-debugger-pane'; +import { OrganizationTabList } from '~/ui/components/tabs/tab-list'; + +import type { Route } from './+types/organization.$organizationId.project.$projectId.konnect-debugger'; + +export async function clientLoader({ params }: Route.ClientLoaderArgs) { + const { organizationId, projectId } = params; + const project = await services.project.getById(projectId); + + if (!project) { + throw redirect(href('/organization/:organizationId', { organizationId })); + } + + // Redirect to the project page if the project is not connected to a Konnect control plane or region. + if (!models.project.isKonnectProject(project)) { + throw redirect(href('/organization/:organizationId/project/:projectId', { organizationId, projectId })); + } + + return { project }; +} + +const Component = ({ loaderData }: Route.ComponentProps) => { + return ( + +
+ +
+ +
+
+
+ ); +}; + +export default Component; diff --git a/packages/insomnia/src/ui/components/dropdowns/sidebar-project-dropdown.tsx b/packages/insomnia/src/ui/components/dropdowns/sidebar-project-dropdown.tsx index aa56b8d1fb2..acd799c85c5 100644 --- a/packages/insomnia/src/ui/components/dropdowns/sidebar-project-dropdown.tsx +++ b/packages/insomnia/src/ui/components/dropdowns/sidebar-project-dropdown.tsx @@ -26,6 +26,7 @@ import { AnalyticsEvent } from '~/ui/analytics'; import { ImportModal } from '~/ui/components/modals/import-modal/import-modal'; import { NewWorkspaceModal } from '~/ui/components/modals/new-workspace-modal'; import { exportProjectToFile } from '~/ui/components/settings/import-export'; +import { useOpenKonnectDebuggerTab } from '~/ui/hooks/use-insomnia-tab'; import { Icon } from '../icon'; import { ProjectModal } from '../modals/project-modal'; @@ -84,6 +85,8 @@ export const ProjectDropdown: FC = ({ }); const { workspaceId } = useParams() as { workspaceId?: string }; const [importModalType, setImportModalType] = useState<'file' | 'clipboard' | 'uri' | null>(null); + const openKonnectDebuggerTab = useOpenKonnectDebuggerTab(); + const isKonnectProject = models.project.isKonnectProject(project); const isRemoteProjectInconsistent = models.project.isRemoteProject(project) && !storageRules.enableCloudSync; const isLocalProjectInconsistent = @@ -156,6 +159,16 @@ export const ProjectDropdown: FC = ({ icon: 'trash', action: onDelete, }, + ...(isKonnectProject + ? [ + { + id: 'debugger', + name: 'Start Debugging', + icon: 'bug' as IconProp, + action: () => openKonnectDebuggerTab(organizationId, project._id), + }, + ] + : []), ]; const createInProjectActionList: ProjectActionItem[] = createWorkspaceActionItems({ diff --git a/packages/insomnia/src/ui/components/modals/konnect-settings-modal.tsx b/packages/insomnia/src/ui/components/modals/konnect-settings-modal.tsx index cd761ea4318..4f4931965f3 100644 --- a/packages/insomnia/src/ui/components/modals/konnect-settings-modal.tsx +++ b/packages/insomnia/src/ui/components/modals/konnect-settings-modal.tsx @@ -5,7 +5,7 @@ import { Button, Dialog, Form, Heading, Modal, ModalOverlay } from 'react-aria-c import { database } from '~/common/database'; import { fetchKonnectOrganizationId, validatePat } from '~/konnect/api'; import { AnalyticsEvent } from '~/ui/analytics'; -import uiEventBus, { KONNECT_SYNC_TRIGGER } from '~/ui/event-bus'; +import uiEventBus, { KONNECT_PAT_CHANGE, KONNECT_SYNC_TRIGGER } from '~/ui/event-bus'; import { useRootLoaderData } from '~/ui/hooks/use-root-loader-data'; import { useSettingsPatcher } from '../../hooks/use-request'; @@ -15,6 +15,7 @@ export const KonnectSettingsModal = ({ onClose, onDisconnect, konnectSyncEnabled = true, + onlyUpdateKonnectPat = false, }: { onClose: () => void; onDisconnect?: () => void; @@ -22,6 +23,8 @@ export const KonnectSettingsModal = ({ * when false, mirroring the sidebar's Sync button — connecting a PAT here would validate and * store it but syncing still could not run. */ konnectSyncEnabled?: boolean; + // Whether the modal is only for updating the Konnect PAT, without affecting sync settings. + onlyUpdateKonnectPat?: boolean; }) => { const { settings } = useRootLoaderData()!; const patchSettings = useSettingsPatcher(); @@ -79,9 +82,12 @@ export const KonnectSettingsModal = ({ return; } await window.main.secretStorage.setSecret('konnectPat', trimmed); + uiEventBus.emit(KONNECT_PAT_CHANGE, trimmed); setConnectedPat(trimmed); patchSettings({ hasKonnectPat: true, konnectOrganizationId: orgId ?? null }); - uiEventBus.emit(KONNECT_SYNC_TRIGGER, orgId ?? null); + if (!onlyUpdateKonnectPat) { + uiEventBus.emit(KONNECT_SYNC_TRIGGER, orgId ?? null); + } onClose(); }; @@ -233,7 +239,13 @@ export const KonnectSettingsModal = ({ className="rounded-xs border border-solid border-(--hl-sm) px-3 py-1.5 text-sm text-(--color-font) hover:bg-(--hl-xs) disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50" isDisabled={!pat.trim() || status === 'validating' || isPatUnchanged || !konnectSyncEnabled} > - {status === 'validating' ? : 'Connect & Sync'} + {status === 'validating' ? ( + + ) : onlyUpdateKonnectPat ? ( + 'Update PAT' + ) : ( + 'Connect & Sync' + )} {hasStoredPat && ( + + )} + + {isCapturing && ( + <> + + {hasSession && isActive && `Capturing... ${capturedSecs}s/${debugSession.durationSecs}s`} + {hasSession && isCompleting && 'Wrapping up —— waiting for Konnect to finish the session'} + + + + )} + + + + + {showEmptyState ? ( +
+ {isLoadingDebugSession + ? 'Loading data for existing debugger session…' + : 'Start a debugger session to observe live traffic on this control plane.'} +
+ ) : ( +
+ +
+ {selectedTrace ? ( + + ) : ( +
+ {isActive && traces.length === 0 && ( + <> +
Waiting for the first request...
+
+ Send any request against this control plane now —— results may take a few seconds to appear. +
+ + )} + {traces.length > 0 && 'Select a trace from the list to view its details.'} + {!isActive && traces.length === 0 && 'No traces captured.'} +
+ )} +
+
+ )} + + ); +}; + +const MutationErrorMessage = ({ error }: { error: DebugApiError }) => { + const { responseText, message } = error; + const parsed = useMemo(() => parseKonnectError(responseText), [responseText]); + const [expanded, setExpanded] = useState(false); + + if (!parsed) { + return `Konnect error: ${message}`; + } + + return ( +
+ {parsed.title &&

{parsed.title}

} +

{parsed.detail}

+ + {expanded && ( +
+          {parsed.raw}
+        
+ )} +
+ ); +}; + +const RetryButton = ({ onPress }: { onPress: () => void }) => ( + +); + +const StatusBanner = ({ + type, + children, + action, +}: { + type: 'info' | 'warning' | 'error'; + children: ReactNode; + action?: ReactNode; +}) => ( +
+ + {children} + {action} +
+); + +const StatusBanners = ({ + debug, + onRetry, +}: { + debug: ReturnType; + onRetry: () => void; +}) => { + const { debugSession, debugSessionState, debugSessionAction, hasKonnectPat, authError, mutationError } = debug; + const startedAtText = formatStartedAt(debugSession?.startedAt ?? null); + const [isKonnectSettingsModalOpen, setIsKonnectSettingsModalOpen] = useState(false); + const konnectSyncEnabled = useKonnectSyncEnabled(); + + if (!hasKonnectPat) { + return ( + + No Konnect token found. Connect one from the Konnect sync bar in the sidebar. + + ); + } + + if (authError) { + return ( + setIsKonnectSettingsModalOpen(true)} + > + Configure + + } + > + + {isKonnectSettingsModalOpen && ( + setIsKonnectSettingsModalOpen(false)} + konnectSyncEnabled={konnectSyncEnabled} + onlyUpdateKonnectPat + /> + )} + + ); + } + + if (mutationError) { + return ( + }> + + + ); + } + + if (debugSessionAction === 'starting') { + return Starting debug session…; + } + return ( + <> + {debugSessionState === 'active' && ( + + {startedAtText ? ( + <> + Session started {startedAtText} + + ) : ( + 'Debugger session is in progress' + )} + + )} + + {debug.sessionDeleted && ( + Current debug session was deleted in Konnect. + )} + {debugSessionState === 'completing' && Wait for the session to complete.} + {debugSessionState === 'cancelled' && ( + + {debug.isRefreshingTraces ? 'Refreshing…' : 'Refresh traces'} + + } + > + Session cancelled. Traces captured before cancelling may still arrive. + + )} + {debugSessionState === 'completed' && Session completed.} + + ); +}; + +const TraceList = ({ + traces, + selectedId, + onSelect, + isActive, +}: { + traces: DebugTraceSummary[]; + selectedId: string | null; + onSelect: (id: string) => void; + isActive: boolean; +}) => ( +
+
+
Captured ({traces.length})
+
Whole control plane and results may take a few seconds to appear.
+
+ {traces.length === 0 && isActive &&
Listening for traffic…
} + {traces.map(trace => { + const isSelected = trace.traceId === selectedId; + const upperTraceMethod = (trace.method || '').toUpperCase(); + return ( +
+ + + + +
+ ); + })} +
+); + +const MetadataPane = ({ + projectName, + controlPlaneId, + region, + debugSessionId, +}: { + projectName: string; + controlPlaneId: string | null; + region: string | null; + debugSessionId: string | null; +}) => { + const items: { label: string; value?: string | null; allowCopy?: boolean; copyValue?: string | null }[] = [ + { label: 'Control Plane', value: projectName, copyValue: controlPlaneId, allowCopy: true }, + { label: 'Region', value: region?.toLocaleUpperCase() }, + { label: 'Session ID', value: debugSessionId, allowCopy: true }, + ].filter(item => !!item.value); + + return ( +
+ {items.map(({ label, value, allowCopy = false, copyValue }) => ( +
+
{label}
+
{value}
+ {allowCopy && ( + + + + )} +
+ ))} +
+ ); +}; + +const summaryParts = (summary: TraceSummaryBreakdown) => + [ + { part: 'kong', ms: summary.kongMs, pct: summary.kongPct }, + { part: 'upstream', ms: summary.upstreamMs, pct: summary.upstreamPct }, + { part: 'client', ms: summary.clientMs, pct: summary.clientPct }, + { part: 'third_party', ms: summary.thirdPartyMs, pct: summary.thirdPartyPct }, + ] as const; + +const TraceDetail = ({ + trace, + ctx, + sessionId, + routeRequests, + onOpenRequest, +}: { + trace: DebugTraceSummary; + ctx: DebugSessionApiContext; + sessionId: string; + routeRequests: KonnectRouteRequest[]; + onOpenRequest: (routeRequest: KonnectRouteRequest) => void; +}) => { + const { detail, errorKind, refetch: onRetry } = useKonnectDebuggerSessionTrace(ctx, sessionId, trace.traceId); + const tree = useMemo(() => (detail ? buildSpanTree(detail) : null), [detail]); + const summary = useMemo(() => (tree ? summarizeTrace(tree) : null), [tree]); + const routeRequest = useMemo( + () => (summary ? findRouteRequestForTrace(routeRequests, summary) : null), + [summary, routeRequests], + ); + const [collapsed, setCollapsed] = useState>(new Set()); + const [expandedAttrs, setExpandedAttrs] = useState>(new Set()); + + const toggle = (set: ReadonlySet, id: string) => { + const next = new Set(set); + if (next.has(id)) { + next.delete(id); + } else { + next.add(id); + } + return next; + }; + + return ( +
+
+ {trace.statusCode !== null && } + + + {routeRequest && ( + + )} +
+ + {errorKind ? ( +
+ + + {errorKind === 'not_found' ? 'This trace is no longer available.' : 'Could not load this trace.'} + + {errorKind !== 'not_found' && } +
+ ) : !tree ? ( +
Loading trace…
+ ) : tree.roots.length === 0 ? ( +
This trace has no spans.
+ ) : ( + <> + {summary && ( + <> +
+ {summaryParts(summary).map(({ part, pct }) => ( +
+ ))} +
+
+ {summaryParts(summary).map(({ part, ms, pct }) => ( +
+ + {PART_LABEL[part]} + {formatSummaryMs(ms)} + ({pct.toFixed(2)}%) +
+ ))} +
+ + )} + +
+ {flattenVisible(tree.roots, collapsed).map(node => ( + setCollapsed(current => toggle(current, node.span.spanId))} + onToggleAttrs={() => setExpandedAttrs(current => toggle(current, node.span.spanId))} + /> + ))} +
+ + )} +
+ ); +}; + +const SpanRow = ({ + node, + totalMs, + isCollapsed, + isAttrsOpen, + onToggleChildren, + onToggleAttrs, +}: { + node: SpanNode; + totalMs: number; + isCollapsed: boolean; + isAttrsOpen: boolean; + onToggleChildren: () => void; + onToggleAttrs: () => void; +}) => { + const attributes = Object.entries(node.span.attributes); + const nameRef = useRef(null); + const left = totalMs > 0 ? (node.startOffsetMs / totalMs) * 100 : 0; + const width = totalMs > 0 ? Math.max((node.durationMs / totalMs) * 100, 0.4) : 0; + return ( +
+
+
+ {node.children.length > 0 ? ( + + ) : ( + + )} + { + const el = nameRef.current; + return !!el && el.scrollWidth > el.clientWidth; + }} + > + + +
+
+
+
+ {formatMs(node.durationMs)} +
+ {isAttrsOpen && attributes.length > 0 && ( +
+ {attributes.map(([key, value]) => ( +
+ {key} + + {typeof value === 'string' ? value : JSON.stringify(value)} + +
+ ))} +
+ )} +
+ ); +}; diff --git a/packages/insomnia/src/ui/components/panes/response-pane.tsx b/packages/insomnia/src/ui/components/panes/response-pane.tsx index 83c749abc25..f5015f9555f 100644 --- a/packages/insomnia/src/ui/components/panes/response-pane.tsx +++ b/packages/insomnia/src/ui/components/panes/response-pane.tsx @@ -2,11 +2,13 @@ import type { ResponseTimelineEntry } from 'insomnia-data'; import { services } from 'insomnia-data'; import { PREVIEW_MODE_SOURCE } from 'insomnia-data/common'; import { type FC, useCallback, useEffect, useMemo, useState } from 'react'; -import { Tab, TabList, TabPanel, Tabs, Toolbar } from 'react-aria-components'; -import { useFetcher } from 'react-router'; +import { Button, Tab, TabList, TabPanel, Tabs, Toolbar } from 'react-aria-components'; +import { useFetcher, useParams } from 'react-router'; import { bodyBufferToUtf8 } from '~/common/utils/utf8-bytes'; import { AnalyticsEvent } from '~/ui/analytics'; +import { KongLogo } from '~/ui/components/kong-logo'; +import { useOpenKonnectDebuggerTab } from '~/ui/hooks/use-insomnia-tab'; import { useRootLoaderData } from '~/ui/hooks/use-root-loader-data'; import { getSetCookieHeaders } from '../../../common/misc'; @@ -41,13 +43,19 @@ interface Props { } export const ResponsePane: FC = ({ activeRequestId }) => { + const { organizationId, projectId } = useParams() as { + organizationId: string; + projectId: string; + }; const { activeRequest, activeRequestMeta, activeResponse, responses, requestVersions } = useRequestLoaderData() as RequestLoaderData; const filterHistory = activeRequestMeta.responseFilterHistory || []; const filter = activeRequestMeta.responseFilter || ''; const patchRequestMeta = useRequestMetaPatcher(); const { settings } = useRootLoaderData()!; + const openKonnectDebuggerTab = useOpenKonnectDebuggerTab(); const previewMode = activeRequestMeta.previewMode || PREVIEW_MODE_SOURCE; + const isKonnectRequest = 'konnectRouteKey' in activeRequest && !!activeRequest.konnectRouteKey; const handleSetFilter = async (responseFilter: string) => { if (!activeResponse) { return; @@ -155,6 +163,15 @@ export const ResponsePane: FC = ({ activeRequestId }) => { + {isKonnectRequest && ( + + )}
; } + if (type === 'konnectDebugger') { + return ; + } + if (type === 'testSuite') { return ; } @@ -151,7 +156,11 @@ export const InsomniaTab = ({ tab, fileIssue }: { tab: BaseTab; fileIssue?: Work ref={scrollIntoView} > {({ isSelected, isHovered }) => ( - +
handleAuxClick(e, tab.id)} diff --git a/packages/insomnia/src/ui/components/tags/size-tag.tsx b/packages/insomnia/src/ui/components/tags/size-tag.tsx index 64a2f4a0f8e..b5483e6a242 100644 --- a/packages/insomnia/src/ui/components/tags/size-tag.tsx +++ b/packages/insomnia/src/ui/components/tags/size-tag.tsx @@ -10,44 +10,46 @@ interface Props { small?: boolean; className?: string; tooltipDelay?: number; + showTooltip?: boolean; } -export const SizeTag: FC = memo(({ bytesRead, bytesContent, small, className, tooltipDelay }) => { - const responseSizeReadStringShort = misc.describeByteSize(bytesRead); - const responseSizeReadString = misc.describeByteSize(bytesRead, true); - const responseSizeRawString = misc.describeByteSize(bytesContent, true); - const message = ( - - - - - - - {bytesContent >= 0 && ( +export const SizeTag: FC = memo( + ({ bytesRead, bytesContent, small, className, tooltipDelay, showTooltip = true }) => { + const responseSizeReadStringShort = misc.describeByteSize(bytesRead); + const responseSizeReadString = misc.describeByteSize(bytesRead, true); + const responseSizeRawString = misc.describeByteSize(bytesContent, true); + const message = ( +
Read{responseSizeReadString}
+ - - + + + {bytesContent >= 0 && ( + + + + + )} + +
Content{responseSizeRawString}Read{responseSizeReadString}
Content{responseSizeRawString}
+ ); + return ( +
- - ); - return ( -
- - {responseSizeReadStringShort} - -
- ); -}); + > + + {responseSizeReadStringShort} + +
+ ); + }, +); SizeTag.displayName = 'SizeTag'; diff --git a/packages/insomnia/src/ui/context/app/insomnia-tab-context.tsx b/packages/insomnia/src/ui/context/app/insomnia-tab-context.tsx index 5c18c2e5a8d..8dcb12321eb 100644 --- a/packages/insomnia/src/ui/context/app/insomnia-tab-context.tsx +++ b/packages/insomnia/src/ui/context/app/insomnia-tab-context.tsx @@ -14,6 +14,7 @@ export type TabType = | 'document' | 'collection' | 'runner' + | 'konnectDebugger' | 'test' | 'testSuite'; export interface BaseTab { diff --git a/packages/insomnia/src/ui/hooks/use-insomnia-navigation.ts b/packages/insomnia/src/ui/hooks/use-insomnia-navigation.ts index 9c445030c14..10b31d3da57 100644 --- a/packages/insomnia/src/ui/hooks/use-insomnia-navigation.ts +++ b/packages/insomnia/src/ui/hooks/use-insomnia-navigation.ts @@ -102,6 +102,12 @@ const NAVIGATION_ROUTES = [ getResourceId: params => params.workspaceId, getResource: (resourceId: string) => services.workspace.getById(resourceId), }, + { + id: 'project:konnect-debugger', + path: '/organization/:organizationId/project/:projectId/konnect-debugger', + getResourceId: params => params.projectId, + getResource: (resourceId: string) => services.project.getById(resourceId), + }, { id: 'project', path: '/organization/:organizationId/project/:projectId', diff --git a/packages/insomnia/src/ui/hooks/use-insomnia-tab.ts b/packages/insomnia/src/ui/hooks/use-insomnia-tab.ts index af979a31668..9cbe8f2638e 100644 --- a/packages/insomnia/src/ui/hooks/use-insomnia-tab.ts +++ b/packages/insomnia/src/ui/hooks/use-insomnia-tab.ts @@ -112,6 +112,34 @@ const buildRunnerTab = ({ }; }; +export const buildKonnectDebuggerTabId = (projectId: string) => `konnect_debugger_${projectId}`; + +// The Konnect debugger tab belongs to a project (one global debug session per project), not to a workspace +const buildKonnectDebuggerTab = async ({ + organizationId, + projectId, +}: { + organizationId: string; + projectId: string; +}): Promise => { + const project = await services.project.getById(projectId); + if (!project) { + throw new Error(`Project not found: ${projectId}`); + } + + return { + type: 'konnectDebugger', + id: buildKonnectDebuggerTabId(project._id), + name: 'Debugger', + url: `/organization/${organizationId}/project/${project._id}/konnect-debugger`, + organizationId, + projectId: project._id, + workspaceId: '', + projectName: project.name, + workspaceName: '', + }; +}; + const buildTabUrlFromResource = ({ resource, organizationId, @@ -211,6 +239,12 @@ const buildTabFromNavigation = async ( ): Promise => { const { project, workspace, resource } = await getNavigationResources(); + if (routeInfo.routeId === 'project:konnect-debugger') { + return project + ? await buildKonnectDebuggerTab({ organizationId: routeInfo.organizationId, projectId: project._id }) + : null; + } + if (!project || !workspace || !resource || models.project.isProject(resource)) { return null; } @@ -237,6 +271,10 @@ const buildTabFromNavigation = async ( }; const getNavigationTabId = async (routeInfo?: InsomniaNavigationRouteInfo | null) => { + if (routeInfo?.routeId === 'project:konnect-debugger' && routeInfo.projectId) { + return buildKonnectDebuggerTabId(routeInfo.projectId); + } + if (!routeInfo || !routeInfo.workspaceId || !routeInfo.resourceId) { return null; } @@ -311,6 +349,19 @@ export const useTabNavigate = () => { return tabNavigate; }; +export const useOpenKonnectDebuggerTab = () => { + const navigate = useNavigate(); + const { addTab } = useInsomniaTabContext(); + return useCallback( + async (organizationId: string, projectId: string) => { + const tab = await buildKonnectDebuggerTab({ organizationId, projectId }); + addTab(tab); + navigate(tab.url); + }, + [addTab, navigate], + ); +}; + export const useInsomniaTab = ({ organizationId }: InsomniaTabProps) => { const { appTabsRef, changeActiveTab, closeTabById, addTemporaryTab } = useInsomniaTabContext(); const { routeInfo, getNavigationResources } = useInsomniaNavigation(); diff --git a/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts b/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts index 337cc0fc65b..d70faecf754 100644 --- a/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts +++ b/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts @@ -65,7 +65,6 @@ export function useKonnectDebuggerSession({ ); const [sessionId, setSessionId] = useState(konnectDebugSessionId || null); - // const [isDebugSessionMissing, setDebugSessionMissing] = useState(false); const [now, setNow] = useState(() => Date.now()); // Adopt a debug session by updating the query cache, local state, and project data. @@ -105,7 +104,6 @@ export function useKonnectDebuggerSession({ useEffect(() => { if (isDebugSessionMissingFromServer) { - // setDebugSessionMissing(true); setSessionId(null); services.project.update(projectId, { konnectDebugSessionId: null }); } @@ -149,8 +147,8 @@ export function useKonnectDebuggerSession({ queryClient, ); - const { mutateAsync: startAsync, reset: resetStart } = startMutation; - const { mutateAsync: stopAsync, reset: resetStop } = stopMutation; + const { mutateAsync: startAsync, reset: resetStart, error: startError } = startMutation; + const { mutateAsync: stopAsync, reset: resetStop, error: stopError } = stopMutation; const startDebugSession = useCallback( async (durationSecs: number) => { @@ -171,6 +169,10 @@ export function useKonnectDebuggerSession({ await stopAsync().catch(() => {}); }, [ctx, sessionId, stopAsync, resetStart]); + const refreshTraces = useCallback(() => { + refetchTraces(); + }, [refetchTraces]); + const retryDebugSession = useCallback(() => { resetStart(); resetStop(); @@ -184,11 +186,11 @@ export function useKonnectDebuggerSession({ const errors = [ isFetchingDebugSession ? null : debugSessionError, isFetchingTraces ? null : tracesError, - asDebugError(startMutation.error), - asDebugError(stopMutation.error), + asDebugError(startError), + asDebugError(stopError), ]; const authError = errors.find(error => error && AUTH_KINDS.has(error.kind)) ?? null; - const mutationError = asDebugError(startMutation.error) || asDebugError(stopMutation.error); + const mutationError = asDebugError(startError) || asDebugError(stopError); return { ctx, @@ -206,6 +208,8 @@ export function useKonnectDebuggerSession({ startDebugSession, stopDebugSession, retryDebugSession, + refreshTraces, + isRefreshingTraces: isFetchingTraces, }; } diff --git a/packages/insomnia/src/ui/utils/method-colors.ts b/packages/insomnia/src/ui/utils/method-colors.ts index c62b37acf93..1f1ddd594e7 100644 --- a/packages/insomnia/src/ui/utils/method-colors.ts +++ b/packages/insomnia/src/ui/utils/method-colors.ts @@ -21,7 +21,8 @@ import { // The themed methods use the existing theme colour families (so they recolour // with the active theme); in the default theme they render as the design hexes: // POST #7ECF2B, PUT #FF9A1F, PATCH #F0E137, DELETE #FF5631, OPTIONS/HEAD #46C1E6. -const METHOD_PILL_CLASSES: Record = { +export const METHOD_PILL_CLASSES: Record = { + [METHOD_GET]: 'bg-(--color-surprise) text-(--color-font-surprise)', [METHOD_POST]: 'bg-(--color-success) text-(--color-font-success)', [METHOD_PUT]: 'bg-(--color-warning) text-(--color-font-warning)', [METHOD_PATCH]: 'bg-(--color-notice) text-(--color-font-notice)',