Skip to content

Commit

Permalink
MNTOR-3814 - use context to fetch experiment data from Cirrus (#5440)
Browse files Browse the repository at this point in the history
* attempt to use context for experiment data and glean
* searchParams is unavaiable in layout, store in x-header instead
  • Loading branch information
rhelmer authored Jan 8, 2025
1 parent 5edcb11 commit 780dfd4
Show file tree
Hide file tree
Showing 11 changed files with 410 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ export default async function DashboardPage({ params, searchParams }: Props) {
totalNumberOfPerformedScans={profileStats?.total}
isNewUser={isNewUser}
elapsedTimeInDaysSinceInitialScan={elapsedTimeInDaysSinceInitialScan}
experimentData={experimentData}
experimentData={experimentData["Features"]}
activeTab={activeTab}
hasFirstMonitoringScan={hasFirstMonitoringScan}
signInCount={signInCount}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export default async function SettingsPage({ params, searchParams }: Props) {
yearlySubscriptionUrl={`${yearlySubscriptionUrl}&${additionalSubplatParams.toString()}`}
subscriptionBillingAmount={getSubscriptionBillingAmount()}
enabledFeatureFlags={enabledFeatureFlags}
experimentData={experimentData}
experimentData={experimentData["Features"]}
lastScanDate={lastOneRepScan?.created_at}
isMonthlySubscriber={isMonthlySubscriber}
activeTab={activeTab}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export default async function Onboarding({ params, searchParams }: Props) {
breachesTotalCount={allBreachesCount}
stepId={firstSlug === FreeScanSlug ? "enterInfo" : "getStarted"}
previousRoute={previousRoute}
experimentData={experimentData}
experimentData={experimentData["Features"]}
/>
);
}
8 changes: 4 additions & 4 deletions src/app/(proper_react)/(redesign)/(public)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ export default async function Page({ searchParams }: Props) {
oneRepActivations > monthlySubscribersQuota;
return (
<AccountsMetricsFlowProvider
enabled={experimentData["landing-page-free-scan-cta"].enabled}
enabled={experimentData["Features"]["landing-page-free-scan-cta"].enabled}
metricsFlowParams={{
entrypoint: CONST_URL_MONITOR_LANDING_PAGE_ID,
entrypoint_experiment: "landing-page-free-scan-cta",
entrypoint_variation:
experimentData["landing-page-free-scan-cta"].variant,
experimentData["Features"]["landing-page-free-scan-cta"].variant,
form_type:
experimentData["landing-page-free-scan-cta"].variant ===
experimentData["Features"]["landing-page-free-scan-cta"].variant ===
"ctaWithEmail"
? "email"
: "button",
Expand All @@ -73,7 +73,7 @@ export default async function Page({ searchParams }: Props) {
l10n={getL10n()}
countryCode={countryCode}
scanLimitReached={scanLimitReached}
experimentData={experimentData}
experimentData={experimentData["Features"]}
/>
</AccountsMetricsFlowProvider>
);
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/v1/user/welcome-scan/create/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export async function POST(
previewMode: searchParams.get("nimbus_preview") === "true",
});
const optionalInfoExperimentData =
experimentData["welcome-scan-optional-info"];
experimentData["Features"]["welcome-scan-optional-info"];

const profileData: CreateProfileRequest = {
first_name: firstName,
Expand Down
11 changes: 4 additions & 7 deletions src/app/functions/server/getExperiments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ export async function getExperiments(params: {
locale: string;
countryCode: string;
previewMode: boolean;
}): Promise<ExperimentData["Features"]> {
}): Promise<ExperimentData> {
if (["local"].includes(process.env.APP_ENV ?? "local")) {
return localExperimentData["Features"];
return localExperimentData;
}

if (!process.env.NIMBUS_SIDECAR_URL) {
Expand Down Expand Up @@ -74,13 +74,10 @@ export async function getExperiments(params: {
experimentData = json;
}

return (
(experimentData as ExperimentData["Features"]) ??
defaultExperimentData["Features"]
);
return (experimentData as ExperimentData) ?? defaultExperimentData;
} catch (ex) {
logger.error("Could not connect to Cirrus", { serverUrl, ex });
captureException(ex);
return defaultExperimentData["Features"];
return defaultExperimentData;
}
}
24 changes: 23 additions & 1 deletion src/app/hooks/useGlean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ import EventMetricType from "@mozilla/glean/private/metrics/event";
import type { GleanMetricMap } from "../../telemetry/generated/_map";
import { useSession } from "next-auth/react";
import { hasPremium } from "../functions/universal/user";
import { useExperiments } from "../../contextProviders/experiments";

export const useGlean = () => {
const session = useSession();
const experimentData = useExperiments();
const isPremiumUser = hasPremium(session.data?.user);

const record = useCallback(
Expand All @@ -37,10 +39,30 @@ export const useGlean = () => {
? "Plus"
: "Free";

// Record the `nimbus_*` keys on all events.
// `nimbus_*` is set on every metric, but it's too much work for TypeScript
// to infer that — hence the type assertion.
if (experimentData) {
(data as GleanMetricMap["button"]["click"]).nimbus_user_id =
experimentData["Enrollments"]["nimbus_user_id"];
(data as GleanMetricMap["button"]["click"]).nimbus_app_id =
experimentData["Enrollments"]["app_id"];
(data as GleanMetricMap["button"]["click"]).nimbus_experiment =
experimentData["Enrollments"]["experiment"];
(data as GleanMetricMap["button"]["click"]).nimbus_branch =
experimentData["Enrollments"]["branch"];
(data as GleanMetricMap["button"]["click"]).nimbus_experiment_type =
experimentData["Enrollments"]["experiment_type"];
(data as GleanMetricMap["button"]["click"]).nimbus_is_preview =
experimentData["Enrollments"]["is_preview"].toString();
} else {
console.warn("No experiment data available for Glean");
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
mod[event].record(data as any);
},
[isPremiumUser],
[isPremiumUser, experimentData],
);

return record;
Expand Down
30 changes: 28 additions & 2 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import { GoogleAnalyticsWorkaround } from "./components/client/GoogleAnalyticsWo
import StripeScript from "./components/client/StripeScript";
import { GleanScript } from "./components/client/GleanScript";
import { getExperimentationId } from "./functions/server/getExperimentationId";
import { getExperiments } from "./functions/server/getExperiments";
import { getCountryCode } from "./functions/server/getCountryCode";
import { ExperimentsProvider } from "../contextProviders/experiments";
import * as Sentry from "@sentry/nextjs";

const inter = Inter({ subsets: ["latin"], variable: "--font-inter" });

Expand Down Expand Up @@ -54,6 +58,26 @@ export default async function RootLayout({
const nonce = headers().get("x-nonce") ?? "";
const currentLocale = getLocale(getL10nBundles());
const session = await getServerSession();
const headersList = headers();
const countryCode = getCountryCode(headersList);

// Check for Nimbus preview mode. Note that this requires a full page reload
// to activate: https://nextjs.org/docs/app/api-reference/file-conventions/layout#caveats
const nimbusPreviewMode = headers().get("x-nimbus-preview-mode");
const experimentationId = getExperimentationId(session?.user ?? null);
const experimentData = await getExperiments({
experimentationId: experimentationId,
countryCode: countryCode,
locale: currentLocale,
previewMode: nimbusPreviewMode === "true",
});

const nimbus_user_id = experimentData["Enrollments"].nimbus_user_id;
if (nimbus_user_id !== experimentationId) {
Sentry.captureMessage(
`Nimbus user ID from Cirrus: [${nimbus_user_id}] did not match experimentationId: [${experimentationId}]`,
);
}

return (
<html lang={currentLocale}>
Expand All @@ -64,12 +88,14 @@ export default async function RootLayout({
data-ga4-measurement-id={CONST_GA4_MEASUREMENT_ID}
data-node-env={process.env.NODE_ENV}
>
<SessionProvider session={session}>{children}</SessionProvider>
<ExperimentsProvider experimentData={experimentData}>
<SessionProvider session={session}>{children}</SessionProvider>
</ExperimentsProvider>
</body>
<StripeScript />
<GleanScript
channel={process.env.APP_ENV ?? ""}
experimentationId={getExperimentationId(session?.user ?? null)}
experimentationId={experimentationId}
/>
{headers().get("DNT") !== "1" && (
<GoogleAnalyticsWorkaround
Expand Down
31 changes: 31 additions & 0 deletions src/contextProviders/experiments.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use client";

import { ReactNode, createContext, useContext } from "react";
import { ExperimentData } from "../telemetry/generated/nimbus/experiments";

interface ExperimentsProviderProps {
children: ReactNode;
experimentData: ExperimentData;
}

export const ExperimentsContext = createContext<ExperimentData | null>(null);

export const ExperimentsProvider = ({
children,
experimentData,
}: ExperimentsProviderProps) => {
return (
<ExperimentsContext.Provider value={experimentData}>
{children}
</ExperimentsContext.Provider>
);
};

export const useExperiments = () => {
const context = useContext(ExperimentsContext);
return context;
};
8 changes: 8 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ export function middleware(request: NextRequest) {
existingExperimentationId?.value ?? `guest-${crypto.randomUUID()}`;
requestHeaders.set("x-experimentation-id", experimentationId);

// Check for Nimbus preview mode. Note that this requires a full page reload
// to activate: https://nextjs.org/docs/app/api-reference/file-conventions/layout#caveats
const nimbusPreviewMode = request.nextUrl.searchParams.get("nimbus_preview");
requestHeaders.set(
"x-nimbus-preview-mode",
nimbusPreviewMode === "true" ? "true" : "false",
);

const response = NextResponse.next({
request: {
headers: requestHeaders,
Expand Down
Loading

0 comments on commit 780dfd4

Please sign in to comment.