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: Vercel Edge Config Adapter #896

Merged
merged 9 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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 @@ -172,7 +172,7 @@ describe('EnvironmentConfigManager Unit Tests', () => {
expect(trackSDKConfigEvent_mock).toBeCalledWith(
'https://config-cdn.devcycle.com/config/v1/server/sdkKey.json',
expect.any(Number),
expect.objectContaining({ status: 200 }),
expect.objectContaining({ resStatus: 200 }),
undefined,
undefined,
undefined,
Expand Down Expand Up @@ -211,7 +211,7 @@ describe('EnvironmentConfigManager Unit Tests', () => {

const envConfig = getConfigManager(logger, 'sdkKey', {})
expect(envConfig.fetchConfigPromise).rejects.toThrow(
'Invalid SDK key provided:',
'Invalid SDK key provided',
)
expect(setInterval_mock).toHaveBeenCalledTimes(0)
})
Expand Down
78 changes: 78 additions & 0 deletions lib/shared/config-manager/src/CDNConfigSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { ConfigBody, DVCLogger } from '@devcycle/types'
import { ConfigSource } from './ConfigSource'
import { getEnvironmentConfig } from './request'
import { ResponseError, UserError } from '@devcycle/server-request'

export class CDNConfigSource extends ConfigSource {
constructor(
private cdnURI: string,
private logger: DVCLogger,
private requestTimeoutMS: number,
) {
super()
}

async getConfig(
sdkKey: string,
kind: 'server' | 'bootstrap',
lastModifiedThreshold?: string,
): Promise<[ConfigBody | null, Record<string, unknown>]> {
let res: Response
try {
res = await getEnvironmentConfig({
logger: this.logger,
url: this.getConfigURL(sdkKey, kind),
requestTimeout: this.requestTimeoutMS,
currentEtag: this.configEtag,
currentLastModified: this.configLastModified,
sseLastModified: lastModifiedThreshold,
})
} catch (e) {
if (e instanceof ResponseError && e.status === 403) {
throw new UserError(`Invalid SDK key provided: ${sdkKey}`)
}
throw e
}

const metadata = {
resEtag: res.headers.get('etag') ?? undefined,
resLastModified: res.headers.get('last-modified') ?? undefined,
resRayId: res.headers.get('cf-ray') ?? undefined,
resStatus: res.status ?? undefined,
}

const projectConfig = (await res.json()) as unknown

this.logger.debug(
`Downloaded config, status: ${
res?.status
}, etag: ${res?.headers.get('etag')}`,
)

if (res.status === 304) {
this.logger.debug(
`Config not modified, using cache, etag: ${this.configEtag}` +
`, last-modified: ${this.configLastModified}`,
)
} else if (res.status === 200 && projectConfig) {
const lastModifiedHeader = res.headers.get('last-modified')
if (this.isLastModifiedHeaderOld(lastModifiedHeader ?? null)) {
this.logger.debug(
'Skipping saving config, existing last modified date is newer.',
)
return [null, metadata]
}
this.configEtag = res.headers.get('etag') || ''
this.configLastModified = lastModifiedHeader || ''
return [projectConfig as ConfigBody, metadata]
}
return [null, metadata]
}

getConfigURL(sdkKey: string, kind: 'server' | 'bootstrap'): string {
if (kind === 'bootstrap') {
return `${this.cdnURI}/config/v1/server/bootstrap/${sdkKey}.json`
}
return `${this.cdnURI}/config/v1/server/${sdkKey}.json`
}
}
44 changes: 44 additions & 0 deletions lib/shared/config-manager/src/ConfigSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { ConfigBody } from '@devcycle/types'
import { isValidDate } from './request'

export abstract class ConfigSource {
configEtag?: string
configLastModified?: string

/**
* Method to get the config from the source.
* Should return null if the config has not changed, and throw an error if it could not be retrieved.
* @param sdkKey
* @param kind
* @param lastModifiedThreshold
*/
abstract getConfig(
sdkKey: string,
kind: 'server' | 'bootstrap',
lastModifiedThreshold?: string,
): Promise<[ConfigBody | null, Record<string, unknown>]>

/**
* Return the URL (or path or storage key etc.) that will be used to retrieve the config for the given SDK key
* @param sdkKey
* @param kind
*/
abstract getConfigURL(sdkKey: string, kind: 'server' | 'bootstrap'): string

protected isLastModifiedHeaderOld(
lastModifiedHeader: string | null,
): boolean {
const lastModifiedHeaderDate = lastModifiedHeader
? new Date(lastModifiedHeader)
: null
const configLastModifiedDate = this.configLastModified
? new Date(this.configLastModified)
: null

return (
isValidDate(configLastModifiedDate) &&
isValidDate(lastModifiedHeaderDate) &&
lastModifiedHeaderDate <= configLastModifiedDate
)
}
}
Loading
Loading