Skip to content

Commit

Permalink
Feat/feature environment strategy execution reorder (#4248)
Browse files Browse the repository at this point in the history
<!-- Thanks for creating a PR! To make it easier for reviewers and
everyone else to understand what your changes relate to, please add some
relevant content to the headings below. Feel free to ignore or delete
sections that you don't think are relevant. Thank you! ❤️ -->
When reordering strategies for a feature environment:
- Adds stop when CR are enabled
- Emits an event 

## About the changes
<!-- Describe the changes introduced. What are they and why are they
being introduced? Feel free to also add screenshots or steps to view the
changes if they're visual. -->

<!-- Does it close an issue? Multiple? -->
Closes #

<!-- (For internal contributors): Does it relate to an issue on public
roadmap? -->
<!--
Relates to [roadmap](https://github.com/orgs/Unleash/projects/10) item:
#
-->

### Important files
<!-- PRs can contain a lot of changes, but not all changes are equally
important. Where should a reviewer start looking to get an overview of
the changes? Are any files particularly important? -->


## Discussion points
<!-- Anything about the PR you'd like to discuss before it gets merged?
Got any questions or doubts? -->

---------

Signed-off-by: andreas-unleash <andreas@getunleash.ai>
  • Loading branch information
andreas-unleash committed Jul 17, 2023
1 parent 3f913ef commit 1f21770
Show file tree
Hide file tree
Showing 6 changed files with 293 additions and 23 deletions.
6 changes: 4 additions & 2 deletions src/lib/db/event-store.ts
Expand Up @@ -372,8 +372,10 @@ class EventStore implements IEventStore {
return {
type: e.type,
created_by: e.createdBy,
data: e.data,
pre_data: e.preData,
data: Array.isArray(e.data) ? JSON.stringify(e.data) : e.data,
pre_data: Array.isArray(e.preData)
? JSON.stringify(e.preData)
: e.preData,
// @ts-expect-error workaround for json-array
tags: JSON.stringify(e.tags),
feature_name: e.featureName,
Expand Down
7 changes: 7 additions & 0 deletions src/lib/openapi/spec/event-schema.ts
Expand Up @@ -12,41 +12,48 @@ const eventDataSchema = {
description:
'Name of the feature toggle/strategy/environment that this event relates to',
example: 'my.first.toggle',
nullable: true,
},
description: {
type: 'string',
description: 'The description of the object this event relates to',
example: 'Toggle description',
nullable: true,
},
type: {
type: 'string',
description:
'If this event relates to a feature toggle, the type of feature toggle.',
example: 'release',
nullable: true,
},
project: {
type: 'string',
description: 'The project this event relates to',
example: 'default',
nullable: true,
},
stale: {
description: 'Is the feature toggle this event relates to stale',
type: 'boolean',
example: true,
nullable: true,
},
variants: {
description: 'Variants configured for this toggle',
type: 'array',
items: {
$ref: '#/components/schemas/variantSchema',
},
nullable: true,
},
createdAt: {
type: 'string',
format: 'date-time',
description:
'The time the event happened as a RFC 3339-conformant timestamp.',
example: '2023-07-05T12:56:00.000Z',
nullable: true,
},
lastSeenAt: {
type: 'string',
Expand Down
20 changes: 15 additions & 5 deletions src/lib/routes/admin-api/project/project-features.ts
Expand Up @@ -985,18 +985,28 @@ export default class ProjectFeaturesController extends Controller {
}

async setStrategiesSortOrder(
req: Request<
req: IAuthRequest<
FeatureStrategyParams,
any,
SetStrategySortOrderSchema,
any
>,
res: Response,
): Promise<void> {
const { featureName } = req.params;
await this.featureService.updateStrategiesSortOrder(
featureName,
req.body,
const { featureName, projectId, environment } = req.params;
const createdBy = extractUsername(req);
await this.startTransaction(async (tx) =>
this.transactionalFeatureToggleService(
tx,
).updateStrategiesSortOrder(
{
featureName,
environment,
projectId,
},
req.body,
createdBy,
),
);

res.status(200).send();
Expand Down
118 changes: 103 additions & 15 deletions src/lib/services/feature-toggle-service.ts
@@ -1,5 +1,6 @@
import {
CREATE_FEATURE_STRATEGY,
StrategyIds,
EnvironmentVariantEvent,
FEATURE_UPDATED,
FeatureArchivedEvent,
Expand Down Expand Up @@ -40,6 +41,7 @@ import {
Unsaved,
WeightType,
FEATURE_POTENTIALLY_STALE_UPDATED,
StrategiesOrderChangedEvent,
} from '../types';
import { Logger } from '../logger';
import BadDataError from '../error/bad-data-error';
Expand Down Expand Up @@ -370,7 +372,7 @@ class FeatureToggleService {
featureStrategy: IFeatureStrategy,
segments: ISegment[] = [],
): Saved<IStrategyConfig> {
return {
const result: Saved<IStrategyConfig> = {
id: featureStrategy.id,
name: featureStrategy.strategyName,
title: featureStrategy.title,
Expand All @@ -379,17 +381,96 @@ class FeatureToggleService {
parameters: featureStrategy.parameters,
segments: segments.map((segment) => segment.id) ?? [],
};

if (this.flagResolver.isEnabled('strategyVariant')) {
result.sortOrder = featureStrategy.sortOrder;
}
return result;
}

async updateStrategiesSortOrder(
featureName: string,
context: IFeatureStrategyContext,
sortOrders: SetStrategySortOrderSchema,
createdBy: string,
user?: User,
): Promise<Saved<any>> {
await this.stopWhenChangeRequestsEnabled(
context.projectId,
context.environment,
user,
);

return this.unprotectedUpdateStrategiesSortOrder(
context,
sortOrders,
createdBy,
);
}

async unprotectedUpdateStrategiesSortOrder(
context: IFeatureStrategyContext,
sortOrders: SetStrategySortOrderSchema,
createdBy: string,
): Promise<Saved<any>> {
const { featureName, environment, projectId: project } = context;
const existingOrder = (
await this.getStrategiesForEnvironment(
project,
featureName,
environment,
)
)
.sort((strategy1, strategy2) => {
if (
typeof strategy1.sortOrder === 'number' &&
typeof strategy2.sortOrder === 'number'
) {
return strategy1.sortOrder - strategy2.sortOrder;
}
return 0;
})
.map((strategy) => strategy.id);

const eventPreData: StrategyIds = { strategyIds: existingOrder };

await Promise.all(
sortOrders.map(async ({ id, sortOrder }) =>
this.featureStrategiesStore.updateSortOrder(id, sortOrder),
),
sortOrders.map(async ({ id, sortOrder }) => {
await this.featureStrategiesStore.updateSortOrder(
id,
sortOrder,
);
}),
);
const newOrder = (
await this.getStrategiesForEnvironment(
project,
featureName,
environment,
)
)
.sort((strategy1, strategy2) => {
if (
typeof strategy1.sortOrder === 'number' &&
typeof strategy2.sortOrder === 'number'
) {
return strategy1.sortOrder - strategy2.sortOrder;
}
return 0;
})
.map((strategy) => strategy.id);

const eventData: StrategyIds = { strategyIds: newOrder };
const tags = await this.tagStore.getAllTagsForFeature(featureName);
const event = new StrategiesOrderChangedEvent({
featureName,
environment,
project,
createdBy,
preData: eventPreData,
data: eventData,
tags: tags,
});
await this.eventStore.store(event);
}

async createStrategy(
Expand Down Expand Up @@ -473,24 +554,31 @@ class FeatureToggleService {
);
}

const tags = await this.tagStore.getAllTagsForFeature(featureName);
const segments = await this.segmentService.getByStrategy(
newFeatureStrategy.id,
);

const strategy = this.featureStrategyToPublic(
newFeatureStrategy,
segments,
);
await this.eventStore.store(
new FeatureStrategyAddEvent({
project: projectId,

if (this.flagResolver.isEnabled('strategyVariant')) {
const tags = await this.tagStore.getAllTagsForFeature(
featureName,
createdBy,
environment,
data: strategy,
tags,
}),
);
);

await this.eventStore.store(
new FeatureStrategyAddEvent({
project: projectId,
featureName,
createdBy,
environment,
data: strategy,
tags,
}),
);
}
return strategy;
} catch (e) {
if (e.code === FOREIGN_KEY_VIOLATION) {
Expand Down
36 changes: 35 additions & 1 deletion src/lib/types/events.ts
Expand Up @@ -31,7 +31,7 @@ export const FEATURE_ENVIRONMENT_ENABLED =
'feature-environment-enabled' as const;
export const FEATURE_ENVIRONMENT_DISABLED =
'feature-environment-disabled' as const;

export const STRATEGY_ORDER_CHANGED = 'strategy-order-changed';
export const STRATEGY_CREATED = 'strategy-created' as const;
export const STRATEGY_DELETED = 'strategy-deleted' as const;
export const STRATEGY_DEPRECATED = 'strategy-deprecated' as const;
Expand Down Expand Up @@ -142,6 +142,7 @@ export const IEventTypes = [
FEATURE_STRATEGY_UPDATE,
FEATURE_STRATEGY_ADD,
FEATURE_STRATEGY_REMOVE,
STRATEGY_ORDER_CHANGED,
DROP_FEATURE_TAGS,
FEATURE_UNTAGGED,
FEATURE_STALE_ON,
Expand Down Expand Up @@ -330,6 +331,39 @@ export class FeatureEnvironmentEvent extends BaseEvent {
this.environment = p.environment;
}
}
export type StrategyIds = { strategyIds: string[] };
export class StrategiesOrderChangedEvent extends BaseEvent {
readonly project: string;

readonly featureName: string;

readonly environment: string;

readonly data: StrategyIds;

readonly preData: StrategyIds;

/**
* @param createdBy accepts a string for backward compatibility. Prefer using IUser for standardization
*/
constructor(p: {
project: string;
featureName: string;
environment: string;
createdBy: string | IUser;
data: StrategyIds;
preData: StrategyIds;
tags: ITag[];
}) {
super(STRATEGY_ORDER_CHANGED, p.createdBy, p.tags);
const { project, featureName, environment, data, preData } = p;
this.project = project;
this.featureName = featureName;
this.environment = environment;
this.data = data;
this.preData = preData;
}
}

export class FeatureVariantEvent extends BaseEvent {
readonly project: string;
Expand Down

0 comments on commit 1f21770

Please sign in to comment.