@microsoft/rayfin-semantic-model-pack 1.1.0 → 2.0.0

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.
Files changed (39) hide show
  1. package/CHANGELOG +4 -0
  2. package/README.md +16 -5
  3. package/kit/hooks/use-query-factory-target.spec.ts +191 -0
  4. package/kit/hooks/use-query-factory-target.ts +123 -0
  5. package/kit/hooks/use-semantic-model-query.spec.ts +51 -34
  6. package/kit/hooks/use-semantic-model-query.ts +30 -49
  7. package/kit/lib/query-factory.spec.ts +97 -0
  8. package/kit/lib/query-factory.ts +68 -0
  9. package/kit/lib/semantic-model-errors.spec.ts +131 -0
  10. package/kit/lib/semantic-model-errors.ts +110 -0
  11. package/kit/lib/to-data-table.spec.ts +444 -0
  12. package/kit/lib/to-data-table.ts +221 -0
  13. package/pack.json +122 -25
  14. package/package.json +1 -1
  15. package/skills/analytics/SKILL.md +126 -422
  16. package/skills/dax-authoring/SKILL.md +98 -31
  17. package/skills/query-design/SKILL.md +22 -29
  18. package/skills/query-design/references/anti-patterns.md +13 -11
  19. package/skills/query-design/references/format-strings.md +6 -12
  20. package/skills/query-design/references/multi-grain-patterns.md +121 -108
  21. package/skills/schema-discovery/SKILL.md +197 -368
  22. package/skills/schema-discovery/references/discovery-queries.md +6 -8
  23. package/skills/visual-interactivity/SKILL.md +68 -0
  24. package/skills/visual-interactivity/references/advanced-query-shapes.md +155 -0
  25. package/skills/visual-interactivity/references/filter-aware-grid-totals.md +101 -0
  26. package/skills/visual-interactivity/references/highlight-queries.md +88 -0
  27. package/skills/visual-interactivity/references/interaction-manager.md +127 -0
  28. package/skills/visual-interactivity/references/native-selections.md +20 -0
  29. package/skills/visual-interactivity/references/query-factories.md +169 -0
  30. package/kit/scripts/rayfin-connector.mjs +0 -265
  31. package/kit/scripts/rayfin-connector.test.mjs +0 -243
  32. package/kit/scripts/schema-sql-batch.test.mjs +0 -2097
  33. package/kit/scripts/schema-sql-cli.test.mjs +0 -488
  34. package/kit/scripts/schema-sql.mjs +0 -2650
  35. package/kit/scripts/schema-sql.test.mjs +0 -1387
  36. package/kit/scripts/schema.mjs +0 -166
  37. package/kit/scripts/schema.test.mjs +0 -271
  38. package/skills/query-design/references/filter-strategy.md +0 -68
  39. package/skills/query-design/references/highlight-queries.md +0 -122
@@ -11,9 +11,11 @@ import type {
11
11
  SemanticModelQueryResult,
12
12
  } from '@microsoft/rayfin-connector-fabric-semanticmodel';
13
13
  import { toQueryResult } from '@microsoft/rayfin-connector-fabric-semanticmodel';
14
+ import { ConnectorsError } from '@microsoft/rayfin-connectors';
14
15
  import { useCallback, useEffect, useRef, useState } from 'react';
15
16
 
16
17
  import { getRayfinClient } from '@/lib/rayfin-client';
18
+ import { getMissingConnectorMessage, SemanticModelQueryError, toThrownQueryResult } from '@/lib/semantic-model-errors';
17
19
 
