@rawdash/connector-azure-cost 0.17.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.
- package/README.md +111 -0
- package/dist/index.d.ts +133 -0
- package/dist/index.js +790 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -0
package/README.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
<!-- This file is generated from connector metadata by scripts/generate-connector-docs.ts. Do not edit by hand. -->
|
|
2
|
+
|
|
3
|
+
# @rawdash/connector-azure-cost
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@rawdash/connector-azure-cost)
|
|
6
|
+
[](https://github.com/rawdash/rawdash/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
Track daily Azure spend over time, optionally broken down by resource group, service, or tag, via the Cost Management query API.
|
|
9
|
+
|
|
10
|
+
> **Cost & frequency.** Azure Cost Management queries are throttled aggressively per subscription; avoid syncing more often than necessary. Recommended sync interval: **1 day**. Minimum sensible interval: **1 hour**.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install @rawdash/connector-azure-cost
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Authentication
|
|
19
|
+
|
|
20
|
+
Authenticates with a Microsoft Entra ID (Azure AD) service principal (tenant ID + client ID + client secret) scoped to the target subscription. The principal needs the built-in Cost Management Reader role at the subscription scope (or Reader).
|
|
21
|
+
|
|
22
|
+
1. In the Azure portal open Microsoft Entra ID → App registrations → New registration and create an app for rawdash.
|
|
23
|
+
2. Under Certificates & secrets, generate a client secret and copy its value (it is only shown once).
|
|
24
|
+
3. In the target subscription open Access control (IAM) → Add role assignment and grant the new service principal the built-in Cost Management Reader role.
|
|
25
|
+
4. Store the client secret as a secret and reference it from config as `clientSecret: secret("AZ_CLIENT_SECRET")`, alongside `tenantId`, `clientId`, and `subscriptionId`.
|
|
26
|
+
5. Cost Management must be enabled for the subscription; the first activation can take up to 24 hours before data is queryable.
|
|
27
|
+
|
|
28
|
+
## Configuration
|
|
29
|
+
|
|
30
|
+
| Field | Type | Required | Description |
|
|
31
|
+
| ---------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
32
|
+
| `tenantId` | string | Yes | Microsoft Entra ID (Azure AD) tenant ID - the directory that hosts the app registration. |
|
|
33
|
+
| `clientId` | string | Yes | Application (client) ID of the Entra ID app registration / service principal used for authentication. |
|
|
34
|
+
| `clientSecret` | secret | Yes | Client secret of the Entra ID app registration. Generate one under App registrations → Certificates & secrets. |
|
|
35
|
+
| `subscriptionId` | string | Yes | Azure subscription ID the cost query is scoped to. The service principal needs Cost Management Reader (or Reader) on this subscription. |
|
|
36
|
+
| `groupBy` | array | No | Up to two Cost Management dimensions to break costs down by, e.g. ServiceName, ResourceGroup, or TAG:Environment. Omit for total cost only. |
|
|
37
|
+
| `lookbackDays` | number | No | How many days of history to fetch on a full sync. Defaults to 90. |
|
|
38
|
+
|
|
39
|
+
## Resources
|
|
40
|
+
|
|
41
|
+
- **`azure_cost_daily`** _(metric)_ - Daily Azure actual cost per time bucket, optionally split across the configured group-by dimensions.
|
|
42
|
+
- Endpoint: `POST /subscriptions/{subId}/providers/Microsoft.CostManagement/query`
|
|
43
|
+
- Unit: currency reported by Azure
|
|
44
|
+
- Granularity: daily
|
|
45
|
+
- Dimensions: `unit`, `service_name`
|
|
46
|
+
- Cost data can be revised for a couple of days after the fact, so incremental syncs refetch a short trailing window. Cost Management accepts at most two grouping dimensions per query.
|
|
47
|
+
|
|
48
|
+
## Example
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import {
|
|
52
|
+
defineConfig,
|
|
53
|
+
defineDashboard,
|
|
54
|
+
defineMetric,
|
|
55
|
+
secret,
|
|
56
|
+
} from '@rawdash/core';
|
|
57
|
+
|
|
58
|
+
const azureCost = {
|
|
59
|
+
name: 'azure-cost',
|
|
60
|
+
connectorId: 'azure-cost',
|
|
61
|
+
config: {
|
|
62
|
+
tenantId: '00000000-0000-0000-0000-000000000000',
|
|
63
|
+
clientId: '00000000-0000-0000-0000-000000000000',
|
|
64
|
+
clientSecret: secret('AZ_CLIENT_SECRET'),
|
|
65
|
+
subscriptionId: '00000000-0000-0000-0000-000000000000',
|
|
66
|
+
groupBy: ['ServiceName'],
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export default defineConfig({
|
|
71
|
+
connectors: [azureCost],
|
|
72
|
+
dashboards: {
|
|
73
|
+
finance: defineDashboard({
|
|
74
|
+
widgets: {
|
|
75
|
+
spend_30d: {
|
|
76
|
+
kind: 'stat',
|
|
77
|
+
title: 'Azure spend (30d)',
|
|
78
|
+
window: '30d',
|
|
79
|
+
metric: defineMetric({
|
|
80
|
+
connector: azureCost,
|
|
81
|
+
shape: 'metric',
|
|
82
|
+
name: 'azure_cost_daily',
|
|
83
|
+
fn: 'sum',
|
|
84
|
+
}),
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
}),
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Rate limits
|
|
93
|
+
|
|
94
|
+
Cost Management throttles via 429 responses with Retry-After; the shared HTTP client honors Retry-After and backs off on 429.
|
|
95
|
+
|
|
96
|
+
## Limitations
|
|
97
|
+
|
|
98
|
+
- Cost data can be revised for a couple of days after the fact, so incremental syncs refetch a short trailing window.
|
|
99
|
+
- Daily granularity only (the most common dashboard slice). Monthly granularity is not exposed in v1.
|
|
100
|
+
- At most two grouping dimensions are accepted per query (Cost Management limit).
|
|
101
|
+
- Forecast (`forecast` endpoint) is not synced in v1; only historical actual cost.
|
|
102
|
+
|
|
103
|
+
## Links
|
|
104
|
+
|
|
105
|
+
- [Rawdash docs](https://rawdash.dev/docs/connectors/)
|
|
106
|
+
- [Microsoft Azure API docs](https://learn.microsoft.com/en-us/rest/api/cost-management/)
|
|
107
|
+
- [GitHub](https://github.com/rawdash/rawdash)
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
Apache-2.0
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { BaseConnector, ConnectorCost, ConnectorContext, SyncOptions, StorageHandle, SyncResult, ConnectorDoc } from '@rawdash/core';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
declare const configFields: z.ZodObject<{
|
|
5
|
+
tenantId: z.ZodString;
|
|
6
|
+
clientId: z.ZodString;
|
|
7
|
+
clientSecret: z.ZodObject<{
|
|
8
|
+
$secret: z.ZodString;
|
|
9
|
+
}, z.core.$strip>;
|
|
10
|
+
subscriptionId: z.ZodString;
|
|
11
|
+
groupBy: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
12
|
+
lookbackDays: z.ZodOptional<z.ZodNumber>;
|
|
13
|
+
}, z.core.$strip>;
|
|
14
|
+
declare const doc: ConnectorDoc;
|
|
15
|
+
interface AzureCostSettings {
|
|
16
|
+
tenantId: string;
|
|
17
|
+
clientId: string;
|
|
18
|
+
subscriptionId: string;
|
|
19
|
+
groupBy?: readonly string[];
|
|
20
|
+
lookbackDays?: number;
|
|
21
|
+
}
|
|
22
|
+
declare const azureCostCredentials: {
|
|
23
|
+
clientSecret: {
|
|
24
|
+
description: string;
|
|
25
|
+
auth: "required";
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
type AzureCostCredentials = typeof azureCostCredentials;
|
|
29
|
+
declare const azureCostResources: {
|
|
30
|
+
readonly azure_cost_daily: {
|
|
31
|
+
readonly shape: "metric";
|
|
32
|
+
readonly description: "Daily Azure actual cost per time bucket, optionally split across the configured group-by dimensions.";
|
|
33
|
+
readonly endpoint: "POST /subscriptions/{subId}/providers/Microsoft.CostManagement/query";
|
|
34
|
+
readonly unit: "currency reported by Azure";
|
|
35
|
+
readonly granularity: "daily";
|
|
36
|
+
readonly notes: "Cost data can be revised for a couple of days after the fact, so incremental syncs refetch a short trailing window. Cost Management accepts at most two grouping dimensions per query.";
|
|
37
|
+
readonly dimensions: [{
|
|
38
|
+
readonly name: "unit";
|
|
39
|
+
readonly description: "Currency reported by Azure (e.g. USD, EUR).";
|
|
40
|
+
}, {
|
|
41
|
+
readonly name: "service_name";
|
|
42
|
+
readonly description: "Azure service name, present when grouping by ServiceName (other dimensions appear under their normalized key, e.g. resource_group, tag_<key>).";
|
|
43
|
+
}];
|
|
44
|
+
readonly responses: {
|
|
45
|
+
readonly cost_query: z.ZodObject<{
|
|
46
|
+
id: z.ZodOptional<z.ZodString>;
|
|
47
|
+
name: z.ZodOptional<z.ZodString>;
|
|
48
|
+
type: z.ZodOptional<z.ZodString>;
|
|
49
|
+
properties: z.ZodObject<{
|
|
50
|
+
nextLink: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
51
|
+
columns: z.ZodArray<z.ZodObject<{
|
|
52
|
+
name: z.ZodString;
|
|
53
|
+
type: z.ZodOptional<z.ZodString>;
|
|
54
|
+
}, z.core.$strip>>;
|
|
55
|
+
rows: z.ZodArray<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodNull]>>>;
|
|
56
|
+
}, z.core.$strip>;
|
|
57
|
+
}, z.core.$strip>;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
interface CostWindow {
|
|
62
|
+
from: string;
|
|
63
|
+
to: string;
|
|
64
|
+
}
|
|
65
|
+
declare const id = "azure-cost";
|
|
66
|
+
declare const cost: ConnectorCost;
|
|
67
|
+
declare class AzureCostConnector extends BaseConnector<AzureCostSettings, AzureCostCredentials> {
|
|
68
|
+
static readonly id = "azure-cost";
|
|
69
|
+
static readonly resources: {
|
|
70
|
+
readonly azure_cost_daily: {
|
|
71
|
+
readonly shape: "metric";
|
|
72
|
+
readonly description: "Daily Azure actual cost per time bucket, optionally split across the configured group-by dimensions.";
|
|
73
|
+
readonly endpoint: "POST /subscriptions/{subId}/providers/Microsoft.CostManagement/query";
|
|
74
|
+
readonly unit: "currency reported by Azure";
|
|
75
|
+
readonly granularity: "daily";
|
|
76
|
+
readonly notes: "Cost data can be revised for a couple of days after the fact, so incremental syncs refetch a short trailing window. Cost Management accepts at most two grouping dimensions per query.";
|
|
77
|
+
readonly dimensions: [{
|
|
78
|
+
readonly name: "unit";
|
|
79
|
+
readonly description: "Currency reported by Azure (e.g. USD, EUR).";
|
|
80
|
+
}, {
|
|
81
|
+
readonly name: "service_name";
|
|
82
|
+
readonly description: "Azure service name, present when grouping by ServiceName (other dimensions appear under their normalized key, e.g. resource_group, tag_<key>).";
|
|
83
|
+
}];
|
|
84
|
+
readonly responses: {
|
|
85
|
+
readonly cost_query: z.ZodObject<{
|
|
86
|
+
id: z.ZodOptional<z.ZodString>;
|
|
87
|
+
name: z.ZodOptional<z.ZodString>;
|
|
88
|
+
type: z.ZodOptional<z.ZodString>;
|
|
89
|
+
properties: z.ZodObject<{
|
|
90
|
+
nextLink: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
91
|
+
columns: z.ZodArray<z.ZodObject<{
|
|
92
|
+
name: z.ZodString;
|
|
93
|
+
type: z.ZodOptional<z.ZodString>;
|
|
94
|
+
}, z.core.$strip>>;
|
|
95
|
+
rows: z.ZodArray<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodNull]>>>;
|
|
96
|
+
}, z.core.$strip>;
|
|
97
|
+
}, z.core.$strip>;
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
static readonly schemas: {
|
|
102
|
+
readonly cost_query: z.ZodObject<{
|
|
103
|
+
id: z.ZodOptional<z.ZodString>;
|
|
104
|
+
name: z.ZodOptional<z.ZodString>;
|
|
105
|
+
type: z.ZodOptional<z.ZodString>;
|
|
106
|
+
properties: z.ZodObject<{
|
|
107
|
+
nextLink: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
108
|
+
columns: z.ZodArray<z.ZodObject<{
|
|
109
|
+
name: z.ZodString;
|
|
110
|
+
type: z.ZodOptional<z.ZodString>;
|
|
111
|
+
}, z.core.$strip>>;
|
|
112
|
+
rows: z.ZodArray<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodNull]>>>;
|
|
113
|
+
}, z.core.$strip>;
|
|
114
|
+
}, z.core.$strip>;
|
|
115
|
+
} & Readonly<Record<string, z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>>;
|
|
116
|
+
static readonly cost: ConnectorCost;
|
|
117
|
+
static create(input: unknown, ctx?: ConnectorContext): AzureCostConnector;
|
|
118
|
+
readonly id = "azure-cost";
|
|
119
|
+
readonly credentials: {
|
|
120
|
+
clientSecret: {
|
|
121
|
+
description: string;
|
|
122
|
+
auth: "required";
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
private tokenCache;
|
|
126
|
+
private getAccessToken;
|
|
127
|
+
private queryUrl;
|
|
128
|
+
private buildQueryPayload;
|
|
129
|
+
private runQuery;
|
|
130
|
+
sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export { AzureCostConnector, type AzureCostSettings, type CostWindow, configFields, cost, AzureCostConnector as default, doc, id, azureCostResources as resources };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
// ../../connector-shared/dist/index.js
|
|
2
|
+
var HttpClientError = class extends Error {
|
|
3
|
+
response;
|
|
4
|
+
constructor(message, response) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = new.target.name;
|
|
7
|
+
this.response = response;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var TransientError = class extends HttpClientError {
|
|
11
|
+
kind = "transient";
|
|
12
|
+
};
|
|
13
|
+
var RateLimitError = class extends HttpClientError {
|
|
14
|
+
kind = "rate_limit";
|
|
15
|
+
retryAfter;
|
|
16
|
+
constructor(message, response, retryAfter) {
|
|
17
|
+
super(message, response);
|
|
18
|
+
this.retryAfter = retryAfter;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var AuthError = class extends HttpClientError {
|
|
22
|
+
kind = "auth";
|
|
23
|
+
};
|
|
24
|
+
var UpstreamBugError = class extends HttpClientError {
|
|
25
|
+
kind = "upstream_bug";
|
|
26
|
+
};
|
|
27
|
+
var ClientBugError = class extends HttpClientError {
|
|
28
|
+
kind = "client_bug";
|
|
29
|
+
};
|
|
30
|
+
function classifyStatus(status) {
|
|
31
|
+
if (status === 429) {
|
|
32
|
+
return "rate_limit";
|
|
33
|
+
}
|
|
34
|
+
if (status === 401 || status === 403) {
|
|
35
|
+
return "auth";
|
|
36
|
+
}
|
|
37
|
+
if (status === 408) {
|
|
38
|
+
return "transient";
|
|
39
|
+
}
|
|
40
|
+
if (status >= 500) {
|
|
41
|
+
return "upstream_bug";
|
|
42
|
+
}
|
|
43
|
+
if (status >= 400) {
|
|
44
|
+
return "client_bug";
|
|
45
|
+
}
|
|
46
|
+
return "client_bug";
|
|
47
|
+
}
|
|
48
|
+
function errorForStatus(message, response, retryAfter) {
|
|
49
|
+
const kind = classifyStatus(response.status);
|
|
50
|
+
switch (kind) {
|
|
51
|
+
case "rate_limit":
|
|
52
|
+
return new RateLimitError(message, response, retryAfter);
|
|
53
|
+
case "auth":
|
|
54
|
+
return new AuthError(message, response);
|
|
55
|
+
case "transient":
|
|
56
|
+
return new TransientError(message, response);
|
|
57
|
+
case "upstream_bug":
|
|
58
|
+
return new UpstreamBugError(message, response);
|
|
59
|
+
case "client_bug":
|
|
60
|
+
return new ClientBugError(message, response);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
var defaultRetryOn = (status, err) => {
|
|
64
|
+
if (err instanceof RateLimitError) {
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
if (err instanceof TransientError) {
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
if (status === null) {
|
|
71
|
+
return err instanceof Error && !(err instanceof HttpClientError);
|
|
72
|
+
}
|
|
73
|
+
if (status === 408 || status === 429) {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
if (status >= 500) {
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
80
|
+
};
|
|
81
|
+
function parseRetryAfter(headerValue, now = /* @__PURE__ */ new Date()) {
|
|
82
|
+
if (!headerValue) {
|
|
83
|
+
return void 0;
|
|
84
|
+
}
|
|
85
|
+
const trimmed = headerValue.trim();
|
|
86
|
+
if (/^\d+$/.test(trimmed)) {
|
|
87
|
+
return new Date(now.getTime() + Number(trimmed) * 1e3);
|
|
88
|
+
}
|
|
89
|
+
const parsed = Date.parse(trimmed);
|
|
90
|
+
if (Number.isNaN(parsed)) {
|
|
91
|
+
return void 0;
|
|
92
|
+
}
|
|
93
|
+
return new Date(parsed);
|
|
94
|
+
}
|
|
95
|
+
function sleep(ms, signal) {
|
|
96
|
+
if (signal?.aborted) {
|
|
97
|
+
return Promise.reject(signal.reason ?? new Error("Aborted"));
|
|
98
|
+
}
|
|
99
|
+
return new Promise((resolve, reject) => {
|
|
100
|
+
const onAbort = () => {
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
reject(signal.reason ?? new Error("Aborted"));
|
|
103
|
+
};
|
|
104
|
+
const timer = setTimeout(() => {
|
|
105
|
+
signal?.removeEventListener("abort", onAbort);
|
|
106
|
+
resolve();
|
|
107
|
+
}, ms);
|
|
108
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
var HTTP_CLIENT_VERSION = "0.0.0";
|
|
112
|
+
var DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
|
|
113
|
+
function connectorUserAgent(connectorId) {
|
|
114
|
+
return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
|
|
115
|
+
}
|
|
116
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
117
|
+
var DEFAULT_MAX_ATTEMPTS = 3;
|
|
118
|
+
var DEFAULT_INITIAL_DELAY_MS = 1e3;
|
|
119
|
+
var DEFAULT_MAX_DELAY_MS = 6e4;
|
|
120
|
+
var OBSERVER_TIMEOUT_MS = 250;
|
|
121
|
+
async function notifyObserver(observer, event) {
|
|
122
|
+
let result;
|
|
123
|
+
try {
|
|
124
|
+
result = observer(event);
|
|
125
|
+
} catch (err) {
|
|
126
|
+
console.warn("[connector-shared] request observer threw:", err);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (!(result instanceof Promise)) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const guarded = result.catch((err) => {
|
|
133
|
+
console.warn("[connector-shared] request observer rejected:", err);
|
|
134
|
+
});
|
|
135
|
+
let timer;
|
|
136
|
+
const timeout = new Promise((resolve) => {
|
|
137
|
+
timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);
|
|
138
|
+
});
|
|
139
|
+
try {
|
|
140
|
+
await Promise.race([guarded, timeout]);
|
|
141
|
+
} finally {
|
|
142
|
+
if (timer) {
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function newRequestId() {
|
|
148
|
+
const c = globalThis.crypto;
|
|
149
|
+
if (c?.randomUUID) {
|
|
150
|
+
return c.randomUUID();
|
|
151
|
+
}
|
|
152
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
153
|
+
}
|
|
154
|
+
function mergeHeaders(defaults, overrides) {
|
|
155
|
+
const merged = {};
|
|
156
|
+
for (const [k, v] of Object.entries(defaults)) {
|
|
157
|
+
merged[k.toLowerCase()] = v;
|
|
158
|
+
}
|
|
159
|
+
if (overrides) {
|
|
160
|
+
for (const [k, v] of Object.entries(overrides)) {
|
|
161
|
+
merged[k.toLowerCase()] = v;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return merged;
|
|
165
|
+
}
|
|
166
|
+
function linkTimeoutSignal(parent, timeoutMs) {
|
|
167
|
+
const controller = new AbortController();
|
|
168
|
+
const onParentAbort = () => {
|
|
169
|
+
controller.abort(parent?.reason);
|
|
170
|
+
};
|
|
171
|
+
if (parent) {
|
|
172
|
+
if (parent.aborted) {
|
|
173
|
+
controller.abort(parent.reason);
|
|
174
|
+
} else {
|
|
175
|
+
parent.addEventListener("abort", onParentAbort, { once: true });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const timer = setTimeout(() => {
|
|
179
|
+
controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));
|
|
180
|
+
}, timeoutMs);
|
|
181
|
+
return {
|
|
182
|
+
signal: controller.signal,
|
|
183
|
+
cancel: () => {
|
|
184
|
+
clearTimeout(timer);
|
|
185
|
+
if (parent) {
|
|
186
|
+
parent.removeEventListener("abort", onParentAbort);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
async function readBody(res, parseJson) {
|
|
192
|
+
if (res.status === 204 || res.status === 205) {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
196
|
+
if (parseJson && contentType.includes("application/json")) {
|
|
197
|
+
const text = await res.text();
|
|
198
|
+
if (text.length === 0) {
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
return JSON.parse(text);
|
|
202
|
+
}
|
|
203
|
+
return res.text();
|
|
204
|
+
}
|
|
205
|
+
async function request(req, options) {
|
|
206
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
207
|
+
const retry = req.retry ?? {};
|
|
208
|
+
const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
209
|
+
const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
|
|
210
|
+
const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
|
|
211
|
+
const retryOn = retry.retryOn ?? defaultRetryOn;
|
|
212
|
+
const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
213
|
+
const parseJson = req.parseJson ?? true;
|
|
214
|
+
const headers = mergeHeaders(
|
|
215
|
+
{
|
|
216
|
+
"User-Agent": DEFAULT_USER_AGENT,
|
|
217
|
+
Accept: "application/json"
|
|
218
|
+
},
|
|
219
|
+
req.headers
|
|
220
|
+
);
|
|
221
|
+
let lastErr;
|
|
222
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
223
|
+
req.signal?.throwIfAborted();
|
|
224
|
+
const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);
|
|
225
|
+
let res;
|
|
226
|
+
try {
|
|
227
|
+
res = await fetchImpl(req.url, {
|
|
228
|
+
method: req.method ?? "GET",
|
|
229
|
+
headers,
|
|
230
|
+
body: req.body,
|
|
231
|
+
signal
|
|
232
|
+
});
|
|
233
|
+
} catch (err2) {
|
|
234
|
+
cancel();
|
|
235
|
+
if (req.signal?.aborted) {
|
|
236
|
+
throw req.signal.reason ?? err2;
|
|
237
|
+
}
|
|
238
|
+
const error = err2 instanceof Error ? err2 : new Error(String(err2));
|
|
239
|
+
lastErr = error;
|
|
240
|
+
if (attempt < maxAttempts - 1 && retryOn(null, error)) {
|
|
241
|
+
const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);
|
|
242
|
+
await sleep(delay, req.signal);
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
throw new TransientError(error.message);
|
|
246
|
+
}
|
|
247
|
+
cancel();
|
|
248
|
+
const body = await readBody(res, parseJson);
|
|
249
|
+
const httpResponse = {
|
|
250
|
+
status: res.status,
|
|
251
|
+
headers: res.headers,
|
|
252
|
+
body
|
|
253
|
+
};
|
|
254
|
+
if (req.rateLimit) {
|
|
255
|
+
const state = req.rateLimit.parse(res.headers);
|
|
256
|
+
if (state) {
|
|
257
|
+
httpResponse.rateLimitState = state;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (options.observer) {
|
|
261
|
+
await notifyObserver(options.observer, {
|
|
262
|
+
url: req.url,
|
|
263
|
+
method: req.method ?? "GET",
|
|
264
|
+
status: res.status,
|
|
265
|
+
resource: options.resource,
|
|
266
|
+
requestId: options.requestId ?? newRequestId(),
|
|
267
|
+
body
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
if (res.ok) {
|
|
271
|
+
return httpResponse;
|
|
272
|
+
}
|
|
273
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
274
|
+
const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? "GET"} ${req.url}`;
|
|
275
|
+
const err = errorForStatus(message, httpResponse, retryAfter);
|
|
276
|
+
if (attempt < maxAttempts - 1 && retryOn(res.status, err) && !(err instanceof AuthError) && !(err instanceof ClientBugError)) {
|
|
277
|
+
lastErr = err;
|
|
278
|
+
let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);
|
|
279
|
+
if (err instanceof RateLimitError && retryAfter) {
|
|
280
|
+
const wait = retryAfter.getTime() - Date.now();
|
|
281
|
+
if (wait > 0) {
|
|
282
|
+
delay = Math.min(wait, maxDelayMs);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
await sleep(delay, req.signal);
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
throw err;
|
|
289
|
+
}
|
|
290
|
+
throw lastErr ?? new UpstreamBugError("Exhausted retry attempts");
|
|
291
|
+
}
|
|
292
|
+
function computeDelay(attempt, initialDelayMs, maxDelayMs) {
|
|
293
|
+
const base = initialDelayMs * 2 ** attempt;
|
|
294
|
+
const jitter = base * 0.25 * Math.random();
|
|
295
|
+
return Math.min(base + jitter, maxDelayMs);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// src/azure-cost.ts
|
|
299
|
+
import {
|
|
300
|
+
BaseConnector,
|
|
301
|
+
defineConfigFields,
|
|
302
|
+
defineConnectorDoc,
|
|
303
|
+
defineResources,
|
|
304
|
+
schemasFromResources
|
|
305
|
+
} from "@rawdash/core";
|
|
306
|
+
import { z } from "zod";
|
|
307
|
+
|
|
308
|
+
// src/auth.ts
|
|
309
|
+
var TOKEN_HOST = "login.microsoftonline.com";
|
|
310
|
+
var ARM_SCOPE = "https://management.azure.com/.default";
|
|
311
|
+
var TOKEN_TTL_BUFFER_MS = 6e4;
|
|
312
|
+
async function fetchArmAccessToken(input, signal) {
|
|
313
|
+
const params = new URLSearchParams();
|
|
314
|
+
params.set("grant_type", "client_credentials");
|
|
315
|
+
params.set("client_id", input.clientId);
|
|
316
|
+
params.set("client_secret", input.clientSecret);
|
|
317
|
+
params.set("scope", ARM_SCOPE);
|
|
318
|
+
let res;
|
|
319
|
+
try {
|
|
320
|
+
res = await request(
|
|
321
|
+
{
|
|
322
|
+
url: `https://${TOKEN_HOST}/${encodeURIComponent(input.tenantId)}/oauth2/v2.0/token`,
|
|
323
|
+
method: "POST",
|
|
324
|
+
headers: {
|
|
325
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
326
|
+
Accept: "application/json",
|
|
327
|
+
"User-Agent": connectorUserAgent(input.connectorId)
|
|
328
|
+
},
|
|
329
|
+
body: params.toString(),
|
|
330
|
+
signal
|
|
331
|
+
},
|
|
332
|
+
{ resource: "oauth_token" }
|
|
333
|
+
);
|
|
334
|
+
} catch (err) {
|
|
335
|
+
throw classifyTokenError(err);
|
|
336
|
+
}
|
|
337
|
+
const access = res.body.access_token;
|
|
338
|
+
const expiresIn = res.body.expires_in;
|
|
339
|
+
if (typeof access !== "string" || access.length === 0) {
|
|
340
|
+
throw new AuthError(
|
|
341
|
+
"Azure AD token response did not include an access_token"
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
const ttlMs = typeof expiresIn === "number" && Number.isFinite(expiresIn) ? expiresIn * 1e3 : 60 * 60 * 1e3;
|
|
345
|
+
return {
|
|
346
|
+
token: access,
|
|
347
|
+
expiresAt: Date.now() + ttlMs - TOKEN_TTL_BUFFER_MS
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
function classifyTokenError(err) {
|
|
351
|
+
if (!(err instanceof Error) || !("kind" in err)) {
|
|
352
|
+
return err;
|
|
353
|
+
}
|
|
354
|
+
const httpErr = err;
|
|
355
|
+
const status = httpErr.response?.status ?? 0;
|
|
356
|
+
if (status === 400 || status === 401 || status === 403) {
|
|
357
|
+
return new AuthError(httpErr.message, httpErr.response);
|
|
358
|
+
}
|
|
359
|
+
if (status >= 500) {
|
|
360
|
+
return new TransientError(httpErr.message, httpErr.response);
|
|
361
|
+
}
|
|
362
|
+
return err;
|
|
363
|
+
}
|
|
364
|
+
function isTokenFresh(cache, now = Date.now()) {
|
|
365
|
+
return cache !== null && now < cache.expiresAt;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// src/azure-cost.ts
|
|
369
|
+
var dimensionValues = [
|
|
370
|
+
"ResourceGroup",
|
|
371
|
+
"ResourceGroupName",
|
|
372
|
+
"ServiceName",
|
|
373
|
+
"ServiceTier",
|
|
374
|
+
"Meter",
|
|
375
|
+
"MeterCategory",
|
|
376
|
+
"MeterSubCategory",
|
|
377
|
+
"ResourceId",
|
|
378
|
+
"ResourceType",
|
|
379
|
+
"ResourceLocation",
|
|
380
|
+
"ChargeType",
|
|
381
|
+
"PublisherType",
|
|
382
|
+
"BillingPeriod",
|
|
383
|
+
"InvoiceId",
|
|
384
|
+
"SubscriptionId",
|
|
385
|
+
"SubscriptionName"
|
|
386
|
+
];
|
|
387
|
+
var groupByEntrySchema = z.string().min(1).regex(
|
|
388
|
+
new RegExp(`^(${dimensionValues.join("|")}|TAG:.+)$`),
|
|
389
|
+
`groupBy entries must be one of ${dimensionValues.join(", ")}, or TAG:<tag-key>`
|
|
390
|
+
);
|
|
391
|
+
var configFields = defineConfigFields(
|
|
392
|
+
z.object({
|
|
393
|
+
tenantId: z.string().min(1).meta({
|
|
394
|
+
label: "Tenant ID",
|
|
395
|
+
description: "Microsoft Entra ID (Azure AD) tenant ID - the directory that hosts the app registration.",
|
|
396
|
+
placeholder: "00000000-0000-0000-0000-000000000000"
|
|
397
|
+
}),
|
|
398
|
+
clientId: z.string().min(1).meta({
|
|
399
|
+
label: "Client ID",
|
|
400
|
+
description: "Application (client) ID of the Entra ID app registration / service principal used for authentication.",
|
|
401
|
+
placeholder: "00000000-0000-0000-0000-000000000000"
|
|
402
|
+
}),
|
|
403
|
+
clientSecret: z.object({ $secret: z.string().min(1) }).meta({
|
|
404
|
+
label: "Client secret",
|
|
405
|
+
description: "Client secret of the Entra ID app registration. Generate one under App registrations \u2192 Certificates & secrets.",
|
|
406
|
+
placeholder: "azure-client-secret",
|
|
407
|
+
secret: true
|
|
408
|
+
}),
|
|
409
|
+
subscriptionId: z.string().min(1).meta({
|
|
410
|
+
label: "Subscription ID",
|
|
411
|
+
description: "Azure subscription ID the cost query is scoped to. The service principal needs Cost Management Reader (or Reader) on this subscription.",
|
|
412
|
+
placeholder: "00000000-0000-0000-0000-000000000000"
|
|
413
|
+
}),
|
|
414
|
+
groupBy: z.array(groupByEntrySchema).max(2, "Cost Management accepts at most two grouping dimensions").optional().meta({
|
|
415
|
+
label: "Group by (optional)",
|
|
416
|
+
description: "Up to two Cost Management dimensions to break costs down by, e.g. ServiceName, ResourceGroup, or TAG:Environment. Omit for total cost only."
|
|
417
|
+
}),
|
|
418
|
+
lookbackDays: z.number().int().positive().max(365).optional().meta({
|
|
419
|
+
label: "Backfill window (days)",
|
|
420
|
+
description: "How many days of history to fetch on a full sync. Defaults to 90.",
|
|
421
|
+
placeholder: "90"
|
|
422
|
+
})
|
|
423
|
+
})
|
|
424
|
+
);
|
|
425
|
+
var doc = defineConnectorDoc({
|
|
426
|
+
displayName: "Azure Cost Management",
|
|
427
|
+
category: "finance",
|
|
428
|
+
brandColor: "#0078D4",
|
|
429
|
+
tagline: "Track daily Azure spend over time, optionally broken down by resource group, service, or tag, via the Cost Management query API.",
|
|
430
|
+
vendor: {
|
|
431
|
+
name: "Microsoft Azure",
|
|
432
|
+
apiDocs: "https://learn.microsoft.com/en-us/rest/api/cost-management/",
|
|
433
|
+
website: "https://azure.microsoft.com/en-us/products/cost-management"
|
|
434
|
+
},
|
|
435
|
+
auth: {
|
|
436
|
+
summary: "Authenticates with a Microsoft Entra ID (Azure AD) service principal (tenant ID + client ID + client secret) scoped to the target subscription. The principal needs the built-in Cost Management Reader role at the subscription scope (or Reader).",
|
|
437
|
+
setup: [
|
|
438
|
+
"In the Azure portal open Microsoft Entra ID \u2192 App registrations \u2192 New registration and create an app for rawdash.",
|
|
439
|
+
"Under Certificates & secrets, generate a client secret and copy its value (it is only shown once).",
|
|
440
|
+
"In the target subscription open Access control (IAM) \u2192 Add role assignment and grant the new service principal the built-in Cost Management Reader role.",
|
|
441
|
+
'Store the client secret as a secret and reference it from config as `clientSecret: secret("AZ_CLIENT_SECRET")`, alongside `tenantId`, `clientId`, and `subscriptionId`.',
|
|
442
|
+
"Cost Management must be enabled for the subscription; the first activation can take up to 24 hours before data is queryable."
|
|
443
|
+
]
|
|
444
|
+
},
|
|
445
|
+
rateLimit: "Cost Management throttles via 429 responses with Retry-After; the shared HTTP client honors Retry-After and backs off on 429.",
|
|
446
|
+
limitations: [
|
|
447
|
+
"Cost data can be revised for a couple of days after the fact, so incremental syncs refetch a short trailing window.",
|
|
448
|
+
"Daily granularity only (the most common dashboard slice). Monthly granularity is not exposed in v1.",
|
|
449
|
+
"At most two grouping dimensions are accepted per query (Cost Management limit).",
|
|
450
|
+
"Forecast (`forecast` endpoint) is not synced in v1; only historical actual cost."
|
|
451
|
+
]
|
|
452
|
+
});
|
|
453
|
+
var azureCostCredentials = {
|
|
454
|
+
clientSecret: {
|
|
455
|
+
description: "Azure AD app-registration client secret",
|
|
456
|
+
auth: "required"
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
var costColumnSchema = z.object({
|
|
460
|
+
name: z.string(),
|
|
461
|
+
type: z.string().optional()
|
|
462
|
+
});
|
|
463
|
+
var costRowSchema = z.array(z.union([z.string(), z.number(), z.null()]));
|
|
464
|
+
var costQueryResponseSchema = z.object({
|
|
465
|
+
id: z.string().optional(),
|
|
466
|
+
name: z.string().optional(),
|
|
467
|
+
type: z.string().optional(),
|
|
468
|
+
properties: z.object({
|
|
469
|
+
nextLink: z.string().nullish(),
|
|
470
|
+
columns: z.array(costColumnSchema),
|
|
471
|
+
rows: z.array(costRowSchema)
|
|
472
|
+
})
|
|
473
|
+
});
|
|
474
|
+
var DAILY_METRIC_NAME = "azure_cost_daily";
|
|
475
|
+
var azureCostResources = defineResources({
|
|
476
|
+
azure_cost_daily: {
|
|
477
|
+
shape: "metric",
|
|
478
|
+
description: "Daily Azure actual cost per time bucket, optionally split across the configured group-by dimensions.",
|
|
479
|
+
endpoint: "POST /subscriptions/{subId}/providers/Microsoft.CostManagement/query",
|
|
480
|
+
unit: "currency reported by Azure",
|
|
481
|
+
granularity: "daily",
|
|
482
|
+
notes: "Cost data can be revised for a couple of days after the fact, so incremental syncs refetch a short trailing window. Cost Management accepts at most two grouping dimensions per query.",
|
|
483
|
+
dimensions: [
|
|
484
|
+
{
|
|
485
|
+
name: "unit",
|
|
486
|
+
description: "Currency reported by Azure (e.g. USD, EUR)."
|
|
487
|
+
},
|
|
488
|
+
{
|
|
489
|
+
name: "service_name",
|
|
490
|
+
description: "Azure service name, present when grouping by ServiceName (other dimensions appear under their normalized key, e.g. resource_group, tag_<key>)."
|
|
491
|
+
}
|
|
492
|
+
],
|
|
493
|
+
responses: { cost_query: costQueryResponseSchema }
|
|
494
|
+
}
|
|
495
|
+
});
|
|
496
|
+
var ARM_HOST = "https://management.azure.com";
|
|
497
|
+
var COST_API_VERSION = "2024-08-01";
|
|
498
|
+
var DEFAULT_BACKFILL_DAYS = 90;
|
|
499
|
+
var INCREMENTAL_LOOKBACK_DAYS = 3;
|
|
500
|
+
var MS_PER_DAY = 864e5;
|
|
501
|
+
function startOfUtcDay(ms) {
|
|
502
|
+
return Math.floor(ms / MS_PER_DAY) * MS_PER_DAY;
|
|
503
|
+
}
|
|
504
|
+
function getCostWindow(options, lookbackDays, now = Date.now()) {
|
|
505
|
+
const sinceMs = options.since !== void 0 ? Date.parse(options.since) : NaN;
|
|
506
|
+
const hasSince = Number.isFinite(sinceMs);
|
|
507
|
+
let days = lookbackDays;
|
|
508
|
+
if (options.mode === "latest") {
|
|
509
|
+
days = INCREMENTAL_LOOKBACK_DAYS;
|
|
510
|
+
} else if (hasSince) {
|
|
511
|
+
const elapsed = Math.ceil((now - sinceMs) / MS_PER_DAY);
|
|
512
|
+
days = Math.min(Math.max(elapsed, 1), lookbackDays);
|
|
513
|
+
}
|
|
514
|
+
const todayStart = startOfUtcDay(now);
|
|
515
|
+
const fromMs = todayStart - (days - 1) * MS_PER_DAY;
|
|
516
|
+
const toMs = todayStart + MS_PER_DAY - 1;
|
|
517
|
+
return {
|
|
518
|
+
from: new Date(fromMs).toISOString(),
|
|
519
|
+
to: new Date(toMs).toISOString()
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
function dimensionAttrKey(dimension) {
|
|
523
|
+
if (dimension.startsWith("TAG:")) {
|
|
524
|
+
return `tag_${dimension.slice(4)}`;
|
|
525
|
+
}
|
|
526
|
+
return dimension.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase();
|
|
527
|
+
}
|
|
528
|
+
function toGrouping(dimension) {
|
|
529
|
+
if (dimension.startsWith("TAG:")) {
|
|
530
|
+
return { type: "Tag", name: dimension.slice(4) };
|
|
531
|
+
}
|
|
532
|
+
return { type: "Dimension", name: dimension };
|
|
533
|
+
}
|
|
534
|
+
function parseUsageDate(value) {
|
|
535
|
+
if (value === null) {
|
|
536
|
+
return null;
|
|
537
|
+
}
|
|
538
|
+
const s = String(value);
|
|
539
|
+
const m = /^(\d{4})(\d{2})(\d{2})$/.exec(s);
|
|
540
|
+
if (!m) {
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
const ts = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
|
|
544
|
+
return Number.isFinite(ts) ? ts : null;
|
|
545
|
+
}
|
|
546
|
+
function lookupColumns(columns, groupBy) {
|
|
547
|
+
const out = {
|
|
548
|
+
costIdx: null,
|
|
549
|
+
dateIdx: null,
|
|
550
|
+
currencyIdx: null,
|
|
551
|
+
groupingIdx: /* @__PURE__ */ new Map()
|
|
552
|
+
};
|
|
553
|
+
const named = columns ?? [];
|
|
554
|
+
for (let i = 0; i < named.length; i++) {
|
|
555
|
+
const name = named[i]?.name ?? "";
|
|
556
|
+
const lower = name.toLowerCase();
|
|
557
|
+
if (lower === "cost" || lower === "costusd" || lower === "pretaxcost") {
|
|
558
|
+
out.costIdx = i;
|
|
559
|
+
} else if (lower === "usagedate" || lower === "date") {
|
|
560
|
+
out.dateIdx = i;
|
|
561
|
+
} else if (lower === "currency") {
|
|
562
|
+
out.currencyIdx = i;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
if (groupBy) {
|
|
566
|
+
for (const dim of groupBy) {
|
|
567
|
+
const wantName = dim.startsWith("TAG:") ? dim.slice(4) : dim;
|
|
568
|
+
const idx = named.findIndex(
|
|
569
|
+
(c) => (c.name ?? "").toLowerCase() === wantName.toLowerCase() || // Cost Management sometimes prefixes tag columns with TagValue.
|
|
570
|
+
(c.name ?? "").toLowerCase() === `tagvalue${wantName.toLowerCase()}`
|
|
571
|
+
);
|
|
572
|
+
if (idx >= 0) {
|
|
573
|
+
out.groupingIdx.set(dim, idx);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
return out;
|
|
578
|
+
}
|
|
579
|
+
function buildCostSamples(body, groupBy) {
|
|
580
|
+
const props = body.properties;
|
|
581
|
+
if (!props) {
|
|
582
|
+
return [];
|
|
583
|
+
}
|
|
584
|
+
const lookup = lookupColumns(props.columns, groupBy);
|
|
585
|
+
if (lookup.costIdx === null || lookup.dateIdx === null) {
|
|
586
|
+
return [];
|
|
587
|
+
}
|
|
588
|
+
const samples = [];
|
|
589
|
+
for (const row of props.rows ?? []) {
|
|
590
|
+
const rawCost = row[lookup.costIdx];
|
|
591
|
+
const rawDate = row[lookup.dateIdx];
|
|
592
|
+
if (rawCost === null || rawCost === void 0) {
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
const cost2 = typeof rawCost === "number" ? rawCost : Number.parseFloat(String(rawCost));
|
|
596
|
+
if (!Number.isFinite(cost2)) {
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
const ts = parseUsageDate(
|
|
600
|
+
typeof rawDate === "string" || typeof rawDate === "number" ? rawDate : null
|
|
601
|
+
);
|
|
602
|
+
if (ts === null) {
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
const currency = lookup.currencyIdx !== null ? row[lookup.currencyIdx] ?? null : null;
|
|
606
|
+
const attributes = {
|
|
607
|
+
unit: typeof currency === "string" ? currency : currency ?? "unknown"
|
|
608
|
+
};
|
|
609
|
+
for (const [dim, idx] of lookup.groupingIdx.entries()) {
|
|
610
|
+
const val = row[idx];
|
|
611
|
+
attributes[dimensionAttrKey(dim)] = typeof val === "string" || typeof val === "number" || val === null ? val : null;
|
|
612
|
+
}
|
|
613
|
+
samples.push({
|
|
614
|
+
name: DAILY_METRIC_NAME,
|
|
615
|
+
ts,
|
|
616
|
+
value: cost2,
|
|
617
|
+
attributes
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
return samples;
|
|
621
|
+
}
|
|
622
|
+
function mapArmError(err) {
|
|
623
|
+
if (!(err instanceof Error) || !("kind" in err)) {
|
|
624
|
+
return err;
|
|
625
|
+
}
|
|
626
|
+
const httpErr = err;
|
|
627
|
+
const status = httpErr.response?.status ?? 0;
|
|
628
|
+
if (status === 401 || status === 403) {
|
|
629
|
+
return new AuthError(httpErr.message, httpErr.response);
|
|
630
|
+
}
|
|
631
|
+
if (status === 429) {
|
|
632
|
+
return new RateLimitError(httpErr.message, httpErr.response);
|
|
633
|
+
}
|
|
634
|
+
if (status >= 500) {
|
|
635
|
+
return new TransientError(httpErr.message, httpErr.response);
|
|
636
|
+
}
|
|
637
|
+
return err;
|
|
638
|
+
}
|
|
639
|
+
function isAllowedArmUrl(value) {
|
|
640
|
+
try {
|
|
641
|
+
const u = new URL(value);
|
|
642
|
+
return u.protocol === "https:" && u.host === "management.azure.com";
|
|
643
|
+
} catch {
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
var id = "azure-cost";
|
|
648
|
+
var cost = {
|
|
649
|
+
recommendedInterval: "1 day",
|
|
650
|
+
minInterval: "1 hour",
|
|
651
|
+
warning: "Azure Cost Management queries are throttled aggressively per subscription; avoid syncing more often than necessary."
|
|
652
|
+
};
|
|
653
|
+
var AzureCostConnector = class _AzureCostConnector extends BaseConnector {
|
|
654
|
+
static id = id;
|
|
655
|
+
static resources = azureCostResources;
|
|
656
|
+
static schemas = schemasFromResources(azureCostResources);
|
|
657
|
+
static cost = cost;
|
|
658
|
+
static create(input, ctx) {
|
|
659
|
+
const parsed = configFields.parse(input);
|
|
660
|
+
return new _AzureCostConnector(
|
|
661
|
+
{
|
|
662
|
+
tenantId: parsed.tenantId,
|
|
663
|
+
clientId: parsed.clientId,
|
|
664
|
+
subscriptionId: parsed.subscriptionId,
|
|
665
|
+
groupBy: parsed.groupBy,
|
|
666
|
+
lookbackDays: parsed.lookbackDays
|
|
667
|
+
},
|
|
668
|
+
{ clientSecret: parsed.clientSecret },
|
|
669
|
+
ctx
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
id = id;
|
|
673
|
+
credentials = azureCostCredentials;
|
|
674
|
+
tokenCache = null;
|
|
675
|
+
async getAccessToken(signal) {
|
|
676
|
+
if (isTokenFresh(this.tokenCache)) {
|
|
677
|
+
return this.tokenCache.token;
|
|
678
|
+
}
|
|
679
|
+
this.tokenCache = await fetchArmAccessToken(
|
|
680
|
+
{
|
|
681
|
+
tenantId: this.settings.tenantId,
|
|
682
|
+
clientId: this.settings.clientId,
|
|
683
|
+
clientSecret: this.creds.clientSecret,
|
|
684
|
+
connectorId: this.id
|
|
685
|
+
},
|
|
686
|
+
signal
|
|
687
|
+
);
|
|
688
|
+
return this.tokenCache.token;
|
|
689
|
+
}
|
|
690
|
+
queryUrl() {
|
|
691
|
+
const params = new URLSearchParams();
|
|
692
|
+
params.set("api-version", COST_API_VERSION);
|
|
693
|
+
return `${ARM_HOST}/subscriptions/${encodeURIComponent(this.settings.subscriptionId)}/providers/Microsoft.CostManagement/query?${params.toString()}`;
|
|
694
|
+
}
|
|
695
|
+
buildQueryPayload(window) {
|
|
696
|
+
const groupBy = this.settings.groupBy ?? [];
|
|
697
|
+
const grouping = groupBy.slice(0, 2).map(toGrouping);
|
|
698
|
+
return {
|
|
699
|
+
type: "ActualCost",
|
|
700
|
+
timeframe: "Custom",
|
|
701
|
+
timePeriod: { from: window.from, to: window.to },
|
|
702
|
+
dataset: {
|
|
703
|
+
granularity: "Daily",
|
|
704
|
+
aggregation: {
|
|
705
|
+
totalCost: { name: "Cost", function: "Sum" }
|
|
706
|
+
},
|
|
707
|
+
...grouping.length > 0 ? { grouping } : {}
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
async runQuery(url, payload, signal) {
|
|
712
|
+
const token = await this.getAccessToken(signal);
|
|
713
|
+
try {
|
|
714
|
+
return await this.post(url, {
|
|
715
|
+
resource: "cost_query",
|
|
716
|
+
headers: {
|
|
717
|
+
Authorization: `Bearer ${token}`,
|
|
718
|
+
"Content-Type": "application/json",
|
|
719
|
+
Accept: "application/json",
|
|
720
|
+
"User-Agent": connectorUserAgent(this.id)
|
|
721
|
+
},
|
|
722
|
+
body: payload ? JSON.stringify(payload) : void 0,
|
|
723
|
+
signal
|
|
724
|
+
});
|
|
725
|
+
} catch (err) {
|
|
726
|
+
throw mapArmError(err);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
async sync(options, storage, signal) {
|
|
730
|
+
if (options.resources && options.resources.size > 0 && !options.resources.has("azure_cost_daily")) {
|
|
731
|
+
return { done: true };
|
|
732
|
+
}
|
|
733
|
+
const lookbackDays = this.settings.lookbackDays ?? DEFAULT_BACKFILL_DAYS;
|
|
734
|
+
const window = getCostWindow(options, lookbackDays);
|
|
735
|
+
const payload = this.buildQueryPayload(window);
|
|
736
|
+
const phaseStart = Date.now();
|
|
737
|
+
const samples = [];
|
|
738
|
+
let pages = 0;
|
|
739
|
+
let url = this.queryUrl();
|
|
740
|
+
let body = payload;
|
|
741
|
+
while (true) {
|
|
742
|
+
if (signal?.aborted) {
|
|
743
|
+
return { done: false };
|
|
744
|
+
}
|
|
745
|
+
const res = await this.runQuery(url, body, signal);
|
|
746
|
+
const chunk = buildCostSamples(res.body, this.settings.groupBy);
|
|
747
|
+
samples.push(...chunk);
|
|
748
|
+
pages += 1;
|
|
749
|
+
this.logger.info("fetched page", {
|
|
750
|
+
resource: "cost_query",
|
|
751
|
+
page: pages,
|
|
752
|
+
items: chunk.length
|
|
753
|
+
});
|
|
754
|
+
const next = res.body.properties?.nextLink;
|
|
755
|
+
if (typeof next === "string" && next.length > 0) {
|
|
756
|
+
if (!isAllowedArmUrl(next)) {
|
|
757
|
+
throw new UpstreamBugError(
|
|
758
|
+
`Azure Cost nextLink rejected by ARM host allowlist: ${next}`,
|
|
759
|
+
res
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
url = next;
|
|
763
|
+
body = void 0;
|
|
764
|
+
} else {
|
|
765
|
+
break;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
await storage.metrics(samples, { names: [DAILY_METRIC_NAME] });
|
|
769
|
+
this.logger.info("resource done", {
|
|
770
|
+
resource: "cost_query",
|
|
771
|
+
pages,
|
|
772
|
+
items: samples.length,
|
|
773
|
+
duration_ms: Date.now() - phaseStart
|
|
774
|
+
});
|
|
775
|
+
return { done: true };
|
|
776
|
+
}
|
|
777
|
+
};
|
|
778
|
+
|
|
779
|
+
// src/index.ts
|
|
780
|
+
var index_default = AzureCostConnector;
|
|
781
|
+
export {
|
|
782
|
+
AzureCostConnector,
|
|
783
|
+
configFields,
|
|
784
|
+
cost,
|
|
785
|
+
index_default as default,
|
|
786
|
+
doc,
|
|
787
|
+
id,
|
|
788
|
+
azureCostResources as resources
|
|
789
|
+
};
|
|
790
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/azure-cost.ts","../src/auth.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n AuthError,\n type HttpResponse,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n connectorUserAgent,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ConnectorContext,\n type ConnectorCost,\n type ConnectorDoc,\n type CredentialsSchema,\n type JSONValue,\n type MetricSample,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n schemasFromResources,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nimport {\n type TokenCacheEntry,\n fetchArmAccessToken,\n isTokenFresh,\n} from './auth';\n\n// ---------------------------------------------------------------------------\n// configFields\n// ---------------------------------------------------------------------------\n\nconst dimensionValues = [\n 'ResourceGroup',\n 'ResourceGroupName',\n 'ServiceName',\n 'ServiceTier',\n 'Meter',\n 'MeterCategory',\n 'MeterSubCategory',\n 'ResourceId',\n 'ResourceType',\n 'ResourceLocation',\n 'ChargeType',\n 'PublisherType',\n 'BillingPeriod',\n 'InvoiceId',\n 'SubscriptionId',\n 'SubscriptionName',\n] as const;\n\ntype CostDimension = (typeof dimensionValues)[number];\n\nconst groupByEntrySchema = z\n .string()\n .min(1)\n .regex(\n new RegExp(`^(${dimensionValues.join('|')}|TAG:.+)$`),\n `groupBy entries must be one of ${dimensionValues.join(', ')}, or TAG:<tag-key>`,\n );\n\nexport const configFields = defineConfigFields(\n z.object({\n tenantId: z.string().min(1).meta({\n label: 'Tenant ID',\n description:\n 'Microsoft Entra ID (Azure AD) tenant ID - the directory that hosts the app registration.',\n placeholder: '00000000-0000-0000-0000-000000000000',\n }),\n clientId: z.string().min(1).meta({\n label: 'Client ID',\n description:\n 'Application (client) ID of the Entra ID app registration / service principal used for authentication.',\n placeholder: '00000000-0000-0000-0000-000000000000',\n }),\n clientSecret: z.object({ $secret: z.string().min(1) }).meta({\n label: 'Client secret',\n description:\n 'Client secret of the Entra ID app registration. Generate one under App registrations → Certificates & secrets.',\n placeholder: 'azure-client-secret',\n secret: true,\n }),\n subscriptionId: z.string().min(1).meta({\n label: 'Subscription ID',\n description:\n 'Azure subscription ID the cost query is scoped to. The service principal needs Cost Management Reader (or Reader) on this subscription.',\n placeholder: '00000000-0000-0000-0000-000000000000',\n }),\n groupBy: z\n .array(groupByEntrySchema)\n .max(2, 'Cost Management accepts at most two grouping dimensions')\n .optional()\n .meta({\n label: 'Group by (optional)',\n description:\n 'Up to two Cost Management dimensions to break costs down by, e.g. ServiceName, ResourceGroup, or TAG:Environment. Omit for total cost only.',\n }),\n lookbackDays: z.number().int().positive().max(365).optional().meta({\n label: 'Backfill window (days)',\n description:\n 'How many days of history to fetch on a full sync. Defaults to 90.',\n placeholder: '90',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Azure Cost Management',\n category: 'finance',\n brandColor: '#0078D4',\n tagline:\n 'Track daily Azure spend over time, optionally broken down by resource group, service, or tag, via the Cost Management query API.',\n vendor: {\n name: 'Microsoft Azure',\n apiDocs: 'https://learn.microsoft.com/en-us/rest/api/cost-management/',\n website: 'https://azure.microsoft.com/en-us/products/cost-management',\n },\n auth: {\n summary:\n 'Authenticates with a Microsoft Entra ID (Azure AD) service principal (tenant ID + client ID + client secret) scoped to the target subscription. The principal needs the built-in Cost Management Reader role at the subscription scope (or Reader).',\n setup: [\n 'In the Azure portal open Microsoft Entra ID → App registrations → New registration and create an app for rawdash.',\n 'Under Certificates & secrets, generate a client secret and copy its value (it is only shown once).',\n 'In the target subscription open Access control (IAM) → Add role assignment and grant the new service principal the built-in Cost Management Reader role.',\n 'Store the client secret as a secret and reference it from config as `clientSecret: secret(\"AZ_CLIENT_SECRET\")`, alongside `tenantId`, `clientId`, and `subscriptionId`.',\n 'Cost Management must be enabled for the subscription; the first activation can take up to 24 hours before data is queryable.',\n ],\n },\n rateLimit:\n 'Cost Management throttles via 429 responses with Retry-After; the shared HTTP client honors Retry-After and backs off on 429.',\n limitations: [\n 'Cost data can be revised for a couple of days after the fact, so incremental syncs refetch a short trailing window.',\n 'Daily granularity only (the most common dashboard slice). Monthly granularity is not exposed in v1.',\n 'At most two grouping dimensions are accepted per query (Cost Management limit).',\n 'Forecast (`forecast` endpoint) is not synced in v1; only historical actual cost.',\n ],\n});\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface AzureCostSettings {\n tenantId: string;\n clientId: string;\n subscriptionId: string;\n groupBy?: readonly string[];\n lookbackDays?: number;\n}\n\nconst azureCostCredentials = {\n clientSecret: {\n description: 'Azure AD app-registration client secret',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype AzureCostCredentials = typeof azureCostCredentials;\n\n// ---------------------------------------------------------------------------\n// API response schemas\n// ---------------------------------------------------------------------------\n\nconst costColumnSchema = z.object({\n name: z.string(),\n type: z.string().optional(),\n});\n\nconst costRowSchema = z.array(z.union([z.string(), z.number(), z.null()]));\n\nconst costQueryResponseSchema = z.object({\n id: z.string().optional(),\n name: z.string().optional(),\n type: z.string().optional(),\n properties: z.object({\n nextLink: z.string().nullish(),\n columns: z.array(costColumnSchema),\n rows: z.array(costRowSchema),\n }),\n});\n\n// ---------------------------------------------------------------------------\n// Runtime response shapes (permissive — assertions live in the Zod schemas)\n// ---------------------------------------------------------------------------\n\ninterface CostColumn {\n name?: string;\n type?: string;\n}\n\ninterface CostQueryProperties {\n nextLink?: string | null;\n columns?: CostColumn[];\n rows?: Array<Array<string | number | null>>;\n}\n\ninterface CostQueryResponseBody {\n properties?: CostQueryProperties;\n}\n\n// ---------------------------------------------------------------------------\n// Resources\n// ---------------------------------------------------------------------------\n\nconst DAILY_METRIC_NAME = 'azure_cost_daily';\n\nexport const azureCostResources = defineResources({\n azure_cost_daily: {\n shape: 'metric',\n description:\n 'Daily Azure actual cost per time bucket, optionally split across the configured group-by dimensions.',\n endpoint:\n 'POST /subscriptions/{subId}/providers/Microsoft.CostManagement/query',\n unit: 'currency reported by Azure',\n granularity: 'daily',\n notes:\n 'Cost data can be revised for a couple of days after the fact, so incremental syncs refetch a short trailing window. Cost Management accepts at most two grouping dimensions per query.',\n dimensions: [\n {\n name: 'unit',\n description: 'Currency reported by Azure (e.g. USD, EUR).',\n },\n {\n name: 'service_name',\n description:\n 'Azure service name, present when grouping by ServiceName (other dimensions appear under their normalized key, e.g. resource_group, tag_<key>).',\n },\n ],\n responses: { cost_query: costQueryResponseSchema },\n },\n});\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ARM_HOST = 'https://management.azure.com';\nconst COST_API_VERSION = '2024-08-01';\nconst DEFAULT_BACKFILL_DAYS = 90;\nconst INCREMENTAL_LOOKBACK_DAYS = 3;\nconst MS_PER_DAY = 86_400_000;\n\n// ---------------------------------------------------------------------------\n// Pure helpers — exported for unit testing\n// ---------------------------------------------------------------------------\n\nfunction startOfUtcDay(ms: number): number {\n return Math.floor(ms / MS_PER_DAY) * MS_PER_DAY;\n}\n\nexport interface CostWindow {\n from: string;\n to: string;\n}\n\nexport function getCostWindow(\n options: SyncOptions,\n lookbackDays: number,\n now: number = Date.now(),\n): CostWindow {\n const sinceMs = options.since !== undefined ? Date.parse(options.since) : NaN;\n const hasSince = Number.isFinite(sinceMs);\n\n let days = lookbackDays;\n if (options.mode === 'latest') {\n days = INCREMENTAL_LOOKBACK_DAYS;\n } else if (hasSince) {\n const elapsed = Math.ceil((now - sinceMs) / MS_PER_DAY);\n days = Math.min(Math.max(elapsed, 1), lookbackDays);\n }\n // Inclusive end at end of today UTC so the still-estimating current day is\n // captured and overwritten on each later sync.\n const todayStart = startOfUtcDay(now);\n const fromMs = todayStart - (days - 1) * MS_PER_DAY;\n const toMs = todayStart + MS_PER_DAY - 1;\n return {\n from: new Date(fromMs).toISOString(),\n to: new Date(toMs).toISOString(),\n };\n}\n\nfunction dimensionAttrKey(dimension: string): string {\n if (dimension.startsWith('TAG:')) {\n return `tag_${dimension.slice(4)}`;\n }\n // Normalize dimension names (\"ResourceGroup\" → \"resource_group\") so attribute\n // keys are stable regardless of the case Azure echoes back in column headers.\n return dimension\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')\n .toLowerCase();\n}\n\nfunction toGrouping(dimension: string): { type: string; name: string } {\n if (dimension.startsWith('TAG:')) {\n return { type: 'Tag', name: dimension.slice(4) };\n }\n return { type: 'Dimension', name: dimension };\n}\n\nfunction parseUsageDate(value: string | number | null): number | null {\n if (value === null) {\n return null;\n }\n // Cost Management returns UsageDate as an integer YYYYMMDD (column type\n // 'Number') for Daily granularity. We normalize to the start-of-day Unix ms.\n const s = String(value);\n const m = /^(\\d{4})(\\d{2})(\\d{2})$/.exec(s);\n if (!m) {\n return null;\n }\n const ts = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));\n return Number.isFinite(ts) ? ts : null;\n}\n\ninterface ColumnLookup {\n costIdx: number | null;\n dateIdx: number | null;\n currencyIdx: number | null;\n // Map of grouping dimension (as configured) -> column index.\n groupingIdx: Map<string, number>;\n}\n\nfunction lookupColumns(\n columns: CostColumn[] | undefined,\n groupBy: readonly string[] | undefined,\n): ColumnLookup {\n const out: ColumnLookup = {\n costIdx: null,\n dateIdx: null,\n currencyIdx: null,\n groupingIdx: new Map(),\n };\n const named = columns ?? [];\n for (let i = 0; i < named.length; i++) {\n const name = named[i]?.name ?? '';\n const lower = name.toLowerCase();\n if (lower === 'cost' || lower === 'costusd' || lower === 'pretaxcost') {\n out.costIdx = i;\n } else if (lower === 'usagedate' || lower === 'date') {\n out.dateIdx = i;\n } else if (lower === 'currency') {\n out.currencyIdx = i;\n }\n }\n if (groupBy) {\n for (const dim of groupBy) {\n const wantName = dim.startsWith('TAG:') ? dim.slice(4) : dim;\n const idx = named.findIndex(\n (c) =>\n (c.name ?? '').toLowerCase() === wantName.toLowerCase() ||\n // Cost Management sometimes prefixes tag columns with TagValue.\n (c.name ?? '').toLowerCase() === `tagvalue${wantName.toLowerCase()}`,\n );\n if (idx >= 0) {\n out.groupingIdx.set(dim, idx);\n }\n }\n }\n return out;\n}\n\nexport function buildCostSamples(\n body: CostQueryResponseBody,\n groupBy: readonly string[] | undefined,\n): MetricSample[] {\n const props = body.properties;\n if (!props) {\n return [];\n }\n const lookup = lookupColumns(props.columns, groupBy);\n if (lookup.costIdx === null || lookup.dateIdx === null) {\n return [];\n }\n const samples: MetricSample[] = [];\n for (const row of props.rows ?? []) {\n const rawCost = row[lookup.costIdx];\n const rawDate = row[lookup.dateIdx];\n if (rawCost === null || rawCost === undefined) {\n continue;\n }\n const cost =\n typeof rawCost === 'number'\n ? rawCost\n : Number.parseFloat(String(rawCost));\n if (!Number.isFinite(cost)) {\n continue;\n }\n const ts = parseUsageDate(\n typeof rawDate === 'string' || typeof rawDate === 'number'\n ? rawDate\n : null,\n );\n if (ts === null) {\n continue;\n }\n const currency =\n lookup.currencyIdx !== null ? (row[lookup.currencyIdx] ?? null) : null;\n const attributes: Record<string, JSONValue> = {\n unit: typeof currency === 'string' ? currency : (currency ?? 'unknown'),\n };\n for (const [dim, idx] of lookup.groupingIdx.entries()) {\n const val = row[idx];\n attributes[dimensionAttrKey(dim)] =\n typeof val === 'string' || typeof val === 'number' || val === null\n ? val\n : null;\n }\n samples.push({\n name: DAILY_METRIC_NAME,\n ts,\n value: cost,\n attributes,\n });\n }\n return samples;\n}\n\n// ---------------------------------------------------------------------------\n// Error mapping\n// ---------------------------------------------------------------------------\n\nfunction mapArmError(err: unknown): unknown {\n if (!(err instanceof Error) || !('kind' in err)) {\n return err;\n }\n const httpErr = err as Error & { response?: HttpResponse };\n const status = httpErr.response?.status ?? 0;\n if (status === 401 || status === 403) {\n return new AuthError(httpErr.message, httpErr.response);\n }\n if (status === 429) {\n return new RateLimitError(httpErr.message, httpErr.response);\n }\n if (status >= 500) {\n return new TransientError(httpErr.message, httpErr.response);\n }\n return err;\n}\n\n// nextLink can be a fully-qualified URL Azure hands back; sanitize before reuse\n// so a corrupted cursor cannot exfiltrate the bearer token to an attacker host.\nfunction isAllowedArmUrl(value: string): boolean {\n try {\n const u = new URL(value);\n return u.protocol === 'https:' && u.host === 'management.azure.com';\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// AzureCostConnector\n// ---------------------------------------------------------------------------\n\nexport const id = 'azure-cost';\n\nexport const cost: ConnectorCost = {\n recommendedInterval: '1 day',\n minInterval: '1 hour',\n warning:\n 'Azure Cost Management queries are throttled aggressively per subscription; avoid syncing more often than necessary.',\n};\n\nexport class AzureCostConnector extends BaseConnector<\n AzureCostSettings,\n AzureCostCredentials\n> {\n static readonly id = id;\n\n static readonly resources = azureCostResources;\n\n static readonly schemas = schemasFromResources(azureCostResources);\n\n static readonly cost = cost;\n\n static create(input: unknown, ctx?: ConnectorContext): AzureCostConnector {\n const parsed = configFields.parse(input);\n return new AzureCostConnector(\n {\n tenantId: parsed.tenantId,\n clientId: parsed.clientId,\n subscriptionId: parsed.subscriptionId,\n groupBy: parsed.groupBy,\n lookbackDays: parsed.lookbackDays,\n },\n { clientSecret: parsed.clientSecret },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = azureCostCredentials;\n\n private tokenCache: TokenCacheEntry | null = null;\n\n private async getAccessToken(signal?: AbortSignal): Promise<string> {\n if (isTokenFresh(this.tokenCache)) {\n return this.tokenCache!.token;\n }\n this.tokenCache = await fetchArmAccessToken(\n {\n tenantId: this.settings.tenantId,\n clientId: this.settings.clientId,\n clientSecret: this.creds.clientSecret,\n connectorId: this.id,\n },\n signal,\n );\n return this.tokenCache.token;\n }\n\n private queryUrl(): string {\n const params = new URLSearchParams();\n params.set('api-version', COST_API_VERSION);\n return `${ARM_HOST}/subscriptions/${encodeURIComponent(this.settings.subscriptionId)}/providers/Microsoft.CostManagement/query?${params.toString()}`;\n }\n\n private buildQueryPayload(window: CostWindow): Record<string, unknown> {\n const groupBy = this.settings.groupBy ?? [];\n const grouping = groupBy.slice(0, 2).map(toGrouping);\n return {\n type: 'ActualCost',\n timeframe: 'Custom',\n timePeriod: { from: window.from, to: window.to },\n dataset: {\n granularity: 'Daily',\n aggregation: {\n totalCost: { name: 'Cost', function: 'Sum' },\n },\n ...(grouping.length > 0 ? { grouping } : {}),\n },\n };\n }\n\n private async runQuery(\n url: string,\n payload: Record<string, unknown> | undefined,\n signal?: AbortSignal,\n ): Promise<HttpResponse<CostQueryResponseBody>> {\n const token = await this.getAccessToken(signal);\n try {\n return await this.post<CostQueryResponseBody>(url, {\n resource: 'cost_query',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent(this.id),\n },\n body: payload ? JSON.stringify(payload) : undefined,\n signal,\n });\n } catch (err) {\n throw mapArmError(err);\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n if (\n options.resources &&\n options.resources.size > 0 &&\n !options.resources.has('azure_cost_daily')\n ) {\n return { done: true };\n }\n\n const lookbackDays = this.settings.lookbackDays ?? DEFAULT_BACKFILL_DAYS;\n const window = getCostWindow(options, lookbackDays);\n const payload = this.buildQueryPayload(window);\n const phaseStart = Date.now();\n const samples: MetricSample[] = [];\n let pages = 0;\n\n let url = this.queryUrl();\n let body: Record<string, unknown> | undefined = payload;\n while (true) {\n if (signal?.aborted) {\n return { done: false };\n }\n const res = await this.runQuery(url, body, signal);\n const chunk = buildCostSamples(res.body, this.settings.groupBy);\n samples.push(...chunk);\n pages += 1;\n this.logger.info('fetched page', {\n resource: 'cost_query',\n page: pages,\n items: chunk.length,\n });\n const next = res.body.properties?.nextLink;\n if (typeof next === 'string' && next.length > 0) {\n if (!isAllowedArmUrl(next)) {\n throw new UpstreamBugError(\n `Azure Cost nextLink rejected by ARM host allowlist: ${next}`,\n res,\n );\n }\n url = next;\n // Cost Management's nextLink is a continuation token URL; the request\n // body is empty on subsequent calls.\n body = undefined;\n } else {\n break;\n }\n }\n\n await storage.metrics(samples, { names: [DAILY_METRIC_NAME] });\n this.logger.info('resource done', {\n resource: 'cost_query',\n pages,\n items: samples.length,\n duration_ms: Date.now() - phaseStart,\n });\n return { done: true };\n }\n}\n\n// Exported only so it shows up in the connector's typed surface for tests.\nexport type { CostDimension };\n","import {\n AuthError,\n type HttpResponse,\n TransientError,\n connectorUserAgent,\n request as sharedRequest,\n} from '@rawdash/connector-shared';\n\n// Azure AD client-credentials token caching, scoped to ARM\n// (https://management.azure.com/.default). Both Monitor and Cost connectors\n// share an identical flow against the Microsoft Entra ID token endpoint, so the\n// helper is co-located in each package (rather than a shared sub-package, which\n// would force consumers to install a second runtime dependency).\n\nconst TOKEN_HOST = 'login.microsoftonline.com';\nconst ARM_SCOPE = 'https://management.azure.com/.default';\nconst TOKEN_TTL_BUFFER_MS = 60_000;\n\nexport interface AzureAuthInput {\n tenantId: string;\n clientId: string;\n clientSecret: string;\n connectorId: string;\n}\n\ninterface TokenResponse {\n access_token?: string;\n expires_in?: number;\n token_type?: string;\n}\n\nexport interface TokenCacheEntry {\n token: string;\n expiresAt: number;\n}\n\nexport async function fetchArmAccessToken(\n input: AzureAuthInput,\n signal?: AbortSignal,\n): Promise<TokenCacheEntry> {\n const params = new URLSearchParams();\n params.set('grant_type', 'client_credentials');\n params.set('client_id', input.clientId);\n params.set('client_secret', input.clientSecret);\n params.set('scope', ARM_SCOPE);\n\n let res: HttpResponse<TokenResponse>;\n try {\n res = await sharedRequest<TokenResponse>(\n {\n url: `https://${TOKEN_HOST}/${encodeURIComponent(input.tenantId)}/oauth2/v2.0/token`,\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent(input.connectorId),\n },\n body: params.toString(),\n signal,\n },\n { resource: 'oauth_token' },\n );\n } catch (err) {\n throw classifyTokenError(err);\n }\n\n const access = res.body.access_token;\n const expiresIn = res.body.expires_in;\n if (typeof access !== 'string' || access.length === 0) {\n throw new AuthError(\n 'Azure AD token response did not include an access_token',\n );\n }\n const ttlMs =\n typeof expiresIn === 'number' && Number.isFinite(expiresIn)\n ? expiresIn * 1000\n : 60 * 60 * 1000;\n return {\n token: access,\n expiresAt: Date.now() + ttlMs - TOKEN_TTL_BUFFER_MS,\n };\n}\n\nfunction classifyTokenError(err: unknown): unknown {\n if (!(err instanceof Error) || !('kind' in err)) {\n return err;\n }\n const httpErr = err as Error & { response?: HttpResponse };\n const status = httpErr.response?.status ?? 0;\n if (status === 400 || status === 401 || status === 403) {\n return new AuthError(httpErr.message, httpErr.response);\n }\n if (status >= 500) {\n return new TransientError(httpErr.message, httpErr.response);\n }\n return err;\n}\n\nexport function isTokenFresh(\n cache: TokenCacheEntry | null,\n now: number = Date.now(),\n): boolean {\n return cache !== null && now < cache.expiresAt;\n}\n","import { AzureCostConnector } from './azure-cost';\n\nexport {\n AzureCostConnector,\n azureCostResources as resources,\n configFields,\n cost,\n doc,\n id,\n} from './azure-cost';\nexport type { AzureCostSettings, CostWindow } from './azure-cost';\nexport default AzureCostConnector;\n"],"mappings":";AASO,IAAe,kBAAf,cAAuC,MAAM;EAEzC;EAET,YAAY,SAAiB,UAAyB;AACpD,UAAM,OAAO;AACb,SAAK,OAAO,WAAW;AACvB,SAAK,WAAW;EAClB;AACF;AAEO,IAAM,iBAAN,cAA6B,gBAAgB;EACzC,OAAO;AAClB;AAEO,IAAM,iBAAN,cAA6B,gBAAgB;EACzC,OAAO;EACP;EAET,YAAY,SAAiB,UAAyB,YAAmB;AACvE,UAAM,SAAS,QAAQ;AACvB,SAAK,aAAa;EACpB;AAC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MAAM,KAAK,SAAS,OAAO;AAC9D,cAAQ,KAAK,GAAG,KAAK;AACrB,eAAS;AACT,WAAK,OAAO,KAAK,gBAAgB;AAAA,QAC/B,UAAU;AAAA,QACV,MAAM;AAAA,QACN,OAAO,MAAM;AAAA,MACf,CAAC;AACD,YAAM,OAAO,IAAI,KAAK,YAAY;AAClC,UAAI,OAAO,SAAS,YAAY,KAAK,SAAS,GAAG;AAC/C,YAAI,CAAC,gBAAgB,IAAI,GAAG;AAC1B,gBAAM,IAAI;AAAA,YACR,uDAAuD,IAAI;AAAA,YAC3D;AAAA,UACF;AAAA,QACF;AACA,cAAM;AAGN,eAAO;AAAA,MACT,OAAO;AACL;AAAA,MACF;AAAA,IACF;AAEA,UAAM,QAAQ,QAAQ,SAAS,EAAE,OAAO,CAAC,iBAAiB,EAAE,CAAC;AAC7D,SAAK,OAAO,KAAK,iBAAiB;AAAA,MAChC,UAAU;AAAA,MACV;AAAA,MACA,OAAO,QAAQ;AAAA,MACf,aAAa,KAAK,IAAI,IAAI;AAAA,IAC5B,CAAC;AACD,WAAO,EAAE,MAAM,KAAK;AAAA,EACtB;AACF;;;AEpmBA,IAAO,gBAAQ;","names":["err","cost"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rawdash/connector-azure-cost",
|
|
3
|
+
"version": "0.17.0",
|
|
4
|
+
"description": "Rawdash connector for Azure Cost Management — pulls daily Azure spend (optionally grouped by resource group, service, or tag) into the six-shape storage model via the Cost Management query API",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/rawdash/rawdash.git",
|
|
11
|
+
"directory": "packages/connectors/azure-cost"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"@rawdash/source": "./src/index.ts",
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsup",
|
|
27
|
+
"typecheck": "tsc --noEmit",
|
|
28
|
+
"lint": "eslint src",
|
|
29
|
+
"test": "vitest run"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@rawdash/core": "workspace:*",
|
|
33
|
+
"zod": "^4.4.3"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@rawdash/connector-shared": "workspace:*",
|
|
37
|
+
"@rawdash/connector-test-utils": "workspace:*",
|
|
38
|
+
"fast-check": "^4.8.0",
|
|
39
|
+
"tsup": "^8.0.0",
|
|
40
|
+
"typescript": "^5.7.2",
|
|
41
|
+
"vitest": "^4.1.4"
|
|
42
|
+
}
|
|
43
|
+
}
|