Skip to content

Commit

Permalink
feat: Vercel Edge Config Adapter (#896)
Browse files Browse the repository at this point in the history
Co-authored-by: emmawillis <[email protected]>
  • Loading branch information
ajwootto and emmawillis authored Jul 22, 2024
1 parent a868a66 commit 11aa09c
Show file tree
Hide file tree
Showing 21 changed files with 525 additions and 86 deletions.
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

0 comments on commit 11aa09c

Please sign in to comment.