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

Allow re-enrollment in recipe #51

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
49 changes: 38 additions & 11 deletions src/apis/nimbus.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,39 @@ var nimbus = class extends ExtensionAPI {
return {
experiments: {
nimbus: {
async enrollInExperiment(jsonData) {
async enrollInExperiment(jsonData, forceEnroll) {
try {
const slugExistsInStore = ExperimentManager.store
.getAll()
.some((experiment) => experiment.slug === jsonData.slug);
const activeEnrollment =
ExperimentManager.store
.getAll()
.find(
(experiment) =>
experiment.slug === jsonData.slug && experiment.active,
)?.slug ?? null;
if (slugExistsInStore || activeEnrollment) {
if (!forceEnroll) {
return {
enrolled: false,
error: { slugExistsInStore, activeEnrollment },
};
}

if (activeEnrollment) {
this.unenroll(activeEnrollment);
}
if (slugExistsInStore) {
this.deleteInactiveEnrollment(jsonData.slug);
}
}

const result = await ExperimentManager.enroll(
jsonData,
"nimbus-devtools",
);
return result !== null;
return { enrolled: result !== null, error: null };
} catch (error) {
console.error(error);
throw error;
Expand Down Expand Up @@ -85,16 +111,17 @@ var nimbus = class extends ExtensionAPI {
"userFacingDescription": "Testing the feature with feature ID: ${featureId}."
}`);

const experimentStore = ExperimentManager.store.getAll();
const slugExistsInStore = experimentStore.some(
(experiment) => experiment.slug === recipe.slug,
);
const slugExistsInStore = ExperimentManager.store
.getAll()
.some((experiment) => experiment.slug === recipe.slug);
const activeEnrollment =
experimentStore.find(
(experiment) =>
experiment.featureIds.includes(featureId) &&
experiment.active,
)?.slug || null;
ExperimentManager.store
.getAll()
.find(
(experiment) =>
experiment.featureIds.includes(featureId) &&
experiment.active,
)?.slug ?? null;

if (slugExistsInStore || activeEnrollment) {
if (!forceEnroll) {
Expand Down
5 changes: 5 additions & 0 deletions src/apis/nimbus.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
"type": "object",
"additionalProperties": true,
"description": "An object representing the experiment to enroll in."
},
{
"name": "forceEnroll",
"type": "boolean",
"description": "A boolean representing whether or not the enrollment should be forced."
}
]
},
Expand Down
31 changes: 17 additions & 14 deletions src/types/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,28 +57,31 @@ declare module "mozjexl/lib/parser/Parser" {
}
}

declare namespace browser.experiments.nimbus {
type EnrollWithFeatureConfigResult =
| {
enrolled: true;
error: null;
}
| {
enrolled: false;
error: {
slugExistsInStore: boolean;
activeEnrollment: string | null;
};
type EnrollInExperimentResult =
| {
enrolled: true;
error: null;
}
| {
enrolled: false;
error: {
slugExistsInStore: boolean;
activeEnrollment: string | null;
};
};

function enrollInExperiment(jsonData: object): Promise<boolean>;
declare namespace browser.experiments.nimbus {
function enrollInExperiment(
jsonData: object,
forceEnroll: boolean,
): Promise<EnrollInExperimentResult>;

function enrollWithFeatureConfig(
featureId: string,
featureValue: object,
isRollout: boolean,
forceEnroll: boolean,
): Promise<EnrollWithFeatureConfigResult>;
): Promise<EnrollInExperimentResult>;

function getFeatureConfigs(): Promise<string[]>;

Expand Down
21 changes: 3 additions & 18 deletions src/ui/components/FeatureConfigPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,12 @@ import { Form, Container, Button, Row, Col, Modal } from "react-bootstrap";
import { useToastsContext } from "../hooks/useToasts";
import DropdownMenu from "./DropdownMenu";

type EnrollWithFeatureConfigResult =
| {
enrolled: true;
error: null;
}
| {
enrolled: false;
error: {
slugExistsInStore: boolean;
activeEnrollment: string | null;
};
};

const FeatureConfigPage: FC = () => {
const [jsonInput, setJsonInput] = useState("");
const [selectedFeatureId, setSelectedFeatureId] = useState("");
const [isRollout, setIsRollout] = useState(false);
const [enrollError, setEnrollError] =
useState<EnrollWithFeatureConfigResult["error"]>(null);
useState<EnrollInExperimentResult["error"]>(null);
const { addToast } = useToastsContext();

const slug = useMemo(() => {
Expand Down Expand Up @@ -54,8 +41,6 @@ const FeatureConfigPage: FC = () => {
event?: React.MouseEvent<HTMLButtonElement>,
forceEnroll = false,
) => {
event?.preventDefault();

if (selectedFeatureId === "") {
addToast({
message: "Invalid Input: Select feature",
Expand All @@ -65,7 +50,7 @@ const FeatureConfigPage: FC = () => {
addToast({ message: "Invalid Input: Enter JSON", variant: "danger" });
} else {
try {
const result: EnrollWithFeatureConfigResult =
const result =
await browser.experiments.nimbus.enrollWithFeatureConfig(
selectedFeatureId,
JSON.parse(jsonInput) as object,
Expand Down Expand Up @@ -102,7 +87,7 @@ const FeatureConfigPage: FC = () => {

function EnrollmentError(
slug: string,
enrollError: EnrollWithFeatureConfigResult["error"],
enrollError: EnrollInExperimentResult["error"],
) {
if (!enrollError) {
return null;
Expand Down
144 changes: 125 additions & 19 deletions src/ui/components/RecipeEnrollmentPage.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,129 @@
import { ChangeEvent, FC, useState, useCallback } from "react";
import { Form, Container, Button } from "react-bootstrap";
import { ChangeEvent, FC, useState, useCallback, useMemo } from "react";
import { Form, Container, Button, Modal } from "react-bootstrap";
import { NimbusExperiment } from "@mozilla/nimbus-schemas";

import { useToastsContext } from "../hooks/useToasts";

const RecipeEnrollmentPage: FC = () => {
const [jsonInput, setJsonInput] = useState("");
const [enrollError, setEnrollError] =
useState<EnrollInExperimentResult["error"]>(null);
const { addToast } = useToastsContext();

const recipe = useMemo<NimbusExperiment | null>(() => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

We don't actually know its a valid NimbusExperiment here, unfortunately. It should be unknown | null

try {
return JSON.parse(jsonInput) as NimbusExperiment;
} catch {
return null;
}
}, [jsonInput]);

const slug = recipe?.slug || "";
Comment on lines +13 to +21
Copy link
Collaborator

Choose a reason for hiding this comment

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

We're doing this all to get the slug. Instead, lets change this slightly:

type EnrollError = EnrollInExperimentResult["error"] & { slug: string; };
const [enrollError, setEnrollError] = useState<EnrollError | null>(null);

// line 63
setEnrollError({ slug: parsedRecipe.slug ?? "", ...result.error });

Since we're already parsing this to pass it off to the API, we may as well grab the slug there and only if we're parsing successfully and there is an error. otherwise, just wasted work and threading data through awkwardly.


const handleInputChange = useCallback(
(event: ChangeEvent<HTMLTextAreaElement>) => {
setJsonInput(event.target.value);
},
[],
[setJsonInput],
);

const handleEnrollClick = useCallback(async () => {
try {
const result = await browser.experiments.nimbus.enrollInExperiment(
JSON.parse(jsonInput) as object,
);
const handleEnrollClick = useCallback(
async (
event?: React.MouseEvent<HTMLButtonElement>,
forceEnroll = false,
) => {
if (!jsonInput) {
addToast({ message: "Invalid Input: Enter JSON", variant: "danger" });
return;
}

if (result) {
addToast({ message: "Enrollment successful", variant: "success" });
setJsonInput("");
} else {
addToast({ message: "Enrollment failed", variant: "danger" });
let parsedRecipe;
try {
parsedRecipe = JSON.parse(jsonInput) as object;
} catch (error) {
addToast({
message: `Error enrolling into experiment: ${
(error as Error).message ?? String(error)
}`,
variant: "danger",
});
return;
}
} catch (error) {
addToast({
message: `Error enrolling into experiment: ${(error as Error).message ?? String(error)}`,
variant: "danger",
});

try {
const result = await browser.experiments.nimbus.enrollInExperiment(
parsedRecipe as object,
forceEnroll,
);

if (result.enrolled) {
addToast({ message: "Enrollment successful", variant: "success" });
setJsonInput("");
} else if (result.error) {
setEnrollError(result.error);
}
} catch (error) {
addToast({
message: `Error enrolling into experiment: ${
(error as Error).message ?? String(error)
}`,
variant: "danger",
});
}
},
[jsonInput, setJsonInput, addToast, setEnrollError],
);

const handleModalConfirm = useCallback(async () => {
setEnrollError(null);
await handleEnrollClick(undefined, true);
}, [handleEnrollClick, setEnrollError]);

const handleModalClose = useCallback(() => {
setEnrollError(null);
}, [setEnrollError]);

function EnrollmentError(
Copy link
Collaborator

Choose a reason for hiding this comment

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

This should be a top level function, not nested inside the component fn

if its nested inside, it will always trigger a re-render because the function is redefined every time the component is called

slug: string,
enrollError: EnrollInExperimentResult["error"],
) {
if (!enrollError) {
return null;
}
}, [jsonInput, setJsonInput, addToast]);
const { activeEnrollment, slugExistsInStore } = enrollError;

if (activeEnrollment && slugExistsInStore) {
return (
<p>
There is already an enrollment for the slug: <strong>{slug}</strong>.
Copy link
Collaborator

Choose a reason for hiding this comment

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

This is only true if slug == activeEnrollment

There are technically two cases, slug == activeEnrollment and slug !== activeEnrollment (ie there is already an active enrollment for this feature but the slug doesnt match this one)

Would you like to proceed with force enrollment by unenrolling,
deleting, and re-enrolling into the new configuration?
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
deleting, and re-enrolling into the new configuration?
deleting, and enrolling into the new configuration?

</p>
);
}

if (activeEnrollment) {
return (
<p>
There is an active enrollment for the slug: <strong>{slug}</strong>.
Copy link
Collaborator

Choose a reason for hiding this comment

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

This actually might not be the same slug.

Suggested change
There is an active enrollment for the slug: <strong>{slug}</strong>.
There is an active enrollment for the slug: <strong>{activeEnrollment}</strong>.

Would you like to unenroll from the active enrollment and re-enroll
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
Would you like to unenroll from the active enrollment and re-enroll
Would you like to unenroll from the active enrollment and enroll

into the new configuration?
</p>
);
}

if (slugExistsInStore) {
return (
<p>
There is an inactive enrollment stored for the slug:{" "}
<strong>{slug}</strong>. Would you like to delete the inactive
enrollment and re-enroll into the new configuration?
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
enrollment and re-enroll into the new configuration?
enrollment and enroll into the new configuration?

</p>
);
}

return null;
}

return (
<Container className="main-content m-0 p-2">
Expand All @@ -53,6 +144,21 @@ const RecipeEnrollmentPage: FC = () => {
Enroll
</Button>
</Form>

<Modal show={!!enrollError} onHide={handleModalClose}>
<Modal.Header closeButton>
<Modal.Title>Force Enrollment</Modal.Title>
</Modal.Header>
<Modal.Body>{EnrollmentError(slug, enrollError)}</Modal.Body>
Copy link
Collaborator

Choose a reason for hiding this comment

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

EnrollmentError is a component:

Suggested change
<Modal.Body>{EnrollmentError(slug, enrollError)}</Modal.Body>
<Modal.Body><EnrollmentError slug{slug} enrollError={enrollError} /></Modal.Body>

<Modal.Footer>
<Button variant="secondary" onClick={handleModalClose}>
Cancel
</Button>
<Button variant="danger" onClick={handleModalConfirm}>
Force Enroll
</Button>
</Modal.Footer>
</Modal>
</Container>
);
};
Expand Down