Skip to content

Commit

Permalink
build: set "target":"es2021"
Browse files Browse the repository at this point in the history
Problem:
"es6" is very old and all of our targets support es2021.
Targeting es6 disallows new javascript features such as Promise.allSettled().

Solution:
- increase target to "es2021".
    - also update webpack config (why is this duplicated across configs?)
- improve logging
- invalidate(): use Promise.allSettled() instead of all()
  • Loading branch information
justinmk3 committed Sep 19, 2023
1 parent de8244c commit 5b0621b
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 34 deletions.
4 changes: 1 addition & 3 deletions src/auth/providers/credentialsProviderManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ export class CredentialsProviderManager {
telemetry.aws_loadCredentials.emit({ credentialSourceId: telemType, value: 1 })
providers = providers.concat(provider)
} else {
getLogger().verbose(
`provider for ${provider.getCredentialsId().credentialTypeId} unavailable in this environment`
)
getLogger().verbose('auth: "%s" provider unavailable', provider.getCredentialsId().credentialTypeId)
}
}

Expand Down
5 changes: 2 additions & 3 deletions src/auth/providers/sharedCredentialsProviderFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,17 @@ export class SharedCredentialsProviderFactory extends BaseCredentialsProviderFac
private async loadSharedCredentialsProviders(): Promise<void> {
this.resetProviders()

this.logger.verbose('Loading all Shared Credentials Sections')
const result = await loadSharedCredentialsSections()
if (result.errors.length > 0) {
const errors = result.errors.map(e => e.message).join('\t\n')
getLogger().verbose(`credentials: errors occurred while parsing:\n%s`, errors)
getLogger().warn(`credentials: errors while parsing:\n%s`, errors)
}

this.loadedCredentialsModificationMillis = await this.getLastModifiedMillis(getCredentialsFilename())
this.loadedConfigModificationMillis = await this.getLastModifiedMillis(getConfigFilename())
await updateAwsSdkLoadConfigEnvVar()

getLogger().verbose(`credentials: found sections: ${result.sections.map(s => `${s.type}:${s.name}`)}`)
getLogger().verbose(`credentials: found sections: ${result.sections.map(s => `${s.type}:${s.name}`).join(' ')}`)
for (const section of result.sections) {
if (section.type === 'profile') {
await this.addProviderIfValid(
Expand Down
2 changes: 1 addition & 1 deletion src/auth/sso/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function getRegistrationCache(directory = getCacheDir()): KeyedCache<Clie
const read = (data: StoredRegistration) => ({ ...data, expiresAt: new Date(data.expiresAt) })
const write = (data: ClientRegistration) => ({ ...data, expiresAt: data.expiresAt.toISOString() })

const logger = (message: string) => getLogger().debug(`SSO registration cache: ${message}`)
const logger = (message: string) => getLogger().debug('auth: SSO registration cache: %s', message)
const cache: KeyedCache<StoredRegistration, RegistrationKey> = createDiskCache(
(registrationKey: RegistrationKey) => getRegistrationCacheFile(directory, registrationKey),
logger
Expand Down
14 changes: 9 additions & 5 deletions src/auth/sso/ssoAccessTokenProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,10 @@ export class SsoAccessTokenProvider {
) {}

public async invalidate(): Promise<void> {
await Promise.all([
this.cache.token.clear(this.tokenCacheKey),
this.cache.registration.clear(this.registrationCacheKey),
// Use allSettled() instead of all() to ensure all clear() calls are resolved.
await Promise.allSettled([
this.cache.token.clear(this.tokenCacheKey, 'SsoAccessTokenProvider.invalidate()'),
this.cache.registration.clear(this.registrationCacheKey, 'SsoAccessTokenProvider.invalidate()'),
])
}

Expand Down Expand Up @@ -114,7 +115,7 @@ export class SsoAccessTokenProvider {
return await this.authorize(registration)
} catch (err) {
if (err instanceof SSOOIDCServiceException && isClientFault(err)) {
await this.cache.registration.clear(cacheKey)
await this.cache.registration.clear(cacheKey, `client fault: SSOOIDCServiceException: ${err.message}`)
}

throw err
Expand All @@ -141,7 +142,10 @@ export class SsoAccessTokenProvider {
} as AwsRefreshCredentials)

if (err instanceof SSOOIDCServiceException && isClientFault(err)) {
await this.cache.token.clear(this.tokenCacheKey)
await this.cache.token.clear(
this.tokenCacheKey,
`client fault: SSOOIDCServiceException: ${err.message}`
)
}
}

Expand Down
37 changes: 19 additions & 18 deletions src/shared/utilities/cacheUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,12 @@ export interface KeyedCache<T, K = string> {
save(key: K, data: T): Promise<void>

/**
* Removes the data stored at {@link key}, if any.
* Deletes data stored at {@link key}, if any.
*
* @param key Target key to clear.
* @param reason Partial log message explaining why the data is being deleted.
*/
clear(key: K): Promise<void>
clear(key: K, reason: string): Promise<void>
}

/**
Expand Down Expand Up @@ -71,7 +72,7 @@ export function mapCache<T, U, K>(cache: KeyedCache<T, K>, get: (data: T) => U,
const getIf = (data?: T) => (data !== undefined ? get(data) : undefined)

return {
clear: key => cache.clear(key),
clear: (key, reason) => cache.clear(key, reason),
load: key => cache.load(key).then(getIf),
save: (key, data) => cache.save(key, set(data)),
}
Expand All @@ -91,10 +92,10 @@ export function createDiskCache<T, K>(
mapKey: (key: K) => string,
logger?: (message: string) => void
): KeyedCache<T, K> {
function log(prefix: string, key: K): void {
function log(msg: string, key: K): void {
if (logger) {
const keyMessage = typeof key === 'object' ? JSON.stringify(key) : key
logger(`${prefix} for key '${keyMessage}'`)
logger(`${msg} key: ${keyMessage}`)
}
}

Expand All @@ -104,11 +105,11 @@ export function createDiskCache<T, K>(

try {
const result = JSON.parse(await SystemUtilities.readFile(target))
log('load succeeded', key)
log('loaded', key)
return result
} catch (error) {
if (isFileNotFoundError(error)) {
log('load missed', key)
log('read failed (file not found)', key)
return
}

Expand All @@ -131,16 +132,16 @@ export function createDiskCache<T, K>(
})
}

log('save succeeded', key)
log('saved', key)
},
clear: async key => {
clear: async (key, reason) => {
const target = mapKey(key)

try {
await SystemUtilities.delete(target)
} catch (error) {
if (isFileNotFoundError(error)) {
return log('clear succeeded, file does not exist', key)
return log('file not found', key)
}

throw ToolkitError.chain(error, `Failed to delete "${target}"`, {
Expand All @@ -149,7 +150,7 @@ export function createDiskCache<T, K>(
})
}

log('clear succeeded', key)
log(`deleted (reason: ${reason})`, key)
},
}
}
Expand All @@ -158,9 +159,9 @@ export function createSecretsCache(
secrets: vscode.SecretStorage,
logger?: (message: string) => void
): KeyedCache<string> {
function log(prefix: string, key: string): void {
function log(msg: string, key: string): void {
if (logger) {
logger(`${prefix} for key '${key}'`)
logger(`${msg} key: ${key}`)
}
}

Expand All @@ -170,11 +171,11 @@ export function createSecretsCache(
const value = await secrets.get(key)

if (value === undefined) {
log('load missed', key)
log('read failed (key not found)', key)
return
}

log('load succeeded', key)
log('loaded', key)
return value
} catch (error) {
throw ToolkitError.chain(error, 'Failed to get value from secrets storage', {
Expand All @@ -193,9 +194,9 @@ export function createSecretsCache(
})
}

log('save succeeded', key)
log('saved', key)
},
clear: async key => {
clear: async (key, reason) => {
try {
await secrets.delete(key)
} catch (error) {
Expand All @@ -205,7 +206,7 @@ export function createSecretsCache(
})
}

log('clear succeeded', key)
log(`deleted (reason: ${reason})`, key)
},
}
}
4 changes: 2 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
},
"incremental": true,
"module": "commonjs",
"target": "es6",
"target": "es2021",
"outDir": "dist",
"sourceMap": true,
"moduleResolution": "node",
Expand All @@ -16,7 +16,7 @@
"strict": true,
"noUnusedLocals": true,
"noImplicitOverride": true,
"lib": ["dom", "es6", "esnext.asynciterable"],
"lib": ["dom", "es2021"],
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"jsx": "preserve",
Expand Down
4 changes: 2 additions & 2 deletions webpack.base.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ const baseConfig = {
loader: 'esbuild-loader',
options: {
loader: 'ts',
target: 'es2018',
target: 'es2021',
},
},
],
Expand All @@ -94,7 +94,7 @@ const baseConfig = {
minimize: true,
minimizer: [
new ESBuildMinifyPlugin({
target: 'es2018',
target: 'es2021',
}),
],
},
Expand Down

0 comments on commit 5b0621b

Please sign in to comment.