Skip to content
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

feat(telemetry): Add telemetry via @sentry/node #213

Merged
merged 9 commits into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"@typescript-eslint/require-array-sort-compare": "error",
"@typescript-eslint/restrict-plus-operands": "error",
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "error"
"@typescript-eslint/unbound-method": "error",
"github/array-foreach": "off",
},
"env": {
"node": true,
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ Adding the following to your workflow will create a new Sentry release and tell
|`url_prefix`|Adds a prefix to source map urls after stripping them.|-|
|`strip_common_prefix`|Will remove a common prefix from uploaded filenames. Useful for removing a path that is build-machine-specific.|`false`|
|`working_directory`|Directory to collect sentry release information from. Useful when collecting information from a non-standard checkout directory.|-|
|`disable_telemetry`|The action sends telemetry data and crash reports to Sentry. This helps us improve the action. You can turn this off by setting this flag.|`false`|

### Examples

Expand Down
3 changes: 3 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ inputs:
working_directory:
description: 'Directory to collect sentry release information from. Useful when collecting information from a non-standard checkout directory.'
required: false
disable_telemetry:
description: 'The action sends telemetry data and crash reports to Sentry. This helps us improve the action. You can turn this off by setting this flag.'
required: false
runs:
using: 'docker'
# If you change this, update the use-local-dockerfile action
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"license": "MIT",
"dependencies": {
"@actions/core": "^1.10.0",
"@sentry/cli": "^2.24.1"
"@sentry/cli": "^2.24.1",
"@sentry/node": "^8.48.0"
},
"devDependencies": {
"@types/jest": "^29.5.6",
Expand Down
35 changes: 16 additions & 19 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {getTraceData} from '@sentry/node';
import SentryCli, {SentryCliReleases} from '@sentry/cli';
// @ts-ignore
import {version} from '../package.json';
Expand All @@ -7,30 +8,26 @@ import {version} from '../package.json';
*
* When the `MOCK` environment variable is set, stub out network calls.
*/
let cli: SentryCliReleases;
export const getCLI = (): SentryCliReleases => {
// Set the User-Agent string.
process.env['SENTRY_PIPELINE'] = `github-action-release/${version}`;

if (!cli) {
cli = new SentryCli().releases;
if (process.env['MOCK']) {
// Set environment variables if they aren't already
for (const variable of [
'SENTRY_AUTH_TOKEN',
'SENTRY_ORG',
'SENTRY_PROJECT',
])
!(variable in process.env) && (process.env[variable] = variable);
const cli = new SentryCli(null, {
headers: {
// Propagate sentry trace if we have one
...getTraceData(),
},
}).releases;

Comment on lines +20 to 21
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to confirm: the for loop for setting the variables was moved to checkEnvironmentVariables, right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, correct. That was really only necessary once at startup and since getCli is now not returning a singleton anymore I moved it over there.

cli.execute = async (
args: string[],
// eslint-disable-next-line @typescript-eslint/no-unused-vars
live: boolean
): Promise<string> => {
return Promise.resolve(args.join(' '));
};
}
if (process.env['MOCK']) {
cli.execute = async (
args: string[],
// eslint-disable-next-line @typescript-eslint/no-unused-vars
live: boolean
): Promise<string> => {
return Promise.resolve(args.join(' '));
};
}

return cli;
};
155 changes: 84 additions & 71 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,86 +2,99 @@ import * as core from '@actions/core';
import {getCLI} from './cli';
import * as options from './options';
import * as process from 'process';
import {isTelemetryEnabled, traceStep, withTelemetry} from './telemetry';

(async () => {
try {
const cli = getCLI();
withTelemetry(
{
enabled: isTelemetryEnabled(),
},
async () => {
try {
// Validate options first so we can fail early.
options.checkEnvironmentVariables();

// Validate options first so we can fail early.
options.checkEnvironmentVariables();
const environment = options.getEnvironment();
const sourcemaps = options.getSourcemaps();
const dist = options.getDist();
const shouldFinalize = options.getBooleanOption('finalize', true);
const ignoreMissing = options.getBooleanOption('ignore_missing', false);
const ignoreEmpty = options.getBooleanOption('ignore_empty', false);
const deployStartedAtOption = options.getStartedAt();
const setCommitsOption = options.getSetCommitsOption();
const projects = options.getProjects();
const urlPrefix = options.getUrlPrefixOption();
const stripCommonPrefix = options.getBooleanOption(
'strip_common_prefix',
false
);
const version = await options.getVersion();
const workingDirectory = options.getWorkingDirectory();

const environment = options.getEnvironment();
const sourcemaps = options.getSourcemaps();
const dist = options.getDist();
const shouldFinalize = options.getBooleanOption('finalize', true);
const ignoreMissing = options.getBooleanOption('ignore_missing', false);
const ignoreEmpty = options.getBooleanOption('ignore_empty', false);
const deployStartedAtOption = options.getStartedAt();
const setCommitsOption = options.getSetCommitsOption();
const projects = options.getProjects();
const urlPrefix = options.getUrlPrefixOption();
const stripCommonPrefix = options.getBooleanOption(
'strip_common_prefix',
false
);
const version = await options.getVersion();
const workingDirectory = options.getWorkingDirectory();
core.debug(`Version is ${version}`);
await getCLI().new(version, {projects});

core.debug(`Version is ${version}`);
await cli.new(version, {projects});
const currentWorkingDirectory = process.cwd();
if (workingDirectory !== null && workingDirectory.length > 0) {
process.chdir(workingDirectory);
}

const currentWorkingDirectory = process.cwd();
if (workingDirectory !== null && workingDirectory.length > 0) {
process.chdir(workingDirectory);
}
if (setCommitsOption !== 'skip') {
await traceStep('set-commits', async () => {
core.debug(`Setting commits with option '${setCommitsOption}'`);
await getCLI().setCommits(version, {
auto: true,
ignoreMissing,
ignoreEmpty,
});
});
}

if (setCommitsOption !== 'skip') {
core.debug(`Setting commits with option '${setCommitsOption}'`);
await cli.setCommits(version, {
auto: true,
ignoreMissing,
ignoreEmpty,
});
}
if (sourcemaps.length) {
await traceStep('upload-sourcemaps', async () => {
core.debug(`Adding sourcemaps`);
await Promise.all(
projects.map(async project => {
// upload source maps can only do one project at a time
const localProjects: [string] = [project];
const sourceMapOptions = {
include: sourcemaps,
projects: localProjects,
dist,
urlPrefix,
stripCommonPrefix,
};
return getCLI().uploadSourceMaps(version, sourceMapOptions);
})
);
});
}

if (sourcemaps.length) {
core.debug(`Adding sourcemaps`);
await Promise.all(
projects.map(async project => {
// upload source maps can only do one project at a time
const localProjects: [string] = [project];
const sourceMapOptions = {
include: sourcemaps,
projects: localProjects,
dist,
urlPrefix,
stripCommonPrefix,
};
return cli.uploadSourceMaps(version, sourceMapOptions);
})
);
}
if (environment) {
await traceStep('add-environment', async () => {
core.debug(`Adding deploy to release`);
await getCLI().newDeploy(version, {
env: environment,
...(deployStartedAtOption && {started: deployStartedAtOption}),
});
});
}

if (environment) {
core.debug(`Adding deploy to release`);
await cli.newDeploy(version, {
env: environment,
...(deployStartedAtOption && {started: deployStartedAtOption}),
});
}
if (shouldFinalize) {
await traceStep('finalizing-release', async () => {
core.debug(`Finalizing the release`);
await getCLI().finalize(version);
});
}

core.debug(`Finalizing the release`);
if (shouldFinalize) {
await cli.finalize(version);
}
if (workingDirectory !== null && workingDirectory.length > 0) {
process.chdir(currentWorkingDirectory);
}

if (workingDirectory !== null && workingDirectory.length > 0) {
process.chdir(currentWorkingDirectory);
core.debug(`Done`);
core.setOutput('version', version);
} catch (error) {
core.setFailed((error as Error).message);
throw error;
}

core.debug(`Done`);
core.setOutput('version', version);
} catch (error) {
core.setFailed((error as Error).message);
}
})();
);
13 changes: 13 additions & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,19 @@ export const getSetCommitsOption = (): 'auto' | 'skip' => {
* Check for required environment variables.
*/
export const checkEnvironmentVariables = (): void => {
if (process.env['MOCK']) {
// Set environment variables for mock runs if they aren't already
for (const variable of [
'SENTRY_AUTH_TOKEN',
'SENTRY_ORG',
'SENTRY_PROJECT',
]) {
if (!(variable in process.env)) {
process.env[variable] = variable;
}
}
}

if (!process.env['SENTRY_ORG']) {
throw Error(
'Environment variable SENTRY_ORG is missing an organization slug'
Expand Down
94 changes: 94 additions & 0 deletions src/telemetry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import * as options from './options';
import * as Sentry from '@sentry/node';
import packageJson from '../package.json';

const SENTRY_SAAS_HOSTNAME = 'sentry.io';

/**
* Initializes Sentry and wraps the given callback
* in a span.
*/
export async function withTelemetry<F>(
options: {enabled: boolean},
callback: () => F | Promise<F>
): Promise<F> {
Sentry.initWithoutDefaultIntegrations({
dsn: 'https://[email protected]/4508608809533441',
enabled: options.enabled,
environment: `production-sentry-github-action`,
tracesSampleRate: 1,
sampleRate: 1,
release: packageJson.version,
integrations: [Sentry.httpIntegration()],
tracePropagationTargets: ['sentry.io/api'],
});

const session = Sentry.startSession();

Sentry.setTag('node', process.version);
Sentry.setTag('platform', process.platform);

try {
return await Sentry.startSpan(
{
name: 'sentry-github-action-execution',
op: 'action.flow',
},
async () => {
updateProgress('start');
const res = await callback();
updateProgress('finished');

return res;
}
);
} catch (e) {
session.status = 'crashed';
Sentry.captureException('Error during sentry-github-action execution.');
throw e;
} finally {
Sentry.endSession();
await safeFlush();
}
}

/**
* Sets the `progress` tag to a given step.
*/
export function updateProgress(step: string): void {
Sentry.setTag('progress', step);
}

/**
* Wraps the given callback in a span.
*/
export function traceStep<T>(step: string, callback: () => T): T {
updateProgress(step);
return Sentry.startSpan({name: step, op: 'action.step'}, () => callback());
}

/**
* Flushing can fail, we never want to crash because of telemetry.
*/
export async function safeFlush(): Promise<void> {
try {
await Sentry.flush(3000);
} catch {
// Noop when flushing fails.
// We don't even need to log anything because there's likely nothing the user can do and they likely will not care.
}
}

/**
* Determine if telemetry should be enabled
*/
export function isTelemetryEnabled(): boolean {
const url = new URL(
process.env['SENTRY_URL'] || `https://${SENTRY_SAAS_HOSTNAME}`
);

return (
!options.getBooleanOption('disable_telemetry', false) &&
url.hostname === SENTRY_SAAS_HOSTNAME
);
}
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"resolveJsonModule": true /* Enables importing JSON files. */
},
"exclude": ["node_modules", "**/*.test.ts"]
}
Loading
Loading