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: onboarding store #8027

Merged
merged 8 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 2 additions & 0 deletions src/lib/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import { IntegrationEventsStore } from '../features/integration-events/integrati
import { FeatureCollaboratorsReadModel } from '../features/feature-toggle/feature-collaborators-read-model';
import { createProjectReadModel } from '../features/project/createProjectReadModel';
import { OnboardingReadModel } from '../features/onboarding/onboarding-read-model';
import { OnboardingStore } from '../features/onboarding/onboarding-store';

export const createStores = (
config: IUnleashConfig,
Expand Down Expand Up @@ -173,6 +174,7 @@ export const createStores = (
featureLifecycleStore: new FeatureLifecycleStore(db),
featureStrategiesReadModel: new FeatureStrategiesReadModel(db),
onboardingReadModel: new OnboardingReadModel(db),
onboardingStore: new OnboardingStore(db),
featureLifecycleReadModel: new FeatureLifecycleReadModel(
db,
config.flagResolver,
Expand Down
10 changes: 10 additions & 0 deletions src/lib/features/onboarding/fake-onboarding-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type {
IOnboardingStore,
OnboardingEvent,
} from './onboarding-store-type';

export class FakeOnboardingStore implements IOnboardingStore {
async insert(event: OnboardingEvent): Promise<void> {
return;
}
}
63 changes: 63 additions & 0 deletions src/lib/features/onboarding/onboarding-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import type { IFlagResolver, IUnleashConfig } from '../../types';
import type EventEmitter from 'events';
import type { Logger } from '../../logger';
import { STAGE_ENTERED, USER_LOGIN } from '../../metric-events';
import type { NewStage } from '../feature-lifecycle/feature-lifecycle-store-type';
import type { IOnboardingStore } from './onboarding-store-type';

export class OnboardingService {
private flagResolver: IFlagResolver;

private eventBus: EventEmitter;

private logger: Logger;

private onboardingStore: IOnboardingStore;

constructor(
{ onboardingStore }: { onboardingStore: IOnboardingStore },
{
flagResolver,
eventBus,
getLogger,
}: Pick<IUnleashConfig, 'flagResolver' | 'eventBus' | 'getLogger'>,
) {
this.onboardingStore = onboardingStore;
this.flagResolver = flagResolver;
this.eventBus = eventBus;
this.logger = getLogger('onboarding/onboarding-service.ts');
}

listen() {
this.eventBus.on(USER_LOGIN, async (event: { loginOrder: number }) => {
if (!this.flagResolver.isEnabled('onboardingMetrics')) return;

if (event.loginOrder === 0) {
await this.onboardingStore.insert({ type: 'firstUserLogin' });
}
if (event.loginOrder === 1) {
await this.onboardingStore.insert({ type: 'secondUserLogin' });
}
});
this.eventBus.on(STAGE_ENTERED, async (stage: NewStage) => {
if (!this.flagResolver.isEnabled('onboardingMetrics')) return;

if (stage.stage === 'initial') {
Copy link
Contributor Author

@kwasniew kwasniew Aug 30, 2024

Choose a reason for hiding this comment

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

we do this translation since there's not 100% domain vocab match between lifecycle and onboarding. lifecycle cares about initial flag, while onboarding cares about the first flag created

await this.onboardingStore.insert({
type: 'flagCreated',
flag: stage.feature,
});
} else if (stage.stage === 'pre-live') {
await this.onboardingStore.insert({
type: 'preLive',
flag: stage.feature,
});
} else if (stage.stage === 'live') {
await this.onboardingStore.insert({
type: 'live',
flag: stage.feature,
});
}
});
}
}
12 changes: 12 additions & 0 deletions src/lib/features/onboarding/onboarding-store-type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export type SharedEvent =
| { type: 'flagCreated'; flag: string }
| { type: 'preLive'; flag: string }
| { type: 'live'; flag: string };
export type InstanceEvent =
| { type: 'firstUserLogin' }
| { type: 'secondUserLogin' };
export type OnboardingEvent = SharedEvent | InstanceEvent;

export interface IOnboardingStore {
insert(event: OnboardingEvent): Promise<void>;
}
72 changes: 72 additions & 0 deletions src/lib/features/onboarding/onboarding-store.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import type { IUnleashStores } from '../../../lib/types';
import dbInit, { type ITestDb } from '../../../test/e2e/helpers/database-init';
import getLogger from '../../../test/fixtures/no-logger';
import { minutesToMilliseconds } from 'date-fns';

let db: ITestDb;
let stores: IUnleashStores;

beforeAll(async () => {
db = await dbInit('onboarding_store', getLogger);
stores = db.stores;
});

afterAll(async () => {
await db.destroy();
});

beforeEach(async () => {
jest.useRealTimers();
});

test('Storing onboarding events', async () => {
jest.useFakeTimers();
jest.setSystemTime(new Date());
const { userStore, onboardingStore, featureToggleStore, projectStore } =
stores;
const user = await userStore.insert({});
await projectStore.create({ id: 'test_project', name: 'irrelevant' });
await featureToggleStore.create('test_project', {
name: 'test',
createdByUserId: user.id,
});

jest.advanceTimersByTime(minutesToMilliseconds(1));
await onboardingStore.insert({ type: 'firstUserLogin' });
jest.advanceTimersByTime(minutesToMilliseconds(1));
await onboardingStore.insert({ type: 'secondUserLogin' });
jest.advanceTimersByTime(minutesToMilliseconds(1));
await onboardingStore.insert({ type: 'flagCreated', flag: 'test' });
await onboardingStore.insert({ type: 'flagCreated', flag: 'test' });
await onboardingStore.insert({ type: 'flagCreated', flag: 'invalid' });
jest.advanceTimersByTime(minutesToMilliseconds(1));
await onboardingStore.insert({ type: 'preLive', flag: 'test' });
await onboardingStore.insert({ type: 'preLive', flag: 'test' });
await onboardingStore.insert({ type: 'preLive', flag: 'invalid' });
jest.advanceTimersByTime(minutesToMilliseconds(1));
await onboardingStore.insert({ type: 'live', flag: 'test' });
jest.advanceTimersByTime(minutesToMilliseconds(1));
await onboardingStore.insert({ type: 'live', flag: 'test' });
jest.advanceTimersByTime(minutesToMilliseconds(1));
await onboardingStore.insert({ type: 'live', flag: 'invalid' });

const { rows: instanceEvents } = await db.rawDatabase.raw(
'SELECT * FROM onboarding_events_instance',
);
expect(instanceEvents).toMatchObject([
{ event: 'firstUserLogin', time_to_event: 60 },
{ event: 'secondUserLogin', time_to_event: 120 },
{ event: 'firstFlag', time_to_event: 180 },
{ event: 'firstPreLive', time_to_event: 240 },
{ event: 'firstLive', time_to_event: 300 },
]);

const { rows: projectEvents } = await db.rawDatabase.raw(
'SELECT * FROM onboarding_events_project',
);
expect(projectEvents).toMatchObject([
{ event: 'firstFlag', time_to_event: 180, project: 'test_project' },
{ event: 'firstPreLive', time_to_event: 240, project: 'test_project' },
{ event: 'firstLive', time_to_event: 300, project: 'test_project' },
]);
});
136 changes: 136 additions & 0 deletions src/lib/features/onboarding/onboarding-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import type { Db } from '../../db/db';
import type {
IOnboardingStore,
OnboardingEvent,
SharedEvent,
} from './onboarding-store-type';
import { millisecondsToSeconds } from 'date-fns';

type DBInstanceType = {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

sticking to dashed convention as in lifecycle events instead of camel casing

event:
| 'firstUserLogin'
| 'secondUserLogin'
| 'firstFlag'
| 'firstPreLive'
| 'firstLive';
time_to_event: number;
};

type DBProjectType = {
event: 'firstFlag' | 'firstPreLive' | 'firstLive';
time_to_event: number;
project: string;
};

const translateEvent = (
event: OnboardingEvent['type'],
): DBInstanceType['event'] => {
if (event === 'flagCreated') {
return 'firstFlag';
}
if (event === 'preLive') {
return 'firstPreLive';
}
if (event === 'live') {
return 'firstLive';
}
return event as DBInstanceType['event'];
};

const calculateTimeDifferenceInSeconds = (date1?: Date, date2?: Date) => {
if (date1 && date2) {
const diffInMilliseconds = date2.getTime() - date1.getTime();
return millisecondsToSeconds(diffInMilliseconds);
}
return null;
};

export class OnboardingStore implements IOnboardingStore {
private db: Db;

constructor(db: Db) {
this.db = db;
}

async insert(event: OnboardingEvent): Promise<void> {
await this.insertInstanceEvent(event);
if (
event.type !== 'firstUserLogin' &&
event.type !== 'secondUserLogin'
) {
await this.insertProjectEvent(event);
}
}

private async insertInstanceEvent(event: OnboardingEvent): Promise<void> {
const dbEvent = translateEvent(event.type);
const exists = await this.db<DBInstanceType>(
'onboarding_events_instance',
)
.where({ event: dbEvent })
.first();

if (exists) return;

const firstInstanceUser = await this.db('users')
.select('created_at')
.orderBy('created_at', 'asc')
.first();

if (!firstInstanceUser) return;

const timeToEvent = calculateTimeDifferenceInSeconds(
firstInstanceUser.created_at,
new Date(),
);
if (timeToEvent === null) return;

await this.db('onboarding_events_instance').insert({
event: dbEvent,
time_to_event: timeToEvent,
});
}

private async insertProjectEvent(event: SharedEvent): Promise<void> {
const dbEvent = translateEvent(event.type) as DBProjectType['event'];

const projectRow = await this.db<{ project: string; name: string }>(
'features',
)
.select('project')
.where({ name: event.flag })
.first();

if (!projectRow) return;

const project = projectRow.project;

const exists = await this.db('onboarding_events_project')
.where({ event: dbEvent, project })
.first();

if (exists) return;

const projectCreatedAt = await this.db<{
created_at: Date;
id: string;
}>('projects')
.select('created_at')
.where({ id: project })
.first();

if (!projectCreatedAt) return;

const timeToEvent = calculateTimeDifferenceInSeconds(
projectCreatedAt.created_at,
new Date(),
);
if (timeToEvent === null) return;

await this.db<DBProjectType>('onboarding_events_project').insert({
event: dbEvent,
time_to_event: timeToEvent,
project: project,
});
}
}
2 changes: 1 addition & 1 deletion src/lib/features/project/project-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ class ProjectStore implements IProjectStore {
project: IProjectInsert & IProjectSettings,
): Promise<IProject> {
const row = await this.db(TABLE)
.insert(this.fieldToRow(project))
.insert({ ...this.fieldToRow(project), created_at: new Date() })
.returning('*');
const settingsRow = await this.db(SETTINGS_TABLE)
.insert({
Expand Down
3 changes: 3 additions & 0 deletions src/lib/types/stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import type { IntegrationEventsStore } from '../features/integration-events/inte
import { IFeatureCollaboratorsReadModel } from '../features/feature-toggle/types/feature-collaborators-read-model-type';
import type { IProjectReadModel } from '../features/project/project-read-model-type';
import { IOnboardingReadModel } from '../features/onboarding/onboarding-read-model-type';
import { IOnboardingStore } from '../features/onboarding/onboarding-store-type';

export interface IUnleashStores {
accessStore: IAccessStore;
Expand Down Expand Up @@ -104,6 +105,7 @@ export interface IUnleashStores {
featureCollaboratorsReadModel: IFeatureCollaboratorsReadModel;
projectReadModel: IProjectReadModel;
onboardingReadModel: IOnboardingReadModel;
onboardingStore: IOnboardingStore;
}

export {
Expand Down Expand Up @@ -157,4 +159,5 @@ export {
IOnboardingReadModel,
type IntegrationEventsStore,
type IProjectReadModel,
IOnboardingStore,
};
2 changes: 2 additions & 0 deletions src/test/fixtures/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import { FakeLargestResourcesReadModel } from '../../lib/features/metrics/sizes/
import { FakeFeatureCollaboratorsReadModel } from '../../lib/features/feature-toggle/fake-feature-collaborators-read-model';
import { createFakeProjectReadModel } from '../../lib/features/project/createProjectReadModel';
import { FakeOnboardingReadModel } from '../../lib/features/onboarding/fake-onboarding-read-model';
import { FakeOnboardingStore } from '../../lib/features/onboarding/fake-onboarding-store';

const db = {
select: () => ({
Expand Down Expand Up @@ -115,6 +116,7 @@ const createStores: () => IUnleashStores = () => {
integrationEventsStore: {} as IntegrationEventsStore,
featureCollaboratorsReadModel: new FakeFeatureCollaboratorsReadModel(),
projectReadModel: createFakeProjectReadModel(),
onboardingStore: new FakeOnboardingStore(),
};
};

Expand Down
Loading