-
Notifications
You must be signed in to change notification settings - Fork 46
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adds typespec-azure-telemetry package #2156
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
--- | ||
changeKind: feature | ||
packages: | ||
- "@azure-tools/typespec-azure-telemetry" | ||
--- | ||
|
||
Adds the @azure-tools/typespec-azure-telemetry package |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# Change Log - @azure-tools/typespec-azure-telemetry |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) Microsoft Corporation. All rights reserved. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
# @azure-tools/typespec-azure-telemetry | ||
|
||
TypeSpec Azure Telemetry package | ||
|
||
## Install | ||
|
||
```bash | ||
npm install @azure-tools/typespec-azure-telemetry | ||
``` | ||
|
||
## Telemetry Configuration | ||
|
||
Telemetry collection is on by default. | ||
|
||
To opt out, set the environment variable `DISABLE_TYPESPEC_AZURE_TELEMETRY` to a truthy value. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can add basic docs on how to use this package? |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
{ | ||
"name": "@azure-tools/typespec-azure-telemetry", | ||
"version": "0.50.0", | ||
"author": "Microsoft Corporation", | ||
"description": "TypeSpec Azure Telemetry library", | ||
"homepage": "https://azure.github.io/typespec-azure", | ||
"docusaurusWebsite": "https://azure.github.io/typespec-azure/docs", | ||
"readme": "https://github.com/Azure/typespec-azure/blob/main/packages/typespec-azure-telemetry/README.md", | ||
"license": "MIT", | ||
"repository": { | ||
"type": "git", | ||
"url": "git+https://github.com/Azure/typespec-azure.git" | ||
}, | ||
"bugs": { | ||
"url": "https://github.com/Azure/typespec-azure/issues" | ||
}, | ||
"keywords": [ | ||
"typespec" | ||
], | ||
"main": "dist/src/index.js", | ||
"exports": { | ||
".": { | ||
"types": "./dist/src/index.d.ts", | ||
"default": "./dist/src/index.js" | ||
} | ||
}, | ||
"browser": { | ||
"./dist/src/reporters/telemetry-reporter.js": "./dist/src/reporters/no-op-reporter.js", | ||
"./dist/src/utils/common-properties.js": "./dist/src/utils/common-properties.browser.js", | ||
"./dist/src/utils/config.js": "./dist/src/utils/config.browser.js", | ||
"./dist/src/utils/machine-id.js": "./dist/src/utils/machine-id.browser.js" | ||
}, | ||
"type": "module", | ||
"engines": { | ||
"node": ">=18.0.0" | ||
}, | ||
"scripts": { | ||
"clean": "rimraf ./dist ./temp", | ||
"build": "tsc -p .", | ||
"watch": "tsc -p . --watch", | ||
"test": "vitest run", | ||
"test:watch": "vitest -w", | ||
"test:ui": "vitest --ui", | ||
"test:ci": "vitest run --coverage --reporter=junit --reporter=default", | ||
"lint": "eslint . --max-warnings=0", | ||
"lint:fix": "eslint . --fix " | ||
}, | ||
"files": [ | ||
"dist/**", | ||
"!dist/test/**" | ||
], | ||
"dependencies": { | ||
"@microsoft/applicationinsights-common": "^3.3.4", | ||
"@microsoft/applicationinsights-web-basic": "^3.3.4" | ||
}, | ||
"devDependencies": { | ||
"@types/node": "~22.10.10", | ||
"@vitest/coverage-v8": "^3.0.4", | ||
"@vitest/ui": "^3.0.3", | ||
"c8": "^10.1.3", | ||
"rimraf": "~6.0.1", | ||
"typescript": "~5.7.3", | ||
"vitest": "^3.0.4" | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { BreezeChannelIdentifier } from "@microsoft/applicationinsights-common"; | ||
import { ApplicationInsights } from "@microsoft/applicationinsights-web-basic"; | ||
import { ExtensionConfig } from "../reporters/types.js"; | ||
|
||
export interface GetAppInsightsClientProps { | ||
endpointUrl?: string; | ||
httpXHROverride: ExtensionConfig["httpXHROverride"]; | ||
instrumentationKey: string; | ||
} | ||
|
||
export function getAppInsightsClient(props: GetAppInsightsClientProps): ApplicationInsights { | ||
const appInsightsClient = new ApplicationInsights({ | ||
instrumentationKey: props.instrumentationKey, | ||
endpointUrl: props.endpointUrl, | ||
autoTrackPageVisitTime: false, | ||
disableAjaxTracking: true, | ||
disableExceptionTracking: true, | ||
disableFetchTracking: true, | ||
disableCorrelationHeaders: true, | ||
disableCookiesUsage: true, | ||
disableFlushOnBeforeUnload: true, | ||
disableFlushOnUnload: true, | ||
emitLineDelimitedJson: true, | ||
maxBatchInterval: 100, // 100 ms | ||
extensionConfig: { | ||
[BreezeChannelIdentifier]: { | ||
alwaysUseXhrOverride: true, | ||
httpXHROverride: props.httpXHROverride, | ||
}, | ||
}, | ||
}); | ||
|
||
return appInsightsClient; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { ExtensionConfig } from "../reporters/types.js"; | ||
|
||
export function getFetchHttpOverride(): ExtensionConfig["httpXHROverride"] { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. whats the reason for those overrides, can add a comment? |
||
return { | ||
sendPOST: (payload, onComplete) => { | ||
fetch(payload.urlString, { | ||
method: "POST", | ||
headers: { | ||
...payload.headers, | ||
}, | ||
body: payload.data, | ||
}) | ||
.then(async (response) => { | ||
const body = await response.text(); | ||
onComplete(response.status, convertHeadersToRecord(response.headers), body); | ||
}) | ||
.catch(() => { | ||
// set to 0 so we can retry events | ||
onComplete(0, {}); | ||
}); | ||
}, | ||
}; | ||
} | ||
|
||
function convertHeadersToRecord(headers: Headers): Record<string, string> { | ||
const result: Record<string, string> = {}; | ||
headers.forEach((value, key) => { | ||
result[key] = value; | ||
}); | ||
return result; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import type { IncomingHttpHeaders } from "http"; | ||
import * as https from "https"; | ||
import { ExtensionConfig } from "../reporters/types.js"; | ||
|
||
export function getNodeHttpOverride(): ExtensionConfig["httpXHROverride"] { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same here |
||
return { | ||
sendPOST: (payload, onComplete) => { | ||
const req = https.request(payload.urlString, { | ||
method: "POST", | ||
headers: { | ||
...payload.headers, | ||
"Content-Type": "application/json", | ||
}, | ||
}); | ||
|
||
req.on("error", () => onComplete(0, {})); | ||
req.on("response", (res) => { | ||
const statusCode = res.statusCode; | ||
if (!statusCode) { | ||
onComplete(0, {}); | ||
return; | ||
} | ||
|
||
res.on("error", () => onComplete(0, {})); | ||
|
||
let body = ""; | ||
res.on("data", (chunk) => { | ||
body += chunk.toString(); | ||
}); | ||
res.on("end", () => { | ||
const headers = convertHeadersToRecord(res.headers); | ||
onComplete(statusCode, headers, body); | ||
}); | ||
}); | ||
|
||
req.write(payload.data); | ||
req.end(); | ||
}, | ||
}; | ||
} | ||
|
||
function convertHeadersToRecord(headers: IncomingHttpHeaders): Record<string, string> { | ||
const result: Record<string, string> = {}; | ||
for (const name of Object.keys(headers)) { | ||
const value = headers[name]; | ||
if (Array.isArray(value)) { | ||
result[name] = value.join(", "); | ||
} else if (typeof value === "string") { | ||
result[name] = value; | ||
} | ||
} | ||
return result; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
export { createTelemetryReporter as createNoOpTelemetryReporter } from "./reporters/no-op-reporter.js"; | ||
export { createTelemetryReporter } from "./reporters/telemetry-reporter.js"; | ||
|
||
export { CreateTelemetryReporterProps, TelemetryReporter } from "./reporters/types.js"; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import { TelemetryReporter } from "./types.js"; | ||
|
||
export function createTelemetryReporter(): TelemetryReporter { | ||
return { | ||
logEvent() { | ||
// do nothing | ||
}, | ||
flush() { | ||
// do nothing | ||
}, | ||
}; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
import { ContextTagKeys } from "@microsoft/applicationinsights-common"; | ||
import { getAppInsightsClient } from "../clients/app-insights.js"; | ||
import { getFetchHttpOverride } from "../http-overrides/fetch.js"; | ||
import { getNodeHttpOverride } from "../http-overrides/node-http.js"; | ||
import { getCommonProperties } from "../utils/common-properties.js"; | ||
import { isTelemetryDisabled } from "../utils/config.js"; | ||
import { getMachineId } from "../utils/machine-id.js"; | ||
import { supportsFetch } from "../utils/supports-fetch.js"; | ||
import { createTelemetryReporter as createNoOpTelemetryReporter } from "./no-op-reporter.js"; | ||
import { CreateTelemetryReporterProps, TelemetryReporter } from "./types.js"; | ||
|
||
export function createTelemetryReporter(props: CreateTelemetryReporterProps): TelemetryReporter { | ||
try { | ||
// Some quick checking to return no-op reporter | ||
if (!props || !props.instrumentationKey || isTelemetryDisabled()) { | ||
return createNoOpTelemetryReporter(); | ||
} | ||
|
||
const appInsightsClient = getAppInsightsClient({ | ||
instrumentationKey: props.instrumentationKey, | ||
httpXHROverride: supportsFetch() ? getFetchHttpOverride() : getNodeHttpOverride(), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. don't we always have fetch? compiler depends on it too |
||
endpointUrl: props.endpointUrl, | ||
}); | ||
|
||
const commonProps = getCommonProperties(); | ||
const machineId = getMachineId(); | ||
|
||
const tags = new ContextTagKeys(); | ||
return { | ||
logEvent(eventName, data) { | ||
try { | ||
appInsightsClient.track({ | ||
name: eventName, | ||
data: data, | ||
baseType: "EventData", | ||
ext: { | ||
user: { | ||
id: machineId, | ||
}, | ||
}, | ||
tags: { [tags.sessionId]: commonProps.sessionId }, | ||
baseData: { | ||
name: eventName, | ||
properties: { | ||
...commonProps, | ||
...data.properties, | ||
}, | ||
measurements: data.measurements, | ||
}, | ||
}); | ||
} catch { | ||
// Ignore any errors - any telemetry errors should not affect the main application | ||
} | ||
}, | ||
flush() { | ||
try { | ||
// Setting async to false causes the flush to be processed immediately without delay. | ||
// The actual HTTP requests are still async. | ||
appInsightsClient.flush(false); | ||
} catch { | ||
// Ignore any errors - any telemetry errors should not affect the main application | ||
} | ||
}, | ||
}; | ||
} catch { | ||
// If any errors are encountered, fallback to a no-op reporter to prevent errors | ||
// impacting the actual application. | ||
return createNoOpTelemetryReporter(); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import type { ISenderConfig } from "@microsoft/applicationinsights-web-basic"; | ||
|
||
export interface LogEventData { | ||
properties?: Record<string, string | undefined>; | ||
measurements?: Record<string, number | undefined>; | ||
} | ||
|
||
export interface TelemetryReporter { | ||
/** | ||
* Logs an event to the telemetry system. | ||
* Events are automatically batched before sending to the telemetry service. | ||
* Call `flush()` to immediately send the events. | ||
* @param eventName The name of the event. | ||
* @param data Fields to be associated with the event. | ||
*/ | ||
logEvent(eventName: string, data: LogEventData): void; | ||
/** | ||
* Immediately sends buffered events to the telemetry service. | ||
*/ | ||
flush(): void; | ||
} | ||
|
||
export interface CreateTelemetryReporterProps { | ||
/** | ||
* The instrumentation key for the telemetry service receiving events. | ||
*/ | ||
instrumentationKey: string; | ||
/** | ||
* Custom ingestion endpoint URL to send events. | ||
*/ | ||
endpointUrl?: string; | ||
} | ||
|
||
export type CreateTelemetryReporter = (props: CreateTelemetryReporterProps) => TelemetryReporter; | ||
export type ExtensionConfig = Required< | ||
Pick<ISenderConfig, "alwaysUseXhrOverride" | "httpXHROverride"> | ||
>; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
export function getCommonProperties() { | ||
return { | ||
sessionId: getRandomUUID(), | ||
"telemetry.sdk.name": "typespec-azure-telemetry", | ||
"telemetry.sdk.language": "javascript", | ||
}; | ||
} | ||
|
||
function getRandomUUID() { | ||
try { | ||
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") { | ||
return crypto.randomUUID(); | ||
} | ||
} catch { | ||
// ignore error | ||
} | ||
return; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. what happens if it errors out? no session id or empty id? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No sessionId in that case. It will still show up in app insights, but each event will be treated as being part of their own session. That said - this file is mostly inconsequential for now since we'll use the NoOpTelemetryReporter in browser builds. |
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import { randomUUID } from "node:crypto"; | ||
import { arch, platform, release } from "node:os"; | ||
|
||
export function getCommonProperties() { | ||
return { | ||
sessionId: randomUUID(), | ||
"host.arch": arch(), | ||
"os.type": platform(), | ||
"os.version": release(), | ||
"telemetry.sdk.name": "typespec-azure-telemetry", | ||
"telemetry.sdk.language": "javascript", | ||
}; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export function isTelemetryDisabled() { | ||
return true; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just as it will show up in the following version otherwise