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

Handle both V1 and V2 of Cirrus' data structure #5508

Merged
merged 4 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from 3 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
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"]}
/>
);
}
20 changes: 11 additions & 9 deletions src/app/(proper_react)/(redesign)/(public)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,39 +59,41 @@ 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",
service: process.env.OAUTH_CLIENT_ID as string,
}}
>
{enabledFeatureFlags.includes("LandingPageRedesign") &&
experimentData["landing-page-redesign-plus-eligible-experiment"]
.enabled &&
experimentData["landing-page-redesign-plus-eligible-experiment"]
.variant === "redesign" ? (
experimentData["Features"][
"landing-page-redesign-plus-eligible-experiment"
].enabled &&
experimentData["Features"][
"landing-page-redesign-plus-eligible-experiment"
].variant === "redesign" ? (
<LandingViewRedesign
eligibleForPremium={eligibleForPremium}
l10n={getL10n()}
countryCode={countryCode}
scanLimitReached={scanLimitReached}
experimentData={experimentData}
experimentData={experimentData["Features"]}
/>
) : (
<LandingView
eligibleForPremium={eligibleForPremium}
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
33 changes: 22 additions & 11 deletions src/app/functions/server/getExperiments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ import {
import { ExperimentationId } from "./getExperimentationId";
import { getEnabledFeatureFlags } from "../../../db/tables/featureFlags";

/**
* After we removing the `CirrusV2` flag, we can return the full `ExperimentData`/
* But until then, we can make the old experiment data object look like the new one,
* but we can't backfill the `Enrollments` property.
*/
export type ExperimentData_V2_Or_V2LikeV1 = Partial<ExperimentData> &
Required<Pick<ExperimentData, "Features">>;

/**
* Call the Cirrus sidecar, which returns a list of eligible experiments for the current user.
*
Expand All @@ -28,9 +36,9 @@ export async function getExperiments(params: {
locale: string;
countryCode: string;
previewMode: boolean;
}): Promise<ExperimentData["Features"]> {
}): Promise<ExperimentData_V2_Or_V2LikeV1> {
if (["local"].includes(process.env.APP_ENV ?? "local")) {
return localExperimentData["Features"];
return localExperimentData;
}

if (!process.env.NIMBUS_SIDECAR_URL) {
Expand Down Expand Up @@ -78,19 +86,22 @@ export async function getExperiments(params: {
throw new Error(`Cirrus request failed: ${response.statusText}`);
}

const json = await response.json();
// With the `CirrusV2` flag enabled, the response is `ExperimentData`,
// otherwise, it's just `ExperimentData["Features"]`.
const json = (await response.json()) as
| ExperimentData
| ExperimentData["Features"];

let experimentData;
let experimentData: ExperimentData_V2_Or_V2LikeV1;
if (flags.includes("CirrusV2")) {
experimentData = json["Features"];
experimentData = json as ExperimentData;
} else {
experimentData = json;
experimentData = {
Features: json as ExperimentData["Features"],
};
}

return (
(experimentData as ExperimentData["Features"]) ??
defaultExperimentData["Features"]
);
return experimentData ?? defaultExperimentData;
} catch (ex) {
logger.error("Could not connect to Cirrus", {
serverUrl,
Expand All @@ -99,6 +110,6 @@ export async function getExperiments(params: {
params,
});
captureException(ex);
return defaultExperimentData["Features"];
return defaultExperimentData;
}
}
30 changes: 29 additions & 1 deletion src/app/hooks/useGlean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ 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();
// Telemetry recording is mocked in our unit tests, therefore we
// do not have test coverage for this method.
/* c8 ignore start */
const isPremiumUser = hasPremium(session.data?.user);
const record = useCallback(
async <
Expand All @@ -36,10 +41,33 @@ 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 &&
typeof experimentData["Enrollments"] !== "undefined"
) {
(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],
);
/* c8 ignore end */

Expand Down
33 changes: 31 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,29 @@ 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 (
typeof nimbus_user_id !== "undefined" &&
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 +91,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
32 changes: 32 additions & 0 deletions src/contextProviders/experiments.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* 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_V2_Or_V2LikeV1 } from "../app/functions/server/getExperiments";

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

export const ExperimentsContext =
createContext<ExperimentData_V2_Or_V2LikeV1 | 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
Loading