|
| 1 | +import type { CcApiContextQuery } from '@aws-cdk/cloud-assembly-schema'; |
| 2 | +import type { ResourceDescription } from '@aws-sdk/client-cloudcontrol'; |
| 3 | +import { ResourceNotFoundException } from '@aws-sdk/client-cloudcontrol'; |
| 4 | +import type { ICloudControlClient, SdkProvider } from '../api/aws-auth'; |
| 5 | +import { initContextProviderSdk } from '../api/aws-auth'; |
| 6 | +import type { ContextProviderPlugin } from '../api/plugin'; |
| 7 | +import { ContextProviderError } from '../api/toolkit-error'; |
| 8 | +import { findJsonValue, getResultObj } from '../util'; |
| 9 | + |
| 10 | +export class CcApiContextProviderPlugin implements ContextProviderPlugin { |
| 11 | + constructor(private readonly aws: SdkProvider) { |
| 12 | + } |
| 13 | + |
| 14 | + /** |
| 15 | + * This returns a data object with the value from CloudControl API result. |
| 16 | + * |
| 17 | + * See the documentation in the Cloud Assembly Schema for the semantics of |
| 18 | + * each query parameter. |
| 19 | + */ |
| 20 | + public async getValue(args: CcApiContextQuery) { |
| 21 | + // Validate input |
| 22 | + if (args.exactIdentifier && args.propertyMatch) { |
| 23 | + throw new ContextProviderError(`Provider protocol error: specify either exactIdentifier or propertyMatch, but not both (got ${JSON.stringify(args)})`); |
| 24 | + } |
| 25 | + if (args.ignoreErrorOnMissingContext && args.dummyValue === undefined) { |
| 26 | + throw new ContextProviderError(`Provider protocol error: if ignoreErrorOnMissingContext is set, a dummyValue must be supplied (got ${JSON.stringify(args)})`); |
| 27 | + } |
| 28 | + if (args.dummyValue !== undefined && (!Array.isArray(args.dummyValue) || !args.dummyValue.every(isObject))) { |
| 29 | + throw new ContextProviderError(`Provider protocol error: dummyValue must be an array of objects (got ${JSON.stringify(args.dummyValue)})`); |
| 30 | + } |
| 31 | + |
| 32 | + // Do the lookup |
| 33 | + const cloudControl = (await initContextProviderSdk(this.aws, args)).cloudControl(); |
| 34 | + |
| 35 | + try { |
| 36 | + let resources: FoundResource[]; |
| 37 | + if (args.exactIdentifier) { |
| 38 | + // use getResource to get the exact indentifier |
| 39 | + resources = await this.getResource(cloudControl, args.typeName, args.exactIdentifier); |
| 40 | + } else if (args.propertyMatch) { |
| 41 | + // use listResource |
| 42 | + resources = await this.listResources(cloudControl, args.typeName, args.propertyMatch, args.expectedMatchCount); |
| 43 | + } else { |
| 44 | + throw new ContextProviderError(`Provider protocol error: neither exactIdentifier nor propertyMatch is specified in ${JSON.stringify(args)}.`); |
| 45 | + } |
| 46 | + |
| 47 | + return resources.map((r) => getResultObj(r.properties, r.identifier, args.propertiesToReturn)); |
| 48 | + } catch (err) { |
| 49 | + if (err instanceof ZeroResourcesFoundError && args.ignoreErrorOnMissingContext) { |
| 50 | + // We've already type-checked dummyValue. |
| 51 | + return args.dummyValue; |
| 52 | + } |
| 53 | + throw err; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Calls getResource from CC API to get the resource. |
| 59 | + * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/get-resource.html |
| 60 | + * |
| 61 | + * Will always return exactly one resource, or fail. |
| 62 | + */ |
| 63 | + private async getResource( |
| 64 | + cc: ICloudControlClient, |
| 65 | + typeName: string, |
| 66 | + exactIdentifier: string, |
| 67 | + ): Promise<FoundResource[]> { |
| 68 | + try { |
| 69 | + const result = await cc.getResource({ |
| 70 | + TypeName: typeName, |
| 71 | + Identifier: exactIdentifier, |
| 72 | + }); |
| 73 | + if (!result.ResourceDescription) { |
| 74 | + throw new ContextProviderError('Unexpected CloudControl API behavior: returned empty response'); |
| 75 | + } |
| 76 | + |
| 77 | + return [foundResourceFromCcApi(result.ResourceDescription)]; |
| 78 | + } catch (err: any) { |
| 79 | + if (err instanceof ResourceNotFoundException || (err as any).name === 'ResourceNotFoundException') { |
| 80 | + throw new ZeroResourcesFoundError(`No resource of type ${typeName} with identifier: ${exactIdentifier}`); |
| 81 | + } |
| 82 | + if (!(err instanceof ContextProviderError)) { |
| 83 | + throw new ContextProviderError(`Encountered CC API error while getting ${typeName} resource ${exactIdentifier}: ${err.message}`); |
| 84 | + } |
| 85 | + throw err; |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Calls listResources from CC API to get the resources and apply args.propertyMatch to find the resources. |
| 91 | + * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/list-resources.html |
| 92 | + * |
| 93 | + * Will return 0 or more resources. |
| 94 | + * |
| 95 | + * Does not currently paginate through more than one result page. |
| 96 | + */ |
| 97 | + private async listResources( |
| 98 | + cc: ICloudControlClient, |
| 99 | + typeName: string, |
| 100 | + propertyMatch: Record<string, unknown>, |
| 101 | + expectedMatchCount?: CcApiContextQuery['expectedMatchCount'], |
| 102 | + ): Promise<FoundResource[]> { |
| 103 | + try { |
| 104 | + const result = await cc.listResources({ |
| 105 | + TypeName: typeName, |
| 106 | + |
| 107 | + }); |
| 108 | + const found = (result.ResourceDescriptions ?? []) |
| 109 | + .map(foundResourceFromCcApi) |
| 110 | + .filter((r) => { |
| 111 | + return Object.entries(propertyMatch).every(([propPath, expected]) => { |
| 112 | + const actual = findJsonValue(r.properties, propPath); |
| 113 | + return propertyMatchesFilter(actual, expected); |
| 114 | + }); |
| 115 | + }); |
| 116 | + |
| 117 | + if ((expectedMatchCount === 'at-least-one' || expectedMatchCount === 'exactly-one') && found.length === 0) { |
| 118 | + throw new ZeroResourcesFoundError(`Could not find any resources matching ${JSON.stringify(propertyMatch)}`); |
| 119 | + } |
| 120 | + if ((expectedMatchCount === 'at-most-one' || expectedMatchCount === 'exactly-one') && found.length > 1) { |
| 121 | + throw new ContextProviderError(`Found ${found.length} resources matching ${JSON.stringify(propertyMatch)}; please narrow the search criteria`); |
| 122 | + } |
| 123 | + |
| 124 | + return found; |
| 125 | + } catch (err: any) { |
| 126 | + if (!(err instanceof ContextProviderError) && !(err instanceof ZeroResourcesFoundError)) { |
| 127 | + throw new ContextProviderError(`Encountered CC API error while listing ${typeName} resources matching ${JSON.stringify(propertyMatch)}: ${err.message}`); |
| 128 | + } |
| 129 | + throw err; |
| 130 | + } |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +/** |
| 135 | + * Convert a CC API response object into a nicer object (parse the JSON) |
| 136 | + */ |
| 137 | +function foundResourceFromCcApi(desc: ResourceDescription): FoundResource { |
| 138 | + return { |
| 139 | + identifier: desc.Identifier ?? '*MISSING*', |
| 140 | + properties: JSON.parse(desc.Properties ?? '{}'), |
| 141 | + }; |
| 142 | +} |
| 143 | + |
| 144 | +/** |
| 145 | + * Whether the given property value matches the given filter |
| 146 | + * |
| 147 | + * For now we just check for strict equality, but we can implement pattern matching and fuzzy matching here later |
| 148 | + */ |
| 149 | +function propertyMatchesFilter(actual: unknown, expected: unknown) { |
| 150 | + return expected === actual; |
| 151 | +} |
| 152 | + |
| 153 | +function isObject(x: unknown): x is {[key: string]: unknown} { |
| 154 | + return typeof x === 'object' && x !== null && !Array.isArray(x); |
| 155 | +} |
| 156 | + |
| 157 | +/** |
| 158 | + * A parsed version of the return value from CCAPI |
| 159 | + */ |
| 160 | +interface FoundResource { |
| 161 | + readonly identifier: string; |
| 162 | + readonly properties: Record<string, unknown>; |
| 163 | +} |
| 164 | + |
| 165 | +/** |
| 166 | + * A specific lookup failure indicating 0 resources found that can be recovered |
| 167 | + */ |
| 168 | +class ZeroResourcesFoundError extends Error { |
| 169 | +} |
0 commit comments