also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,548 +0,0 @@ | ||
| 1 | # Extend Cloud | |
| 2 | ||
| 3 | This guide covers extending Stacks cloud functionality with custom cloud providers, infrastructure configurations, and advanced cloud resources. | |
| 4 | ||
| 5 | ## Getting Started | |
| 6 | ||
| 7 | Stacks provides a flexible cloud infrastructure layer that can be extended with custom providers and configurations. | |
| 8 | ||
| 9 | ```ts | |
| 10 | import { Cloud } from '@stacksjs/cloud' | |
| 11 | ``` | |
| 12 | ||
| 13 | ## Custom Cloud Providers | |
| 14 | ||
| 15 | ### Creating a Custom Provider | |
| 16 | ||
| 17 | ```ts | |
| 18 | // cloud/providers/custom-provider.ts | |
| 19 | import type { CloudProvider, DeploymentConfig, DeploymentResult } from '@stacksjs/cloud' | |
| 20 | ||
| 21 | export class CustomCloudProvider implements CloudProvider { | |
| 22 | name = 'custom' | |
| 23 | ||
| 24 | async deploy(config: DeploymentConfig): Promise<DeploymentResult> { | |
| 25 | // Implementation for custom deployment | |
| 26 | const resources = await this.createResources(config) | |
| 27 | ||
| 28 | return { | |
| 29 | success: true, | |
| 30 | url: resources.url, | |
| 31 | deploymentId: resources.id, | |
| 32 | } | |
| 33 | } | |
| 34 | ||
| 35 | async destroy(deploymentId: string): Promise<boolean> { | |
| 36 | // Implementation for destroying resources | |
| 37 | return true | |
| 38 | } | |
| 39 | ||
| 40 | async getStatus(deploymentId: string): Promise<DeploymentStatus> { | |
| 41 | // Implementation for getting deployment status | |
| 42 | return { | |
| 43 | status: 'running', | |
| 44 | health: 'healthy', | |
| 45 | } | |
| 46 | } | |
| 47 | ||
| 48 | private async createResources(config: DeploymentConfig) { | |
| 49 | // Custom resource creation logic | |
| 50 | return { | |
| 51 | id: 'deployment-123', | |
| 52 | url: 'https://app.custom-cloud.com', | |
| 53 | } | |
| 54 | } | |
| 55 | } | |
| 56 | ``` | |
| 57 | ||
| 58 | ### Registering Custom Providers | |
| 59 | ||
| 60 | ```ts | |
| 61 | // config/cloud.ts | |
| 62 | import { CustomCloudProvider } from '../cloud/providers/custom-provider' | |
| 63 | ||
| 64 | export default { | |
| 65 | driver: 'custom', | |
| 66 | ||
| 67 | providers: { | |
| 68 | custom: new CustomCloudProvider(), | |
| 69 | }, | |
| 70 | ||
| 71 | // Provider-specific configuration | |
| 72 | custom: { | |
| 73 | apiKey: process.env.CUSTOM_CLOUD_API_KEY, | |
| 74 | region: 'us-east-1', | |
| 75 | }, | |
| 76 | } | |
| 77 | ``` | |
| 78 | ||
| 79 | ## Extending AWS Infrastructure | |
| 80 | ||
| 81 | ### Custom CDK Constructs | |
| 82 | ||
| 83 | ```ts | |
| 84 | // cloud/constructs/custom-api.ts | |
| 85 | import _ as cdk from 'aws-cdk-lib' | |
| 86 | import _ as apigateway from 'aws-cdk-lib/aws-apigateway' | |
| 87 | import _ as lambda from 'aws-cdk-lib/aws-lambda' | |
| 88 | import { Construct } from 'constructs' | |
| 89 | ||
| 90 | export interface CustomApiProps { | |
| 91 | functionName: string | |
| 92 | handler: string | |
| 93 | memorySize?: number | |
| 94 | timeout?: number | |
| 95 | } | |
| 96 | ||
| 97 | export class CustomApi extends Construct { | |
| 98 | public readonly api: apigateway.RestApi | |
| 99 | public readonly function: lambda.Function | |
| 100 | ||
| 101 | constructor(scope: Construct, id: string, props: CustomApiProps) { | |
| 102 | super(scope, id) | |
| 103 | ||
| 104 | // Create Lambda function | |
| 105 | this.function = new lambda.Function(this, 'Function', { | |
| 106 | functionName: props.functionName, | |
| 107 | runtime: lambda.Runtime.PROVIDED_AL2, | |
| 108 | handler: props.handler, | |
| 109 | code: lambda.Code.fromAsset('./dist'), | |
| 110 | memorySize: props.memorySize || 256, | |
| 111 | timeout: cdk.Duration.seconds(props.timeout || 30), | |
| 112 | }) | |
| 113 | ||
| 114 | // Create API Gateway | |
| 115 | this.api = new apigateway.RestApi(this, 'Api', { | |
| 116 | restApiName: `${props.functionName}-api`, | |
| 117 | deployOptions: { | |
| 118 | stageName: 'prod', | |
| 119 | }, | |
| 120 | }) | |
| 121 | ||
| 122 | // Add Lambda integration | |
| 123 | const integration = new apigateway.LambdaIntegration(this.function) | |
| 124 | this.api.root.addMethod('ANY', integration) | |
| 125 | this.api.root.addProxy({ | |
| 126 | defaultIntegration: integration, | |
| 127 | anyMethod: true, | |
| 128 | }) | |
| 129 | } | |
| 130 | } | |
| 131 | ``` | |
| 132 | ||
| 133 | ### Custom Stack | |
| 134 | ||
| 135 | ```ts | |
| 136 | // cloud/stacks/custom-stack.ts | |
| 137 | import _ as cdk from 'aws-cdk-lib' | |
| 138 | import _ as s3 from 'aws-cdk-lib/aws-s3' | |
| 139 | import _ as dynamodb from 'aws-cdk-lib/aws-dynamodb' | |
| 140 | import _ as sqs from 'aws-cdk-lib/aws-sqs' | |
| 141 | import { Construct } from 'constructs' | |
| 142 | import { CustomApi } from '../constructs/custom-api' | |
| 143 | ||
| 144 | export interface CustomStackProps extends cdk.StackProps { | |
| 145 | environment: string | |
| 146 | appName: string | |
| 147 | } | |
| 148 | ||
| 149 | export class CustomStack extends cdk.Stack { | |
| 150 | constructor(scope: Construct, id: string, props: CustomStackProps) { | |
| 151 | super(scope, id, props) | |
| 152 | ||
| 153 | // S3 Bucket for assets | |
| 154 | const bucket = new s3.Bucket(this, 'AssetsBucket', { | |
| 155 | bucketName: `${props.appName}-${props.environment}-assets`, | |
| 156 | versioned: true, | |
| 157 | encryption: s3.BucketEncryption.S3_MANAGED, | |
| 158 | removalPolicy: props.environment === 'production' | |
| 159 | ? cdk.RemovalPolicy.RETAIN | |
| 160 | : cdk.RemovalPolicy.DESTROY, | |
| 161 | }) | |
| 162 | ||
| 163 | // DynamoDB Table | |
| 164 | const table = new dynamodb.Table(this, 'MainTable', { | |
| 165 | tableName: `${props.appName}-${props.environment}`, | |
| 166 | partitionKey: { | |
| 167 | name: 'pk', | |
| 168 | type: dynamodb.AttributeType.STRING, | |
| 169 | }, | |
| 170 | sortKey: { | |
| 171 | name: 'sk', | |
| 172 | type: dynamodb.AttributeType.STRING, | |
| 173 | }, | |
| 174 | billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, | |
| 175 | pointInTimeRecovery: props.environment === 'production', | |
| 176 | }) | |
| 177 | ||
| 178 | // SQS Queue for background jobs | |
| 179 | const queue = new sqs.Queue(this, 'JobsQueue', { | |
| 180 | queueName: `${props.appName}-${props.environment}-jobs`, | |
| 181 | visibilityTimeout: cdk.Duration.seconds(300), | |
| 182 | retentionPeriod: cdk.Duration.days(14), | |
| 183 | }) | |
| 184 | ||
| 185 | // Custom API | |
| 186 | const api = new CustomApi(this, 'Api', { | |
| 187 | functionName: `${props.appName}-${props.environment}-api`, | |
| 188 | handler: 'index.handler', | |
| 189 | memorySize: 512, | |
| 190 | timeout: 30, | |
| 191 | }) | |
| 192 | ||
| 193 | // Grant permissions | |
| 194 | bucket.grantReadWrite(api.function) | |
| 195 | table.grantReadWriteData(api.function) | |
| 196 | queue.grantSendMessages(api.function) | |
| 197 | ||
| 198 | // Outputs | |
| 199 | new cdk.CfnOutput(this, 'ApiUrl', { | |
| 200 | value: api.api.url, | |
| 201 | }) | |
| 202 | ||
| 203 | new cdk.CfnOutput(this, 'BucketName', { | |
| 204 | value: bucket.bucketName, | |
| 205 | }) | |
| 206 | } | |
| 207 | } | |
| 208 | ``` | |
| 209 | ||
| 210 | ### Using Custom Stack | |
| 211 | ||
| 212 | ```ts | |
| 213 | // cloud/app.ts | |
| 214 | import _ as cdk from 'aws-cdk-lib' | |
| 215 | import { CustomStack } from './stacks/custom-stack' | |
| 216 | ||
| 217 | const app = new cdk.App() | |
| 218 | ||
| 219 | const environment = app.node.tryGetContext('environment') || 'development' | |
| 220 | ||
| 221 | new CustomStack(app, `MyApp-${environment}`, { | |
| 222 | environment, | |
| 223 | appName: 'my-app', | |
| 224 | env: { | |
| 225 | account: process.env.AWS_ACCOUNT_ID, | |
| 226 | region: process.env.AWS_REGION || 'us-east-1', | |
| 227 | }, | |
| 228 | }) | |
| 229 | ||
| 230 | app.synth() | |
| 231 | ``` | |
| 232 | ||
| 233 | ## Custom Infrastructure Resources | |
| 234 | ||
| 235 | ### Adding Custom Lambda Functions | |
| 236 | ||
| 237 | ```ts | |
| 238 | // cloud/functions/custom-function.ts | |
| 239 | import _ as lambda from 'aws-cdk-lib/aws-lambda' | |
| 240 | import _ as events from 'aws-cdk-lib/aws-events' | |
| 241 | import _ as targets from 'aws-cdk-lib/aws-events-targets' | |
| 242 | import { Construct } from 'constructs' | |
| 243 | ||
| 244 | export function addScheduledFunction( | |
| 245 | scope: Construct, | |
| 246 | id: string, | |
| 247 | options: { | |
| 248 | schedule: string // cron expression | |
| 249 | handler: string | |
| 250 | memorySize?: number | |
| 251 | } | |
| 252 | ) { | |
| 253 | const fn = new lambda.Function(scope, id, { | |
| 254 | runtime: lambda.Runtime.PROVIDED_AL2, | |
| 255 | handler: options.handler, | |
| 256 | code: lambda.Code.fromAsset('./dist/functions'), | |
| 257 | memorySize: options.memorySize || 128, | |
| 258 | }) | |
| 259 | ||
| 260 | // Create scheduled rule | |
| 261 | const rule = new events.Rule(scope, `${id}Rule`, { | |
| 262 | schedule: events.Schedule.expression(options.schedule), | |
| 263 | }) | |
| 264 | ||
| 265 | rule.addTarget(new targets.LambdaFunction(fn)) | |
| 266 | ||
| 267 | return fn | |
| 268 | } | |
| 269 | ||
| 270 | // Usage | |
| 271 | addScheduledFunction(this, 'DailyCleanup', { | |
| 272 | schedule: 'cron(0 0 _ _ ? _)', // Every day at midnight | |
| 273 | handler: 'cleanup.handler', | |
| 274 | }) | |
| 275 | ``` | |
| 276 | ||
| 277 | ### Adding Custom Databases | |
| 278 | ||
| 279 | ```ts | |
| 280 | // cloud/databases/custom-database.ts | |
| 281 | import _ as rds from 'aws-cdk-lib/aws-rds' | |
| 282 | import _ as ec2 from 'aws-cdk-lib/aws-ec2' | |
| 283 | import _ as cdk from 'aws-cdk-lib' | |
| 284 | import { Construct } from 'constructs' | |
| 285 | ||
| 286 | export function addRdsDatabase( | |
| 287 | scope: Construct, | |
| 288 | id: string, | |
| 289 | vpc: ec2.IVpc, | |
| 290 | options: { | |
| 291 | instanceType?: string | |
| 292 | engine?: string | |
| 293 | multiAz?: boolean | |
| 294 | } | |
| 295 | ) { | |
| 296 | const database = new rds.DatabaseInstance(scope, id, { | |
| 297 | engine: rds.DatabaseInstanceEngine.mysql({ | |
| 298 | version: rds.MysqlEngineVersion.VER_8_0, | |
| 299 | }), | |
| 300 | instanceType: ec2.InstanceType.of( | |
| 301 | ec2.InstanceClass.T3, | |
| 302 | ec2.InstanceSize.SMALL | |
| 303 | ), | |
| 304 | vpc, | |
| 305 | vpcSubnets: { | |
| 306 | subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, | |
| 307 | }, | |
| 308 | multiAz: options.multiAz ?? false, | |
| 309 | allocatedStorage: 20, | |
| 310 | maxAllocatedStorage: 100, | |
| 311 | backupRetention: cdk.Duration.days(7), | |
| 312 | deletionProtection: true, | |
| 313 | }) | |
| 314 | ||
| 315 | return database | |
| 316 | } | |
| 317 | ``` | |
| 318 | ||
| 319 | ### Adding Custom Caching | |
| 320 | ||
| 321 | ```ts | |
| 322 | // cloud/caching/elasticache.ts | |
| 323 | import _ as elasticache from 'aws-cdk-lib/aws-elasticache' | |
| 324 | import _ as ec2 from 'aws-cdk-lib/aws-ec2' | |
| 325 | import { Construct } from 'constructs' | |
| 326 | ||
| 327 | export function addRedisCluster( | |
| 328 | scope: Construct, | |
| 329 | id: string, | |
| 330 | vpc: ec2.IVpc, | |
| 331 | options: { | |
| 332 | nodeType?: string | |
| 333 | numCacheNodes?: number | |
| 334 | } | |
| 335 | ) { | |
| 336 | const subnetGroup = new elasticache.CfnSubnetGroup(scope, `${id}SubnetGroup`, { | |
| 337 | description: 'Subnet group for Redis cluster', | |
| 338 | subnetIds: vpc.privateSubnets.map(subnet => subnet.subnetId), | |
| 339 | }) | |
| 340 | ||
| 341 | const cluster = new elasticache.CfnCacheCluster(scope, id, { | |
| 342 | cacheNodeType: options.nodeType || 'cache.t3.micro', | |
| 343 | engine: 'redis', | |
| 344 | numCacheNodes: options.numCacheNodes || 1, | |
| 345 | cacheSubnetGroupName: subnetGroup.ref, | |
| 346 | }) | |
| 347 | ||
| 348 | return cluster | |
| 349 | } | |
| 350 | ``` | |
| 351 | ||
| 352 | ## Custom Deployment Hooks | |
| 353 | ||
| 354 | ### Pre-Deployment Hooks | |
| 355 | ||
| 356 | ```ts | |
| 357 | // cloud/hooks/pre-deploy.ts | |
| 358 | export async function preDeployHook(context: DeploymentContext): Promise<void> { | |
| 359 | console.log('Running pre-deployment checks...') | |
| 360 | ||
| 361 | // Run database migrations | |
| 362 | await runMigrations() | |
| 363 | ||
| 364 | // Validate configuration | |
| 365 | await validateConfig() | |
| 366 | ||
| 367 | // Backup current state | |
| 368 | await createBackup() | |
| 369 | ||
| 370 | console.log('Pre-deployment checks complete') | |
| 371 | } | |
| 372 | ||
| 373 | async function runMigrations() { | |
| 374 | // Run pending migrations | |
| 375 | const migrations = await getPendingMigrations() | |
| 376 | ||
| 377 | for (const migration of migrations) { | |
| 378 | console.log(`Running migration: ${migration.name}`) | |
| 379 | await migration.up() | |
| 380 | } | |
| 381 | } | |
| 382 | ||
| 383 | async function validateConfig() { | |
| 384 | const requiredEnvVars = [ | |
| 385 | 'DATABASE_URL', | |
| 386 | 'REDIS_URL', | |
| 387 | 'AWS_ACCESS_KEY_ID', | |
| 388 | ] | |
| 389 | ||
| 390 | for (const envVar of requiredEnvVars) { | |
| 391 | if (!process.env[envVar]) { | |
| 392 | throw new Error(`Missing required environment variable: ${envVar}`) | |
| 393 | } | |
| 394 | } | |
| 395 | } | |
| 396 | ||
| 397 | async function createBackup() { | |
| 398 | // Create backup before deployment | |
| 399 | const timestamp = new Date().toISOString() | |
| 400 | console.log(`Creating backup: backup-${timestamp}`) | |
| 401 | } | |
| 402 | ``` | |
| 403 | ||
| 404 | ### Post-Deployment Hooks | |
| 405 | ||
| 406 | ```ts | |
| 407 | // cloud/hooks/post-deploy.ts | |
| 408 | export async function postDeployHook(context: DeploymentContext): Promise<void> { | |
| 409 | console.log('Running post-deployment tasks...') | |
| 410 | ||
| 411 | // Clear caches | |
| 412 | await clearCaches() | |
| 413 | ||
| 414 | // Warm up endpoints | |
| 415 | await warmUp() | |
| 416 | ||
| 417 | // Notify team | |
| 418 | await notifyDeployment(context) | |
| 419 | ||
| 420 | console.log('Post-deployment tasks complete') | |
| 421 | } | |
| 422 | ||
| 423 | async function clearCaches() { | |
| 424 | // Clear CDN cache | |
| 425 | await cloudfront.createInvalidation({ | |
| 426 | DistributionId: process.env.CLOUDFRONT_DISTRIBUTION_ID, | |
| 427 | InvalidationBatch: { | |
| 428 | Paths: { Quantity: 1, Items: ['/_'] }, | |
| 429 | CallerReference: Date.now().toString(), | |
| 430 | }, | |
| 431 | }) | |
| 432 | ||
| 433 | // Clear Redis cache | |
| 434 | await redis.flushall() | |
| 435 | } | |
| 436 | ||
| 437 | async function warmUp() { | |
| 438 | const endpoints = [ | |
| 439 | '/api/health', | |
| 440 | '/api/products', | |
| 441 | '/api/categories', | |
| 442 | ] | |
| 443 | ||
| 444 | for (const endpoint of endpoints) { | |
| 445 | await fetch(`${process.env.APP_URL}${endpoint}`) | |
| 446 | } | |
| 447 | } | |
| 448 | ||
| 449 | async function notifyDeployment(context: DeploymentContext) { | |
| 450 | await sendSlackNotification({ | |
| 451 | channel: '#deployments', | |
| 452 | text: `Deployed ${context.version} to ${context.environment}`, | |
| 453 | }) | |
| 454 | } | |
| 455 | ``` | |
| 456 | ||
| 457 | ### Registering Hooks | |
| 458 | ||
| 459 | ```ts | |
| 460 | // config/cloud.ts | |
| 461 | import { preDeployHook } from '../cloud/hooks/pre-deploy' | |
| 462 | import { postDeployHook } from '../cloud/hooks/post-deploy' | |
| 463 | ||
| 464 | export default { | |
| 465 | hooks: { | |
| 466 | preDeploy: preDeployHook, | |
| 467 | postDeploy: postDeployHook, | |
| 468 | ||
| 469 | onError: async (error: Error, context: DeploymentContext) => { | |
| 470 | console.error('Deployment failed:', error) | |
| 471 | ||
| 472 | // Rollback on failure | |
| 473 | await context.rollback() | |
| 474 | ||
| 475 | // Notify team | |
| 476 | await sendSlackNotification({ | |
| 477 | channel: '#deployments', | |
| 478 | text: `Deployment failed: ${error.message}`, | |
| 479 | }) | |
| 480 | }, | |
| 481 | }, | |
| 482 | } | |
| 483 | ``` | |
| 484 | ||
| 485 | ## Multi-Region Deployment | |
| 486 | ||
| 487 | ### Configuration | |
| 488 | ||
| 489 | ```ts | |
| 490 | // config/cloud.ts | |
| 491 | export default { | |
| 492 | multiRegion: { | |
| 493 | enabled: true, | |
| 494 | primaryRegion: 'us-east-1', | |
| 495 | replicaRegions: ['eu-west-1', 'ap-southeast-1'], | |
| 496 | routing: 'latency', // 'latency' | 'geolocation' | 'weighted' | |
| 497 | }, | |
| 498 | } | |
| 499 | ``` | |
| 500 | ||
| 501 | ### Multi-Region Stack | |
| 502 | ||
| 503 | ```ts | |
| 504 | // cloud/stacks/multi-region-stack.ts | |
| 505 | import _ as cdk from 'aws-cdk-lib' | |
| 506 | import _ as route53 from 'aws-cdk-lib/aws-route53' | |
| 507 | import { Construct } from 'constructs' | |
| 508 | ||
| 509 | export class MultiRegionStack extends cdk.Stack { | |
| 510 | constructor(scope: Construct, id: string, props: cdk.StackProps) { | |
| 511 | super(scope, id, props) | |
| 512 | ||
| 513 | const regions = ['us-east-1', 'eu-west-1', 'ap-southeast-1'] | |
| 514 | ||
| 515 | // Create resources in each region | |
| 516 | for (const region of regions) { | |
| 517 | // Resources are created using nested stacks or cross-region references | |
| 518 | } | |
| 519 | ||
| 520 | // Set up Route53 latency-based routing | |
| 521 | const hostedZone = route53.HostedZone.fromLookup(this, 'Zone', { | |
| 522 | domainName: 'myapp.com', | |
| 523 | }) | |
| 524 | ||
| 525 | // Add latency-based records for each region | |
| 526 | } | |
| 527 | } | |
| 528 | ``` | |
| 529 | ||
| 530 | ## Error Handling | |
| 531 | ||
| 532 | ```ts | |
| 533 | try { | |
| 534 | await Cloud.deploy(config) | |
| 535 | } catch (error) { | |
| 536 | if (error instanceof CloudProviderError) { | |
| 537 | console.error('Provider error:', error.message) | |
| 538 | // Handle provider-specific errors | |
| 539 | } else if (error instanceof InfrastructureError) { | |
| 540 | console.error('Infrastructure error:', error.message) | |
| 541 | // Handle infrastructure errors | |
| 542 | } else { | |
| 543 | console.error('Unknown error:', error) | |
| 544 | } | |
| 545 | } | |
| 546 | ``` | |
| 547 | ||
| 548 | This documentation covers extending Stacks cloud functionality with custom providers and infrastructure configurations. Each example is designed for flexible cloud infrastructure management. | |