@pattform/api-kit 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ Proprietary License
2
+
3
+ Copyright (c) 2024 Pattform, Inc. All rights reserved.
4
+
5
+ Permission is hereby granted to Pattform and its authorized subsidiaries and sub-companies to use, modify, and distribute this software internally, subject to the following conditions:
6
+
7
+ 1. The software may only be used by authorized entities within Pattform and its subsidiaries.
8
+ 2. Redistribution outside of Pattform or its subsidiaries is prohibited.
9
+ 3. This software is provided "as is," without any warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the authors or copyright holders be liable for any claim, damages, or other liability.
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ # pattform-api-kit
2
+ This is a Pulumi Component Library built to allow for extremely quick API creation.
3
+ In particular, this library is designed to provide a fast and simple way to deploy a containerised API to Google Cloud Run,
4
+ and then expose it to the internet via AWS Api Gateway.
5
+
6
+ ## Requirements
7
+ * [Node.js](https://nodejs.org/en/download/)
8
+ * [Pulumi](https://www.pulumi.com/docs/get-started/install/)
9
+ * Docker (for CI image builds)
10
+ * [Google Cloud SDK](https://cloud.google.com/sdk/docs/install)
11
+ * [Google Cloud Project](https://cloud.google.com/resource-manager/docs/creating-managing-projects)
12
+ * [Google Cloud Service Account](https://cloud.google.com/iam/docs/creating-managing-service-accounts)
13
+ * [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)
14
+ * [AWS Account](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)
15
+ * [AWS IAM User](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html)
16
+ * [AWS Route53 Hosted Zone](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingHostedZone.html)
17
+
18
+ ## Installation
19
+ ```bash
20
+ npm install @pattform/infra-api-library
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ### App Component
26
+ #### Pulumi Config Requirements
27
+ * `aws:region` - AWS Region
28
+ * `cloudflare:apiToken` - Cloudflare API Token (not needed when `manageDns: false`)
29
+ * `github:apiToken` - GitHub API Token (Must have `repo` scope)
30
+
31
+ #### DNS
32
+ By default the component creates the certificate-validation and subdomain CNAMEs in Cloudflare. When the client owns their domain elsewhere (GoDaddy, Squarespace, their IT provider, ...), set `manageDns: false`: no Cloudflare config is needed, and the records the client must create are exposed on the `requiredDnsRecords` output (`{ name, type, value, purpose }[]` - the ACM validation CNAME plus one CNAME per subdomain). Export it from the stack and send it to the client:
33
+
34
+ ```typescript
35
+ export const dnsRecordsForClient = app.requiredDnsRecords;
36
+ ```
37
+
38
+ The Amplify domain association is created with `waitForVerification: false`, so `pulumi up` completes before the client adds their records; the domain goes live once the records exist and the certificate validates.
39
+
40
+ #### AWS credentials
41
+ The component picks AWS credentials in this order:
42
+ 1. `roleArn` arg (or `aws:roleArn` config) - assume-role into the client account, e.g. the `deployRoleArn` output of a `ClientAccountComponent`. Preferred.
43
+ 2. `aws:accessKey` + `aws:secretKey` config - legacy static keys for shared-account stacks.
44
+ 3. Ambient credentials - e.g. a Pulumi ESC environment with `aws-login` (OIDC).
45
+
46
+ ```typescript
47
+ import { AppComponent } from '@pattform/api-kit';
48
+
49
+ const app = new AppComponent("app", {
50
+ domain: domain, // domain of the app
51
+ repoUrl: repoUrl, // url of the repo
52
+ subDomains: ["www", ""], // subdomains to create. If not provided, defaults to ["www", ""]
53
+ roleArn: roleArn, // optional: role to assume in the client account
54
+ manageDns: true, // optional: set false when the domain is not in Cloudflare (see DNS section)
55
+ buildSpec: // If not provided, defaults to running `npm run build` and expects an outputed `dist` directory
56
+ `
57
+ version: 0.2
58
+ phases:
59
+ pre_build:
60
+ commands:
61
+ - npm install
62
+ build:
63
+ commands:
64
+ - npm run build
65
+ artifacts:
66
+ files:
67
+ - '**/*'
68
+ cache:
69
+ paths:
70
+ - node_modules/**/*
71
+ `
72
+ })
73
+ ```
74
+
75
+ ### Client Account Component
76
+ Creates an AWS member account for a client under the Pattform organization's Clients OU, plus a monthly cost budget with email alerts inside that account. Run with management-account credentials (e.g. the `Pattform/Prod` ESC environment).
77
+
78
+ #### Pulumi Config Requirements
79
+ * `aws:region` - AWS Region (unless `region` arg is given)
80
+
81
+ ```typescript
82
+ import { ClientAccountComponent, AppComponent } from '@pattform/api-kit';
83
+
84
+ const org = new pulumi.StackReference("Pattform/pattform-infrastructure/prod");
85
+
86
+ const clientAccount = new ClientAccountComponent("kaloblock", {
87
+ email: "aws+kaloblock@pattform.io", // root email for the new account
88
+ parentId: org.getOutput("clientsOuId"), // Clients OU
89
+ budgetLimitUsd: 10, // optional, defaults to 10
90
+ budgetAlertEmails: ["contact@pattform.io"], // optional
91
+ });
92
+
93
+ // Deploy the client's app into their account:
94
+ const app = new AppComponent("app", {
95
+ domain: domain,
96
+ repoUrl: repoUrl,
97
+ roleArn: clientAccount.deployRoleArn,
98
+ });
99
+ ```
100
+
101
+ Notes:
102
+ * The account resource is `protect: true` and `closeOnDeletion: false` - a `pulumi destroy` will not close a client's AWS account.
103
+ * AWS limits account closures to 10% of the org per 30 days; closed accounts stay suspended for 90 days.
104
+ * `deployRoleArn` is the account's `OrganizationAccountAccessRole`, assumable from the management account.
105
+
106
+ ### Container Component
107
+
108
+ #### Pulumi Config Requirements
109
+ * `gcp:project` - Google Cloud Project ID
110
+ * `gcp:region` - Google Cloud Region
111
+ * `gcp:credentials` - Google Cloud Service Account Credentials (or ambient credentials)
112
+ * `imageRef` - Image digest (sha256:...) set by CI; defaults to `latest` tag when not set
113
+
114
+ ```typescript
115
+ import { ContainerComponent } from '@pattform/api-kit';
116
+
117
+ const container = new ContainerComponent("container", {
118
+ environment: environment, // dev, staging, prod
119
+ imageName: imageName, // name of the image to use
120
+ memory: memory, // memory to allocate
121
+ cpu: cpu, // cpu to allocate
122
+ containerPort: containerPort, // port to expose
123
+ envVars: {
124
+ NODE_ENV: environment, // environment variable to set
125
+ API_URL: apiUrl, // url of the api
126
+ }
127
+ });
128
+ ```
129
+
130
+ Cloud Run is configured with one concurrent request per instance and a maximum of two instances.
131
+
132
+ #### CI build and Pulumi config
133
+ The image must be built and pushed before `pulumi up`. CI should set `imageRef` (the digest) into the stack config.
134
+
135
+ ```yaml
136
+ - name: Set image digest for Pulumi
137
+ run: |
138
+ pulumi config set imageRef "${IMAGE_DIGEST}" --stack "${PULUMI_STACK}"
139
+ ```
140
+
141
+ ### Api Component
142
+ #### Pulumi Config Requirements
143
+ * `aws:region` - AWS Region
144
+ * `aws:accessKey` - AWS Access Key
145
+ * `aws:secretKey` - AWS Secret Key
146
+
147
+ ```typescript
148
+ import { ApiComponent } from '@pattform/api-kit';
149
+
150
+ const api = new ApiComponent("api", {
151
+ environment: environment, // dev, staging, prod
152
+ imageName: imageName, // name of the image to use
153
+ containerUrl: containerComponent.serviceUrl, // url of the container
154
+ appDomain: appUrl, // domain of the app
155
+ apiDomain: apiDomain, // domain of the api
156
+ });
157
+ ```
158
+
159
+ ## License
160
+ See the [LICENSE](LICENSE) file.
161
+
162
+ ## Reference
163
+ * [Pulumi](https://www.pulumi.com/)
164
+ * [Pulumi Component Resource](https://www.pulumi.com/docs/intro/concepts/programming-model/#component-resources)
@@ -0,0 +1,20 @@
1
+ import * as pulumi from "@pulumi/pulumi";
2
+ /**
3
+ * ApiComponent
4
+ * This component creates an HTTP API Gateway for the container image.
5
+ */
6
+ export declare class ApiComponent extends pulumi.ComponentResource {
7
+ private readonly httpApi;
8
+ private readonly stage;
9
+ private readonly apiMapping;
10
+ readonly endpoint: pulumi.Output<string>;
11
+ constructor(name: string, args: ApiComponentArgs, opts?: pulumi.ComponentResourceOptions);
12
+ }
13
+ export interface ApiComponentArgs {
14
+ environment: pulumi.Input<string>;
15
+ imageName: pulumi.Input<string>;
16
+ containerUrl: pulumi.Input<string>;
17
+ appDomain: pulumi.Input<string>;
18
+ localAppDomain: pulumi.Input<string>;
19
+ apiDomain: pulumi.Input<string>;
20
+ }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiComponent = void 0;
4
+ const pulumi = require("@pulumi/pulumi");
5
+ const aws = require("@pulumi/aws");
6
+ const pattformHelper_1 = require("./pattformHelper");
7
+ /**
8
+ * ApiComponent
9
+ * This component creates an HTTP API Gateway for the container image.
10
+ */
11
+ class ApiComponent extends pulumi.ComponentResource {
12
+ constructor(name, args, opts) {
13
+ super("custom:pattform:ApiComponent", name, args, opts);
14
+ const awsConfig = new pulumi.Config("aws");
15
+ const awsRegion = awsConfig.require("region");
16
+ const awsAccessKey = awsConfig.requireSecret("accessKey");
17
+ const awsSecretKey = awsConfig.requireSecret("secretKey");
18
+ const awsProvider = new aws.Provider("api-component-aws-" + args.environment, {
19
+ region: (0, pattformHelper_1.verifyRegion)(awsRegion),
20
+ accessKey: awsAccessKey,
21
+ secretKey: awsSecretKey,
22
+ });
23
+ // Create an HTTP API for the load balancer to route to
24
+ this.httpApi = new aws.apigatewayv2.Api("api-component-" + args.imageName + "-api-" + args.environment, {
25
+ name: args.imageName,
26
+ protocolType: "HTTP",
27
+ disableExecuteApiEndpoint: true,
28
+ target: args.containerUrl,
29
+ routeKey: "$default",
30
+ corsConfiguration: {
31
+ allowMethods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
32
+ allowHeaders: ["*"],
33
+ allowOrigins: [args.appDomain, args.localAppDomain],
34
+ allowCredentials: true,
35
+ exposeHeaders: ["*"],
36
+ },
37
+ }, {
38
+ provider: awsProvider,
39
+ });
40
+ if (args.environment != "prod") {
41
+ this.stage = new aws.apigatewayv2.Stage("api-component-" + args.imageName + "-stage-" + args.environment, {
42
+ apiId: this.httpApi.id,
43
+ autoDeploy: true,
44
+ name: args.environment,
45
+ }, {
46
+ provider: awsProvider,
47
+ });
48
+ this.apiMapping = new aws.apigatewayv2.ApiMapping("api-component-" + args.imageName + "-mapping-" + args.environment, {
49
+ apiId: this.httpApi.id,
50
+ domainName: args.apiDomain,
51
+ stage: this.stage.name,
52
+ apiMappingKey: pulumi.interpolate `${args.imageName}/${args.environment}`,
53
+ }, {
54
+ provider: awsProvider,
55
+ });
56
+ }
57
+ else {
58
+ this.apiMapping = new aws.apigatewayv2.ApiMapping("api-component-" + args.imageName + "-mapping-" + args.environment, {
59
+ apiId: this.httpApi.id,
60
+ domainName: args.apiDomain,
61
+ stage: "$default",
62
+ apiMappingKey: pulumi.interpolate `${args.imageName}`,
63
+ }, {
64
+ provider: awsProvider,
65
+ });
66
+ }
67
+ if (args.environment != "prod") {
68
+ this.endpoint = pulumi.interpolate `https://${args.apiDomain}/${args.imageName}/${args.environment}`;
69
+ }
70
+ else {
71
+ this.endpoint = pulumi.interpolate `https://${args.apiDomain}/${args.imageName}`;
72
+ }
73
+ this.registerOutputs({
74
+ endpoint: this.endpoint,
75
+ });
76
+ }
77
+ }
78
+ exports.ApiComponent = ApiComponent;
@@ -0,0 +1,24 @@
1
+ import * as pulumi from "@pulumi/pulumi";
2
+ export declare class AppComponent extends pulumi.ComponentResource {
3
+ readonly requiredDnsRecords: pulumi.Output<DnsRecordInstruction[]>;
4
+ private readonly amplifyApp;
5
+ private readonly amplifyBranch;
6
+ private readonly domainAssociation;
7
+ private readonly validationRecord?;
8
+ private readonly subDomainRecords?;
9
+ constructor(name: string, args: AppComponentArgs, opts?: pulumi.ComponentResourceOptions);
10
+ }
11
+ export interface AppComponentArgs {
12
+ domain: string;
13
+ repoUrl: string;
14
+ subDomains?: string;
15
+ buildSpec?: string;
16
+ roleArn?: pulumi.Input<string>;
17
+ manageDns?: boolean;
18
+ }
19
+ export interface DnsRecordInstruction {
20
+ name: string;
21
+ type: string;
22
+ value: string;
23
+ purpose: string;
24
+ }
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AppComponent = void 0;
4
+ const pulumi = require("@pulumi/pulumi");
5
+ const aws = require("@pulumi/aws");
6
+ const cloudflare = require("@pulumi/cloudflare");
7
+ const pattformHelper_1 = require("./pattformHelper");
8
+ class AppComponent extends pulumi.ComponentResource {
9
+ constructor(name, args, opts) {
10
+ var _a, _b;
11
+ super("custom:pattform:AppComponent", name, args, opts);
12
+ const awsConfig = new pulumi.Config("aws");
13
+ const awsRegion = awsConfig.require("region");
14
+ const awsAccessKey = awsConfig.getSecret("accessKey");
15
+ const awsSecretKey = awsConfig.getSecret("secretKey");
16
+ const githubConfig = new pulumi.Config("github");
17
+ const githubToken = githubConfig.requireSecret("apiToken");
18
+ const cloudFlareConfig = new pulumi.Config("cloudflare");
19
+ const cloudFrontToken = cloudFlareConfig.getSecret("apiToken");
20
+ const appName = pulumi.getProject();
21
+ const env = pulumi.getStack();
22
+ // DNS is managed in Cloudflare unless the client owns their domain
23
+ // elsewhere; then the required records are surfaced via
24
+ // requiredDnsRecords for the client to create themselves.
25
+ const manageDns = (_a = args.manageDns) !== null && _a !== void 0 ? _a : true;
26
+ if (manageDns && !cloudFrontToken) {
27
+ throw new Error(`${appName}: cloudflare:apiToken config is required when DNS is managed by Pattform. ` +
28
+ `If the client owns their domain outside Cloudflare, set manageDns: false and ` +
29
+ `send them the records from the requiredDnsRecords output.`);
30
+ }
31
+ // Credential precedence: assume-role into the client account (preferred),
32
+ // then static keys (legacy shared-account stacks), then ambient
33
+ // credentials (e.g. an ESC aws-login environment).
34
+ const roleArn = (_b = args.roleArn) !== null && _b !== void 0 ? _b : awsConfig.get("roleArn");
35
+ // Static keys and assumeRole are complementary, not exclusive: the
36
+ // keys (or ambient credentials) are the identity that performs the
37
+ // sts:AssumeRole call into the client account.
38
+ const awsProvider = new aws.Provider(`pattform-app-aws-${appName}-${env}`, Object.assign(Object.assign({ region: (0, pattformHelper_1.verifyRegion)(awsRegion) }, (awsAccessKey && awsSecretKey ? {
39
+ accessKey: awsAccessKey,
40
+ secretKey: awsSecretKey,
41
+ } : {})), (roleArn ? {
42
+ assumeRole: {
43
+ roleArn: roleArn,
44
+ sessionName: `pattform-app-${appName}-${env}`,
45
+ },
46
+ } : {})));
47
+ function getSubDomains() {
48
+ if (args.subDomains && args.subDomains !== "") {
49
+ return args.subDomains.split(",").map((subDomain) => {
50
+ if (subDomain === "@") {
51
+ console.log("Branch name: main, prefix: @");
52
+ return {
53
+ branchName: "main",
54
+ prefix: "",
55
+ };
56
+ }
57
+ else {
58
+ console.log(`Branch name: main, prefix: ${subDomain}`);
59
+ return {
60
+ branchName: "main",
61
+ prefix: subDomain,
62
+ };
63
+ }
64
+ });
65
+ }
66
+ else {
67
+ return [
68
+ {
69
+ branchName: "main",
70
+ prefix: "www",
71
+ },
72
+ {
73
+ branchName: "main",
74
+ prefix: "",
75
+ }
76
+ ];
77
+ }
78
+ }
79
+ const subDomains = getSubDomains();
80
+ const isWWW = subDomains.find((subDomain) => subDomain.prefix === "www");
81
+ this.amplifyApp = new aws.amplify.App(`${appName}-amplifyApp-${env}`, Object.assign(Object.assign({ name: appName, repository: args.repoUrl, accessToken: githubToken, autoBranchCreationConfig: {
82
+ enableAutoBuild: true,
83
+ enableBasicAuth: false,
84
+ enablePerformanceMode: false,
85
+ enablePullRequestPreview: false,
86
+ }, autoBranchCreationPatterns: [
87
+ "main",
88
+ "feature/*",
89
+ "bugfix/*",
90
+ "hotfix/*",
91
+ ], enableBranchAutoDeletion: true, enableBranchAutoBuild: true, enableAutoBranchCreation: true }, isWWW && {
92
+ customRules: [
93
+ {
94
+ source: "https://" + args.domain,
95
+ target: "https://www." + args.domain,
96
+ status: "302",
97
+ }
98
+ ]
99
+ }), { buildSpec: args.buildSpec || `
100
+ version: 1.0
101
+ frontend:
102
+ phases:
103
+ preBuild:
104
+ commands:
105
+ - npm install
106
+ build:
107
+ commands:
108
+ - npm run build
109
+ artifacts:
110
+ baseDirectory: dist
111
+ files:
112
+ - '**/*'
113
+ cache:
114
+ paths:
115
+ - node_modules/**/*
116
+ ` }), {
117
+ provider: awsProvider,
118
+ });
119
+ this.amplifyBranch = new aws.amplify.Branch(`${appName}-amplifyBranch-${env}`, {
120
+ appId: this.amplifyApp.id.apply(id => id),
121
+ branchName: "main",
122
+ enableAutoBuild: true,
123
+ enablePerformanceMode: false,
124
+ enablePullRequestPreview: false,
125
+ enableNotification: false,
126
+ }, {
127
+ dependsOn: [this.amplifyApp],
128
+ provider: awsProvider,
129
+ });
130
+ this.domainAssociation = new aws.amplify.DomainAssociation(`${appName}-amplifyDomainAssociation-${env}`, {
131
+ appId: this.amplifyApp.id.apply(id => id),
132
+ domainName: args.domain,
133
+ waitForVerification: false,
134
+ subDomains: subDomains,
135
+ }, {
136
+ dependsOn: [this.amplifyApp],
137
+ provider: awsProvider,
138
+ });
139
+ if (manageDns) {
140
+ const cloudFlareProvider = new cloudflare.Provider(`pattform-app-cloudflare-${appName}-${env}`, {
141
+ apiToken: cloudFrontToken,
142
+ });
143
+ const cloudflareZone = cloudflare.getZoneOutput({
144
+ name: args.domain
145
+ }, {
146
+ provider: cloudFlareProvider,
147
+ });
148
+ this.validationRecord = new cloudflare.Record(`${appName}-cloudflareValidateRecord-${env}`, {
149
+ zoneId: cloudflareZone.id,
150
+ name: this.domainAssociation.certificateVerificationDnsRecord.apply(record => record.split(' ')[0]),
151
+ type: "CNAME",
152
+ proxied: false,
153
+ content: this.domainAssociation.certificateVerificationDnsRecord.apply(record => record.split(' ')[2]),
154
+ }, {
155
+ provider: cloudFlareProvider,
156
+ });
157
+ this.subDomainRecords = this.domainAssociation.subDomains.apply(subDomains => {
158
+ return subDomains.map((subDomain) => {
159
+ const subDomainName = subDomain.dnsRecord.split(' ')[0];
160
+ return new cloudflare.Record(`${appName}-cloudflareSubDomainRecord-${env}-${subDomainName}`, {
161
+ zoneId: cloudflareZone.id,
162
+ name: subDomainName === "" ? "@" : subDomainName,
163
+ type: "CNAME",
164
+ proxied: false,
165
+ content: subDomain.dnsRecord.split(' ')[2],
166
+ }, {
167
+ provider: cloudFlareProvider,
168
+ });
169
+ });
170
+ });
171
+ }
172
+ // Every record Amplify needs at the domain's DNS host, whether or not
173
+ // Cloudflare manages them. With manageDns: false, send these to the
174
+ // client so they can create them wherever the domain lives.
175
+ this.requiredDnsRecords = pulumi.all([
176
+ this.domainAssociation.certificateVerificationDnsRecord,
177
+ this.domainAssociation.subDomains,
178
+ ]).apply(([certRecord, associatedSubDomains]) => {
179
+ const parse = (record, purpose) => {
180
+ const [recordName, type, value] = record.split(' ');
181
+ return {
182
+ name: recordName === "" ? "@" : recordName,
183
+ type: type,
184
+ value: value,
185
+ purpose: purpose,
186
+ };
187
+ };
188
+ return [
189
+ parse(certRecord, "SSL certificate validation"),
190
+ ...associatedSubDomains.map(subDomain => parse(subDomain.dnsRecord, "points the (sub)domain at Amplify")),
191
+ ];
192
+ });
193
+ this.registerOutputs({
194
+ amplifyDomain: pulumi.interpolate `https://${this.amplifyApp.defaultDomain}`,
195
+ appDomain: pulumi.interpolate `https://${args.domain}`,
196
+ requiredDnsRecords: this.requiredDnsRecords,
197
+ });
198
+ }
199
+ }
200
+ exports.AppComponent = AppComponent;
@@ -0,0 +1,16 @@
1
+ import * as pulumi from "@pulumi/pulumi";
2
+ export declare class ClientAccountComponent extends pulumi.ComponentResource {
3
+ readonly accountId: pulumi.Output<string>;
4
+ readonly deployRoleArn: pulumi.Output<string>;
5
+ private readonly account;
6
+ private readonly budget;
7
+ constructor(name: string, args: ClientAccountComponentArgs, opts?: pulumi.ComponentResourceOptions);
8
+ }
9
+ export interface ClientAccountComponentArgs {
10
+ email: pulumi.Input<string>;
11
+ parentId: pulumi.Input<string>;
12
+ accountName?: string;
13
+ region?: string;
14
+ budgetLimitUsd?: number;
15
+ budgetAlertEmails?: string[];
16
+ }
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ClientAccountComponent = void 0;
4
+ const pulumi = require("@pulumi/pulumi");
5
+ const aws = require("@pulumi/aws");
6
+ const pattformHelper_1 = require("./pattformHelper");
7
+ class ClientAccountComponent extends pulumi.ComponentResource {
8
+ constructor(name, args, opts) {
9
+ var _a, _b, _c, _d;
10
+ super("custom:pattform:ClientAccountComponent", name, args, opts);
11
+ const awsConfig = new pulumi.Config("aws");
12
+ const awsRegion = (_a = args.region) !== null && _a !== void 0 ? _a : awsConfig.require("region");
13
+ const awsAccessKey = awsConfig.getSecret("accessKey");
14
+ const awsSecretKey = awsConfig.getSecret("secretKey");
15
+ // Member accounts are deliberately hard to destroy: AWS suspends closed
16
+ // accounts for 90 days and limits closures to 10% of the org per month.
17
+ this.account = new aws.organizations.Account(`${name}-account`, {
18
+ name: (_b = args.accountName) !== null && _b !== void 0 ? _b : name,
19
+ email: args.email,
20
+ parentId: args.parentId,
21
+ roleName: "OrganizationAccountAccessRole",
22
+ iamUserAccessToBilling: "ALLOW",
23
+ closeOnDeletion: false,
24
+ }, {
25
+ parent: this,
26
+ protect: true,
27
+ });
28
+ this.accountId = this.account.id;
29
+ this.deployRoleArn = pulumi.interpolate `arn:aws:iam::${this.account.id}:role/OrganizationAccountAccessRole`;
30
+ // Explicit providers do not inherit aws:accessKey/aws:secretKey from
31
+ // stack config, so the management-account credentials must be passed
32
+ // through for the assume-role call; otherwise it falls back to ambient
33
+ // credentials (e.g. the Pulumi Deployments runner), which the member
34
+ // account's role does not trust.
35
+ const memberProvider = new aws.Provider(`pattform-client-aws-${name}`, Object.assign(Object.assign({ region: (0, pattformHelper_1.verifyRegion)(awsRegion) }, (awsAccessKey && awsSecretKey ? {
36
+ accessKey: awsAccessKey,
37
+ secretKey: awsSecretKey,
38
+ } : {})), { assumeRole: {
39
+ roleArn: this.deployRoleArn,
40
+ sessionName: `pattform-vend-${name}`,
41
+ } }), {
42
+ parent: this,
43
+ });
44
+ const budgetLimitUsd = (_c = args.budgetLimitUsd) !== null && _c !== void 0 ? _c : 10;
45
+ const budgetAlertEmails = (_d = args.budgetAlertEmails) !== null && _d !== void 0 ? _d : ["contact@pattform.io"];
46
+ this.budget = new aws.budgets.Budget(`${name}-budget`, {
47
+ budgetType: "COST",
48
+ limitAmount: budgetLimitUsd.toFixed(2),
49
+ limitUnit: "USD",
50
+ timeUnit: "MONTHLY",
51
+ notifications: [
52
+ {
53
+ comparisonOperator: "GREATER_THAN",
54
+ threshold: 80,
55
+ thresholdType: "PERCENTAGE",
56
+ notificationType: "ACTUAL",
57
+ subscriberEmailAddresses: budgetAlertEmails,
58
+ },
59
+ {
60
+ comparisonOperator: "GREATER_THAN",
61
+ threshold: 100,
62
+ thresholdType: "PERCENTAGE",
63
+ notificationType: "FORECASTED",
64
+ subscriberEmailAddresses: budgetAlertEmails,
65
+ },
66
+ ],
67
+ }, {
68
+ parent: this,
69
+ provider: memberProvider,
70
+ });
71
+ this.registerOutputs({
72
+ accountId: this.accountId,
73
+ deployRoleArn: this.deployRoleArn,
74
+ });
75
+ }
76
+ }
77
+ exports.ClientAccountComponent = ClientAccountComponent;
@@ -0,0 +1,24 @@
1
+ import * as pulumi from "@pulumi/pulumi";
2
+ /**
3
+ * ContainerComponent
4
+ * This component deploys a pre-built container image to Cloud Run using an image digest.
5
+ */
6
+ export declare class ContainerComponent extends pulumi.ComponentResource {
7
+ private readonly repository;
8
+ private readonly service;
9
+ readonly serviceUrl: pulumi.Output<string>;
10
+ constructor(name: string, args: ContainerComponentArgs, opts?: pulumi.ComponentResourceOptions);
11
+ }
12
+ export interface ContainerComponentArgs {
13
+ environment: pulumi.Input<string>;
14
+ imageName: pulumi.Input<string>;
15
+ maxImages: pulumi.Input<number>;
16
+ memory: pulumi.Input<string>;
17
+ cpu: pulumi.Input<string>;
18
+ containerPort: pulumi.Input<number>;
19
+ envVars?: pulumi.Input<{
20
+ [key: string]: pulumi.Input<string>;
21
+ }>;
22
+ readinessPath?: pulumi.Input<string>;
23
+ livenessPath?: pulumi.Input<string>;
24
+ }
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ContainerComponent = void 0;
4
+ const pulumi = require("@pulumi/pulumi");
5
+ const gcp = require("@pulumi/gcp");
6
+ /**
7
+ * ContainerComponent
8
+ * This component deploys a pre-built container image to Cloud Run using an image digest.
9
+ */
10
+ class ContainerComponent extends pulumi.ComponentResource {
11
+ constructor(name, args, opts) {
12
+ var _a, _b;
13
+ super("custom:pattform:ContainerComponent", name, args, opts);
14
+ const gcpConfig = new pulumi.Config("gcp");
15
+ const gcpProject = gcpConfig.require("project");
16
+ const gcpRegion = gcpConfig.require("region");
17
+ const componentConfig = new pulumi.Config();
18
+ const imageRefFromConfig = componentConfig.get("imageRef");
19
+ // Create an Artifact Registry repository
20
+ this.repository = new gcp.artifactregistry.Repository("container-component-" + args.imageName + "-repo-" + args.environment, {
21
+ description: args.environment + " repository for " + args.imageName + " Docker images",
22
+ format: "DOCKER",
23
+ location: gcpRegion,
24
+ repositoryId: args.imageName + "-" + args.environment,
25
+ cleanupPolicies: [
26
+ {
27
+ id: "max_images",
28
+ action: "KEEP",
29
+ mostRecentVersions: {
30
+ keepCount: args.maxImages,
31
+ }
32
+ },
33
+ {
34
+ id: "all_artifacts",
35
+ action: "DELETE",
36
+ condition: {
37
+ olderThan: "43200s"
38
+ }
39
+ }
40
+ ]
41
+ }, {
42
+ parent: this,
43
+ });
44
+ // Form the repository URL
45
+ const repoUrl = pulumi.concat(gcpRegion, "-docker.pkg.dev/", gcpProject, "/", this.repository.repositoryId);
46
+ const imageRef = imageRefFromConfig
47
+ ? pulumi.interpolate `${repoUrl}/${args.imageName}@${imageRefFromConfig}`
48
+ : pulumi.interpolate `${repoUrl}/${args.imageName}:latest`;
49
+ // Default Spring Boot probe paths (can be overridden via args)
50
+ const defaultReadinessPath = (_a = args.readinessPath) !== null && _a !== void 0 ? _a : "/actuator/health/readiness";
51
+ const defaultLivenessPath = (_b = args.livenessPath) !== null && _b !== void 0 ? _b : "/actuator/health/liveness";
52
+ // Create a Cloud Run service for the container image.
53
+ this.service = new gcp.cloudrunv2.Service("container-component-" + args.imageName + "-service-" + args.environment, {
54
+ location: gcpRegion,
55
+ ingress: "INGRESS_TRAFFIC_ALL",
56
+ name: args.imageName + "-" + args.environment,
57
+ invokerIamDisabled: true,
58
+ template: {
59
+ maxInstanceRequestConcurrency: 30,
60
+ scaling: {
61
+ maxInstanceCount: 2
62
+ },
63
+ containers: [
64
+ {
65
+ image: imageRef,
66
+ resources: {
67
+ limits: {
68
+ memory: args.memory,
69
+ cpu: args.cpu.toString(),
70
+ },
71
+ },
72
+ envs: [
73
+ ...(args.envVars ? Object.entries(args.envVars).map(([key, value]) => ({
74
+ name: key,
75
+ value: value,
76
+ })) : []),
77
+ ],
78
+ ports: {
79
+ containerPort: args.containerPort,
80
+ },
81
+ livenessProbe: {
82
+ httpGet: {
83
+ path: defaultLivenessPath,
84
+ port: 8081,
85
+ },
86
+ initialDelaySeconds: 30,
87
+ periodSeconds: 20,
88
+ timeoutSeconds: 5,
89
+ failureThreshold: 3,
90
+ },
91
+ startupProbe: {
92
+ httpGet: {
93
+ path: defaultReadinessPath,
94
+ port: 8081,
95
+ },
96
+ initialDelaySeconds: 2,
97
+ periodSeconds: 5,
98
+ timeoutSeconds: 1,
99
+ failureThreshold: 3,
100
+ }
101
+ }
102
+ ],
103
+ },
104
+ }, {
105
+ dependsOn: [this.repository],
106
+ parent: this,
107
+ });
108
+ this.serviceUrl = this.service.uri;
109
+ // We also need to register all the expected outputs for this
110
+ // component resource that will get returned by default.
111
+ this.registerOutputs({
112
+ serviceUrl: this.serviceUrl,
113
+ });
114
+ }
115
+ }
116
+ exports.ContainerComponent = ContainerComponent;
@@ -0,0 +1,4 @@
1
+ export { ContainerComponent, ContainerComponentArgs } from "./ContainerComponent";
2
+ export { ApiComponent, ApiComponentArgs } from "./ApiComponent";
3
+ export { AppComponent, AppComponentArgs, DnsRecordInstruction } from "./AppComponent";
4
+ export { ClientAccountComponent, ClientAccountComponentArgs } from "./ClientAccountComponent";
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ClientAccountComponent = exports.AppComponent = exports.ApiComponent = exports.ContainerComponent = void 0;
4
+ var ContainerComponent_1 = require("./ContainerComponent");
5
+ Object.defineProperty(exports, "ContainerComponent", { enumerable: true, get: function () { return ContainerComponent_1.ContainerComponent; } });
6
+ var ApiComponent_1 = require("./ApiComponent");
7
+ Object.defineProperty(exports, "ApiComponent", { enumerable: true, get: function () { return ApiComponent_1.ApiComponent; } });
8
+ var AppComponent_1 = require("./AppComponent");
9
+ Object.defineProperty(exports, "AppComponent", { enumerable: true, get: function () { return AppComponent_1.AppComponent; } });
10
+ var ClientAccountComponent_1 = require("./ClientAccountComponent");
11
+ Object.defineProperty(exports, "ClientAccountComponent", { enumerable: true, get: function () { return ClientAccountComponent_1.ClientAccountComponent; } });
@@ -0,0 +1 @@
1
+ export declare function verifyRegion(awsRegion: string): any;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.verifyRegion = void 0;
4
+ const aws = require("@pulumi/aws");
5
+ function verifyRegion(awsRegion) {
6
+ for (const [key, value] of Object.entries(aws.Region)) {
7
+ if (value == awsRegion) {
8
+ return aws.Region[key];
9
+ }
10
+ }
11
+ throw new Error(`Region ${awsRegion} not found`);
12
+ }
13
+ exports.verifyRegion = verifyRegion;
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@pattform/api-kit",
3
+ "version": "2.1.1",
4
+ "description": "Pulumi infra library for building and deploying an API",
5
+ "author": "Pattform <contact@pattform.io>",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "publishConfig": {
8
+ "registry": "https://registry.npmjs.org",
9
+ "access": "public"
10
+ },
11
+ "main": "dist/index.js",
12
+ "types": "dist/index.d.ts",
13
+ "files": ["dist", "LICENSE", "README.md", "package.json"],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/Pattform/pulumi-quickstart-library.git"
17
+ },
18
+ "scripts": {
19
+ "test": "echo \"Error: no test specified\"",
20
+ "build": "tsc",
21
+ "deploy": "npm build && npm publish"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^16"
25
+ },
26
+ "dependencies": {
27
+ "@pulumi/aws": "^6.53.0",
28
+ "@pulumi/gcp": "^8.41.1",
29
+ "@pulumi/pulumi": "^3.0.0",
30
+ "@pulumi/cloudflare": "^5.39.1",
31
+ "typescript": "^5.1.6"
32
+ }
33
+ }