18
20
  /**
19
21
  * One entry of the typed `client.connectors` proxy, narrowed to the operation
@@ -27,7 +29,7 @@ import { getRayfinClient } from '@/lib/rayfin-client';
27
29
  type ExecuteQueryClient = {
28
30
  executeQuery(
29
31
  input: ExecuteQueryInput
30
- ): Promise<FabricSemanticModelTabularResponse>;
32
+ ): Promise<FabricSemanticModelTabularResponse | SemanticModelQueryResult>;
31
33
  };
32
34
 
33
35
  interface UseSemanticModelQueryOptions {
@@ -52,55 +54,34 @@ interface QueryState {
52
54
  error: Error | undefined;
53
55
  }
54
56
 
55
- /** Message for a connector this app has not registered. Names the fix, not the symptom. */
56
- function notRegistered(connection: string): string {
57
- return (
58
- `No connector named "${connection}". Check that the name matches rayfin/rayfin.yml, ` +
59
- `or add it with \`npx rayfin connector add\`.`
60
- );
61
- }
62
-
63
57
  /**
64
58
  * Runs one DAX query through the semantic model connector and normalizes the
65
59
  * response.
66
60
  *
67
- * Throws for wiring, transport and auth failures. A query that reached Power BI
68
- * and failed there comes back as a result whose `status` is `error` instead.
61
+ * Folds wiring, transport and auth failures into the query error union.
69
62
  */
