feat(api): add AppSync GraphQL APIs to the cloud explorer #30

Merged
Zakaria merged 1 commits from feat/appsync into main 2026-10-25 23:46:34 +00:00
23 changed files with 1509 additions and 1 deletions
Showing only changes of commit ca3e67a803 - Show all commits
+1
View File
@@ -81,6 +81,7 @@ cd packages/api && bun run scripts/service-matrix.ts
| Networking | CloudFront / CDN | Yes (list, create, delete, inspect) | No | No |
| Integration | SQS / Messaging / Pub/Sub | Yes (list, create, inspect, delete) | Yes (list, create, delete, inspect) | Yes (list, create, inspect, delete) |
| Integration | API Gateway | Yes (list, create, delete, inspect) | No | No |
| Integration | AppSync / GraphQL APIs | Yes (list, create, delete, inspect) | No | No |
| Integration | SNS / Notifications | Yes (list, create, inspect, delete) | No | No |
| Integration | EventBridge / Events | Yes (list, create, delete, inspect) | No | No |
| Integration | EventBridge Pipes / Pipes | Yes (list, create, delete, inspect) | No | No |
+1
View File
@@ -14,6 +14,7 @@
"@aws-sdk/client-api-gateway": "^3.1076.0",
"@aws-sdk/client-apigatewayv2": "^3.1076.0",
"@aws-sdk/client-appconfig": "^3.1076.0",
"@aws-sdk/client-appsync": "^3.1146.0",
"@aws-sdk/client-athena": "^3.1146.0",
"@aws-sdk/client-auto-scaling": "^3.1146.0",
"@aws-sdk/client-cloudformation": "^3.1111.0",
@@ -0,0 +1,165 @@
import {describe, expect, test} from 'bun:test'
import {
type AppSyncClient,
CreateApiKeyCommand,
CreateDataSourceCommand,
CreateGraphqlApiCommand,
CreateResolverCommand,
DeleteResolverCommand,
GetGraphqlApiCommand,
GetIntrospectionSchemaCommand,
GetSchemaCreationStatusCommand,
ListApiKeysCommand,
ListDataSourcesCommand,
ListGraphqlApisCommand,
ListResolversCommand,
StartSchemaCreationCommand,
} from '@aws-sdk/client-appsync'
import {AwsGraphqlAdapter, objectTypes, schemaFailure, sdlFrom} from './AwsGraphqlAdapter'
import {ValidationError} from '../cloud-spi/errors'
type SendResult = Record<string, unknown>
const sdl = `"""A note"""
type Note { id: ID! text: String }
# the entry points
type Query { note(id: ID!): Note notes(filter: NoteFilter, limit: Int = 10): [Note] }
type Mutation {
addNote(text: String!): Note
}
input NoteFilter { text: String }
schema { query: Query mutation: Mutation }`
const api = {
apiId: 'a1', name: 'notes-api', authenticationType: 'API_KEY', arn: 'arn:aws:appsync:eu-west-1:000000000000:apis/a1',
uris: {GRAPHQL: 'http://localhost:4566/v1/apis/a1/graphql', REALTIME: 'ws://localhost:4566/v1/apis/a1/graphql/realtime'},
}
function adapterWith(handler: (command: object) => SendResult | undefined = () => undefined) {
const sent: object[] = []
const client = {
async send(command: object) {
sent.push(command)
const result = handler(command)
if (result) return result
if (command instanceof GetGraphqlApiCommand) return {graphqlApi: api}
if (command instanceof CreateGraphqlApiCommand) return {graphqlApi: api}
if (command instanceof GetIntrospectionSchemaCommand) return {schema: new TextEncoder().encode(sdl)}
if (command instanceof GetSchemaCreationStatusCommand) return {status: 'SUCCESS'}
if (command instanceof ListApiKeysCommand) return {apiKeys: [{id: 'da2-key', description: 'web', expires: 1793570400}]}
if (command instanceof ListDataSourcesCommand) return {dataSources: [{name: 'notesTable', type: 'AMAZON_DYNAMODB', dynamodbConfig: {tableName: 'notes'}, serviceRoleArn: 'arn:aws:iam::000000000000:role/appsync'}]}
if (command instanceof ListResolversCommand) {
return command.input.typeName === 'Query' ? {resolvers: [{typeName: 'Query', fieldName: 'note', dataSourceName: 'notesTable', kind: 'UNIT', runtime: {name: 'APPSYNC_JS'}, code: 'export function request() {}'}]} : {resolvers: []}
}
return {}
},
}
return {sent, adapter: new AwsGraphqlAdapter(client as unknown as AppSyncClient, async () => {})}
}
describe('AwsGraphqlAdapter', () => {
test('reads the object types and fields a resolver can attach to', () => {
expect(objectTypes(sdl)).toEqual([
{name: 'Query', fields: ['note', 'notes']},
{name: 'Mutation', fields: ['addNote']},
{name: 'Note', fields: ['id', 'text']},
])
expect(objectTypes('type Query { a: String }\nextend type Query { b: Int }')).toEqual([{name: 'Query', fields: ['a', 'b']}])
})
test('reads the SDL whether it comes bare, as from AWS, or wrapped, as from the runtime', () => {
expect(sdlFrom('type Query { a: String }')).toBe('type Query { a: String }')
expect(sdlFrom(JSON.stringify({schema: {definition: 'type Query { a: String }'}}))).toBe('type Query { a: String }')
})
test('explains a rejected schema in the parser\'s words', () => {
const runtime = JSON.stringify({reason: 'CODE_ERROR', detail: {codeErrors: [{errorType: 'PARSER_ERROR', value: "Invalid syntax with offending token '<EOF>' at line 1 column 20"}]}})
expect(schemaFailure(runtime)).toBe("Invalid syntax with offending token '<EOF>' at line 1 column 20")
expect(schemaFailure('Failed to parse schema document')).toBe('Failed to parse schema document')
expect(schemaFailure(undefined)).toBe('AppSync rejected it')
})
test('lists APIs with their endpoint and authorization', async () => {
const {adapter} = adapterWith((command) => command instanceof ListGraphqlApisCommand ? {graphqlApis: [api]} : undefined)
const [listed] = await adapter.list()
expect([listed.id, listed.name, listed.metadata.authenticationLabel, listed.metadata.graphqlUrl]).toEqual(['a1', 'notes-api', 'API key', 'http://localhost:4566/v1/apis/a1/graphql'])
expect(await adapter.list({search: 'other'})).toEqual([])
})
test('describes the schema, keys, data sources and resolvers', async () => {
const {adapter, sent} = adapterWith()
const detail = await adapter.get('a1')
expect(detail?.metadata.definition).toBe(sdl)
expect(detail?.metadata.apiKeys).toEqual([{id: 'da2-key', description: 'web', expiresAt: '2026-11-01T22:00:00.000Z'}])
expect(detail?.metadata.dataSources).toEqual([{name: 'notesTable', type: 'AMAZON_DYNAMODB', description: null, tableName: 'notes', functionArn: null, serviceRoleArn: 'arn:aws:iam::000000000000:role/appsync'}])
expect(detail?.metadata.resolvers).toEqual([{typeName: 'Query', fieldName: 'note', dataSourceName: 'notesTable', kind: 'UNIT', runtime: 'APPSYNC_JS', code: 'export function request() {}'}])
expect((sent.filter((command) => command instanceof ListResolversCommand) as ListResolversCommand[]).map((command) => command.input.typeName)).toEqual(['Query', 'Mutation', 'Note'])
})
test('a new API-key API gets its first key, and Cognito needs a user pool', async () => {
const {adapter, sent} = adapterWith()
await adapter.create({values: {name: 'notes-api', authenticationType: 'API_KEY'}})
expect(sent.some((command) => command instanceof CreateApiKeyCommand)).toBe(true)
await adapter.create({values: {name: 'members', authenticationType: 'AMAZON_COGNITO_USER_POOLS', userPoolId: 'us-east-1_AbC123'}})
const cognito = (sent.filter((command) => command instanceof CreateGraphqlApiCommand) as CreateGraphqlApiCommand[])[1]
expect(cognito.input.userPoolConfig).toEqual({userPoolId: 'us-east-1_AbC123', awsRegion: 'us-east-1', defaultAction: 'ALLOW'})
await expect(adapter.create({values: {name: 'members', authenticationType: 'AMAZON_COGNITO_USER_POOLS'}})).rejects.toBeInstanceOf(ValidationError)
})
test('saving a schema waits for AppSync to compile it and reports a rejection', async () => {
let polls = 0
const {adapter, sent} = adapterWith((command) => command instanceof GetSchemaCreationStatusCommand ? {status: ++polls < 3 ? 'PROCESSING' : 'SUCCESS'} : undefined)
await adapter.updateGraphqlSchema('a1', 'type Query { a: String }')
expect(new TextDecoder().decode((sent.find((command) => command instanceof StartSchemaCreationCommand) as StartSchemaCreationCommand).input.definition)).toBe('type Query { a: String }')
expect(polls).toBeGreaterThanOrEqual(3)
const failing = adapterWith((command) => command instanceof GetSchemaCreationStatusCommand ? {status: 'FAILED', details: 'Syntax Error: Unexpected Name "typo"'} : undefined)
await expect(failing.adapter.updateGraphqlSchema('a1', 'typo Query')).rejects.toThrow('The schema was not saved: Syntax Error: Unexpected Name "typo"')
})
test('creates an API key that expires after the given days', async () => {
const {adapter, sent} = adapterWith()
const before = Math.floor(Date.now() / 1000)
await adapter.createGraphqlApiKey('a1', {description: 'mobile', expiresInDays: 30})
const create = sent.find((command) => command instanceof CreateApiKeyCommand) as CreateApiKeyCommand
expect(create.input.description).toBe('mobile')
expect((create.input.expires ?? 0) - before).toBeGreaterThanOrEqual(30 * 86_400)
await expect(adapter.createGraphqlApiKey('a1', {expiresInDays: 400})).rejects.toBeInstanceOf(ValidationError)
})
test('creates DynamoDB and Lambda data sources with a role, in the API region', async () => {
const {adapter, sent} = adapterWith()
const role = 'arn:aws:iam::000000000000:role/appsync'
await adapter.createGraphqlDataSource('a1', {name: 'notesTable', type: 'AMAZON_DYNAMODB', tableName: 'notes', serviceRoleArn: role})
await adapter.createGraphqlDataSource('a1', {name: 'notesFn', type: 'AWS_LAMBDA', functionArn: 'arn:aws:lambda:eu-west-1:000000000000:function:notes', serviceRoleArn: role})
await adapter.createGraphqlDataSource('a1', {name: 'local', type: 'NONE'})
const [table, fn, none] = (sent.filter((command) => command instanceof CreateDataSourceCommand) as CreateDataSourceCommand[]).map((command) => command.input)
expect(table).toEqual({apiId: 'a1', name: 'notesTable', type: 'AMAZON_DYNAMODB', serviceRoleArn: role, dynamodbConfig: {tableName: 'notes', awsRegion: 'eu-west-1'}})
expect(fn.lambdaConfig).toEqual({lambdaFunctionArn: 'arn:aws:lambda:eu-west-1:000000000000:function:notes'})
expect(none).toEqual({apiId: 'a1', name: 'local', type: 'NONE'})
await expect(adapter.createGraphqlDataSource('a1', {name: 'notesTable', type: 'AMAZON_DYNAMODB', tableName: 'notes'})).rejects.toBeInstanceOf(ValidationError)
await expect(adapter.createGraphqlDataSource('a1', {name: 'bad-name', type: 'NONE'})).rejects.toBeInstanceOf(ValidationError)
})
test('attaches a JavaScript resolver only to a field the schema has', async () => {
const {adapter, sent} = adapterWith()
const code = 'export function request(ctx) { return {} }\nexport function response(ctx) { return ctx.result }'
await adapter.createGraphqlResolver('a1', {typeName: 'Mutation', fieldName: 'addNote', dataSourceName: 'notesTable', code})
expect((sent.find((command) => command instanceof CreateResolverCommand) as CreateResolverCommand).input).toEqual({
apiId: 'a1', typeName: 'Mutation', fieldName: 'addNote', dataSourceName: 'notesTable', kind: 'UNIT', code, runtime: {name: 'APPSYNC_JS', runtimeVersion: '1.0.0'},
})
await expect(adapter.createGraphqlResolver('a1', {typeName: 'Query', fieldName: 'nope', dataSourceName: 'notesTable', code})).rejects.toThrow('Query has no field nope')
await expect(adapter.createGraphqlResolver('a1', {typeName: 'Ghost', fieldName: 'a', dataSourceName: 'notesTable', code})).rejects.toThrow('The schema has no type Ghost')
await expect(adapter.createGraphqlResolver('a1', {typeName: 'Query', fieldName: 'note', dataSourceName: 'notesTable', code: 'return 1'})).rejects.toBeInstanceOf(ValidationError)
})
test('detaches a resolver', async () => {
const {adapter, sent} = adapterWith()
await adapter.deleteGraphqlResolver('a1', 'Query', 'note')
expect((sent.find((command) => command instanceof DeleteResolverCommand) as DeleteResolverCommand).input).toEqual({apiId: 'a1', typeName: 'Query', fieldName: 'note'})
})
})
@@ -0,0 +1,405 @@
import {
type ApiKey,
type AppSyncClient,
CreateApiKeyCommand,
CreateDataSourceCommand,
CreateGraphqlApiCommand,
CreateResolverCommand,
type DataSource,
DeleteApiKeyCommand,
DeleteDataSourceCommand,
DeleteGraphqlApiCommand,
DeleteResolverCommand,
GetGraphqlApiCommand,
GetIntrospectionSchemaCommand,
GetSchemaCreationStatusCommand,
type GetSchemaCreationStatusCommandOutput,
type GraphqlApi,
ListApiKeysCommand,
ListDataSourcesCommand,
ListGraphqlApisCommand,
ListResolversCommand,
type Resolver,
StartSchemaCreationCommand,
} from '@aws-sdk/client-appsync'
import {NotFoundError, RuntimeError, ValidationError} from '../cloud-spi/errors'
import {
awsGraphqlSchema,
GRAPHQL_API_KEY_MAX_DAYS,
GRAPHQL_API_NAME_PATTERN,
GRAPHQL_AUTH_TYPES,
GRAPHQL_DATA_SOURCE_NAME_PATTERN,
GRAPHQL_DATA_SOURCE_TYPES,
} from '../cloud-spi/graphqlSchema'
import type {
CloudResource,
CloudServiceAdapter,
CreateResourceInput,
GraphqlApiKeyInput,
GraphqlDataSourceInput,
GraphqlResolverInput,
ResourceQuery,
ServiceSchema,
} from '../cloud-spi/types'
const AUTH_LABELS: Record<string, string> = {API_KEY: 'API key', AWS_IAM: 'IAM', AMAZON_COGNITO_USER_POOLS: 'Cognito user pool', OPENID_CONNECT: 'OpenID Connect', AWS_LAMBDA: 'Lambda'}
const DAY_SECONDS = 86_400
/** How long a schema save waits for AppSync to finish compiling it before reporting PROCESSING. */
const SCHEMA_WAIT_ATTEMPTS = 20
const SCHEMA_WAIT_MS = 250
const ROLE_ARN = /^arn:aws[a-z-]*:iam::\d{12}:role\/.+$/
const LAMBDA_ARN = /^arn:aws[a-z-]*:lambda:[a-z0-9-]+:\d{12}:function:.+$/
/**
* Talks to AWS AppSync, verified against Floci core (community, `latest`).
*
* Notes from probing the runtime:
* - APIs, schemas, API keys, data sources and resolvers are all stored, and the
* GraphQL endpoint checks queries against the schema and the caller's key.
* - Resolvers are never run, so every field of a query comes back null. The
* console says so instead of offering a query runner that looks broken.
* - GetIntrospectionSchema wraps the SDL in {"schema": {"definition": …}} where
* AWS returns the SDL itself; both are read.
* - ListTypes returns nothing, so the types a resolver can attach to come from
* the schema's own SDL.
*/
export class AwsGraphqlAdapter implements CloudServiceAdapter {
readonly cloud = 'aws' as const
readonly service = 'graphql' as const
constructor(private readonly appsync: AppSyncClient, private readonly sleep: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) {}
schema(): ServiceSchema {
return awsGraphqlSchema()
}
async list(query: ResourceQuery = {}): Promise<CloudResource[]> {
const found: GraphqlApi[] = []
let next: string | undefined
do {
const res = await this.appsync.send(new ListGraphqlApisCommand({maxResults: 25, ...(next ? {nextToken: next} : {})}))
found.push(...(res.graphqlApis ?? []))
next = res.nextToken
} while (next)
const search = query.search?.trim().toLowerCase()
return found.map((api) => toResource(api)).filter((api) => !search
|| api.name.toLowerCase().includes(search)
|| api.id.toLowerCase().includes(search))
}
async get(id: string): Promise<CloudResource | null> {
let api: GraphqlApi | undefined
try {
api = (await this.appsync.send(new GetGraphqlApiCommand({apiId: id}))).graphqlApi
} catch (error) {
if (errorName(error) === 'NotFoundException') return null
throw error
}
if (!api) return null
const [definition, schemaStatus, apiKeys, dataSources] = await Promise.all([this.definition(id), this.schemaStatus(id), this.apiKeys(id), this.dataSources(id)])
const types = definition ? objectTypes(definition) : []
const resolvers = (await Promise.all(types.map((type) => this.resolvers(id, type.name)))).flat()
return toResource(api, {definition, schemaStatus, apiKeys, dataSources, resolvers, types})
}
async create(input: CreateResourceInput): Promise<CloudResource> {
const values = input.values
const name = text(values.name)
if (!new RegExp(GRAPHQL_API_NAME_PATTERN).test(name)) throw new ValidationError('name must be up to 128 letters, numbers, spaces, dashes or underscores')
const authenticationType = text(values.authenticationType) || 'API_KEY'
if (!(GRAPHQL_AUTH_TYPES as readonly string[]).includes(authenticationType)) throw new ValidationError(`authenticationType must be one of ${GRAPHQL_AUTH_TYPES.join(', ')}`)
const userPoolId = text(values.userPoolId)
if (authenticationType === 'AMAZON_COGNITO_USER_POOLS' && !userPoolId) throw new ValidationError('userPoolId is required for Cognito user pool authorization')
const created = await this.appsync.send(new CreateGraphqlApiCommand({
name,
authenticationType: authenticationType as (typeof GRAPHQL_AUTH_TYPES)[number],
...(authenticationType === 'AMAZON_COGNITO_USER_POOLS' ? {userPoolConfig: {userPoolId, awsRegion: userPoolId.split('_')[0], defaultAction: 'ALLOW'}} : {}),
}))
const apiId = created.graphqlApi?.apiId
if (!apiId) throw new RuntimeError('AppSync did not return the new API id')
// The AppSync console gives a new API-key API its first key, valid for seven days.
if (authenticationType === 'API_KEY') await this.appsync.send(new CreateApiKeyCommand({apiId, expires: expiry(7)}))
return this.detail(apiId)
}
async delete(id: string): Promise<void> {
await this.appsync.send(new DeleteGraphqlApiCommand({apiId: id}))
}
async updateGraphqlSchema(apiId: string, definition: string): Promise<CloudResource> {
const sdl = typeof definition === 'string' ? definition.trim() : ''
if (!sdl) throw new ValidationError('Enter a schema to save')
await this.appsync.send(new StartSchemaCreationCommand({apiId, definition: new TextEncoder().encode(sdl)}))
let status: GetSchemaCreationStatusCommandOutput | null = null
for (let attempt = 0; attempt < SCHEMA_WAIT_ATTEMPTS; attempt++) {
status = await this.appsync.send(new GetSchemaCreationStatusCommand({apiId}))
if (status.status !== 'PROCESSING') break
await this.sleep(SCHEMA_WAIT_MS)
}
if (status?.status === 'FAILED') throw new ValidationError(`The schema was not saved: ${schemaFailure(status.details)}`)
return this.detail(apiId)
}
async createGraphqlApiKey(apiId: string, input: GraphqlApiKeyInput): Promise<CloudResource> {
const days = input.expiresInDays ?? 7
if (!Number.isInteger(days) || days < 1 || days > GRAPHQL_API_KEY_MAX_DAYS) throw new ValidationError(`expiresInDays must be a whole number from 1 to ${GRAPHQL_API_KEY_MAX_DAYS}`)
const description = text(input.description)
await this.appsync.send(new CreateApiKeyCommand({apiId, expires: expiry(days), ...(description ? {description} : {})}))
return this.detail(apiId)
}
async deleteGraphqlApiKey(apiId: string, keyId: string): Promise<CloudResource> {
await this.appsync.send(new DeleteApiKeyCommand({apiId, id: keyId}))
return this.detail(apiId)
}
async createGraphqlDataSource(apiId: string, input: GraphqlDataSourceInput): Promise<CloudResource> {
const name = text(input.name)
if (!new RegExp(GRAPHQL_DATA_SOURCE_NAME_PATTERN).test(name)) throw new ValidationError('name must start with a letter or underscore and use only letters, numbers and underscores')
const type = text(input.type)
if (!(GRAPHQL_DATA_SOURCE_TYPES as readonly string[]).includes(type)) throw new ValidationError(`type must be one of ${GRAPHQL_DATA_SOURCE_TYPES.join(', ')}`)
const description = text(input.description)
const serviceRoleArn = text(input.serviceRoleArn)
if (type !== 'NONE' && !ROLE_ARN.test(serviceRoleArn)) throw new ValidationError('serviceRoleArn must be the IAM role AppSync uses to reach the table or function')
const tableName = text(input.tableName)
if (type === 'AMAZON_DYNAMODB' && !tableName) throw new ValidationError('tableName is required for a DynamoDB data source')
const functionArn = text(input.functionArn)
if (type === 'AWS_LAMBDA' && !LAMBDA_ARN.test(functionArn)) throw new ValidationError('functionArn must be a Lambda function ARN')
const region = await this.region(apiId)
await this.appsync.send(new CreateDataSourceCommand({
apiId,
name,
type: type as (typeof GRAPHQL_DATA_SOURCE_TYPES)[number],
...(description ? {description} : {}),
...(type !== 'NONE' ? {serviceRoleArn} : {}),
...(type === 'AMAZON_DYNAMODB' ? {dynamodbConfig: {tableName, awsRegion: region}} : {}),
...(type === 'AWS_LAMBDA' ? {lambdaConfig: {lambdaFunctionArn: functionArn}} : {}),
}))
return this.detail(apiId)
}
async deleteGraphqlDataSource(apiId: string, name: string): Promise<CloudResource> {
await this.appsync.send(new DeleteDataSourceCommand({apiId, name}))
return this.detail(apiId)
}
async createGraphqlResolver(apiId: string, input: GraphqlResolverInput): Promise<CloudResource> {
const typeName = text(input.typeName)
const fieldName = text(input.fieldName)
const dataSourceName = text(input.dataSourceName)
const code = typeof input.code === 'string' ? input.code : ''
if (!dataSourceName) throw new ValidationError('dataSourceName is required')
if (!/export\s+function\s+request\b/.test(code) || !/export\s+function\s+response\b/.test(code)) {
throw new ValidationError('code must export a request(ctx) and a response(ctx) function')
}
// AppSync refuses a resolver for a field the schema does not have; the runtime does not, so check here.
const definition = await this.definition(apiId)
const type = definition ? objectTypes(definition).find((candidate) => candidate.name === typeName) : undefined
if (!type) throw new ValidationError(`The schema has no type ${typeName}`)
if (!type.fields.includes(fieldName)) throw new ValidationError(`${typeName} has no field ${fieldName}`)
await this.appsync.send(new CreateResolverCommand({
apiId, typeName, fieldName, dataSourceName, kind: 'UNIT', code, runtime: {name: 'APPSYNC_JS', runtimeVersion: '1.0.0'},
}))
return this.detail(apiId)
}
async deleteGraphqlResolver(apiId: string, typeName: string, fieldName: string): Promise<CloudResource> {
await this.appsync.send(new DeleteResolverCommand({apiId, typeName, fieldName}))
return this.detail(apiId)
}
private async detail(apiId: string): Promise<CloudResource> {
const detail = await this.get(apiId)
if (!detail) throw new NotFoundError(`GraphQL API ${apiId} not found`)
return detail
}
private async region(apiId: string): Promise<string> {
const api = (await this.appsync.send(new GetGraphqlApiCommand({apiId}))).graphqlApi
return api?.arn?.split(':')[3] || 'us-east-1'
}
private async definition(apiId: string): Promise<string | null> {
try {
const res = await this.appsync.send(new GetIntrospectionSchemaCommand({apiId, format: 'SDL'}))
return res.schema ? sdlFrom(new TextDecoder().decode(res.schema)) : null
} catch (error) {
if (errorName(error) === 'NotFoundException') return null
throw error
}
}
private async schemaStatus(apiId: string): Promise<{status: string; details: string | null} | null> {
try {
const res = await this.appsync.send(new GetSchemaCreationStatusCommand({apiId}))
return res.status ? {status: res.status, details: res.details ?? null} : null
} catch (error) {
if (errorName(error) === 'NotFoundException') return null
throw error
}
}
private async apiKeys(apiId: string): Promise<ApiKey[]> {
const found: ApiKey[] = []
let next: string | undefined
do {
const res = await this.appsync.send(new ListApiKeysCommand({apiId, maxResults: 25, ...(next ? {nextToken: next} : {})}))
found.push(...(res.apiKeys ?? []))
next = res.nextToken
} while (next)
return found
}
private async dataSources(apiId: string): Promise<DataSource[]> {
const found: DataSource[] = []
let next: string | undefined
do {
const res = await this.appsync.send(new ListDataSourcesCommand({apiId, maxResults: 25, ...(next ? {nextToken: next} : {})}))
found.push(...(res.dataSources ?? []))
next = res.nextToken
} while (next)
return found.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''))
}
private async resolvers(apiId: string, typeName: string): Promise<Resolver[]> {
const found: Resolver[] = []
let next: string | undefined
do {
const res = await this.appsync.send(new ListResolversCommand({apiId, typeName, maxResults: 25, ...(next ? {nextToken: next} : {})}))
found.push(...(res.resolvers ?? []))
next = res.nextToken
} while (next)
return found
}
}
type ApiDetail = {
definition: string | null
schemaStatus: {status: string; details: string | null} | null
apiKeys: ApiKey[]
dataSources: DataSource[]
resolvers: Resolver[]
types: Array<{name: string; fields: string[]}>
}
function toResource(api: GraphqlApi, detail?: ApiDetail): CloudResource {
const id = api.apiId ?? ''
const authenticationType = api.authenticationType ?? null
return {
id,
name: api.name ?? id,
cloud: 'aws',
service: 'graphql',
type: 'graphqlApi',
region: api.arn?.split(':')[3] || null,
createdAt: null,
metadata: {
apiId: id,
arn: api.arn ?? null,
authenticationType,
authenticationLabel: authenticationType ? AUTH_LABELS[authenticationType] ?? authenticationType : null,
userPoolId: api.userPoolConfig?.userPoolId ?? null,
graphqlUrl: api.uris?.GRAPHQL ?? null,
realtimeUrl: api.uris?.REALTIME ?? null,
...(detail ? {
definition: detail.definition,
schemaStatus: detail.schemaStatus,
types: detail.types,
apiKeys: detail.apiKeys.map((key) => ({
id: key.id ?? '',
description: key.description || null,
expiresAt: key.expires ? new Date(key.expires * 1000).toISOString() : null,
})),
dataSources: detail.dataSources.map((source) => ({
name: source.name ?? '',
type: source.type ?? null,
description: source.description || null,
tableName: source.dynamodbConfig?.tableName ?? null,
functionArn: source.lambdaConfig?.lambdaFunctionArn ?? null,
serviceRoleArn: source.serviceRoleArn ?? null,
})),
resolvers: detail.resolvers.map((resolver) => ({
typeName: resolver.typeName ?? '',
fieldName: resolver.fieldName ?? '',
dataSourceName: resolver.dataSourceName ?? null,
kind: resolver.kind ?? null,
runtime: resolver.runtime?.name ?? (resolver.requestMappingTemplate ? 'VTL' : null),
code: resolver.code ?? null,
})),
} : {}),
},
}
}
/**
* Why a schema was rejected. AWS sends a sentence; the runtime sends JSON whose
* codeErrors carry the parser's messages, which are what a person needs.
*/
export function schemaFailure(details: string | undefined): string {
if (!details) return 'AppSync rejected it'
try {
const parsed = JSON.parse(details) as {detail?: {codeErrors?: Array<{value?: unknown}>}}
const messages = (parsed.detail?.codeErrors ?? []).map((error) => error.value).filter((value): value is string => typeof value === 'string' && value !== '')
return messages.length > 0 ? messages.join('; ') : details
} catch {
return details
}
}
/** AWS returns the SDL itself; the runtime wraps it as {"schema": {"definition": …}}. */
export function sdlFrom(body: string): string {
const trimmed = body.trim()
if (!trimmed.startsWith('{"')) return body
try {
const parsed = JSON.parse(trimmed) as {schema?: {definition?: unknown}}
return typeof parsed.schema?.definition === 'string' ? parsed.schema.definition : body
} catch {
return body
}
}
/**
* The object types of an SDL schema and their field names: what a resolver can
* attach to. A small reader, not a GraphQL parser: it drops comments, strings
* and arguments, then reads `type Name { field: … }` blocks.
*/
export function objectTypes(sdl: string): Array<{name: string; fields: string[]}> {
const stripped = sdl
.replace(/"""[\s\S]*?"""/g, '')
.replace(/"(?:[^"\\\n]|\\.)*"/g, '')
.replace(/#[^\n]*/g, '')
const types: Array<{name: string; fields: string[]}> = []
for (const match of stripped.matchAll(/(?:^|\s)(?:extend\s+)?type\s+([_A-Za-z][_0-9A-Za-z]*)[^{]*\{([^}]*)\}/g)) {
let body = match[2]
// Arguments may nest one level of input object literals; drop them before reading fields.
for (let previous = ''; previous !== body;) { previous = body; body = body.replace(/\([^()]*\)/g, '') }
const fields = [...body.matchAll(/([_A-Za-z][_0-9A-Za-z]*)\s*:/g)].map((field) => field[1])
const existing = types.find((type) => type.name === match[1])
if (existing) existing.fields.push(...fields.filter((field) => !existing.fields.includes(field)))
else types.push({name: match[1], fields})
}
const rootOrder = ['Query', 'Mutation', 'Subscription']
return types.sort((a, b) => {
const rank = (name: string) => rootOrder.includes(name) ? rootOrder.indexOf(name) : rootOrder.length
return rank(a.name) - rank(b.name) || a.name.localeCompare(b.name)
})
}
function expiry(days: number): number {
return Math.floor(Date.now() / 1000) + days * DAY_SECONDS
}
function text(value: unknown): string {
return typeof value === 'string' ? value.trim() : ''
}
function errorName(error: unknown): string | undefined {
return typeof error === 'object' && error !== null ? (error as {name?: string}).name : undefined
}
+3
View File
@@ -40,6 +40,7 @@ import { PipesClient } from "@aws-sdk/client-pipes";
import { EFSClient } from "@aws-sdk/client-efs";
import { GlueClient } from "@aws-sdk/client-glue";
import { AthenaClient } from "@aws-sdk/client-athena";
import { AppSyncClient } from "@aws-sdk/client-appsync";
const endpoint = process.env.FLOCI_ENDPOINT;
const region = process.env.AWS_REGION || "us-east-1";
@@ -111,6 +112,7 @@ export type AwsClients = {
efs: EFSClient;
glue: GlueClient;
athena: AthenaClient;
appsync: AppSyncClient;
};
export type AwsClientName = keyof AwsClients;
@@ -166,6 +168,7 @@ function buildClients(accountId: string): AwsClients {
efs: new EFSClient(base),
glue: new GlueClient(base),
athena: new AthenaClient(base),
appsync: new AppSyncClient(base),
};
}
@@ -0,0 +1,83 @@
import type {CloudProvider, FieldSchema, ServiceSchema, TableColumnSchema} from './types'
/** CreateGraphqlApi's name characters; the console keeps names to a readable length. */
export const GRAPHQL_API_NAME_PATTERN = '^[A-Za-z0-9_\\- ]{1,128}$'
/** CreateDataSource's name rule: a GraphQL-style identifier. */
export const GRAPHQL_DATA_SOURCE_NAME_PATTERN = '^[_A-Za-z][_0-9A-Za-z]{0,64}$'
export const GRAPHQL_AUTH_TYPES = ['API_KEY', 'AWS_IAM', 'AMAZON_COGNITO_USER_POOLS'] as const
export const GRAPHQL_DATA_SOURCE_TYPES = ['NONE', 'AMAZON_DYNAMODB', 'AWS_LAMBDA'] as const
/** AppSync's bounds on an API key's lifetime. */
export const GRAPHQL_API_KEY_MAX_DAYS = 365
const apiColumns: TableColumnSchema[] = [
{name: 'name', label: 'Name'},
{name: 'id', label: 'API ID', path: 'metadata.apiId'},
{name: 'auth', label: 'Authorization', path: 'metadata.authenticationLabel'},
{name: 'endpoint', label: 'GraphQL endpoint', path: 'metadata.graphqlUrl', emptyText: '—'},
]
const apiFilters: FieldSchema[] = [{name: 'search', label: 'Search', type: 'text', required: false}]
export function awsGraphqlSchema(): ServiceSchema {
return {
cloud: 'aws',
service: 'graphql',
displayName: 'AppSync GraphQL APIs',
fields: [
{
name: 'name',
label: 'API name',
type: 'text',
required: true,
validation: {pattern: GRAPHQL_API_NAME_PATTERN, message: 'Use up to 128 letters, numbers, spaces, dashes and underscores'},
},
{
name: 'authenticationType',
label: 'Authorization',
type: 'select',
required: false,
defaultValue: 'API_KEY',
description: 'How clients prove who they are. With an API key, AppSync creates the first key for you.',
options: [
{label: 'API key', value: 'API_KEY'},
{label: 'IAM (signed requests)', value: 'AWS_IAM'},
{label: 'Cognito user pool', value: 'AMAZON_COGNITO_USER_POOLS'},
],
},
{
name: 'userPoolId',
label: 'User pool ID',
type: 'text',
required: false,
requiredWhen: {field: 'authenticationType', equals: 'AMAZON_COGNITO_USER_POOLS'},
visibleWhen: {field: 'authenticationType', values: ['AMAZON_COGNITO_USER_POOLS']},
description: 'The Cognito user pool whose ID tokens the API accepts, such as us-east-1_AbC123.',
validation: {pattern: '^[\\w-]+_[0-9a-zA-Z]+$', message: 'Use a user pool ID such as us-east-1_AbC123'},
},
],
actions: ['list', 'create', 'delete', 'inspect'],
capabilities: {
resourceActions: [
{name: 'list', label: 'List GraphQL APIs', enabled: true, status: 'available', runtimeRequired: true},
{name: 'create', label: 'Create GraphQL API', enabled: true, status: 'available', runtimeRequired: true},
{name: 'delete', label: 'Delete GraphQL API', enabled: true, status: 'available', runtimeRequired: true},
{name: 'inspect', label: 'Inspect GraphQL API', enabled: true, status: 'available', runtimeRequired: true},
],
graphqlActions: [
{name: 'updateSchema', label: 'Save schema', enabled: true, status: 'available', runtimeRequired: true},
{name: 'createApiKey', label: 'Create API key', enabled: true, status: 'available', runtimeRequired: true},
{name: 'deleteApiKey', label: 'Delete API key', enabled: true, status: 'available', runtimeRequired: true},
{name: 'createDataSource', label: 'Create data source', enabled: true, status: 'available', runtimeRequired: true},
{name: 'deleteDataSource', label: 'Delete data source', enabled: true, status: 'available', runtimeRequired: true},
{name: 'createResolver', label: 'Attach resolver', enabled: true, status: 'available', runtimeRequired: true},
{name: 'deleteResolver', label: 'Detach resolver', enabled: true, status: 'available', runtimeRequired: true},
],
},
filters: apiFilters,
columns: apiColumns,
}
}
export function graphqlSchemaFor(cloud: CloudProvider): ServiceSchema | null {
return cloud === 'aws' ? awsGraphqlSchema() : null
}
@@ -238,6 +238,13 @@ export const SERVICE_CATALOG = {
},
identity: {displayName: 'Identity', iconKey: 'iam', group: 'Security', order: 5},
apigateway: {displayName: 'API Gateway', iconKey: 'apigateway', group: 'Integration', order: 10},
graphql: {
displayName: 'GraphQL APIs',
displayNameByCloud: {aws: 'AppSync'},
iconKey: 'graphql',
group: 'Integration',
order: 12,
},
email: {
displayName: 'Email',
displayNameByCloud: {aws: 'SES Mailbox'},
+35
View File
@@ -188,6 +188,7 @@ export type UserPoolActionName =
export type DistributionActionName = 'setEnabled' | 'createInvalidation'
export type AutoScalingActionName = 'setCapacity' | 'terminateInstance'
export type CertificateActionName = 'download' | 'export' | 'revoke'
export type GraphqlActionName = 'updateSchema' | 'createApiKey' | 'deleteApiKey' | 'createDataSource' | 'deleteDataSource' | 'createResolver' | 'deleteResolver'
export type QueryActionName = 'run' | 'results' | 'stop' | 'history' | 'catalog'
export type DataCatalogActionName = 'createTable' | 'deleteTable'
export type FileSystemActionName = 'createMountTarget' | 'deleteMountTarget' | 'createAccessPoint' | 'deleteAccessPoint' | 'attachFunction' | 'detachFunction'
@@ -255,6 +256,7 @@ export interface ServiceSchema {
fileSystemActions?: CapabilitySchema<FileSystemActionName>[]
dataCatalogActions?: CapabilitySchema<DataCatalogActionName>[]
queryActions?: CapabilitySchema<QueryActionName>[]
graphqlActions?: CapabilitySchema<GraphqlActionName>[]
monitoringActions?: CapabilitySchema<MonitoringActionName>[]
/** API Gateway v2 (HTTP and WebSocket APIs): what the routes, stages and security panel can do. */
httpApiActions?: CapabilitySchema<HttpApiActionName>[]
@@ -562,6 +564,32 @@ export interface AccessPointInput {
permissions: string
}
export interface GraphqlApiKeyInput {
description?: string
/** Days until the key expires: 1 to 365, 7 when left out, as in the AppSync console. */
expiresInDays?: number
}
export interface GraphqlDataSourceInput {
name: string
description?: string
type: 'NONE' | 'AMAZON_DYNAMODB' | 'AWS_LAMBDA'
/** AMAZON_DYNAMODB: the table the resolvers read and write. */
tableName?: string
/** AWS_LAMBDA: the function the resolvers invoke. */
functionArn?: string
/** The role AppSync assumes to reach the table or function; AWS requires one for both. */
serviceRoleArn?: string
}
export interface GraphqlResolverInput {
typeName: string
fieldName: string
dataSourceName: string
/** An APPSYNC_JS resolver: request() and response() exported from one module. */
code: string
}
export interface QueryInput {
sql: string
/** The Glue database unqualified table names resolve in. */
@@ -1294,6 +1322,13 @@ export interface CloudServiceAdapter {
/** With `replace`, the group launches a new instance in its place; otherwise desired capacity drops by one. */
terminateAutoScalingInstance?(groupName: string, instanceId: string, replace: boolean): Promise<void>
getCertificatePem?(certificateId: string): Promise<CertificatePem>
updateGraphqlSchema?(apiId: string, definition: string): Promise<CloudResource>
createGraphqlApiKey?(apiId: string, input: GraphqlApiKeyInput): Promise<CloudResource>
deleteGraphqlApiKey?(apiId: string, keyId: string): Promise<CloudResource>
createGraphqlDataSource?(apiId: string, input: GraphqlDataSourceInput): Promise<CloudResource>
deleteGraphqlDataSource?(apiId: string, name: string): Promise<CloudResource>
createGraphqlResolver?(apiId: string, input: GraphqlResolverInput): Promise<CloudResource>
deleteGraphqlResolver?(apiId: string, typeName: string, fieldName: string): Promise<CloudResource>
startQuery?(workGroup: string, input: QueryInput): Promise<QueryExecutionSummary>
/** The query's state, and its first rows once it has succeeded. */
getQueryResult?(workGroup: string, queryId: string): Promise<QueryResult>
+21 -1
View File
@@ -2,7 +2,7 @@ import {describe, expect, test} from 'bun:test'
import {createCloudAdapterRegistry} from './cloudProxy'
import {checkChildCapabilities} from './cloud-spi/childCapabilities'
import {isServiceType} from './cloud-spi/serviceCatalog'
import type {AutoScalingActionName, CloudProvider, CloudServiceAdapter, CloudServiceType, CertificateActionName, DatabaseActionName, DataCatalogActionName, DistributionActionName, FileSystemActionName, HttpApiActionName, QueryActionName, KubernetesActionName, MonitoringActionName, ResourceActionName, UserPoolActionName} from './cloud-spi/types'
import type {AutoScalingActionName, CloudProvider, CloudServiceAdapter, CloudServiceType, CertificateActionName, DatabaseActionName, DataCatalogActionName, DistributionActionName, FileSystemActionName, GraphqlActionName, HttpApiActionName, QueryActionName, KubernetesActionName, MonitoringActionName, ResourceActionName, UserPoolActionName} from './cloud-spi/types'
/**
* Guards the schema-to-implementation contract for every registered adapter.
@@ -81,6 +81,16 @@ const METHOD_FOR_CERTIFICATE_ACTION: Record<CertificateActionName, keyof CloudSe
revoke: 'revokeCertificate',
}
const METHOD_FOR_GRAPHQL_ACTION: Record<GraphqlActionName, keyof CloudServiceAdapter> = {
updateSchema: 'updateGraphqlSchema',
createApiKey: 'createGraphqlApiKey',
deleteApiKey: 'deleteGraphqlApiKey',
createDataSource: 'createGraphqlDataSource',
deleteDataSource: 'deleteGraphqlDataSource',
createResolver: 'createGraphqlResolver',
deleteResolver: 'deleteGraphqlResolver',
}
const METHOD_FOR_QUERY_ACTION: Record<QueryActionName, keyof CloudServiceAdapter> = {
run: 'startQuery',
results: 'getQueryResult',
@@ -239,6 +249,15 @@ describe('registered adapters honour their schema', () => {
).toBe('function')
}
const graphqlClaims = (adapter.schema().capabilities?.graphqlActions ?? []).filter((capability) => capability.status === 'available')
for (const capability of graphqlClaims) {
const method = METHOD_FOR_GRAPHQL_ACTION[capability.name]
expect(
typeof adapter[method],
`${label} advertises ${capability.name} as available but has no ${String(method)}()`,
).toBe('function')
}
const queryClaims = (adapter.schema().capabilities?.queryActions ?? []).filter((capability) => capability.status === 'available')
for (const capability of queryClaims) {
const method = METHOD_FOR_QUERY_ACTION[capability.name]
@@ -292,6 +311,7 @@ describe('registered adapters honour their schema', () => {
...(adapter.schema().capabilities?.fileSystemActions ?? []),
...(adapter.schema().capabilities?.dataCatalogActions ?? []),
...(adapter.schema().capabilities?.queryActions ?? []),
...(adapter.schema().capabilities?.graphqlActions ?? []),
...(adapter.schema().capabilities?.certificateActions ?? []),
...(adapter.schema().capabilities?.monitoringActions ?? []),
...(adapter.schema().capabilities?.httpApiActions ?? []),
+2
View File
@@ -56,6 +56,7 @@ import {AwsPipesAdapter} from './adapter-aws/AwsPipesAdapter'
import {AwsFileSystemsAdapter} from './adapter-aws/AwsFileSystemsAdapter'
import {AwsDataCatalogAdapter} from './adapter-aws/AwsDataCatalogAdapter'
import {AwsQueryAdapter} from './adapter-aws/AwsQueryAdapter'
import {AwsGraphqlAdapter} from './adapter-aws/AwsGraphqlAdapter'
import {AwsMonitoringAdapter} from './adapter-aws/AwsMonitoringAdapter'
import {awsClientsForAccount, resolveAccountId} from './aws'
import {createEc2Service} from './services/ec2'
@@ -115,6 +116,7 @@ export function createCloudAdapterRegistry(accountId?: string | null): CloudAdap
new AwsFileSystemsAdapter(clients.efs, clients.lambda, clients.ec2),
new AwsDataCatalogAdapter(clients.glue),
new AwsQueryAdapter(clients.athena),
new AwsGraphqlAdapter(clients.appsync),
new AwsMonitoringAdapter(clients.cloudwatch),
new AzureStorageAdapter(),
new AzureServiceBusAdapter(),
+31
View File
@@ -22,6 +22,7 @@ import {awsAutoScalingSchema} from '../cloud-spi/autoScalingSchema'
import {awsFileSystemsSchema} from '../cloud-spi/fileSystemsSchema'
import {awsDataCatalogSchema} from '../cloud-spi/dataCatalogSchema'
import {awsQuerySchema} from '../cloud-spi/querySchema'
import {awsGraphqlSchema} from '../cloud-spi/graphqlSchema'
import {awsCertificatesSchema} from '../cloud-spi/certificatesSchema'
import {awsMonitoringSchema} from '../cloud-spi/monitoringSchema'
import {awsAppConfigSchema} from '../cloud-spi/appConfigSchema'
@@ -878,6 +879,36 @@ describe('cloud schema routes', () => {
expect(calls).toEqual([['capacity', 'web-asg', {desiredCapacity: 3}], ['terminate', 'web-asg', 'i-abc', true]])
})
test('manages the schema, keys, data sources and resolvers through the AppSync adapter', async () => {
const calls: unknown[] = []
const api = {id: 'a1', name: 'notes', cloud: 'aws' as const, service: 'graphql' as const, type: 'graphqlApi', region: null, createdAt: null, metadata: {}}
const app = appWithRoutes([mockAdapter('aws', {
service: 'graphql',
schema: awsGraphqlSchema,
updateGraphqlSchema: async (id, definition) => { calls.push(['schema', id, definition]); return api },
createGraphqlApiKey: async (id, input) => { calls.push(['key', id, input.expiresInDays]); return api },
deleteGraphqlApiKey: async (id, keyId) => { calls.push(['delete-key', id, keyId]); return api },
createGraphqlDataSource: async (id, input) => { calls.push(['source', id, input.name, input.type]); return api },
deleteGraphqlDataSource: async (id, name) => { calls.push(['delete-source', id, name]); return api },
createGraphqlResolver: async (id, input) => { calls.push(['resolver', id, input.typeName, input.fieldName]); return api },
deleteGraphqlResolver: async (id, typeName, fieldName) => { calls.push(['delete-resolver', id, typeName, fieldName]); return api },
})])
const json = (method: string, body: unknown) => ({method, headers: {'content-type': 'application/json'}, body: JSON.stringify(body)})
const base = '/api/clouds/aws/services/graphql/resources/a1'
expect((await app.request(`${base}/schema`, json('PUT', {definition: 'type Query { a: String }'}))).status).toBe(200)
expect((await app.request(`${base}/api-keys`, json('POST', {expiresInDays: 30}))).status).toBe(201)
expect((await app.request(`${base}/api-keys/da2-x`, {method: 'DELETE'})).status).toBe(200)
expect((await app.request(`${base}/data-sources`, json('POST', {name: 'none', type: 'NONE'}))).status).toBe(201)
expect((await app.request(`${base}/data-sources/none`, {method: 'DELETE'})).status).toBe(200)
expect((await app.request(`${base}/resolvers`, json('POST', {typeName: 'Query', fieldName: 'a', dataSourceName: 'none', code: ''}))).status).toBe(201)
expect((await app.request(`${base}/resolvers/Query/a`, {method: 'DELETE'})).status).toBe(200)
expect(calls).toEqual([
['schema', 'a1', 'type Query { a: String }'], ['key', 'a1', 30], ['delete-key', 'a1', 'da2-x'],
['source', 'a1', 'none', 'NONE'], ['delete-source', 'a1', 'none'], ['resolver', 'a1', 'Query', 'a'], ['delete-resolver', 'a1', 'Query', 'a'],
])
})
test('runs, reads, lists and cancels queries through the Athena adapter', async () => {
const calls: unknown[] = []
const execution = {id: 'q1', sql: 'SELECT 1', database: 'shop', workGroup: 'analysts', state: 'SUCCEEDED', stateReason: null, statementType: 'DML', submittedAt: null, completedAt: null, runtimeMs: 5, dataScannedBytes: 0, outputLocation: 's3://r/q1.csv'}
+55
View File
@@ -6,6 +6,9 @@ import type {
AccessPointInput,
CatalogTableInput,
QueryInput,
GraphqlApiKeyInput,
GraphqlDataSourceInput,
GraphqlResolverInput,
FileSystemAttachmentInput,
CertificateRevocationReason,
CloudProvider,
@@ -558,6 +561,58 @@ export function createCloudRoutes(injectedService?: CloudProxyService) {
})
})
app.put('/:cloud/services/graphql/resources/:id/schema', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => {
const body = await c.req.json<{definition?: string}>()
return c.json(await svc(c).updateGraphqlSchema(cloud, c.req.param('id'), body.definition ?? ''))
})
})
app.post('/:cloud/services/graphql/resources/:id/api-keys', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).createGraphqlApiKey(cloud, c.req.param('id'), await c.req.json<GraphqlApiKeyInput>()), 201))
})
app.delete('/:cloud/services/graphql/resources/:id/api-keys/:keyId', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).deleteGraphqlApiKey(cloud, c.req.param('id'), c.req.param('keyId'))))
})
app.post('/:cloud/services/graphql/resources/:id/data-sources', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).createGraphqlDataSource(cloud, c.req.param('id'), await c.req.json<GraphqlDataSourceInput>()), 201))
})
app.delete('/:cloud/services/graphql/resources/:id/data-sources/:name', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).deleteGraphqlDataSource(cloud, c.req.param('id'), c.req.param('name'))))
})
app.post('/:cloud/services/graphql/resources/:id/resolvers', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).createGraphqlResolver(cloud, c.req.param('id'), await c.req.json<GraphqlResolverInput>()), 201))
})
app.delete('/:cloud/services/graphql/resources/:id/resolvers/:typeName/:fieldName', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
return withRuntime(c, async () => c.json(await svc(c).deleteGraphqlResolver(cloud, c.req.param('id'), c.req.param('typeName'), c.req.param('fieldName'))))
})
app.get('/:cloud/services/query/catalog', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
if (!isCloudProvider(cloud)) return c.json({error: 'Unknown cloud'}, 404)
@@ -97,6 +97,9 @@ import type {
AccessPointInput,
CatalogTableInput,
QueryCatalog,
GraphqlApiKeyInput,
GraphqlDataSourceInput,
GraphqlResolverInput,
QueryExecutionSummary,
QueryInput,
QueryResult,
@@ -971,6 +974,48 @@ export class CloudProxyService {
return adapter.revokeCertificate(certificateId, reason)
}
async updateGraphqlSchema(cloud: CloudProvider, apiId: string, definition: string): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.updateGraphqlSchema) throw new NotSupportedError(`Saving schemas is not supported for ${cloud}/graphql`)
return adapter.updateGraphqlSchema(apiId, definition)
}
async createGraphqlApiKey(cloud: CloudProvider, apiId: string, input: GraphqlApiKeyInput): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.createGraphqlApiKey) throw new NotSupportedError(`API keys are not supported for ${cloud}/graphql`)
return adapter.createGraphqlApiKey(apiId, input)
}
async deleteGraphqlApiKey(cloud: CloudProvider, apiId: string, keyId: string): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.deleteGraphqlApiKey) throw new NotSupportedError(`API keys are not supported for ${cloud}/graphql`)
return adapter.deleteGraphqlApiKey(apiId, keyId)
}
async createGraphqlDataSource(cloud: CloudProvider, apiId: string, input: GraphqlDataSourceInput): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.createGraphqlDataSource) throw new NotSupportedError(`Data sources are not supported for ${cloud}/graphql`)
return adapter.createGraphqlDataSource(apiId, input)
}
async deleteGraphqlDataSource(cloud: CloudProvider, apiId: string, name: string): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.deleteGraphqlDataSource) throw new NotSupportedError(`Data sources are not supported for ${cloud}/graphql`)
return adapter.deleteGraphqlDataSource(apiId, name)
}
async createGraphqlResolver(cloud: CloudProvider, apiId: string, input: GraphqlResolverInput): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.createGraphqlResolver) throw new NotSupportedError(`Resolvers are not supported for ${cloud}/graphql`)
return adapter.createGraphqlResolver(apiId, input)
}
async deleteGraphqlResolver(cloud: CloudProvider, apiId: string, typeName: string, fieldName: string): Promise<CloudResource> {
const adapter = this.requireAdapter(cloud, 'graphql')
if (!adapter.deleteGraphqlResolver) throw new NotSupportedError(`Resolvers are not supported for ${cloud}/graphql`)
return adapter.deleteGraphqlResolver(apiId, typeName, fieldName)
}
async startQuery(cloud: CloudProvider, workGroup: string, input: QueryInput): Promise<QueryExecutionSummary> {
const adapter = this.requireAdapter(cloud, 'query')
if (!adapter.startQuery) throw new NotSupportedError(`Running queries is not supported for ${cloud}/query`)
+58
View File
@@ -155,6 +155,15 @@ export const apiEndpointKeys = {
export: "clouds.services.certificates.export",
revoke: "clouds.services.certificates.revoke",
},
graphql: {
schema: "clouds.services.graphql.schema",
apiKeys: "clouds.services.graphql.apiKeys",
apiKey: "clouds.services.graphql.apiKey",
dataSources: "clouds.services.graphql.dataSources",
dataSource: "clouds.services.graphql.dataSource",
resolvers: "clouds.services.graphql.resolvers",
resolver: "clouds.services.graphql.resolver",
},
query: {
catalog: "clouds.services.query.catalog",
queries: "clouds.services.query.queries",
@@ -975,6 +984,55 @@ export const endpointRegistry: EndpointRegistry = new Map([
method: "POST",
},
],
[
apiEndpointKeys.clouds.graphql.schema,
{
path: "/clouds/:cloud/services/graphql/resources/:id/schema",
method: "PUT",
},
],
[
apiEndpointKeys.clouds.graphql.apiKeys,
{
path: "/clouds/:cloud/services/graphql/resources/:id/api-keys",
method: "POST",
},
],
[
apiEndpointKeys.clouds.graphql.apiKey,
{
path: "/clouds/:cloud/services/graphql/resources/:id/api-keys/:keyId",
method: "DELETE",
},
],
[
apiEndpointKeys.clouds.graphql.dataSources,
{
path: "/clouds/:cloud/services/graphql/resources/:id/data-sources",
method: "POST",
},
],
[
apiEndpointKeys.clouds.graphql.dataSource,
{
path: "/clouds/:cloud/services/graphql/resources/:id/data-sources/:name",
method: "DELETE",
},
],
[
apiEndpointKeys.clouds.graphql.resolvers,
{
path: "/clouds/:cloud/services/graphql/resources/:id/resolvers",
method: "POST",
},
],
[
apiEndpointKeys.clouds.graphql.resolver,
{
path: "/clouds/:cloud/services/graphql/resources/:id/resolvers/:typeName/:fieldName",
method: "DELETE",
},
],
[
apiEndpointKeys.clouds.query.catalog,
{
@@ -37,6 +37,9 @@ import type {
AccessPointInput,
CatalogTableInput,
QueryCatalog,
GraphqlApiKeyInput,
GraphqlDataSourceInput,
GraphqlResolverInput,
QueryExecutionSummary,
QueryInput,
QueryResult,
@@ -1728,6 +1731,98 @@ export async function revokeCertificate(
return res.data;
}
export async function updateGraphqlSchema(
cloud: CloudProvider,
apiId: string,
definition: string,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource, { definition: string }>(
apiEndpointKeys.clouds.graphql.schema,
requestOptions(cloud, "graphql", { body: { definition } }),
{ cloud, id: apiId },
);
return res.data;
}
export async function createGraphqlApiKey(
cloud: CloudProvider,
apiId: string,
input: GraphqlApiKeyInput,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource, GraphqlApiKeyInput>(
apiEndpointKeys.clouds.graphql.apiKeys,
requestOptions(cloud, "graphql", { body: input }),
{ cloud, id: apiId },
);
return res.data;
}
export async function deleteGraphqlApiKey(
cloud: CloudProvider,
apiId: string,
keyId: string,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource>(
apiEndpointKeys.clouds.graphql.apiKey,
requestOptions(cloud, "graphql"),
{ cloud, id: apiId, keyId },
);
return res.data;
}
export async function createGraphqlDataSource(
cloud: CloudProvider,
apiId: string,
input: GraphqlDataSourceInput,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource, GraphqlDataSourceInput>(
apiEndpointKeys.clouds.graphql.dataSources,
requestOptions(cloud, "graphql", { body: input }),
{ cloud, id: apiId },
);
return res.data;
}
export async function deleteGraphqlDataSource(
cloud: CloudProvider,
apiId: string,
name: string,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource>(
apiEndpointKeys.clouds.graphql.dataSource,
requestOptions(cloud, "graphql"),
{ cloud, id: apiId, name },
);
return res.data;
}
export async function createGraphqlResolver(
cloud: CloudProvider,
apiId: string,
input: GraphqlResolverInput,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource, GraphqlResolverInput>(
apiEndpointKeys.clouds.graphql.resolvers,
requestOptions(cloud, "graphql", { body: input }),
{ cloud, id: apiId },
);
return res.data;
}
export async function deleteGraphqlResolver(
cloud: CloudProvider,
apiId: string,
typeName: string,
fieldName: string,
): Promise<CloudResource> {
const res = await apiClient.call<CloudResource>(
apiEndpointKeys.clouds.graphql.resolver,
requestOptions(cloud, "graphql"),
{ cloud, id: apiId, typeName, fieldName },
);
return res.data;
}
export async function describeQueryCatalog(
cloud: CloudProvider,
database?: string,
@@ -72,6 +72,7 @@ import { AutoScalingPanel } from "@/components/AutoScalingPanel";
import { FileSystemPanel } from "@/components/FileSystemPanel";
import { DataCatalogPanel } from "@/components/DataCatalogPanel";
import { QueryPanel } from "@/components/QueryPanel";
import { GraphqlPanel } from "@/components/GraphqlPanel";
import { CertificatePanel } from "@/components/CertificatePanel";
import { PipePanel } from "@/components/PipePanel";
import { CloudWatchAlarmPanel } from "@/components/CloudWatchAlarmPanel";
@@ -1011,6 +1012,9 @@ export function DynamicResourceView({
{service === "query" && cloud === "aws" && (
<QueryPanel resource={activeSelected} runtimeReachable={canUseRuntime} />
)}
{service === "graphql" && cloud === "aws" && (
<GraphqlPanel resource={activeSelected} runtimeReachable={canUseRuntime} />
)}
{service === "cdn" && cloud === "aws" && (
<CloudFrontPanel resource={activeSelected} runtimeReachable={canUseRuntime} />
)}
@@ -0,0 +1,142 @@
import {QueryClient, QueryClientProvider} from '@tanstack/react-query'
import {render, screen, within} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {beforeEach, expect, test, vi} from 'vitest'
import {GraphqlPanel} from './GraphqlPanel'
import type {CloudResource} from '@/types/resource'
const api = vi.hoisted(() => ({
getCloudResource: vi.fn(),
listCloudResources: vi.fn(),
updateGraphqlSchema: vi.fn(),
createGraphqlApiKey: vi.fn(),
deleteGraphqlApiKey: vi.fn(),
createGraphqlDataSource: vi.fn(),
deleteGraphqlDataSource: vi.fn(),
createGraphqlResolver: vi.fn(),
deleteGraphqlResolver: vi.fn(),
}))
vi.mock('@/api/cloudProxyClient', () => api)
vi.mock('@/lib/accountStore', () => ({useAccountId: () => '000000000000'}))
const sdl = 'type Note { id: ID! text: String }\ntype Query { note(id: ID!): Note notes: [Note] }'
function graphqlApi(metadata: Record<string, unknown> = {}): CloudResource {
return {
id: 'a1', name: 'notes-api', cloud: 'aws', service: 'graphql', type: 'graphqlApi', region: 'us-east-1', createdAt: null,
metadata: {
apiId: 'a1', authenticationType: 'API_KEY', authenticationLabel: 'API key',
graphqlUrl: 'http://localhost:4566/v1/apis/a1/graphql', realtimeUrl: 'ws://localhost:4566/v1/apis/a1/graphql/realtime',
definition: sdl, schemaStatus: {status: 'SUCCESS', details: null},
types: [{name: 'Query', fields: ['note', 'notes']}, {name: 'Note', fields: ['id', 'text']}],
apiKeys: [{id: 'da2-key', description: 'web', expiresAt: '2026-11-01T22:00:00.000Z'}],
dataSources: [{name: 'notesTable', type: 'AMAZON_DYNAMODB', description: null, tableName: 'notes', functionArn: null, serviceRoleArn: 'arn:aws:iam::000000000000:role/appsync'}],
resolvers: [{typeName: 'Query', fieldName: 'note', dataSourceName: 'notesTable', kind: 'UNIT', runtime: 'APPSYNC_JS', code: ''}],
...metadata,
},
}
}
function renderPanel(resource: CloudResource) {
api.getCloudResource.mockResolvedValue(resource)
const client = new QueryClient({defaultOptions: {queries: {retry: false}}})
return render(<QueryClientProvider client={client}><GraphqlPanel resource={resource} runtimeReachable/></QueryClientProvider>)
}
beforeEach(() => {
vi.clearAllMocks()
api.listCloudResources.mockResolvedValue([{id: 'notes', name: 'notes', metadata: {}}])
for (const fn of [api.updateGraphqlSchema, api.createGraphqlApiKey, api.deleteGraphqlApiKey, api.createGraphqlDataSource, api.deleteGraphqlDataSource, api.createGraphqlResolver, api.deleteGraphqlResolver]) {
fn.mockResolvedValue(graphqlApi())
}
})
test('shows the endpoint, saved schema, keys, data sources and resolvers, and says resolvers do not run', async () => {
renderPanel(graphqlApi())
expect(await screen.findByText('http://localhost:4566/v1/apis/a1/graphql')).toBeInTheDocument()
expect(screen.getByLabelText('Schema definition')).toHaveValue(sdl)
expect(screen.getByText('da2-key')).toBeInTheDocument()
expect(screen.getByText('Query.note')).toBeInTheDocument()
expect(screen.getByText(/does not run resolvers yet/)).toBeInTheDocument()
})
test('offers a starter schema for a new API and saves an edited one', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi({definition: null, types: [], resolvers: [], schemaStatus: null}))
const schema = await screen.findByLabelText('Schema definition')
expect(await screen.findByText(/This starter schema is not saved/)).toBeInTheDocument()
await user.clear(schema)
await user.type(schema, 'type Query {{ hello: String }')
await user.click(screen.getByRole('button', {name: 'Save schema'}))
expect(api.updateGraphqlSchema).toHaveBeenCalledWith('aws', 'a1', 'type Query { hello: String }')
expect(await screen.findByText('Schema saved.')).toBeInTheDocument()
})
test('saves the starter schema as shown when it is not edited', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi({definition: null, types: [], resolvers: [], schemaStatus: null}))
await screen.findByText(/This starter schema is not saved/)
await user.click(screen.getByRole('button', {name: 'Save schema'}))
expect(api.updateGraphqlSchema).toHaveBeenCalledWith('aws', 'a1', expect.stringContaining('type Query {'))
})
test('creates an API key that lasts the chosen days', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi())
const form = await screen.findByRole('form', {name: 'Create API key'})
await user.type(within(form).getByLabelText('Description'), 'mobile')
const days = within(form).getByLabelText('Expires in (days)')
await user.clear(days)
await user.type(days, '30')
await user.click(within(form).getByRole('button', {name: 'Create API key'}))
expect(api.createGraphqlApiKey).toHaveBeenCalledWith('aws', 'a1', {description: 'mobile', expiresInDays: 30})
})
test('creates a DynamoDB data source from a chosen table and role', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi())
const form = await screen.findByRole('form', {name: 'Create data source'})
await user.type(within(form).getByLabelText('Name'), 'notesStore')
await user.selectOptions(within(form).getByLabelText('Type'), 'AMAZON_DYNAMODB')
await user.selectOptions(within(form).getByLabelText('Table'), await within(form).findByRole('option', {name: 'notes'}))
await user.type(within(form).getByLabelText('Service role ARN'), 'arn:aws:iam::000000000000:role/appsync')
await user.click(within(form).getByRole('button', {name: 'Create data source'}))
expect(api.createGraphqlDataSource).toHaveBeenCalledWith('aws', 'a1', {name: 'notesStore', type: 'AMAZON_DYNAMODB', tableName: 'notes', serviceRoleArn: 'arn:aws:iam::000000000000:role/appsync'})
})
test('attaches a resolver to a field without one, starting from the data source template', async () => {
const user = userEvent.setup()
renderPanel(graphqlApi())
const form = await screen.findByRole('form', {name: 'Attach resolver'})
await user.selectOptions(within(form).getByLabelText('Type'), 'Query')
const field = within(form).getByLabelText('Field')
expect(within(field).queryByRole('option', {name: 'note'})).not.toBeInTheDocument()
await user.selectOptions(field, 'notes')
await user.selectOptions(within(form).getByLabelText('Data source'), 'notesTable')
expect((within(form).getByLabelText('Resolver code') as HTMLTextAreaElement).value).toContain("@aws-appsync/utils/dynamodb")
await user.click(within(form).getByRole('button', {name: 'Attach resolver'}))
expect(api.createGraphqlResolver).toHaveBeenCalledWith('aws', 'a1', expect.objectContaining({typeName: 'Query', fieldName: 'notes', dataSourceName: 'notesTable'}))
expect(await screen.findByText('Attached a resolver to Query.notes.')).toBeInTheDocument()
})
test('deletes a key and detaches a resolver after confirming', async () => {
const user = userEvent.setup()
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderPanel(graphqlApi())
await user.click(await screen.findByRole('button', {name: 'Delete da2-key'}))
expect(api.deleteGraphqlApiKey).toHaveBeenCalledWith('aws', 'a1', 'da2-key')
await user.click(screen.getByRole('button', {name: 'Detach Query.note'}))
expect(api.deleteGraphqlResolver).toHaveBeenCalledWith('aws', 'a1', 'Query', 'note')
})
@@ -0,0 +1,295 @@
import {Copy, RefreshCw} from 'lucide-react'
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
import {useEffect, useState} from 'react'
import {
createGraphqlApiKey,
createGraphqlDataSource,
createGraphqlResolver,
deleteGraphqlApiKey,
deleteGraphqlDataSource,
deleteGraphqlResolver,
getCloudResource,
listCloudResources,
updateGraphqlSchema,
} from '@/api/cloudProxyClient'
import {cloudQueryKeys} from '@/api/queries/cloudQueries'
import {useAccountId} from '@/lib/accountStore'
import {formatDateTime} from '@/lib/format'
import type {CloudResource, GraphqlDataSourceInput} from '@/types/resource'
type Props = {
resource?: CloudResource
runtimeReachable: boolean
}
type ApiKey = {id: string; description: string | null; expiresAt: string | null}
type DataSource = {name: string; type: string | null; description: string | null; tableName: string | null; functionArn: string | null; serviceRoleArn: string | null}
type Resolver = {typeName: string; fieldName: string; dataSourceName: string | null; kind: string | null; runtime: string | null; code: string | null}
type GraphqlType = {name: string; fields: string[]}
type SourceForm = {name: string; type: GraphqlDataSourceInput['type']; tableName: string; functionArn: string; serviceRoleArn: string}
const STARTER_SCHEMA = `type Note {
id: ID!
text: String
}
type Query {
note(id: ID!): Note
}
type Mutation {
addNote(id: ID!, text: String!): Note
}
schema {
query: Query
mutation: Mutation
}
`
const SOURCE_LABELS: Record<string, string> = {NONE: 'None (local resolver)', AMAZON_DYNAMODB: 'DynamoDB table', AWS_LAMBDA: 'Lambda function'}
const EMPTY_SOURCE: SourceForm = {name: '', type: 'NONE', tableName: '', functionArn: '', serviceRoleArn: ''}
/** The resolver AppSync's console starts from for each kind of data source. */
function starterCode(sourceType: string | null | undefined): string {
if (sourceType === 'AMAZON_DYNAMODB') {
return `import * as ddb from '@aws-appsync/utils/dynamodb'
export function request(ctx) {
return ddb.get({ key: { id: ctx.args.id } })
}
export function response(ctx) {
return ctx.result
}
`
}
if (sourceType === 'AWS_LAMBDA') {
return `export function request(ctx) {
return { operation: 'Invoke', payload: { field: ctx.info.fieldName, arguments: ctx.args } }
}
export function response(ctx) {
return ctx.result
}
`
}
return `export function request(ctx) {
return { payload: ctx.args }
}
export function response(ctx) {
return ctx.result
}
`
}
export function GraphqlPanel({resource, runtimeReachable}: Props) {
const accountId = useAccountId()
const queryClient = useQueryClient()
const [definition, setDefinition] = useState<string | null>(null)
const [keyForm, setKeyForm] = useState({description: '', days: '7'})
const [sourceForm, setSourceForm] = useState<SourceForm>(EMPTY_SOURCE)
const [resolverForm, setResolverForm] = useState({typeName: '', fieldName: '', dataSourceName: '', code: ''})
const [notice, setNotice] = useState('')
const detailKey = ['appsync-api', accountId, resource?.id]
const detailQuery = useQuery({
queryKey: detailKey,
queryFn: ({signal}) => getCloudResource('aws', 'graphql', resource?.id ?? '', signal),
enabled: Boolean(resource) && runtimeReachable,
})
const tablesQuery = useQuery({
queryKey: cloudQueryKeys.resources('aws', 'nosql'),
queryFn: ({signal}) => listCloudResources('aws', 'nosql', undefined, signal),
enabled: Boolean(resource) && runtimeReachable && sourceForm.type === 'AMAZON_DYNAMODB',
})
const functionsQuery = useQuery({
queryKey: cloudQueryKeys.resources('aws', 'serverless'),
queryFn: ({signal}) => listCloudResources('aws', 'serverless', undefined, signal),
enabled: Boolean(resource) && runtimeReachable && sourceForm.type === 'AWS_LAMBDA',
})
useEffect(() => {
setNotice('')
setDefinition(null)
setKeyForm({description: '', days: '7'})
setSourceForm(EMPTY_SOURCE)
setResolverForm({typeName: '', fieldName: '', dataSourceName: '', code: ''})
}, [resource?.id])
const id = resource?.id ?? ''
const settle = (updated: CloudResource, message: string) => {
queryClient.setQueryData(detailKey, updated)
setNotice(message)
}
const saveSchema = useMutation({
mutationFn: (text: string) => updateGraphqlSchema('aws', id, text),
onSuccess: (updated) => { setDefinition(null); settle(updated, 'Schema saved.') },
})
const addKey = useMutation({
mutationFn: () => createGraphqlApiKey('aws', id, {...(keyForm.description.trim() ? {description: keyForm.description.trim()} : {}), expiresInDays: Number(keyForm.days)}),
onSuccess: (updated) => { setKeyForm({description: '', days: '7'}); settle(updated, 'Created an API key.') },
})
const removeKey = useMutation({
mutationFn: (keyId: string) => deleteGraphqlApiKey('aws', id, keyId),
onSuccess: (updated, keyId) => settle(updated, `Deleted API key ${keyId}.`),
})
const addSource = useMutation({
mutationFn: () => createGraphqlDataSource('aws', id, {
name: sourceForm.name.trim(),
type: sourceForm.type,
...(sourceForm.type === 'AMAZON_DYNAMODB' ? {tableName: sourceForm.tableName} : {}),
...(sourceForm.type === 'AWS_LAMBDA' ? {functionArn: sourceForm.functionArn} : {}),
...(sourceForm.type !== 'NONE' ? {serviceRoleArn: sourceForm.serviceRoleArn.trim()} : {}),
}),
onSuccess: (updated) => { const name = sourceForm.name.trim(); setSourceForm(EMPTY_SOURCE); settle(updated, `Created data source ${name}.`) },
})
const removeSource = useMutation({
mutationFn: (name: string) => deleteGraphqlDataSource('aws', id, name),
onSuccess: (updated, name) => settle(updated, `Deleted data source ${name}.`),
})
const addResolver = useMutation({
mutationFn: () => createGraphqlResolver('aws', id, resolverForm),
onSuccess: (updated) => {
const field = `${resolverForm.typeName}.${resolverForm.fieldName}`
setResolverForm({typeName: '', fieldName: '', dataSourceName: '', code: ''})
settle(updated, `Attached a resolver to ${field}.`)
},
})
const removeResolver = useMutation({
mutationFn: (resolver: Resolver) => deleteGraphqlResolver('aws', id, resolver.typeName, resolver.fieldName),
onSuccess: (updated, resolver) => settle(updated, `Detached the resolver from ${resolver.typeName}.${resolver.fieldName}.`),
})
if (!resource) {
return <section className="table-panel"><div className="empty compact"><h3>Select a GraphQL API</h3><p>Choose an API to edit its schema, keys, data sources and resolvers.</p></div></section>
}
const api = detailQuery.data ?? resource
const metadata = api.metadata
const savedDefinition = typeof metadata.definition === 'string' ? metadata.definition : ''
const schemaText = definition ?? (savedDefinition || (detailQuery.data ? STARTER_SCHEMA : ''))
const schemaStatus = metadata.schemaStatus as {status: string; details: string | null} | null | undefined
const apiKeys = Array.isArray(metadata.apiKeys) ? metadata.apiKeys as ApiKey[] : []
const dataSources = Array.isArray(metadata.dataSources) ? metadata.dataSources as DataSource[] : []
const resolvers = Array.isArray(metadata.resolvers) ? metadata.resolvers as Resolver[] : []
const types = Array.isArray(metadata.types) ? metadata.types as GraphqlType[] : []
const chosenType = types.find((type) => type.name === resolverForm.typeName)
const openFields = (chosenType?.fields ?? []).filter((field) => !resolvers.some((resolver) => resolver.typeName === chosenType?.name && resolver.fieldName === field))
const mutations = [saveSchema, addKey, removeKey, addSource, removeSource, addResolver, removeResolver]
const disabled = !runtimeReachable || mutations.some((mutation) => mutation.isPending)
const error = detailQuery.error ?? mutations.find((mutation) => mutation.error)?.error
const run = (action: () => void) => { setNotice(''); action() }
const copy = (value: string) => { void navigator.clipboard?.writeText(value) }
const chooseSource = (dataSourceName: string) => {
const source = dataSources.find((candidate) => candidate.name === dataSourceName)
const starterOfCurrent = starterCode(dataSources.find((candidate) => candidate.name === resolverForm.dataSourceName)?.type)
const keepCode = resolverForm.code && resolverForm.code !== starterOfCurrent
setResolverForm({...resolverForm, dataSourceName, code: keepCode ? resolverForm.code : starterCode(source?.type)})
}
return <section className="table-panel" style={{marginTop: 16}} aria-label={`GraphQL API ${api.name}`}>
<div className="input-row resource-table-bar">
<div><p className="eyebrow">AppSync GraphQL API</p><span className="muted">{String(metadata.authenticationLabel ?? '')} authorization</span></div>
<div className="cdn-actions">
<button className="button" type="button" disabled={!runtimeReachable || detailQuery.isFetching} onClick={() => { void detailQuery.refetch() }}><RefreshCw size={14}/>{detailQuery.isFetching ? 'Loading' : 'Refresh'}</button>
</div>
</div>
<dl className="graphql-endpoints">
{typeof metadata.graphqlUrl === 'string' && <><dt>GraphQL endpoint</dt><dd><code>{metadata.graphqlUrl}</code> <button className="button compact" type="button" aria-label="Copy GraphQL endpoint" onClick={() => copy(String(metadata.graphqlUrl))}><Copy size={12}/></button></dd></>}
{typeof metadata.realtimeUrl === 'string' && <><dt>Real-time endpoint</dt><dd><code>{metadata.realtimeUrl}</code></dd></>}
</dl>
<p className="muted compact-text graphql-note">TheCloud keeps the schema, keys, data sources and resolvers, and its endpoint checks each query against the schema and the caller&apos;s key. It does not run resolvers yet, so every field of a query resolves to null.</p>
<form className="graphql-section" aria-label="Schema" onSubmit={(event) => { event.preventDefault(); run(() => saveSchema.mutate(schemaText)) }}>
<div className="graphql-section-head"><p className="eyebrow">Schema</p>{schemaStatus && <code className={`query-state query-state--${schemaStatus.status === 'SUCCESS' ? 'succeeded' : schemaStatus.status === 'FAILED' ? 'failed' : 'running'}`}>{schemaStatus.status}</code>}</div>
<textarea className="textarea mono graphql-schema" aria-label="Schema definition" value={schemaText} spellCheck={false} rows={14} onChange={(event) => setDefinition(event.target.value)} disabled={disabled}/>
{!savedDefinition && detailQuery.data && <small className="muted">No schema yet. This starter schema is not saved until you save it.</small>}
<div><button className="button primary" type="submit" disabled={disabled || !schemaText.trim() || (definition === null && Boolean(savedDefinition))}>{saveSchema.isPending ? 'Saving' : 'Save schema'}</button></div>
</form>
<div className="input-row resource-table-bar"><div><p className="eyebrow">API keys</p><span className="muted">Clients send one in the x-api-key header{metadata.authenticationType === 'API_KEY' ? '.' : ' when API keys are an authorization mode.'}</span></div></div>
{apiKeys.length === 0 ? <p className="muted compact-text graphql-note">No API keys.</p>
: <div className="cognito-table"><table className="table"><thead><tr><th>Key</th><th>Description</th><th>Expires</th><th aria-label="Actions"/></tr></thead><tbody>{apiKeys.map((key) => (
<tr key={key.id}>
<td className="mono">{key.id} <button className="button compact" type="button" aria-label={`Copy ${key.id}`} onClick={() => copy(key.id)}><Copy size={12}/></button></td>
<td>{key.description ?? '—'}</td>
<td>{formatDateTime(key.expiresAt) ?? '—'}</td>
<td className="efs-row-actions"><button className="button compact danger" type="button" disabled={disabled} aria-label={`Delete ${key.id}`} onClick={() => run(() => {
if (window.confirm(`Delete API key ${key.id}? Clients using it are refused.`)) removeKey.mutate(key.id)
})}>Delete</button></td>
</tr>
))}</tbody></table></div>}
<form className="dynamic-form graphql-inline-form" aria-label="Create API key" onSubmit={(event) => { event.preventDefault(); run(() => addKey.mutate()) }}>
<label className="dynamic-field"><span>Description</span><input className="input" value={keyForm.description} onChange={(event) => setKeyForm({...keyForm, description: event.target.value})} disabled={disabled}/></label>
<label className="dynamic-field"><span>Expires in (days)</span><input className="input" type="number" min={1} max={365} value={keyForm.days} onChange={(event) => setKeyForm({...keyForm, days: event.target.value})} disabled={disabled} required/></label>
<div><button className="button" type="submit" disabled={disabled}>{addKey.isPending ? 'Creating' : 'Create API key'}</button></div>
</form>
<div className="input-row resource-table-bar"><div><p className="eyebrow">Data sources</p><span className="muted">What resolvers read from and write to.</span></div></div>
{dataSources.length === 0 ? <p className="muted compact-text graphql-note">No data sources yet.</p>
: <div className="cognito-table"><table className="table"><thead><tr><th>Name</th><th>Type</th><th>Target</th><th aria-label="Actions"/></tr></thead><tbody>{dataSources.map((source) => (
<tr key={source.name}>
<td className="mono">{source.name}</td>
<td>{SOURCE_LABELS[source.type ?? ''] ?? source.type ?? '—'}</td>
<td className="mono graphql-target">{source.tableName ?? source.functionArn ?? '—'}</td>
<td className="efs-row-actions"><button className="button compact danger" type="button" disabled={disabled} aria-label={`Delete data source ${source.name}`} onClick={() => run(() => {
if (window.confirm(`Delete data source ${source.name}?`)) removeSource.mutate(source.name)
})}>Delete</button></td>
</tr>
))}</tbody></table></div>}
<form className="dynamic-form graphql-source-form" aria-label="Create data source" onSubmit={(event) => { event.preventDefault(); run(() => addSource.mutate()) }}>
<label className="dynamic-field"><span>Name</span><input className="input mono" value={sourceForm.name} onChange={(event) => setSourceForm({...sourceForm, name: event.target.value})} disabled={disabled} required pattern="[_A-Za-z][_0-9A-Za-z]*" title="Letters, numbers and underscores, starting with a letter or underscore"/></label>
<label className="dynamic-field"><span>Type</span><select className="input" value={sourceForm.type} onChange={(event) => setSourceForm({...sourceForm, type: event.target.value as SourceForm['type']})} disabled={disabled}>
{Object.entries(SOURCE_LABELS).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
</select></label>
{sourceForm.type === 'AMAZON_DYNAMODB' && <label className="dynamic-field"><span>Table</span><select className="input" value={sourceForm.tableName} onChange={(event) => setSourceForm({...sourceForm, tableName: event.target.value})} disabled={disabled} required>
<option value="">{tablesQuery.data?.length ? 'Choose a table' : 'No tables yet'}</option>
{(tablesQuery.data ?? []).map((table) => <option key={table.id} value={table.name}>{table.name}</option>)}
</select></label>}
{sourceForm.type === 'AWS_LAMBDA' && <label className="dynamic-field"><span>Function</span><select className="input" value={sourceForm.functionArn} onChange={(event) => setSourceForm({...sourceForm, functionArn: event.target.value})} disabled={disabled} required>
<option value="">{functionsQuery.data?.length ? 'Choose a function' : 'No functions yet'}</option>
{(functionsQuery.data ?? []).filter((fn) => typeof fn.metadata.arn === 'string').map((fn) => <option key={fn.id} value={String(fn.metadata.arn)}>{fn.name}</option>)}
</select></label>}
{sourceForm.type !== 'NONE' && <label className="dynamic-field graphql-span"><span>Service role ARN</span><input className="input mono" value={sourceForm.serviceRoleArn} placeholder="arn:aws:iam::000000000000:role/appsync-access" onChange={(event) => setSourceForm({...sourceForm, serviceRoleArn: event.target.value})} disabled={disabled} required pattern="arn:aws[a-z\-]*:iam::\d{12}:role/.+" title="The IAM role AppSync assumes, as AWS requires"/></label>}
<div><button className="button" type="submit" disabled={disabled}>{addSource.isPending ? 'Creating' : 'Create data source'}</button></div>
</form>
<div className="input-row resource-table-bar"><div><p className="eyebrow">Resolvers</p><span className="muted">JavaScript (APPSYNC_JS) resolvers attached to fields of the schema.</span></div></div>
{resolvers.length === 0 ? <p className="muted compact-text graphql-note">No resolvers yet.</p>
: <div className="cognito-table"><table className="table"><thead><tr><th>Field</th><th>Data source</th><th>Runtime</th><th aria-label="Actions"/></tr></thead><tbody>{resolvers.map((resolver) => (
<tr key={`${resolver.typeName}.${resolver.fieldName}`}>
<td className="mono">{resolver.typeName}.{resolver.fieldName}</td>
<td className="mono">{resolver.dataSourceName ?? '—'}</td>
<td>{resolver.runtime ?? '—'}</td>
<td className="efs-row-actions"><button className="button compact danger" type="button" disabled={disabled} aria-label={`Detach ${resolver.typeName}.${resolver.fieldName}`} onClick={() => run(() => {
if (window.confirm(`Detach the resolver from ${resolver.typeName}.${resolver.fieldName}?`)) removeResolver.mutate(resolver)
})}>Detach</button></td>
</tr>
))}</tbody></table></div>}
{types.length === 0 ? <p className="muted compact-text graphql-note">Save a schema to attach resolvers to its fields.</p>
: dataSources.length === 0 ? <p className="muted compact-text graphql-note">Create a data source to attach resolvers.</p>
: <form className="graphql-section" aria-label="Attach resolver" onSubmit={(event) => { event.preventDefault(); run(() => addResolver.mutate()) }}>
<div className="dynamic-form graphql-source-form">
<label className="dynamic-field"><span>Type</span><select className="input" value={resolverForm.typeName} onChange={(event) => setResolverForm({...resolverForm, typeName: event.target.value, fieldName: ''})} disabled={disabled} required>
<option value="">Choose a type</option>
{types.map((type) => <option key={type.name} value={type.name}>{type.name}</option>)}
</select></label>
<label className="dynamic-field"><span>Field</span><select className="input" value={resolverForm.fieldName} onChange={(event) => setResolverForm({...resolverForm, fieldName: event.target.value})} disabled={disabled || !chosenType} required>
<option value="">{chosenType && openFields.length === 0 ? 'Every field has a resolver' : 'Choose a field'}</option>
{openFields.map((field) => <option key={field} value={field}>{field}</option>)}
</select></label>
<label className="dynamic-field"><span>Data source</span><select className="input" value={resolverForm.dataSourceName} onChange={(event) => chooseSource(event.target.value)} disabled={disabled} required>
<option value="">Choose a data source</option>
{dataSources.map((source) => <option key={source.name} value={source.name}>{source.name}</option>)}
</select></label>
</div>
<textarea className="textarea mono graphql-code" aria-label="Resolver code" value={resolverForm.code} spellCheck={false} rows={10} placeholder="Choose a data source to start from its template." onChange={(event) => setResolverForm({...resolverForm, code: event.target.value})} disabled={disabled} required/>
<div><button className="button" type="submit" disabled={disabled}>{addResolver.isPending ? 'Attaching' : 'Attach resolver'}</button></div>
</form>}
{notice && <p className="cognito-outcome cognito-outcome--ok" role="status">{notice}</p>}
{error instanceof Error && <p className="error-text compact-text" role="alert">{error.message}</p>}
</section>
}
@@ -1,6 +1,7 @@
import {
Activity,
Boxes,
Braces,
Circle,
Clock,
Container,
@@ -44,6 +45,7 @@ import autoScalingIcon from '../../../../aws-icons-svg/Compute/EC2-Auto-Scaling.
import efsIcon from '../../../../aws-icons-svg/Storage/EFS.svg'
import glueIcon from '../../../../aws-icons-svg/Analytics/Glue.svg'
import athenaIcon from '../../../../aws-icons-svg/Analytics/Athena.svg'
import appSyncIcon from '../../../../aws-icons-svg/App-Integration/AppSync.svg'
import certificateManagerIcon from '../../../../aws-icons-svg/Security-Identity-Compliance/Certificate-Manager.svg'
import cloudWatchIcon from '../../../../aws-icons-svg/Management-Governance/CloudWatch.svg'
import cloudFormationIcon from '@/assets/aws-services/cloudformation.svg'
@@ -109,6 +111,7 @@ const SERVICE_ICONS: Record<string, LucideIcon> = {
filesystems: FolderTree,
datacatalog: Table2,
query: SearchCode,
graphql: Braces,
certificates: FileBadge,
monitoring: Activity,
loadbalancing: Scale,
@@ -162,6 +165,7 @@ const AWS_SERVICE_ICON_ASSETS: Record<string, string> = {
filesystems: efsIcon,
datacatalog: glueIcon,
query: athenaIcon,
graphql: appSyncIcon,
certificates: certificateManagerIcon,
monitoring: cloudWatchIcon,
workflows: stepFunctionsIcon,
+16
View File
@@ -6675,3 +6675,19 @@ tr[aria-current="true"] td { background: var(--hover-md); }
.query-note { padding: 0 16px 12px; margin: 0; }
.query-history-sql { text-align: left; max-width: 640px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; }
@media (max-width: 760px) { .query-layout { grid-template-columns: minmax(0, 1fr); } }
/* AppSync: endpoints as a definition list, schema and resolver code as tall editors. */
.graphql-endpoints { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 12px; margin: 0; padding: 12px 16px 4px; }
.graphql-endpoints dt { color: var(--text-2); font-size: 11px; font-weight: 600; text-transform: uppercase; align-self: center; }
.graphql-endpoints dd { margin: 0; overflow-wrap: anywhere; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.graphql-note { padding: 0 16px 12px; margin: 0; }
.graphql-section { display: grid; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--border); }
.graphql-section-head { display: flex; align-items: center; gap: 10px; }
.graphql-section-head p { margin: 0; }
.graphql-schema, .graphql-code { min-height: 180px; resize: vertical; }
.graphql-inline-form { grid-template-columns: repeat(auto-fit, minmax(160px, 260px)); align-items: end; padding: 4px 16px 12px; }
.graphql-source-form { grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); align-items: end; padding: 4px 16px 12px; }
.graphql-section .graphql-source-form { padding: 0; }
.graphql-span { grid-column: span 2; }
.graphql-target { overflow-wrap: anywhere; }
@media (max-width: 640px) { .graphql-span { grid-column: auto; } .graphql-endpoints { grid-template-columns: minmax(0, 1fr); } }
+21
View File
@@ -362,6 +362,27 @@ export interface AutoScalingCapacityInput {
maxSize?: number
}
export interface GraphqlApiKeyInput {
description?: string
expiresInDays?: number
}
export interface GraphqlDataSourceInput {
name: string
description?: string
type: 'NONE' | 'AMAZON_DYNAMODB' | 'AWS_LAMBDA'
tableName?: string
functionArn?: string
serviceRoleArn?: string
}
export interface GraphqlResolverInput {
typeName: string
fieldName: string
dataSourceName: string
code: string
}
export interface QueryInput {
sql: string
database?: string
+2
View File
@@ -30,6 +30,7 @@ export type ItemActionName = 'list' | 'get' | 'put' | 'delete' | 'query'
export type DistributionActionName = 'setEnabled' | 'createInvalidation'
export type AutoScalingActionName = 'setCapacity' | 'terminateInstance'
export type CertificateActionName = 'download' | 'export' | 'revoke'
export type GraphqlActionName = 'updateSchema' | 'createApiKey' | 'deleteApiKey' | 'createDataSource' | 'deleteDataSource' | 'createResolver' | 'deleteResolver'
export type QueryActionName = 'run' | 'results' | 'stop' | 'history' | 'catalog'
export type DataCatalogActionName = 'createTable' | 'deleteTable'
export type FileSystemActionName = 'createMountTarget' | 'deleteMountTarget' | 'createAccessPoint' | 'deleteAccessPoint' | 'attachFunction' | 'detachFunction'
@@ -101,6 +102,7 @@ export interface ServiceSchema {
fileSystemActions?: Array<CapabilitySchema<FileSystemActionName>>
dataCatalogActions?: Array<CapabilitySchema<DataCatalogActionName>>
queryActions?: Array<CapabilitySchema<QueryActionName>>
graphqlActions?: Array<CapabilitySchema<GraphqlActionName>>
monitoringActions?: Array<CapabilitySchema<MonitoringActionName>>
}
filters: FieldSchema[]
+18
View File
@@ -22,6 +22,9 @@ importers:
'@aws-sdk/client-appconfig':
specifier: ^3.1076.0
version: 3.1130.0
'@aws-sdk/client-appsync':
specifier: ^3.1146.0
version: 3.1156.0
'@aws-sdk/client-athena':
specifier: ^3.1146.0
version: 3.1156.0
@@ -332,6 +335,10 @@ packages:
resolution: {integrity: sha512-CPVT+sEZLpYYLs6gIUr+O76QWzwjCIMp8ih7VZOQTzUhM8jXlDBwarupCMOkk830STVmKu5zhQjCzYI8i+XU3A==}
engines: {node: '>=20.0.0'}
'@aws-sdk/client-appsync@3.1156.0':
resolution: {integrity: sha512-I3orpZmtgqcxOdMg5Eq6roEbzGnrbR46JwByagLaTfezCakqcJFeE6n4oboQv8EDcAH3/ypfelCsCof6Tngrcg==}
engines: {node: '>=20.0.0'}
'@aws-sdk/client-athena@3.1156.0':
resolution: {integrity: sha512-rqebnBvY6c9DuSKZz99dI0BS01HZl3iqXYTWTqbEbu02C1YCiYoho7tW7buAnNqIhZ1laB+EJh/JncO59pruJA==}
engines: {node: '>=20.0.0'}
@@ -2983,6 +2990,17 @@ snapshots:
'@smithy/types': 4.17.2
tslib: 2.8.1
'@aws-sdk/client-appsync@3.1156.0':
dependencies:
'@aws-sdk/core': 3.978.5
'@aws-sdk/credential-provider-node': 3.972.88
'@aws-sdk/types': 3.975.0
'@smithy/core': 3.36.2
'@smithy/fetch-http-handler': 5.8.0
'@smithy/node-http-handler': 4.12.1
'@smithy/types': 4.19.0
tslib: 2.8.1
'@aws-sdk/client-athena@3.1156.0':
dependencies:
'@aws-sdk/core': 3.978.5