@mhjuma/traverse 0.3.0 → 0.4.1
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/CHANGELOG.md +76 -0
- package/package.json +22 -6
- package/src/bootstrap.spec.tsx +191 -1
- package/src/bootstrap.tsx +172 -6
- package/src/components/Explorer/Explorer.spec.tsx +36 -0
- package/src/components/Explorer/Explorer.tsx +22 -0
- package/src/components/Explorer/MonacoConfigErrorBanner.tsx +86 -0
- package/src/components/ExplorerWorkspace/monacoWorkers.spec.ts +66 -1
- package/src/components/ExplorerWorkspace/monacoWorkers.ts +89 -0
- package/src/index.ts +3 -2
- package/src/services/kusto.spec.ts +155 -1
- package/src/services/kusto.ts +117 -7
- package/src/vite-plugin.spec.ts +118 -0
- package/src/vite-plugin.ts +126 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { MonacoWorkerConfigurationError } from '../ExplorerWorkspace/monacoWorkers';
|
|
2
|
+
|
|
3
|
+
interface MonacoConfigErrorBannerProps {
|
|
4
|
+
error: MonacoWorkerConfigurationError;
|
|
5
|
+
className?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const WRAPPER_STYLE: React.CSSProperties = {
|
|
9
|
+
display: 'flex',
|
|
10
|
+
flexDirection: 'column',
|
|
11
|
+
alignItems: 'center',
|
|
12
|
+
justifyContent: 'center',
|
|
13
|
+
height: '100%',
|
|
14
|
+
minHeight: '300px',
|
|
15
|
+
padding: '32px',
|
|
16
|
+
boxSizing: 'border-box',
|
|
17
|
+
fontFamily:
|
|
18
|
+
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
|
|
19
|
+
color: '#d4d4d4',
|
|
20
|
+
background: '#1f1f1f',
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const CARD_STYLE: React.CSSProperties = {
|
|
24
|
+
maxWidth: '720px',
|
|
25
|
+
width: '100%',
|
|
26
|
+
background: '#2b2b2b',
|
|
27
|
+
border: '1px solid #3f3f46',
|
|
28
|
+
borderRadius: '8px',
|
|
29
|
+
padding: '24px',
|
|
30
|
+
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.3)',
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const HEADING_STYLE: React.CSSProperties = {
|
|
34
|
+
margin: '0 0 12px 0',
|
|
35
|
+
fontSize: '18px',
|
|
36
|
+
fontWeight: 600,
|
|
37
|
+
color: '#e8912d',
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const HINT_STYLE: React.CSSProperties = {
|
|
41
|
+
margin: '0 0 16px 0',
|
|
42
|
+
fontSize: '14px',
|
|
43
|
+
lineHeight: '1.5',
|
|
44
|
+
whiteSpace: 'pre-wrap',
|
|
45
|
+
color: '#cccccc',
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const PRE_STYLE: React.CSSProperties = {
|
|
49
|
+
background: '#0d0d0d',
|
|
50
|
+
border: '1px solid #3f3f46',
|
|
51
|
+
borderRadius: '4px',
|
|
52
|
+
padding: '12px 16px',
|
|
53
|
+
fontSize: '13px',
|
|
54
|
+
fontFamily:
|
|
55
|
+
'"SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
|
56
|
+
color: '#9cdcfe',
|
|
57
|
+
overflowX: 'auto',
|
|
58
|
+
margin: 0,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Rendered in place of the Explorer when Monaco workers have not been
|
|
63
|
+
* configured. The message is verbatim from the assertion helper so the
|
|
64
|
+
* fix instructions stay in lockstep with the actual check.
|
|
65
|
+
*
|
|
66
|
+
* Pure presentational component — no imports from FluentUI to keep it
|
|
67
|
+
* usable even when the host hasn't wrapped us in `<FluentProvider>`.
|
|
68
|
+
*/
|
|
69
|
+
export function MonacoConfigErrorBanner({ error, className }: MonacoConfigErrorBannerProps): React.ReactElement {
|
|
70
|
+
// Split the hint into the conversational prose and the code snippet.
|
|
71
|
+
// The convention is: anything before the first blank line is prose,
|
|
72
|
+
// anything after is code that should render in a <pre> block.
|
|
73
|
+
const blankLineIdx = error.hint.indexOf('\n\n');
|
|
74
|
+
const prose = blankLineIdx >= 0 ? error.hint.slice(0, blankLineIdx) : error.hint;
|
|
75
|
+
const code = blankLineIdx >= 0 ? error.hint.slice(blankLineIdx + 2) : '';
|
|
76
|
+
|
|
77
|
+
return (
|
|
78
|
+
<div className={className} style={WRAPPER_STYLE} role="alert" aria-live="polite">
|
|
79
|
+
<div style={CARD_STYLE}>
|
|
80
|
+
<h2 style={HEADING_STYLE}>⚠ {error.summary}</h2>
|
|
81
|
+
<p style={HINT_STYLE}>{prose}</p>
|
|
82
|
+
{code ? <pre style={PRE_STYLE}><code>{code}</code></pre> : null}
|
|
83
|
+
</div>
|
|
84
|
+
</div>
|
|
85
|
+
);
|
|
86
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
2
2
|
|
|
3
|
-
import { configureTraverseMonacoWorkers, __resetWorkerConfigForTests } from './monacoWorkers';
|
|
3
|
+
import { configureTraverseMonacoWorkers, getMonacoWorkerConfigurationError, __resetWorkerConfigForTests } from './monacoWorkers';
|
|
4
4
|
|
|
5
5
|
interface GlobalWithMonaco {
|
|
6
6
|
MonacoEnvironment?: { getWorker?: (workerId: string, label: string) => Worker };
|
|
@@ -79,3 +79,68 @@ describe('configureTraverseMonacoWorkers', () => {
|
|
|
79
79
|
expect(hostGetWorker).toHaveBeenCalledWith('id-1', 'editorWorkerService');
|
|
80
80
|
});
|
|
81
81
|
});
|
|
82
|
+
|
|
83
|
+
describe('getMonacoWorkerConfigurationError', () => {
|
|
84
|
+
beforeEach(() => {
|
|
85
|
+
__resetWorkerConfigForTests();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('returns an error when configureTraverseMonacoWorkers was never called', () => {
|
|
89
|
+
const err = getMonacoWorkerConfigurationError();
|
|
90
|
+
expect(err).not.toBeNull();
|
|
91
|
+
expect(err!.kind).toBe('missing-kusto-worker');
|
|
92
|
+
expect(err!.summary).toMatch(/not configured/i);
|
|
93
|
+
// The hint must show the consumer the actual snippet to copy.
|
|
94
|
+
expect(err!.hint).toContain('configureTraverseMonacoWorkers');
|
|
95
|
+
expect(err!.hint).toContain('getKustoWorker');
|
|
96
|
+
expect(err!.hint).toContain("'monaco-editor/esm/vs/editor/editor.worker.js?worker'");
|
|
97
|
+
expect(err!.hint).toContain("'@kusto/monaco-kusto/release/esm/kusto.worker.js?worker'");
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('returns an error when configure was called but getKustoWorker is missing', () => {
|
|
101
|
+
// Edge case: host calls configure with only an editor worker.
|
|
102
|
+
configureTraverseMonacoWorkers({ getEditorWorker: () => ({}) as Worker });
|
|
103
|
+
const err = getMonacoWorkerConfigurationError();
|
|
104
|
+
expect(err).not.toBeNull();
|
|
105
|
+
expect(err!.kind).toBe('missing-kusto-worker');
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('returns missing-editor-worker when getKustoWorker is set but getEditorWorker is missing and no host fallback exists', () => {
|
|
109
|
+
configureTraverseMonacoWorkers({ getKustoWorker: () => ({}) as Worker });
|
|
110
|
+
const err = getMonacoWorkerConfigurationError();
|
|
111
|
+
expect(err).not.toBeNull();
|
|
112
|
+
expect(err!.kind).toBe('missing-editor-worker');
|
|
113
|
+
expect(err!.hint).toContain('getEditorWorker');
|
|
114
|
+
expect(err!.hint).toContain("'monaco-editor/esm/vs/editor/editor.worker.js?worker'");
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('does NOT return missing-editor-worker if a host MonacoEnvironment.getWorker was installed BEFORE configure', () => {
|
|
118
|
+
// Host (e.g. another editor wrapper) installed its own getWorker.
|
|
119
|
+
// Configure-with-only-kusto is fine in this case because the host
|
|
120
|
+
// handles non-kusto labels via the fallback chain.
|
|
121
|
+
(globalThis as unknown as GlobalWithMonaco).MonacoEnvironment = {
|
|
122
|
+
getWorker: () => ({}) as Worker,
|
|
123
|
+
};
|
|
124
|
+
configureTraverseMonacoWorkers({ getKustoWorker: () => ({}) as Worker });
|
|
125
|
+
expect(getMonacoWorkerConfigurationError()).toBeNull();
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('returns null when both workers are configured', () => {
|
|
129
|
+
configureTraverseMonacoWorkers({
|
|
130
|
+
getEditorWorker: () => ({}) as Worker,
|
|
131
|
+
getKustoWorker: () => ({}) as Worker,
|
|
132
|
+
});
|
|
133
|
+
expect(getMonacoWorkerConfigurationError()).toBeNull();
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('does NOT trust a host-installed MonacoEnvironment.getWorker — must be configured via traverse', () => {
|
|
137
|
+
// Pretend the host installed its own getWorker (e.g. for its own
|
|
138
|
+
// non-kusto editors). That doesn't mean kusto is set up.
|
|
139
|
+
(globalThis as unknown as GlobalWithMonaco).MonacoEnvironment = {
|
|
140
|
+
getWorker: () => ({}) as Worker,
|
|
141
|
+
};
|
|
142
|
+
const err = getMonacoWorkerConfigurationError();
|
|
143
|
+
expect(err).not.toBeNull();
|
|
144
|
+
expect(err!.kind).toBe('missing-kusto-worker');
|
|
145
|
+
});
|
|
146
|
+
});
|
|
@@ -21,6 +21,11 @@ export interface MonacoWorkerConfig {
|
|
|
21
21
|
|
|
22
22
|
let currentConfig: MonacoWorkerConfig = {};
|
|
23
23
|
let installed = false;
|
|
24
|
+
let configuredByTraverse = false;
|
|
25
|
+
/** Captured at first install: was there a pre-existing host
|
|
26
|
+
* `MonacoEnvironment.getWorker` we can fall back to for non-kusto labels?
|
|
27
|
+
* Determines whether `getEditorWorker` is strictly required. */
|
|
28
|
+
let hadPreviousHostWorker = false;
|
|
24
29
|
|
|
25
30
|
interface GlobalWithMonaco {
|
|
26
31
|
MonacoEnvironment?: { getWorker?: (workerId: string, label: string) => Worker };
|
|
@@ -37,9 +42,90 @@ interface GlobalWithMonaco {
|
|
|
37
42
|
*/
|
|
38
43
|
export function configureTraverseMonacoWorkers(config: MonacoWorkerConfig): void {
|
|
39
44
|
currentConfig = config;
|
|
45
|
+
configuredByTraverse = true;
|
|
40
46
|
installMonacoEnvironment();
|
|
41
47
|
}
|
|
42
48
|
|
|
49
|
+
export interface MonacoWorkerConfigurationError {
|
|
50
|
+
/**
|
|
51
|
+
* Discriminator:
|
|
52
|
+
* - `'missing-kusto-worker'` — no `getKustoWorker` (or configure was never called).
|
|
53
|
+
* - `'missing-editor-worker'` — `getKustoWorker` is set but `getEditorWorker`
|
|
54
|
+
* is also missing and there is no pre-existing host
|
|
55
|
+
* `MonacoEnvironment.getWorker` to fall back to. Without one of these,
|
|
56
|
+
* Monaco will throw at runtime when it requests the editor worker (e.g.
|
|
57
|
+
* for find-in-buffer, default color detection, etc).
|
|
58
|
+
*/
|
|
59
|
+
kind: 'missing-kusto-worker' | 'missing-editor-worker';
|
|
60
|
+
/** Short summary suitable for the banner heading. */
|
|
61
|
+
summary: string;
|
|
62
|
+
/** Multi-line actionable hint with the exact code the consumer needs. */
|
|
63
|
+
hint: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Returns `null` when Monaco workers are wired up correctly, otherwise an
|
|
68
|
+
* `Error`-shaped object describing what's missing and how to fix it.
|
|
69
|
+
*
|
|
70
|
+
* We rely on a sentinel (`configuredByTraverse`) rather than inspecting
|
|
71
|
+
* `globalThis.MonacoEnvironment.getWorker` directly. A host may have set
|
|
72
|
+
* `getWorker` for its own non-kusto editors, but if it doesn't route
|
|
73
|
+
* `label === 'kusto'` to a real kusto worker, the kusto language plugin
|
|
74
|
+
* still breaks silently with the cascading errors
|
|
75
|
+
* (`Missing requestHandler or method: normalizeSchema`, etc).
|
|
76
|
+
*
|
|
77
|
+
* Also catches the partial-config case: when `getKustoWorker` is present
|
|
78
|
+
* but `getEditorWorker` is missing AND there's no pre-existing host
|
|
79
|
+
* `MonacoEnvironment.getWorker` to fall back to. Without one of those,
|
|
80
|
+
* Monaco's editor worker requests (find/replace, color detection, large
|
|
81
|
+
* doc diffing) will throw at runtime — same poor UX as the
|
|
82
|
+
* missing-kusto-worker case, just surfaced later.
|
|
83
|
+
*/
|
|
84
|
+
export function getMonacoWorkerConfigurationError(): MonacoWorkerConfigurationError | null {
|
|
85
|
+
if (typeof window === 'undefined') {
|
|
86
|
+
// SSR / Node — no workers to configure.
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
if (!configuredByTraverse || !currentConfig.getKustoWorker) {
|
|
90
|
+
return {
|
|
91
|
+
kind: 'missing-kusto-worker',
|
|
92
|
+
summary: 'Monaco workers are not configured.',
|
|
93
|
+
hint:
|
|
94
|
+
'Call configureTraverseMonacoWorkers({ getEditorWorker, getKustoWorker }) ' +
|
|
95
|
+
'before mounting <Explorer>. The `?worker` import suffix is bundler-specific, ' +
|
|
96
|
+
"so this package can't ship the worker factories itself — each consumer wires " +
|
|
97
|
+
'them through their own bundler.\n\n' +
|
|
98
|
+
'For Vite hosts, add this to a module imported at app startup:\n\n' +
|
|
99
|
+
"import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker.js?worker';\n" +
|
|
100
|
+
"import KustoWorker from '@kusto/monaco-kusto/release/esm/kusto.worker.js?worker';\n" +
|
|
101
|
+
"import { configureTraverseMonacoWorkers } from '@mhjuma/traverse';\n\n" +
|
|
102
|
+
'configureTraverseMonacoWorkers({\n' +
|
|
103
|
+
' getEditorWorker: () => new EditorWorker(),\n' +
|
|
104
|
+
' getKustoWorker: () => new KustoWorker(),\n' +
|
|
105
|
+
'});',
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
if (!currentConfig.getEditorWorker && !hadPreviousHostWorker) {
|
|
109
|
+
return {
|
|
110
|
+
kind: 'missing-editor-worker',
|
|
111
|
+
summary: 'Monaco editor worker is not configured.',
|
|
112
|
+
hint:
|
|
113
|
+
'configureTraverseMonacoWorkers() was called with `getKustoWorker` but no ' +
|
|
114
|
+
'`getEditorWorker`, and the host has not installed a fallback ' +
|
|
115
|
+
'`globalThis.MonacoEnvironment.getWorker`. Monaco needs an editor worker for ' +
|
|
116
|
+
'features like find/replace, color detection, and large-document diffing — ' +
|
|
117
|
+
'without one it will throw at runtime when those fire.\n\n' +
|
|
118
|
+
'Add `getEditorWorker` alongside your existing `getKustoWorker`:\n\n' +
|
|
119
|
+
"import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker.js?worker';\n\n" +
|
|
120
|
+
'configureTraverseMonacoWorkers({\n' +
|
|
121
|
+
' getEditorWorker: () => new EditorWorker(),\n' +
|
|
122
|
+
' getKustoWorker: /* your existing factory */,\n' +
|
|
123
|
+
'});',
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
43
129
|
function installMonacoEnvironment(): void {
|
|
44
130
|
if (typeof window === 'undefined') {
|
|
45
131
|
return;
|
|
@@ -50,6 +136,7 @@ function installMonacoEnvironment(): void {
|
|
|
50
136
|
installed = true;
|
|
51
137
|
const g = globalThis as unknown as GlobalWithMonaco;
|
|
52
138
|
const previous = g.MonacoEnvironment;
|
|
139
|
+
hadPreviousHostWorker = typeof previous?.getWorker === 'function';
|
|
53
140
|
g.MonacoEnvironment = {
|
|
54
141
|
...(previous ?? {}),
|
|
55
142
|
getWorker(workerId: string, label: string): Worker {
|
|
@@ -83,6 +170,8 @@ function installMonacoEnvironment(): void {
|
|
|
83
170
|
export function __resetWorkerConfigForTests(): void {
|
|
84
171
|
currentConfig = {};
|
|
85
172
|
installed = false;
|
|
173
|
+
configuredByTraverse = false;
|
|
174
|
+
hadPreviousHostWorker = false;
|
|
86
175
|
if (typeof window !== 'undefined') {
|
|
87
176
|
const g = globalThis as unknown as GlobalWithMonaco;
|
|
88
177
|
delete g.MonacoEnvironment;
|
package/src/index.ts
CHANGED
|
@@ -14,5 +14,6 @@ export { bootstrapExplorer, useExplorerTheme } from './bootstrap';
|
|
|
14
14
|
export type { BootstrapExplorerOptions } from './bootstrap';
|
|
15
15
|
export { loadSnapshot, saveSnapshot, clearSnapshot, validateAndCleanSnapshot, extractSnapshot, SNAPSHOT_VERSION } from './state/persistence';
|
|
16
16
|
export type { ExplorerTabsSnapshot } from './state/persistence';
|
|
17
|
-
export { configureTraverseMonacoWorkers } from './components/ExplorerWorkspace/monacoWorkers';
|
|
18
|
-
export type { MonacoWorkerConfig, MonacoWorkerFactory } from './components/ExplorerWorkspace/monacoWorkers';
|
|
17
|
+
export { configureTraverseMonacoWorkers, getMonacoWorkerConfigurationError } from './components/ExplorerWorkspace/monacoWorkers';
|
|
18
|
+
export type { MonacoWorkerConfig, MonacoWorkerFactory, MonacoWorkerConfigurationError } from './components/ExplorerWorkspace/monacoWorkers';
|
|
19
|
+
export { MonacoConfigErrorBanner } from './components/Explorer/MonacoConfigErrorBanner';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
2
2
|
|
|
3
|
-
import { extractStats, createKustoClient, parseVisualizationMetadata, buildResultSets } from './kusto';
|
|
3
|
+
import { extractStats, createKustoClient, parseVisualizationMetadata, buildResultSets, parseRetryAfter, abortableSleep } from './kusto';
|
|
4
4
|
import type { QueryStats, KustoClient, KustoStateService, RawTable, KustoVisualization } from './kusto';
|
|
5
5
|
|
|
6
6
|
const KUSTO_CLUSTER = 'https://test-kusto.kusto.windows.net';
|
|
@@ -917,3 +917,157 @@ describe('queryKusto with custom target', () => {
|
|
|
917
917
|
expect(fetchBody.db).toBe('OtherDB');
|
|
918
918
|
});
|
|
919
919
|
});
|
|
920
|
+
|
|
921
|
+
describe('parseRetryAfter', () => {
|
|
922
|
+
const now = Date.parse('2024-01-01T00:00:00Z');
|
|
923
|
+
|
|
924
|
+
it('returns null for absent / empty values', () => {
|
|
925
|
+
expect(parseRetryAfter(null, now)).toBeNull();
|
|
926
|
+
expect(parseRetryAfter(undefined, now)).toBeNull();
|
|
927
|
+
expect(parseRetryAfter('', now)).toBeNull();
|
|
928
|
+
expect(parseRetryAfter(' ', now)).toBeNull();
|
|
929
|
+
});
|
|
930
|
+
|
|
931
|
+
it('parses delta-seconds (integer)', () => {
|
|
932
|
+
expect(parseRetryAfter('5', now)).toBe(5000);
|
|
933
|
+
expect(parseRetryAfter('0', now)).toBe(0);
|
|
934
|
+
});
|
|
935
|
+
|
|
936
|
+
it('parses delta-seconds (decimal)', () => {
|
|
937
|
+
expect(parseRetryAfter('2.5', now)).toBe(2500);
|
|
938
|
+
});
|
|
939
|
+
|
|
940
|
+
it('rejects signed delta-seconds (spec: non-negative integer only)', () => {
|
|
941
|
+
expect(parseRetryAfter('-1', now)).toBeNull();
|
|
942
|
+
expect(parseRetryAfter('+5', now)).toBeNull();
|
|
943
|
+
});
|
|
944
|
+
|
|
945
|
+
it('rejects garbage', () => {
|
|
946
|
+
expect(parseRetryAfter('soon', now)).toBeNull();
|
|
947
|
+
expect(parseRetryAfter('5x', now)).toBeNull();
|
|
948
|
+
});
|
|
949
|
+
|
|
950
|
+
it('parses HTTP-date and returns delta from now', () => {
|
|
951
|
+
const future = new Date(now + 30_000).toUTCString();
|
|
952
|
+
// Allow 1s slack for parsing precision.
|
|
953
|
+
const got = parseRetryAfter(future, now)!;
|
|
954
|
+
expect(got).toBeGreaterThanOrEqual(29_000);
|
|
955
|
+
expect(got).toBeLessThanOrEqual(31_000);
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
it('returns 0 for HTTP-date in the past', () => {
|
|
959
|
+
const past = new Date(now - 30_000).toUTCString();
|
|
960
|
+
expect(parseRetryAfter(past, now)).toBe(0);
|
|
961
|
+
});
|
|
962
|
+
|
|
963
|
+
it('caps very large values at 60s', () => {
|
|
964
|
+
expect(parseRetryAfter('3600', now)).toBe(60_000);
|
|
965
|
+
const far = new Date(now + 24 * 3600 * 1000).toUTCString();
|
|
966
|
+
expect(parseRetryAfter(far, now)).toBe(60_000);
|
|
967
|
+
});
|
|
968
|
+
});
|
|
969
|
+
|
|
970
|
+
describe('abortableSleep', () => {
|
|
971
|
+
it('resolves after the specified delay', async () => {
|
|
972
|
+
const start = Date.now();
|
|
973
|
+
await abortableSleep(20);
|
|
974
|
+
expect(Date.now() - start).toBeGreaterThanOrEqual(15);
|
|
975
|
+
});
|
|
976
|
+
|
|
977
|
+
it('rejects immediately with AbortError when signal is already aborted', async () => {
|
|
978
|
+
const ctrl = new AbortController();
|
|
979
|
+
ctrl.abort();
|
|
980
|
+
await expect(abortableSleep(100, ctrl.signal)).rejects.toMatchObject({ name: 'AbortError' });
|
|
981
|
+
});
|
|
982
|
+
|
|
983
|
+
it('rejects with AbortError when signal aborts mid-sleep', async () => {
|
|
984
|
+
const ctrl = new AbortController();
|
|
985
|
+
const p = abortableSleep(500, ctrl.signal);
|
|
986
|
+
setTimeout(() => ctrl.abort(), 10);
|
|
987
|
+
await expect(p).rejects.toMatchObject({ name: 'AbortError' });
|
|
988
|
+
});
|
|
989
|
+
});
|
|
990
|
+
|
|
991
|
+
describe('createKustoClient with custom fetch', () => {
|
|
992
|
+
it('routes requests through the injected fetch implementation', async () => {
|
|
993
|
+
const stateService = createMockStateService();
|
|
994
|
+
const customFetch = vi.fn().mockResolvedValue({
|
|
995
|
+
ok: true,
|
|
996
|
+
status: 200,
|
|
997
|
+
json: () => Promise.resolve({
|
|
998
|
+
Tables: [
|
|
999
|
+
{ Columns: [{ ColumnName: 'Id', ColumnType: 'long' }], Rows: [[1]] },
|
|
1000
|
+
{ Columns: [{ ColumnName: 'Kind' }, { ColumnName: 'Ordinal' }], Rows: [['QueryResult', 0]] },
|
|
1001
|
+
],
|
|
1002
|
+
}),
|
|
1003
|
+
text: () => Promise.resolve(''),
|
|
1004
|
+
});
|
|
1005
|
+
// Don't stub global fetch — verify the custom one was used.
|
|
1006
|
+
vi.stubGlobal('fetch', vi.fn(() => { throw new Error('global fetch should NOT be called'); }));
|
|
1007
|
+
const client = createKustoClient({
|
|
1008
|
+
defaultTarget: { clusterUrl: KUSTO_CLUSTER, database: KUSTO_DATABASE },
|
|
1009
|
+
getToken: vi.fn().mockResolvedValue('mock-kusto-token'),
|
|
1010
|
+
stateService,
|
|
1011
|
+
fetch: customFetch,
|
|
1012
|
+
});
|
|
1013
|
+
|
|
1014
|
+
await client.queryKusto('Tbl | take 1');
|
|
1015
|
+
expect(customFetch).toHaveBeenCalledTimes(1);
|
|
1016
|
+
});
|
|
1017
|
+
});
|
|
1018
|
+
|
|
1019
|
+
describe('fetchWithRetry honours Retry-After (via 429/503)', () => {
|
|
1020
|
+
let realDate: typeof Date.now;
|
|
1021
|
+
beforeEach(() => { realDate = Date.now; });
|
|
1022
|
+
afterEach(() => { Date.now = realDate; });
|
|
1023
|
+
|
|
1024
|
+
function makeResp(status: number, retryAfter?: string): Response {
|
|
1025
|
+
return {
|
|
1026
|
+
ok: status >= 200 && status < 300,
|
|
1027
|
+
status,
|
|
1028
|
+
headers: {
|
|
1029
|
+
get: (name: string) => (name.toLowerCase() === 'retry-after' && retryAfter !== undefined) ? retryAfter : null,
|
|
1030
|
+
},
|
|
1031
|
+
text: () => Promise.resolve(''),
|
|
1032
|
+
json: () => Promise.resolve({
|
|
1033
|
+
Tables: [
|
|
1034
|
+
{ Columns: [{ ColumnName: 'Id', ColumnType: 'long' }], Rows: [[1]] },
|
|
1035
|
+
{ Columns: [{ ColumnName: 'Kind' }, { ColumnName: 'Ordinal' }], Rows: [['QueryResult', 0]] },
|
|
1036
|
+
],
|
|
1037
|
+
}),
|
|
1038
|
+
} as unknown as Response;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
it('waits Retry-After seconds before retrying on 429', async () => {
|
|
1042
|
+
const stateService = createMockStateService();
|
|
1043
|
+
// 1st call → 429 with Retry-After: 0 (so test runs fast), 2nd → 200.
|
|
1044
|
+
const fetchImpl = vi.fn()
|
|
1045
|
+
.mockResolvedValueOnce(makeResp(429, '0'))
|
|
1046
|
+
.mockResolvedValueOnce(makeResp(200));
|
|
1047
|
+
const client = createKustoClient({
|
|
1048
|
+
defaultTarget: { clusterUrl: KUSTO_CLUSTER, database: KUSTO_DATABASE },
|
|
1049
|
+
getToken: vi.fn().mockResolvedValue('mock-kusto-token'),
|
|
1050
|
+
stateService,
|
|
1051
|
+
fetch: fetchImpl as unknown as typeof fetch,
|
|
1052
|
+
});
|
|
1053
|
+
|
|
1054
|
+
await client.queryKusto('Tbl | take 1');
|
|
1055
|
+
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
1056
|
+
});
|
|
1057
|
+
|
|
1058
|
+
it('also retries on 503', async () => {
|
|
1059
|
+
const stateService = createMockStateService();
|
|
1060
|
+
const fetchImpl = vi.fn()
|
|
1061
|
+
.mockResolvedValueOnce(makeResp(503, '0'))
|
|
1062
|
+
.mockResolvedValueOnce(makeResp(200));
|
|
1063
|
+
const client = createKustoClient({
|
|
1064
|
+
defaultTarget: { clusterUrl: KUSTO_CLUSTER, database: KUSTO_DATABASE },
|
|
1065
|
+
getToken: vi.fn().mockResolvedValue('mock-kusto-token'),
|
|
1066
|
+
stateService,
|
|
1067
|
+
fetch: fetchImpl as unknown as typeof fetch,
|
|
1068
|
+
});
|
|
1069
|
+
|
|
1070
|
+
await client.queryKusto('Tbl | take 1');
|
|
1071
|
+
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
1072
|
+
});
|
|
1073
|
+
});
|
package/src/services/kusto.ts
CHANGED
|
@@ -13,6 +13,9 @@ import type { Priority } from './concurrency';
|
|
|
13
13
|
const MAX_CONCURRENT = 8;
|
|
14
14
|
const MAX_RETRIES = 3;
|
|
15
15
|
const RETRY_BASE_MS = 2000;
|
|
16
|
+
/** Cap on Retry-After honour. Prevents hostile servers (or stale dates) from
|
|
17
|
+
* stalling Traverse's UI for arbitrarily long. */
|
|
18
|
+
const RETRY_AFTER_CAP_MS = 60_000;
|
|
16
19
|
|
|
17
20
|
export interface KustoTarget {
|
|
18
21
|
clusterUrl: string;
|
|
@@ -236,6 +239,13 @@ export interface KustoClientConfig {
|
|
|
236
239
|
defaultTarget: KustoTarget;
|
|
237
240
|
getToken: (clusterUrl: string) => Promise<string>;
|
|
238
241
|
stateService: KustoStateService;
|
|
242
|
+
/**
|
|
243
|
+
* Optional fetch implementation. Defaults to `globalThis.fetch`. Provide
|
|
244
|
+
* an override to route HTTP requests through a custom transport — for
|
|
245
|
+
* example a Tauri `tauri-plugin-http` shim (CORS-free desktop) or a
|
|
246
|
+
* server-side proxy.
|
|
247
|
+
*/
|
|
248
|
+
fetch?: typeof fetch;
|
|
239
249
|
}
|
|
240
250
|
|
|
241
251
|
export interface KustoClient {
|
|
@@ -251,12 +261,105 @@ export interface KustoClient {
|
|
|
251
261
|
getQueryCacheSize(): number;
|
|
252
262
|
}
|
|
253
263
|
|
|
254
|
-
|
|
264
|
+
/**
|
|
265
|
+
* Parse a `Retry-After` header value (RFC 7231): either delta-seconds or an
|
|
266
|
+
* HTTP-date. Returns the wait in milliseconds, capped at
|
|
267
|
+
* {@link RETRY_AFTER_CAP_MS}. Returns `null` when the header is absent or
|
|
268
|
+
* cannot be parsed so the caller falls back to exponential backoff.
|
|
269
|
+
*/
|
|
270
|
+
export function parseRetryAfter(value: string | null | undefined, now: number = Date.now()): number | null {
|
|
271
|
+
if (value === null || value === undefined || value.trim() === '') {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
const trimmed = value.trim();
|
|
275
|
+
// Numeric form: non-negative integer or float, in seconds. Anchored at
|
|
276
|
+
// both ends; leading signs are explicitly rejected so '-1' doesn't fall
|
|
277
|
+
// through to the much more permissive Date.parse below.
|
|
278
|
+
if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
|
|
279
|
+
const seconds = Number(trimmed);
|
|
280
|
+
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
281
|
+
return Math.min(seconds * 1000, RETRY_AFTER_CAP_MS);
|
|
282
|
+
}
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
// Anything that looks numeric-ish (signed, exponent, etc.) is also
|
|
286
|
+
// rejected — Retry-After's delta-seconds form is strict.
|
|
287
|
+
if (/^[+-]?\d/.test(trimmed) && !/[a-zA-Z]/.test(trimmed)) {
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
// HTTP-date form.
|
|
291
|
+
const dateMs = Date.parse(trimmed);
|
|
292
|
+
if (Number.isFinite(dateMs)) {
|
|
293
|
+
const delta = dateMs - now;
|
|
294
|
+
if (delta < 0) {
|
|
295
|
+
return 0;
|
|
296
|
+
}
|
|
297
|
+
return Math.min(delta, RETRY_AFTER_CAP_MS);
|
|
298
|
+
}
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Sleep for `ms` milliseconds. Rejects with an `AbortError` the moment
|
|
304
|
+
* `signal` aborts. Cleans up its event listener / timer either way.
|
|
305
|
+
*/
|
|
306
|
+
export function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
307
|
+
return new Promise((resolve, reject) => {
|
|
308
|
+
if (signal?.aborted) {
|
|
309
|
+
reject(makeAbortError());
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
const timer = setTimeout(() => {
|
|
313
|
+
if (signal && onAbort) {
|
|
314
|
+
signal.removeEventListener('abort', onAbort);
|
|
315
|
+
}
|
|
316
|
+
resolve();
|
|
317
|
+
}, ms);
|
|
318
|
+
const onAbort = signal
|
|
319
|
+
? () => {
|
|
320
|
+
clearTimeout(timer);
|
|
321
|
+
signal.removeEventListener('abort', onAbort!);
|
|
322
|
+
reject(makeAbortError());
|
|
323
|
+
}
|
|
324
|
+
: null;
|
|
325
|
+
if (signal && onAbort) {
|
|
326
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
327
|
+
}
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function makeAbortError(): Error {
|
|
332
|
+
if (typeof DOMException !== 'undefined') {
|
|
333
|
+
return new DOMException('Aborted', 'AbortError');
|
|
334
|
+
}
|
|
335
|
+
const err = new Error('Aborted');
|
|
336
|
+
err.name = 'AbortError';
|
|
337
|
+
return err;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
async function fetchWithRetry(
|
|
341
|
+
fetchImpl: typeof fetch,
|
|
342
|
+
url: string,
|
|
343
|
+
init: RequestInit,
|
|
344
|
+
retries = MAX_RETRIES,
|
|
345
|
+
): Promise<Response> {
|
|
346
|
+
const signal = init.signal ?? undefined;
|
|
255
347
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
348
|
+
if (signal?.aborted) {
|
|
349
|
+
throw makeAbortError();
|
|
350
|
+
}
|
|
351
|
+
const response = await fetchImpl(url, init);
|
|
352
|
+
const retryable = response.status === 429 || response.status === 503;
|
|
353
|
+
if (retryable && attempt < retries) {
|
|
354
|
+
// Defensive: real Response always has headers, but test doubles
|
|
355
|
+
// often omit them; fall through to exponential backoff in that
|
|
356
|
+
// case.
|
|
357
|
+
const headerVal = typeof response.headers?.get === 'function'
|
|
358
|
+
? response.headers.get('Retry-After')
|
|
359
|
+
: null;
|
|
360
|
+
const fromHeader = parseRetryAfter(headerVal);
|
|
361
|
+
const delay = fromHeader !== null ? fromHeader : RETRY_BASE_MS * Math.pow(2, attempt);
|
|
362
|
+
await abortableSleep(delay, signal);
|
|
260
363
|
continue;
|
|
261
364
|
}
|
|
262
365
|
return response;
|
|
@@ -266,6 +369,13 @@ async function fetchWithRetry(url: string, init: RequestInit, retries = MAX_RETR
|
|
|
266
369
|
|
|
267
370
|
export function createKustoClient(config: KustoClientConfig): KustoClient {
|
|
268
371
|
const { defaultTarget, getToken, stateService } = config;
|
|
372
|
+
/**
|
|
373
|
+
* Resolve the fetch implementation at call time rather than capturing it
|
|
374
|
+
* at construction. Tests stub `globalThis.fetch` after creating the
|
|
375
|
+
* client; capturing at construction would freeze the stale reference.
|
|
376
|
+
*/
|
|
377
|
+
const resolveFetch = (): typeof fetch =>
|
|
378
|
+
config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
269
379
|
const limiter = new ConcurrencyLimiter(MAX_CONCURRENT);
|
|
270
380
|
const inflightQueries = new Map<string, Promise<KustoResult<unknown>>>();
|
|
271
381
|
|
|
@@ -296,7 +406,7 @@ export function createKustoClient(config: KustoClientConfig): KustoClient {
|
|
|
296
406
|
}
|
|
297
407
|
|
|
298
408
|
try {
|
|
299
|
-
const response = await fetchWithRetry(`${t.clusterUrl}/v1/rest/query`, {
|
|
409
|
+
const response = await fetchWithRetry(resolveFetch(), `${t.clusterUrl}/v1/rest/query`, {
|
|
300
410
|
method: 'POST',
|
|
301
411
|
headers: {
|
|
302
412
|
'Authorization': `Bearer ${token}`,
|
|
@@ -409,7 +519,7 @@ export function createKustoClient(config: KustoClientConfig): KustoClient {
|
|
|
409
519
|
const timeout = setTimeout(() => controller.abort(), 60000);
|
|
410
520
|
|
|
411
521
|
try {
|
|
412
|
-
const response = await fetchWithRetry(`${t.clusterUrl}/v1/rest/mgmt`, {
|
|
522
|
+
const response = await fetchWithRetry(resolveFetch(), `${t.clusterUrl}/v1/rest/mgmt`, {
|
|
413
523
|
method: 'POST',
|
|
414
524
|
headers: {
|
|
415
525
|
'Authorization': `Bearer ${token}`,
|