-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathresources.metric.tsx
More file actions
288 lines (262 loc) · 7.87 KB
/
resources.metric.tsx
File metadata and controls
288 lines (262 loc) · 7.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import type { OutputColumnMetadata } from "@internal/clickhouse";
import { type ActionFunctionArgs, json } from "@remix-run/server-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
import { z } from "zod";
import { requireUserId } from "~/services/session.server";
import { hasAccessToEnvironment } from "~/models/runtimeEnvironment.server";
import { executeQuery } from "~/services/queryService.server";
import {
QueryWidget,
type QueryWidgetConfig,
type QueryWidgetData,
} from "~/components/metrics/QueryWidget";
import { useElementVisibility } from "~/hooks/useElementVisibility";
import { useInterval } from "~/hooks/useInterval";
import { env } from "~/env.server";
const Scope = z.union([z.literal("environment"), z.literal("organization"), z.literal("project")]);
// Response type for the action
type MetricWidgetActionResponse =
| { success: false; error: string }
| {
success: true;
data: {
rows: Record<string, unknown>[];
columns: OutputColumnMetadata[];
stats: { elapsed_ns: string } | null;
hiddenColumns: string[] | null;
reachedMaxRows: boolean;
periodClipped: number | null;
maxQueryPeriod: number | undefined;
timeRange: { from: string; to: string };
};
};
const MetricWidgetQuery = z.object({
query: z.string(),
organizationId: z.string(),
projectId: z.string(),
environmentId: z.string(),
scope: Scope,
period: z.string().nullable(),
from: z.string().nullable(),
to: z.string().nullable(),
taskIdentifiers: z.array(z.string()).optional(),
queues: z.array(z.string()).optional(),
tags: z.array(z.string()).optional(),
});
export const action = async ({ request }: ActionFunctionArgs) => {
const userId = await requireUserId(request);
const data = await request.json();
const submission = MetricWidgetQuery.safeParse(data);
if (!submission.success) {
return json(
{
success: false as const,
error: "Invalid input",
},
{ status: 400 }
);
}
const {
query,
organizationId,
projectId,
environmentId,
scope,
period,
from,
to,
taskIdentifiers,
queues,
tags,
} = submission.data;
// Check they should be able to access it
const hasAccess = await hasAccessToEnvironment({
environmentId,
projectId,
organizationId,
userId,
});
if (!hasAccess) {
return json(
{
success: false as const,
error: "You don't have permission for this resource",
},
{ status: 400 }
);
}
const queryResult = await executeQuery({
name: "query-page",
query,
scope,
organizationId,
projectId,
environmentId,
period,
from,
to,
taskIdentifiers,
queues,
// Set higher concurrency if many widgets are on screen at once
customOrgConcurrencyLimit: env.METRIC_WIDGET_DEFAULT_ORG_CONCURRENCY_LIMIT,
});
if (!queryResult.success) {
return json(
{
success: false as const,
error: queryResult.error.message,
},
{ status: 400 }
);
}
return json({
success: true as const,
data: {
rows: queryResult.result.rows,
columns: queryResult.result.columns,
stats: queryResult.result.stats,
hiddenColumns: queryResult.result.hiddenColumns ?? null,
reachedMaxRows: queryResult.result.reachedMaxRows,
periodClipped: queryResult.periodClipped,
maxQueryPeriod: queryResult.maxQueryPeriod,
timeRange: {
from: queryResult.timeRange.from.toISOString(),
to: queryResult.timeRange.to.toISOString(),
},
},
});
};
type MetricWidgetProps = {
/** Unique key for this widget - used to identify the fetcher */
widgetKey: string;
title: string;
config: QueryWidgetConfig;
refreshIntervalMs?: number;
isResizing?: boolean;
isDraggable?: boolean;
/** Callback when edit button is clicked - receives current data */
onEdit?: (data: QueryWidgetData) => void;
/** Callback when rename is clicked - receives new title */
onRename?: (newTitle: string) => void;
/** Callback when delete is clicked */
onDelete?: () => void;
/** Callback when duplicate is clicked - receives current data */
onDuplicate?: (data: QueryWidgetData) => void;
} & z.infer<typeof MetricWidgetQuery>;
export function MetricWidget({
widgetKey,
title,
config,
refreshIntervalMs,
isResizing,
isDraggable,
onEdit,
onRename,
onDelete,
onDuplicate,
...props
}: MetricWidgetProps) {
const [response, setResponse] = useState<MetricWidgetActionResponse | null>(null);
const [isLoading, setIsLoading] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null);
const isDirtyRef = useRef(false);
// Track the latest props so the submit callback always uses fresh values
// without needing to be recreated (which would cause useInterval to re-register listeners).
const propsRef = useRef(props);
propsRef.current = props;
const submit = useCallback(() => {
if (!isVisibleRef.current) {
isDirtyRef.current = true;
return;
}
isDirtyRef.current = false;
// Abort any in-flight request for this widget
abortControllerRef.current?.abort();
const controller = new AbortController();
abortControllerRef.current = controller;
setIsLoading(true);
fetch(`/resources/metric`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(propsRef.current),
signal: controller.signal,
})
.then(async (res) => {
try {
return (await res.json()) as MetricWidgetActionResponse;
} catch {
throw new Error(`Request failed (${res.status})`);
}
})
.then((data) => {
if (!controller.signal.aborted) {
setResponse(data);
setIsLoading(false);
}
})
.catch((err) => {
if (err instanceof DOMException && err.name === "AbortError") return;
if (!controller.signal.aborted) {
// Only surface the error if there's no existing successful data to preserve
setResponse((prev) =>
prev?.success ? prev : { success: false, error: err.message || "Network error" }
);
setIsLoading(false);
}
});
}, []);
// Track visibility so we only fetch for on-screen widgets.
// When a widget scrolls into view and has no data yet, trigger a load.
const { ref: visibilityRef, isVisibleRef } = useElementVisibility({
onVisibilityChange: (visible) => {
if (visible && (!response || isDirtyRef.current)) {
submit();
}
},
});
// Clean up on unmount
useEffect(() => {
return () => {
abortControllerRef.current?.abort();
};
}, []);
// Reload periodically and on focus (onLoad: false — the useEffect below handles initial load)
useInterval({ interval: refreshIntervalMs, callback: submit, onLoad: false });
// Reload on mount and when query, time period, or filters change
useEffect(() => {
submit();
}, [
submit,
props.query,
props.from,
props.to,
props.period,
props.scope,
JSON.stringify(props.taskIdentifiers),
JSON.stringify(props.queues),
]);
const data = response?.success
? { rows: response.data.rows, columns: response.data.columns }
: { rows: [], columns: [] };
const timeRange = response?.success ? response.data.timeRange : undefined;
return (
<div ref={visibilityRef} className="h-full">
<QueryWidget
title={title}
titleString={title}
query={props.query}
config={config}
isLoading={isLoading}
data={data}
timeRange={timeRange}
error={response?.success === false ? response.error : undefined}
isResizing={isResizing}
isDraggable={isDraggable}
onEdit={onEdit}
onRename={onRename}
onDelete={onDelete}
onDuplicate={onDuplicate}
/>
</div>
);
}