-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathuse-analytics-query.ts
More file actions
211 lines (185 loc) · 6.47 KB
/
use-analytics-query.ts
File metadata and controls
211 lines (185 loc) · 6.47 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
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ArrowClient, connectSSE } from "@/js";
import type {
AnalyticsFormat,
InferParams,
InferResultByFormat,
QueryKey,
UseAnalyticsQueryOptions,
UseAnalyticsQueryResult,
} from "./types";
import { useQueryHMR } from "./use-query-hmr";
function getDevMode() {
const url = new URL(window.location.href);
const searchParams = url.searchParams;
const dev = searchParams.get("dev");
return dev ? `?dev=${dev}` : "";
}
function getArrowStreamUrl(id: string) {
return `/api/analytics/arrow-result/${id}`;
}
/**
* Subscribe to an analytics query over SSE and returns its latest result.
* Integration hook between client and analytics plugin.
*
* The return type is automatically inferred based on the format:
* - `format: "JSON"` (default): Returns typed array from QueryRegistry
* - `format: "ARROW"`: Returns TypedArrowTable with row type preserved
*
* Note: User context execution is determined by query file naming:
* - `queryKey.obo.sql`: Executes as user (OBO = on-behalf-of / user delegation)
* - `queryKey.sql`: Executes as service principal
*
* @param queryKey - Analytics query identifier
* @param parameters - Query parameters (type-safe based on QueryRegistry)
* @param options - Analytics query settings including format
* @returns Query result state with format-appropriate data type
*
* @example JSON format (default)
* ```typescript
* const { data } = useAnalyticsQuery("spend_data", params);
* // data: Array<{ group_key: string; cost_usd: number; ... }> | null
* ```
*
* @example Arrow format
* ```typescript
* const { data } = useAnalyticsQuery("spend_data", params, { format: "ARROW" });
* // data: TypedArrowTable<{ group_key: string; cost_usd: number; ... }> | null
* ```
*/
export function useAnalyticsQuery<
T = unknown,
K extends QueryKey = QueryKey,
F extends AnalyticsFormat = "ARROW_STREAM",
>(
queryKey: K,
parameters?: InferParams<K> | null,
options: UseAnalyticsQueryOptions<F> = {} as UseAnalyticsQueryOptions<F>,
): UseAnalyticsQueryResult<InferResultByFormat<T, K, F>> {
const format = options?.format ?? "ARROW_STREAM";
const maxParametersSize = options?.maxParametersSize ?? 100 * 1024;
const autoStart = options?.autoStart ?? true;
const devMode = getDevMode();
const urlSuffix = `/api/analytics/query/${encodeURIComponent(queryKey)}${devMode}`;
type ResultType = InferResultByFormat<T, K, F>;
const [data, setData] = useState<ResultType | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const abortControllerRef = useRef<AbortController | null>(null);
if (!queryKey || queryKey.trim().length === 0) {
throw new Error(
"useAnalyticsQuery: 'queryKey' must be a non-empty string.",
);
}
const payload = useMemo(() => {
try {
const serialized = JSON.stringify({ parameters, format });
const sizeInBytes = new Blob([serialized]).size;
if (sizeInBytes > maxParametersSize) {
throw new Error(
"useAnalyticsQuery: Parameters size exceeds the maximum allowed size",
);
}
return serialized;
} catch (error) {
console.error("useAnalyticsQuery: Failed to serialize parameters", error);
return null;
}
}, [parameters, format, maxParametersSize]);
const start = useCallback(() => {
if (payload === null) {
setError("Failed to serialize query parameters");
return;
}
// Abort previous request if exists
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
setLoading(true);
setError(null);
setData(null);
const abortController = new AbortController();
abortControllerRef.current = abortController;
connectSSE({
url: urlSuffix,
payload: payload,
signal: abortController.signal,
onMessage: async (message) => {
try {
const parsed = JSON.parse(message.data);
// success - JSON format
if (parsed.type === "result") {
setLoading(false);
setData(parsed.data as ResultType);
return;
}
// success - Arrow format
if (parsed.type === "arrow") {
try {
const arrowData = await ArrowClient.fetchArrow(
getArrowStreamUrl(parsed.statement_id),
);
const table = await ArrowClient.processArrowBuffer(arrowData);
setLoading(false);
// Table is cast to TypedArrowTable with row type from QueryRegistry
setData(table as ResultType);
return;
} catch (error) {
console.error(
"[useAnalyticsQuery] Failed to fetch Arrow data",
error,
);
setLoading(false);
setError("Unable to load data, please try again");
return;
}
}
// error
if (parsed.type === "error" || parsed.error || parsed.code) {
const errorMsg =
parsed.error || parsed.message || "Unable to execute query";
setLoading(false);
setError(errorMsg);
if (parsed.code) {
console.error(
`[useAnalyticsQuery] Code: ${parsed.code}, Message: ${errorMsg}`,
);
}
return;
}
} catch (error) {
console.warn("[useAnalyticsQuery] Malformed message received", error);
}
},
onError: (error) => {
if (abortController.signal.aborted) return;
setLoading(false);
let userMessage = "Unable to load data, please try again";
if (error instanceof Error) {
if (error.name === "AbortError") {
userMessage = "Request timed out, please try again";
} else if (error.message.includes("Failed to fetch")) {
userMessage = "Network error. Please check your connection.";
}
console.error("[useAnalyticsQuery] Error", {
queryKey,
error: error.message,
stack: error.stack,
});
}
setError(userMessage);
},
});
}, [queryKey, payload, urlSuffix]);
useEffect(() => {
if (autoStart) {
start();
}
return () => {
abortControllerRef.current?.abort();
};
}, [start, autoStart]);
// Enable HMR for query updates in dev mode
useQueryHMR(queryKey, start);
return { data, loading, error };
}