Skip to content

Commit 0793a4b

Browse files
authored
feat: add cross-origin reporting for telemetry in the dashboard (#13612)
* feat: add cross-origin reporting for telemetry in the dashboard * Respect the telemetry flag * Fix embedded metadata * Fix compilation error * Fix linting
1 parent a1db6d8 commit 0793a4b

File tree

15 files changed

+131
-5
lines changed

15 files changed

+131
-5
lines changed

coderd/apidoc/docs.go

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/apidoc/swagger.json

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/coderd.go

+1
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,7 @@ func New(options *Options) *API {
447447
WorkspaceProxy: false,
448448
UpgradeMessage: api.DeploymentValues.CLIUpgradeMessage.String(),
449449
DeploymentID: api.DeploymentID,
450+
Telemetry: api.Telemetry.Enabled(),
450451
}
451452
api.SiteHandler = site.New(&site.Options{
452453
BinFS: binFS,

coderd/telemetry/telemetry.go

+6
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ type Reporter interface {
9393
// database. For example, if a new user is added, a snapshot can
9494
// contain just that user entry.
9595
Report(snapshot *Snapshot)
96+
Enabled() bool
9697
Close()
9798
}
9899

@@ -109,6 +110,10 @@ type remoteReporter struct {
109110
shutdownAt *time.Time
110111
}
111112

113+
func (*remoteReporter) Enabled() bool {
114+
return true
115+
}
116+
112117
func (r *remoteReporter) Report(snapshot *Snapshot) {
113118
go r.reportSync(snapshot)
114119
}
@@ -948,4 +953,5 @@ type ExternalProvisioner struct {
948953
type noopReporter struct{}
949954

950955
func (*noopReporter) Report(_ *Snapshot) {}
956+
func (*noopReporter) Enabled() bool { return false }
951957
func (*noopReporter) Close() {}

codersdk/deployment.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -2173,11 +2173,12 @@ type BuildInfoResponse struct {
21732173
ExternalURL string `json:"external_url"`
21742174
// Version returns the semantic version of the build.
21752175
Version string `json:"version"`
2176-
21772176
// DashboardURL is the URL to hit the deployment's dashboard.
21782177
// For external workspace proxies, this is the coderd they are connected
21792178
// to.
21802179
DashboardURL string `json:"dashboard_url"`
2180+
// Telemetry is a boolean that indicates whether telemetry is enabled.
2181+
Telemetry bool `json:"telemetry"`
21812182

21822183
WorkspaceProxy bool `json:"workspace_proxy"`
21832184

docs/api/general.md

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/api/schemas.md

+2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

enterprise/wsproxy/wsproxysdk/wsproxysdk_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ func TestDialCoordinator(t *testing.T) {
216216
Node: &proto.Node{
217217
Id: 55,
218218
AsOf: timestamppb.New(time.Unix(1689653252, 0)),
219-
Key: peerNodeKey[:],
219+
Key: peerNodeKey,
220220
Disco: string(peerDiscoKey),
221221
PreferredDerp: 0,
222222
DerpLatency: map[string]float64{

site/jest.setup.ts

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ global.scrollTo = jest.fn();
4141

4242
window.HTMLElement.prototype.scrollIntoView = jest.fn();
4343
window.open = jest.fn();
44+
navigator.sendBeacon = jest.fn();
4445

4546
// Polyfill the getRandomValues that is used on utils/random.ts
4647
Object.defineProperty(global.self, "crypto", {

site/src/api/typesGenerated.ts

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

site/src/pages/LoginPage/LoginPage.tsx

+20
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { useAuthContext } from "contexts/auth/AuthProvider";
88
import { useEmbeddedMetadata } from "hooks/useEmbeddedMetadata";
99
import { getApplicationName } from "utils/appearance";
1010
import { retrieveRedirect } from "utils/redirect";
11+
import { sendDeploymentEvent } from "utils/telemetry";
1112
import { LoginPageView } from "./LoginPageView";
1213

1314
export const LoginPage: FC = () => {
@@ -19,6 +20,7 @@ export const LoginPage: FC = () => {
1920
signIn,
2021
isSigningIn,
2122
signInError,
23+
user,
2224
} = useAuthContext();
2325
const authMethodsQuery = useQuery(authMethods());
2426
const redirectTo = retrieveRedirect(location.search);
@@ -29,6 +31,15 @@ export const LoginPage: FC = () => {
2931
const buildInfoQuery = useQuery(buildInfo(metadata["build-info"]));
3032

3133
if (isSignedIn) {
34+
if (buildInfoQuery.data) {
35+
// This uses `navigator.sendBeacon`, so window.href
36+
// will not stop the request from being sent!
37+
sendDeploymentEvent(buildInfoQuery.data, {
38+
type: "deployment_login",
39+
user_id: user?.id,
40+
});
41+
}
42+
3243
// If the redirect is going to a workspace application, and we
3344
// are missing authentication, then we need to change the href location
3445
// to trigger a HTTP request. This allows the BE to generate the auth
@@ -74,6 +85,15 @@ export const LoginPage: FC = () => {
7485
isSigningIn={isSigningIn}
7586
onSignIn={async ({ email, password }) => {
7687
await signIn(email, password);
88+
if (buildInfoQuery.data) {
89+
// This uses `navigator.sendBeacon`, so navigating away
90+
// will not prevent it!
91+
sendDeploymentEvent(buildInfoQuery.data, {
92+
type: "deployment_login",
93+
user_id: user?.id,
94+
});
95+
}
96+
7797
navigate("/");
7898
}}
7999
/>

site/src/pages/SetupPage/SetupPage.test.tsx

+39-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import userEvent from "@testing-library/user-event";
33
import { HttpResponse, http } from "msw";
44
import { createMemoryRouter } from "react-router-dom";
55
import type { Response, User } from "api/typesGenerated";
6-
import { MockUser } from "testHelpers/entities";
6+
import { MockBuildInfo, MockUser } from "testHelpers/entities";
77
import {
88
renderWithRouter,
99
waitForLoaderToBeRemoved,
@@ -99,4 +99,42 @@ describe("Setup Page", () => {
9999
await fillForm();
100100
await waitFor(() => screen.findByText("Templates"));
101101
});
102+
it("calls sendBeacon with telemetry", async () => {
103+
const sendBeacon = jest.fn();
104+
Object.defineProperty(window.navigator, "sendBeacon", {
105+
value: sendBeacon,
106+
});
107+
renderWithRouter(
108+
createMemoryRouter(
109+
[
110+
{
111+
path: "/setup",
112+
element: <SetupPage />,
113+
},
114+
{
115+
path: "/templates",
116+
element: <h1>Templates</h1>,
117+
},
118+
],
119+
{ initialEntries: ["/setup"] },
120+
),
121+
);
122+
await waitForLoaderToBeRemoved();
123+
await waitFor(() => {
124+
expect(navigator.sendBeacon).toBeCalledWith(
125+
"https://coder.com/api/track-deployment",
126+
new Blob(
127+
[
128+
JSON.stringify({
129+
type: "deployment_setup",
130+
deployment_id: MockBuildInfo.deployment_id,
131+
}),
132+
],
133+
{
134+
type: "application/json",
135+
},
136+
),
137+
);
138+
});
139+
});
102140
});

site/src/pages/SetupPage/SetupPage.tsx

+15-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
import type { FC } from "react";
1+
import { useEffect, type FC } from "react";
22
import { Helmet } from "react-helmet-async";
3-
import { useMutation } from "react-query";
3+
import { useMutation, useQuery } from "react-query";
44
import { Navigate, useNavigate } from "react-router-dom";
5+
import { buildInfo } from "api/queries/buildInfo";
56
import { createFirstUser } from "api/queries/users";
67
import { Loader } from "components/Loader/Loader";
78
import { useAuthContext } from "contexts/auth/AuthProvider";
9+
import { useEmbeddedMetadata } from "hooks/useEmbeddedMetadata";
810
import { pageTitle } from "utils/page";
11+
import { sendDeploymentEvent } from "utils/telemetry";
912
import { SetupPageView } from "./SetupPageView";
1013

1114
export const SetupPage: FC = () => {
@@ -18,7 +21,17 @@ export const SetupPage: FC = () => {
1821
} = useAuthContext();
1922
const createFirstUserMutation = useMutation(createFirstUser());
2023
const setupIsComplete = !isConfiguringTheFirstUser;
24+
const { metadata } = useEmbeddedMetadata();
25+
const buildInfoQuery = useQuery(buildInfo(metadata["build-info"]));
2126
const navigate = useNavigate();
27+
useEffect(() => {
28+
if (!buildInfoQuery.data) {
29+
return;
30+
}
31+
sendDeploymentEvent(buildInfoQuery.data, {
32+
type: "deployment_setup",
33+
});
34+
}, [buildInfoQuery.data]);
2235

2336
if (isLoading) {
2437
return <Loader fullscreen />;

site/src/testHelpers/entities.ts

+1
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ export const MockBuildInfo: TypesGen.BuildInfoResponse = {
205205
workspace_proxy: false,
206206
upgrade_message: "My custom upgrade message",
207207
deployment_id: "510d407f-e521-4180-b559-eab4a6d802b8",
208+
telemetry: true,
208209
};
209210

210211
export const MockSupportLinks: TypesGen.LinkConfig[] = [

site/src/utils/telemetry.ts

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import type { BuildInfoResponse } from "api/typesGenerated";
2+
3+
// sendDeploymentEvent sends a CORs payload to coder.com
4+
// to track a deployment event.
5+
export const sendDeploymentEvent = (
6+
buildInfo: BuildInfoResponse,
7+
payload: {
8+
type: "deployment_setup" | "deployment_login";
9+
user_id?: string;
10+
},
11+
) => {
12+
if (typeof navigator === "undefined" || !navigator.sendBeacon) {
13+
// It's fine if we don't report this, it's not required!
14+
return;
15+
}
16+
if (!buildInfo.telemetry) {
17+
return;
18+
}
19+
navigator.sendBeacon(
20+
"https://coder.com/api/track-deployment",
21+
new Blob(
22+
[
23+
JSON.stringify({
24+
...payload,
25+
deployment_id: buildInfo.deployment_id,
26+
}),
27+
],
28+
{
29+
type: "application/json",
30+
},
31+
),
32+
);
33+
};

0 commit comments

Comments
 (0)