70
- async function executeSemanticModelQuery(
63
+ export async function querySemanticModel(
71
64
  connection: string,
72
65
  query: string
73
66
  ): Promise<SemanticModelQueryResult> {
74
- // Async in this template: it resolves the deployed `rayfin.config.json` first.
75
- const client = await getRayfinClient();
76
- const connectors = (client as { connectors?: unknown }).connectors;
77
-
78
- if (!connectors) {
79
- throw new Error(
80
- `This app's Rayfin client has no "connectors". ` +
81
- `Run \`npm run pack:add -- connectors\` to build ` +
82
- `ConnectorsRayfinClient. See step 1 of the analytics skill.`
83
- );
84
- }
85
-
86
- let connector: ExecuteQueryClient | undefined;
87
- try {
88
- connector = (connectors as Record<string, ExecuteQueryClient | undefined>)[
89
- connection
90
- ];
91
- } catch (err) {
92
- // The connectors proxy throws `UNKNOWN_CONNECTOR` for an unconfigured name
93
- // rather than returning undefined, so the miss arrives here.
94
- throw new Error(notRegistered(connection), { cause: err });
95
- }
96
-
97
- // Also checked: test doubles and any future pass-through may return undefined.
98
- if (!connector) throw new Error(notRegistered(connection));
99
-
100
- // Idempotent, and needed on both paths: a registered runtime normalizes
101
- // already, but a connector missing from `connectorRuntimes` falls through to
102
- // JSON pass-through and arrives in the wire shape.
103
- return toQueryResult(await connector.executeQuery({ query }));
67
+ try {
68
+ // Async here: resolve deployed runtime config before accessing connectors.
69
+ const client = await getRayfinClient();
70
+ const connectors = (client as { connectors?: unknown }).connectors as Record<string, ExecuteQueryClient | undefined> | undefined;
71
+ if (!connectors) {
72
+ throw new Error(
73
+ `This app's Rayfin client has no "connectors". ` +
74
+ `Run \`npm run pack:add -- connectors\` to register ` +
75
+ `connectorsService in the client. See the analytics skill.`
76
+ );
77
+ }
78
+ const connector: ExecuteQueryClient | undefined = connectors[connection];
79
+ if (!connector) throw new ConnectorsError(getMissingConnectorMessage(connection), 'UNKNOWN_CONNECTOR');
80
+ // Registered runtimes normalize already; JSON pass-through still needs this.
81
+ return toQueryResult(await connector.executeQuery({ query }));
82
+ } catch (err) {
83
+ return toThrownQueryResult(err, connection);
84
+ }
104
85
  }
105
86
 
106
87
  /**
@@ -122,11 +103,8 @@ async function executeSemanticModelQuery(
122
103
  * }
123
104
  *
124
105
  * @example
125
- * // Two disjoint error channels - check both, in either order.
126
- * // `error`: what the connector threw (wiring, transport, auth). `data` is cleared.
127
- * // `data.status === 'error'`: what Power BI returned, categorised by the
128
- * // connector as 'query' | 'overflow' | 'api' | 'network'. `error` stays undefined.
129
- * // A component that reads only one renders nothing for half its failures.
106
+ * // Query and transport diagnostics are retained on `error` as a SemanticModelQueryError.
107
+ * // Unexpected internal failures can still set only `error`.
130
108
  * if (error) console.error(error.message);
131
109
  * else if (data?.status === 'error')
132
110
  * console.error(data.error.category, data.error.message);
@@ -172,7 +150,10 @@ export function useSemanticModelQuery(
172
150
  let result: SemanticModelQueryResult | undefined;
173
151
  let thrown: Error | undefined;
174
152
  try {
175
- result = await executeSemanticModelQuery(connection, query);
153
+ result = await querySemanticModel(connection, query);
154
+ if (result.status === 'error') {
155
+ thrown = new SemanticModelQueryError(result.error);
156
+ }
176
157
  } catch (err) {
177
158
  // As-is, not re-wrapped: a transport failure carries its status and
178
159
  // service code as own properties, and a fresh Error would drop them.
@@ -190,7 +171,7 @@ export function useSemanticModelQuery(
190
171
  return {
191
172
  connection,
192
173
  query,
193
- data: thrown ? undefined : (result ?? current.data),
174
+ data: result,
194
175
  isLoading: false,
195
176
  error: thrown,
196
177
  };
@@ -0,0 +1,97 @@
1
+ //-----------------------------------------------------------------------
2
+ // <copyright company="Microsoft Corporation">
3
+ // Copyright (c) Microsoft Corporation. All rights reserved.
4
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
5
+ // </copyright>
6
+ //-----------------------------------------------------------------------
7
+
8
+ import { beforeEach, describe, expect, it, vi } from "vitest";
9
+ import type { SemanticModelQueryResult } from "@microsoft/rayfin-connector-fabric-semanticmodel";
10
+ import { NetworkError } from "@microsoft/rayfin-lib";
11
+ import type { WorkloadFailure } from "@microsoft/rayfin-lib";
12
+ import { executeQueryFactory, insertInteractionFilters } from "./query-factory";
13
+ import type { DataQuery } from "./query-factory";
14
+ import { isThrottlingError } from "./semantic-model-errors";
15
+
16
+ const executeQuery = vi.hoisted(() => vi.fn<() => Promise<SemanticModelQueryResult>>());
17
+ vi.mock("@/lib/rayfin-client", () => ({
18
+ getRayfinClient: () => ({ connectors: { model: { executeQuery } } }),
19
+ }));
20
+ const factory: DataQuery = {
21
+ connection: "model", query: 'EVALUATE ROW("Value", 1)',
22
+ columnMetadata: { "[Value]": { name: "Value", format: "0" } },
23
+ };
24
+ beforeEach(() => {
25
+ executeQuery.mockReset();
26
+ });
27
+
28
+ describe("managed query factory execution", () => {
29
+ it("executes each call without caching while preserving metadata and raw model values", async () => {
30
+ executeQuery.mockResolvedValue({
31
+ status: "success", requestId: "query-1",
32
+ table: { columns: [{ name: "[Value]", dataType: "Int64" }], rows: [[1]] },
33
+ });
34
+ expect(await executeQueryFactory(factory)).toEqual({
35
+ columns: [{ name: "Value", format: "0" }], rows: [[1]],
36
+ });
37
+ await executeQueryFactory(factory);
38
+ expect(executeQuery).toHaveBeenCalledTimes(2);
39
+ });
40
+ it("throws failed SDK results with the query error as the cause", async () => {
41
+ executeQuery.mockResolvedValue({ status: "error", requestId: "query-2", error: { category: "query", code: "DaxError", message: "Invalid DAX" } });
42
+ await expect(executeQueryFactory(factory)).rejects.toMatchObject({
43
+ message: "Invalid DAX",
44
+ cause: { category: "query", code: "DaxError", message: "Invalid DAX" },
45
+ });
46
+ });
47
+ it("preserves the original thrown cause alongside normalized query diagnostics", async () => {
48
+ const failure: Error = new Error("Transport failed");
49
+ executeQuery.mockRejectedValue(failure);
50
+ await expect(executeQueryFactory(factory)).rejects.toMatchObject({
51
+ message: "Transport failed",
52
+ category: "unknown", cause: failure,
53
+ });
54
+ });
55
+ it.each([429, 500])("retains structured throttling diagnostics through the executor for HTTP %s without caching failure", async (httpStatus: number): Promise<void> => {
56
+ const workload: WorkloadFailure = {
57
+ errorCode: "WorkloadException", subErrorCode: "TooManyRequests", status: "Failed",
58
+ };
59
+ const failure: NetworkError = Object.assign(new NetworkError("Invocation failed", httpStatus, "InvocationFailure"), { workload });
60
+ executeQuery.mockRejectedValue(failure);
61
+ await expect(executeQueryFactory(factory)).rejects.toMatchObject({
62
+ category: "api", code: "InvocationFailure", httpStatus, workload, cause: failure,
63
+ });
64
+ await executeQueryFactory(factory).then(
65
+ (): never => { throw new Error("Expected a failed query."); },
66
+ (error: Error): void => { expect(isThrottlingError(error)).toBe(true); },
67
+ );
68
+ executeQuery.mockResolvedValue({
69
+ status: "success", requestId: "recovery",
70
+ table: { columns: [{ name: "[Value]", dataType: "Int64" }], rows: [[2]] },
71
+ });
72
+ expect((await executeQueryFactory(factory)).rows).toEqual([[2]]);
73
+ expect(executeQuery).toHaveBeenCalledTimes(3);
74
+ });
75
+ });
76
+
77
+ describe("authored interaction-filter markers", () => {
78
+ const marker: string = "/*FILTERS*/";
79
+ const filter: string = 'TREATAS({ "$&,$$,A" }, \'Category\'[Name])';
80
+ it("inserts every complete filter before grouped measures without interpreting replacement tokens", () => {
81
+ const query: string = `EVALUATE SUMMARIZECOLUMNS('Category'[Name], ${marker}"Value", [Sales])`;
82
+ expect(insertInteractionFilters(query, [filter, "FILTER(ALL('Date'[Year]), 'Date'[Year] > 2020)"], marker, "beforeMeasures"))
83
+ .toBe(`EVALUATE SUMMARIZECOLUMNS('Category'[Name], ${filter},\n FILTER(ALL('Date'[Year]), 'Date'[Year] > 2020),\n "Value", [Sales])`);
84
+ expect(insertInteractionFilters(query, [], marker, "beforeMeasures")).toBe(query.replace(marker, ""));
85
+ });
86
+ it("uses leading commas after ROW/columns-only table expressions, and removes an empty marker", () => {
87
+ const query: string = `EVALUATE CALCULATETABLE(ROW("Value", [Sales])${marker})`;
88
+ expect(insertInteractionFilters(query, [filter], marker, "afterTable"))
89
+ .toBe(`EVALUATE CALCULATETABLE(ROW("Value", [Sales]),\n ${filter})`);
90
+ expect(insertInteractionFilters(query, [], marker, "afterTable")).toBe('EVALUATE CALCULATETABLE(ROW("Value", [Sales]))');
91
+ });
92
+ it("rejects missing/repeated markers and empty filter strings", () => {
93
+ expect(() => insertInteractionFilters("EVALUATE ROW()", [], marker, "afterTable")).toThrow("exactly one");
94
+ expect(() => insertInteractionFilters(`${marker}${marker}`, [], marker, "afterTable")).toThrow("exactly one");
95
+ expect(() => insertInteractionFilters(marker, [" "], marker, "beforeMeasures")).toThrow("nonempty");
96
+ });
97
+ });
@@ -0,0 +1,68 @@
1
+ //-----------------------------------------------------------------------
2
+ // <copyright company="Microsoft Corporation">
3
+ // Copyright (c) Microsoft Corporation. All rights reserved.
4
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
5
+ // </copyright>
6
+ //-----------------------------------------------------------------------
7
+
8
+ import type { DataTable } from "@microsoft/fabric-visuals-core";
9
+ import { querySemanticModel } from "@/hooks/use-semantic-model-query";
10
+ import { toDataTable } from "@/lib/to-data-table";
11
+ import type { ColumnMetadataMap } from "@/lib/to-data-table";
12
+ import { SemanticModelQueryError } from "@/lib/semantic-model-errors";
13
+
14
+ /** The query portion of the existing { connection, query, columnMetadata, vegaLiteSpec } factory result. */
15
+ export interface DataQuery {
16
+ connection: string;
17
+ query: string;
18
+ columnMetadata: ColumnMetadataMap;
19
+ }
20
+
21
+ /**
22
+ * Executes a factory through the same Rayfin execution and error normalization as useSemanticModelQuery.
23
+ * Failed results throw with structured query/transport diagnostics so a managed target loader
24
+ * publishes an error state. The original thrown cause, or returned query error, is preserved.
25
+ */
26
+ export async function executeQueryFactory(factory: DataQuery): Promise<DataTable> {
27
+ const result = await querySemanticModel(factory.connection, factory.query);
28
+ if (result.status === "error") {
29
+ throw new SemanticModelQueryError(result.error);
30
+ }
31
+
32
+ return toDataTable(result.table, factory.columnMetadata);
33
+ }
34
+
35
+ /** Replaces one explicitly authored argument marker in a DAX query string. */
36
+ export function insertInteractionFilters(
37
+ query: string,
38
+ filters: readonly string[],
39
+ marker: string,
40
+ position: "beforeMeasures" | "afterTable",
41
+ ): string {
42
+ if (marker.length === 0 || query.split(marker).length !== 2) {
43
+ throw new Error("Expected exactly one authored interaction-filter insertion point.");
44
+ }
45
+
46
+ if (position !== "beforeMeasures" && position !== "afterTable") {
47
+ throw new Error("An interaction-filter marker must specify its DAX argument position.");
48
+ }
49
+
50
+ if (filters.some(filter => filter.trim().length === 0)) {
51
+ throw new Error("Interaction filters must be complete, nonempty DAX table-filter arguments.");
52
+ }
53
+
54
+ let argumentsText: string;
55
+ if (filters.length === 0) {
56
+ argumentsText = "";
57
+ }
58
+ else if (position === "beforeMeasures") {
59
+ // beforeMeasures: no leading comma, just join filters and add trailing comma and newline
60
+ argumentsText = `${filters.join(",\n ")},\n `;
61
+ }
62
+ else {
63
+ // afterTable: add leading comma and newline, then join filters
64
+ argumentsText = `,\n ${filters.join(",\n ")}`;
65
+ }
66
+
67
+ return query.replace(marker, () => argumentsText);
68
+ }
@@ -0,0 +1,131 @@
1
+ //-----------------------------------------------------------------------
2
+ // <copyright company="Microsoft Corporation">
3
+ // Copyright (c) Microsoft Corporation. All rights reserved.
4
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
5
+ // </copyright>
6
+ //-----------------------------------------------------------------------
7
+
8
+ import { describe, expect, it } from "vitest";
9
+ import { ConnectorsError } from "@microsoft/rayfin-connectors";
10
+ import { NetworkError, SdkError } from "@microsoft/rayfin-lib";
11
+ import type { WorkloadFailure } from "@microsoft/rayfin-lib";
12
+ import { getErrorCause, isThrottlingError, SemanticModelQueryError, toError, toThrownQueryResult } from "./semantic-model-errors";
13
+ import type { SemanticModelQueryFailure } from "./semantic-model-errors";
14
+
15
+ const throttleWorkload: WorkloadFailure = {
16
+ errorCode: "WorkloadException", subErrorCode: "TooManyRequests", status: "Failed",
17
+ };
18
+
19
+ describe("semantic-model error normalization", () => {
20
+ it.each([
21
+ { thrown: new NetworkError("offline"), category: "network", code: undefined },
22
+ { thrown: new NetworkError("unauthorized", 401), category: "api", code: "401" },
23
+ { thrown: new NetworkError("throttled", 429, "Throttled"), category: "api", code: "Throttled" },
24
+ { thrown: new SdkError("not configured", "NOT_CONFIGURED"), category: "unknown", code: "NOT_CONFIGURED" },
25
+ ])("preserves $category diagnostics and original cause", ({ thrown, category, code }) => {
26
+ const result = toThrownQueryResult(thrown, "sales");
27
+ expect(result.status).toBe("error");
28
+ if (result.status !== "error") throw new Error("Expected an error result");
29
+ expect(result.error).toMatchObject({ category, message: thrown.message, ...(code ? { code } : {}) });
30
+ expect(getErrorCause(result.error)).toBe(thrown);
31
+ expect(toError(result.error.message, getErrorCause(result.error)).cause).toBe(thrown);
32
+ });
33
+
34
+ it("names the CLI registration fix without dropping the connector error code", () => {
35
+ const thrown: ConnectorsError = new ConnectorsError("missing", "UNKNOWN_CONNECTOR");
36
+ const result = toThrownQueryResult(thrown, "sales");
37
+ if (result.status !== "error") throw new Error("Expected an error result");
38
+ expect(result.error).toMatchObject({ category: "unknown", code: "UNKNOWN_CONNECTOR" });
39
+ expect(result.error.message).toBe(
40
+ 'No connector named "sales". Check that the name matches rayfin/rayfin.yml, ' +
41
+ 'or add it with `npx rayfin connector add`.',
42
+ );
43
+ expect(getErrorCause(result.error)).toBe(thrown);
44
+ });
45
+
46
+ it("preserves Fabric workload diagnostics", () => {
47
+ const workload: WorkloadFailure = { errorCode: "WorkloadException", subErrorCode: "Unauthorized", functionName: "executeQuery", status: "Failed" };
48
+ const thrown: NetworkError = Object.assign(new NetworkError("failed", 403), { workload });
49
+ const result = toThrownQueryResult(thrown, "sales");
50
+ if (result.status !== "error") throw new Error("Expected an error result");
51
+ expect(result.error).toMatchObject({ category: "api", code: "403", workload });
52
+ });
53
+
54
+ it("handles arbitrary JavaScript thrown values", () => {
55
+ const result = toThrownQueryResult("failure", "sales");
56
+ expect(result).toMatchObject({ status: "error", error: { category: "unknown", message: "failure", cause: "failure" } });
57
+ });
58
+
59
+ it.each([429, 500])("preserves structured throttling diagnostics for HTTP %s", (httpStatus: number): void => {
60
+ const workload: WorkloadFailure = {
61
+ errorCode: "WorkloadException", subErrorCode: "TooManyRequests", status: "Failed",
62
+ };
63
+ const thrown: NetworkError = Object.assign(new NetworkError("Invocation failed", httpStatus, "InvocationFailure"), { workload });
64
+ const result = toThrownQueryResult(thrown, "sales");
65
+ if (result.status !== "error") throw new Error("Expected an error result");
66
+ const error: SemanticModelQueryError = new SemanticModelQueryError(result.error);
67
+ expect(error).toMatchObject({ category: "api", code: "InvocationFailure", httpStatus, workload, cause: thrown });
68
+ expect(isThrottlingError(error)).toBe(true);
69
+ });
70
+ });
71
+
72
+ describe("semantic model query errors", () => {
73
+ it("retains every available diagnostic and the original cause", (): void => {
74
+ const cause: NetworkError = new NetworkError("Invocation failed", 500, "InvocationFailure");
75
+ const failure: SemanticModelQueryFailure = {
76
+ category: "api", message: "Invocation failed", code: "InvocationFailure",
77
+ details: "Original response", recoveryHint: "Contact the administrator",
78
+ workload: throttleWorkload, httpStatus: 500, cause,
79
+ };
80
+ const error: SemanticModelQueryError = new SemanticModelQueryError(failure);
81
+ expect(error).toBeInstanceOf(Error);
82
+ expect(error).toMatchObject(failure);
83
+ expect(error.cause).toBe(cause);
84
+ expect(error.workload).toBe(throttleWorkload);
85
+ });
86
+
87
+ it("keeps a returned failure as the cause when no thrown cause exists", (): void => {
88
+ const failure: SemanticModelQueryFailure = { category: "query", message: "Invalid DAX", code: "DaxError" };
89
+ expect(new SemanticModelQueryError(failure).cause).toBe(failure);
90
+ });
91
+
92
+ it("preserves non-Error causes without inspecting or replacing them", (): void => {
93
+ expect(new SemanticModelQueryError({ category: "unknown", message: "Failed", cause: "original" }).cause).toBe("original");
94
+ expect(new SemanticModelQueryError({ category: "unknown", message: "Failed", cause: null }).cause).toBeNull();
95
+ });
96
+ });
97
+
98
+ describe("structured throttling detection", () => {
99
+ it.each([
100
+ { name: "HTTP 429", failure: { category: "api", message: "Failed", httpStatus: 429 } },
101
+ { name: "coded HTTP 429", failure: { category: "api", message: "Failed", httpStatus: 429, code: "InvocationFailure" } },
102
+ { name: "workload with HTTP 500", failure: { category: "api", message: "Failed", httpStatus: 500, workload: throttleWorkload } },
103
+ { name: "workload without HTTP status", failure: { category: "api", message: "Failed", workload: throttleWorkload } },
104
+ ] satisfies { name: string; failure: SemanticModelQueryFailure }[])("recognizes $name", ({ failure }): void => {
105
+ expect(isThrottlingError(new SemanticModelQueryError(failure))).toBe(true);
106
+ });
107
+
108
+ it.each([
109
+ { category: "api", message: "TooManyRequests HTTP 429", httpStatus: 500 },
110
+ { category: "api", message: "Failed", code: "429" },
111
+ { category: "api", message: "Too many requests", code: "PowerBIThrottled" },
112
+ { category: "api", message: "Failed", workload: { errorCode: "WorkloadException" } },
113
+ { category: "api", message: "Failed", workload: { subErrorCode: "TooManyRequests" } },
114
+ { category: "api", message: "Failed", workload: { errorCode: "OtherException", subErrorCode: "TooManyRequests" } },
115
+ { category: "api", message: "Forbidden", httpStatus: 403, workload: { errorCode: "WorkloadException", subErrorCode: "Unauthorized" } },
116
+ { category: "network", message: "Failed to fetch" },
117
+ { category: "query", message: "TooManyRequests" },
118
+ ] satisfies SemanticModelQueryFailure[])("does not infer throttling from unrelated diagnostics %#", (failure): void => {
119
+ expect(isThrottlingError(new SemanticModelQueryError(failure))).toBe(false);
120
+ });
121
+
122
+ it("recognizes SDK transport failures without treating arbitrary Error properties as transport status", (): void => {
123
+ expect(isThrottlingError(new NetworkError("Failed", 429, "InvocationFailure"))).toBe(true);
124
+ expect(isThrottlingError(Object.assign(new NetworkError("Failed", 500), { workload: throttleWorkload }))).toBe(true);
125
+ expect(isThrottlingError(new NetworkError("TooManyRequests", 500))).toBe(false);
126
+ expect(isThrottlingError(new NetworkError("Failed to fetch"))).toBe(false);
127
+ expect(isThrottlingError(new SdkError("TooManyRequests", "429"))).toBe(false);
128
+ expect(isThrottlingError(Object.assign(new Error("TooManyRequests"), { status: 429, workload: throttleWorkload }))).toBe(false);
129
+ expect(isThrottlingError(undefined)).toBe(false);
130
+ });
131
+ });
@@ -0,0 +1,110 @@
1
+ //-----------------------------------------------------------------------
2
+ // <copyright company="Microsoft Corporation">
3
+ // Copyright (c) Microsoft Corporation. All rights reserved.
4
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
5
+ // </copyright>
6
+ //-----------------------------------------------------------------------
7
+
8
+ import type { QueryError, SemanticModelQueryResult } from "@microsoft/rayfin-connector-fabric-semanticmodel";
9
+ import { ConnectorsError } from "@microsoft/rayfin-connectors";
10
+ import { NetworkError, SdkError } from "@microsoft/rayfin-lib";
11
+ import type { WorkloadFailure } from "@microsoft/rayfin-lib";
12
+
13
+ /** Query diagnostics augmented with the SDK's thrown transport failure fields. */
14
+ export interface SemanticModelQueryFailure extends QueryError {
15
+ readonly workload?: WorkloadFailure;
16
+ readonly httpStatus?: number;
17
+ // JavaScript can throw any value. Preserve the original cause opaquely, without interpreting its properties.
18
+ readonly cause?: unknown;
19
+ }
20
+
21
+ /** The hook and factory executor expose the same diagnostics as an ordinary Error. */
22
+ export class SemanticModelQueryError extends Error {
23
+ readonly category: QueryError["category"];
24
+ readonly code: string | undefined;
25
+ readonly details: string | undefined;
26
+ readonly recoveryHint: string | undefined;
27
+ readonly workload: WorkloadFailure | undefined;
28
+ readonly httpStatus: number | undefined;
29
+
30
+ constructor(failure: SemanticModelQueryFailure) {
31
+ super(failure.message, { cause: failure.cause !== undefined ? failure.cause : failure });
32
+ this.name = "SemanticModelQueryError";
33
+ this.category = failure.category;
34
+ this.code = failure.code;
35
+ this.details = failure.details;
36
+ this.recoveryHint = failure.recoveryHint;
37
+ this.workload = failure.workload;
38
+ this.httpStatus = failure.httpStatus;
39
+ }
40
+ }
41
+
42
+ /** Identify throttling from typed transport/workload diagnostics, never error text or a code alone. */
43
+ export function isThrottlingError(error: Error | undefined): boolean {
44
+ if (error instanceof SemanticModelQueryError || error instanceof NetworkError) {
45
+ const httpStatus: number | undefined = error instanceof NetworkError ? error.status : error.httpStatus;
46
+ const workload: WorkloadFailure | undefined = error.workload;
47
+ return httpStatus === 429
48
+ || (workload?.errorCode === "WorkloadException" && workload.subErrorCode === "TooManyRequests");
49
+ }
50
+
51
+ return false;
52
+ }
53
+
54
+ type ThrownErrorFields = Pick<SemanticModelQueryFailure, "category" | "message" | "code" | "workload" | "httpStatus">;
55
+
56
+ // JavaScript may throw any value. Keep the existing unknown boundary here rather than
57
+ // claiming arbitrary transport failures or their original causes have a known shape.
58
+ function messageOf(err: unknown): string {
59
+ return err instanceof Error && err.message.length > 0 ? err.message : String(err);
60
+ }
61
+
62
+ function describeThrownError(err: unknown): ThrownErrorFields {
63
+ if (err instanceof NetworkError) {
64
+ const code = err.code ?? (err.status !== undefined ? String(err.status) : undefined);
65
+ return {
66
+ category: err.status === undefined ? "network" : "api",
67
+ message: messageOf(err),
68
+ ...(code !== undefined ? { code } : {}),
69
+ ...(err.status !== undefined ? { httpStatus: err.status } : {}),
70
+ ...(err.workload !== undefined ? { workload: err.workload } : {}),
71
+ };
72
+ }
73
+ if (err instanceof SdkError) {
74
+ return {
75
+ category: "unknown",
76
+ message: messageOf(err),
77
+ ...(err.code !== undefined ? { code: err.code } : {}),
78
+ };
79
+ }
80
+ return { category: "unknown", message: messageOf(err) };
81
+ }
82
+
83
+ export function getMissingConnectorMessage(connection: string): string {
84
+ return (
85
+ `No connector named "${connection}". Check that the name matches rayfin/rayfin.yml, ` +
86
+ `or add it with \`npx rayfin connector add\`.`
87
+ );
88
+ }
89
+
90
+ export function toThrownQueryResult(err: unknown, connection: string): SemanticModelQueryResult {
91
+ const error: SemanticModelQueryFailure = {
92
+ ...describeThrownError(err),
93
+ ...(err instanceof ConnectorsError && err.code === "UNKNOWN_CONNECTOR"
94
+ ? { message: getMissingConnectorMessage(connection) }
95
+ : {}),
96
+ cause: err,
97
+ };
98
+ return { status: "error", error, requestId: "" };
99
+ }
100
+
101
+ // Customized hooks preserved by seed upgrades may still import these helpers.
102
+ export function toError(message: string, cause?: unknown): Error {
103
+ const error: Error & { cause?: unknown } = new Error(message);
104
+ if (cause !== undefined) error.cause = cause;
105
+ return error;
106
+ }
107
+
108
+ export function getErrorCause(error: SemanticModelQueryFailure): unknown {
109
+ return "cause" in error ? error.cause : undefined;
110
+ }