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

chore: added feature flag #121

Merged
merged 2 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 .env.defaults
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,5 @@ AWS_SECRET_ACCESS_KEY=
AWS_S3_BUCKET=
AWS_S3_REGION=
AWS_S3_ENDPOINT=
FF_URL=https://feature-flags.decentraland.org
ATLAS_SERVER_URL=
14 changes: 13 additions & 1 deletion src/components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { createDistrictComponent } from './modules/district/component'
import { createImageComponent } from './modules/image/component'
import { createMapComponent } from './modules/map/component'
import { createRentalsComponent } from './modules/rentals/component'
import { createFeaturesComponent } from './modules/features/component'
import { AppComponents, GlobalContext } from './types'
import { metricDeclarations } from './metrics'
import {
Expand Down Expand Up @@ -113,7 +114,17 @@ export async function initComponents(): Promise<AppComponents> {
const statusChecks = await createStatusCheckComponent({ server, config })
const renderMiniMap = await createMiniMapRendererComponent({ map })
const renderEstateMiniMap = await createEstatesRendererComponent({ map })

const features = await createFeaturesComponent(
{
config,
logs,
fetch,
},
(await config.requireString('ATLAS_SERVER_URL')) ||
`http://${await config.getString(
'HTTP_SERVER_HOST'
)}:${await config.getString('HTTP_SERVER_PORT')}`
)
return {
config,
api,
Expand All @@ -131,5 +142,6 @@ export async function initComponents(): Promise<AppComponents> {
rentals,
renderMiniMap,
renderEstateMiniMap,
features,
}
}
75 changes: 45 additions & 30 deletions src/controllers/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,71 +3,86 @@ import { cacheWrapper } from '../logic/cache-wrapper'
import { extractParams, getFilterFromUrl } from '../logic/filter-params'
import { isErrorWithMessage } from '../logic/error'
import { AppComponents, Context } from '../types'
import { ApplicationName, Feature } from '../modules/features/types'

export const createTilesRequestHandler = (
components: Pick<AppComponents, 'map'>
components: Pick<AppComponents, 'map' | 'features'>
) => {
const { map } = components
const { map, features } = components
return cacheWrapper(
async (context: { url: URL }) => {
if (!map.isReady()) {
return { status: 503, body: 'Not ready' }
}

const lastUploadedUrls = map.getLastUploadedTilesUrl()
if (!lastUploadedUrls.v2) {
const tiles = await map.getTiles()
const data = getFilterFromUrl(context.url, tiles)
return {
status: 200,
headers: {
'content-type': 'application/json',
} as Record<string, string>,
body: JSON.stringify({ ok: true, data }),
if (
await features.getIsFeatureEnabled(
ApplicationName.DAPPS,
Feature.ATLAS_REDIRECT_TO_S3
)
) {
const lastUploadedUrls = map.getLastUploadedTilesUrl()
if (lastUploadedUrls.v2) {
return {
status: 301,
headers: {
location: lastUploadedUrls.v2,
'cache-control': 'public, max-age=60',
} as Record<string, string>,
}
}
}

const tiles = await map.getTiles()
const data = getFilterFromUrl(context.url, tiles)
return {
status: 301,
status: 200,
headers: {
location: lastUploadedUrls.v2,
'cache-control': 'public, max-age=60',
'content-type': 'application/json',
} as Record<string, string>,
body: JSON.stringify({ ok: true, data }),
}
},
[map.getLastUpdatedAt]
)
}

export const createLegacyTilesRequestHandler = (
components: Pick<AppComponents, 'map'>
components: Pick<AppComponents, 'map' | 'features'>
) => {
const { map } = components
const { map, features } = components
return cacheWrapper(
async (context: { url: URL }) => {
if (!map.isReady()) {
return { status: 503, body: 'Not ready' }
}

const lastUploadedUrls = map.getLastUploadedTilesUrl()
if (!lastUploadedUrls.v1) {
const tiles = await map.getTiles()
const data = toLegacyTiles(getFilterFromUrl(context.url, tiles))
return {
status: 200,
headers: {
'content-type': 'application/json',
} as Record<string, string>,
body: JSON.stringify({ ok: true, data }),
if (
await features.getIsFeatureEnabled(
ApplicationName.DAPPS,
Feature.ATLAS_REDIRECT_TO_S3
)
) {
const lastUploadedUrls = map.getLastUploadedTilesUrl()
if (lastUploadedUrls.v1) {
return {
status: 301,
headers: {
location: lastUploadedUrls.v1,
'cache-control': 'public, max-age=60',
} as Record<string, string>,
}
}
}

const tiles = await map.getTiles()
const data = toLegacyTiles(getFilterFromUrl(context.url, tiles))
return {
status: 301,
status: 200,
headers: {
location: lastUploadedUrls.v1,
'cache-control': 'public, max-age=60',
'content-type': 'application/json',
} as Record<string, string>,
body: JSON.stringify({ ok: true, data }),
}
},
[map.getLastUpdatedAt]
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { Router } from '@well-known-components/http-server'

export type RoutesComponents = Pick<
AppComponents,
'server' | 'map' | 'image' | 'config' | 'api' | 'district'
'server' | 'map' | 'image' | 'config' | 'api' | 'district' | 'features'
>

// We return the entire router because it will be easier to test than a whole server
Expand Down
88 changes: 88 additions & 0 deletions src/modules/features/component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { IFetchComponent } from '@well-known-components/http-server'
import {
IConfigComponent,
ILoggerComponent,
} from '@well-known-components/interfaces'
import { FeaturesFlagsResponse, IFeaturesComponent } from './types'

export type NeededComponents = {
config: IConfigComponent
fetch: IFetchComponent
logs: ILoggerComponent
}

export async function createFeaturesComponent(
components: NeededComponents,
referer: string
): Promise<IFeaturesComponent> {
const { config, fetch, logs } = components
const FF_URL =
(await config.getString('FF_URL')) ??
'https://feature-flags.decentraland.org'

const logger = logs.getLogger('transactions-server')

async function getEnvFeature(
app: string,
feature: string
): Promise<string | undefined> {
return config.getString(`FF_${app}_${feature}`.toUpperCase())
}

async function fetchFeatureFlags(
app: string
): Promise<FeaturesFlagsResponse | null> {
try {
const response = await fetch.fetch(`${FF_URL}/${app}.json`, {
headers: {
Referer: referer,
},
})

if (response.ok) {
return await response.json()
} else {
throw new Error(`Could not fetch features service from ${FF_URL}`)
}
} catch (error) {
logger.error(error as Error)
}

return null
}

async function getIsFeatureEnabled(
app: string,
feature: string
): Promise<boolean> {
const envFeatureFlag = await getEnvFeature(app, feature)

if (envFeatureFlag) {
return envFeatureFlag === '1' ? true : false
}

const featureFlags = await fetchFeatureFlags(app)

return !!featureFlags?.flags[`${app}-${feature}`]
}

async function getFeatureVariant<FeatureFlagVariant>(
app: string,
feature: string
): Promise<FeatureFlagVariant | null> {
const ffKey = `${app}-${feature}`
const featureFlags = await fetchFeatureFlags(app)

if (featureFlags?.flags[ffKey] && featureFlags?.variants[ffKey]) {
return featureFlags.variants[ffKey] as unknown as FeatureFlagVariant
}

return null
}

return {
getEnvFeature,
getIsFeatureEnabled,
getFeatureVariant,
}
}
49 changes: 49 additions & 0 deletions src/modules/features/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
export type IFeaturesComponent = {
/**
* Helper to get whether a feature flag is enabled or disabled.
* It will first look into your env file for the feature flag, if it is not defined there,
* it will look it in the requested and stored features data.
* The env key will be determined from the application and the flag. For example, if the
* application is "explorer" and the flag is "some-crazy-feature", it will look
* for it as FF_EXPLORER_SOME_CRAZY_FEATURE.
* @param app Appplication name.
* @param feature Feature key without the application name prefix. For example for the "builder-feature".
* @returns Whether the feature is enabled or not and its variant.
*/
getEnvFeature(app: string, feature: string): Promise<string | undefined>
getIsFeatureEnabled(app: string, feature: string): Promise<boolean>
getFeatureVariant(
app: string,
feature: string
): Promise<FeatureFlagVariant | null>
}

export type FeaturesFlagsResponse = {
flags: Record<string, boolean>
variants: Record<string, FeatureFlagVariant>
}

export type FeatureFlagVariant = {
name: string
payload: {
type: string
value: string
}
enabled: boolean
}

export enum Feature {
ATLAS_REDIRECT_TO_S3 = 'atlas-redirect-to-s3',
}

export enum ApplicationName {
EXPLORER = 'explorer',
BUILDER = 'builder',
MARKETPLACE = 'marketplace',
ACCOUNT = 'account',
DAO = 'dao',
DAPPS = 'dapps',
EVENTS = 'events',
LANDING = 'landing',
TEST = 'test',
}
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { IRentalsComponent } from './modules/rentals/types'
import { ISubgraphComponent } from '@well-known-components/thegraph-component'
import { Metrics } from './metrics'
import { MiniMapRendererComponent } from './adapters/mini-map-renderer'
import { IFeaturesComponent } from './modules/features/types'

export type GlobalContext = {
components: AppComponents
Expand All @@ -37,6 +38,7 @@ export type AppComponents = {
statusChecks: IBaseComponent
renderMiniMap: MiniMapRendererComponent
renderEstateMiniMap: MiniMapRendererComponent
features: IFeaturesComponent
}

export type TestComponents = AppComponents
Expand Down
Loading