@cyc-seattle/platform 0.0.0-stage → 0.2.0

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,145 @@
1
- # Temporary Holding Version
1
+ # platform
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Pulumi stacks for CYC Community Sailing Center's shared Google Cloud platform: the things no single
4
+ app owns. The apps that run on it live in their own repos, such as
5
+ [isthmia](https://github.com/cyc-seattle/isthmia).
6
+
7
+ ## Stacks
8
+
9
+ | Stack | Holds | Applied by |
10
+ | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
11
+ | [`bootstrap`](stacks/bootstrap) | Service accounts and project IAM, the Pulumi state buckets and KMS keys, and the org's GitHub repos and settings | A human with project Owner and `gh` `admin:org`. Never CI. |
12
+ | [`cloud`](stacks/cloud) | The VPC, the cluster subnet and its Cloud NAT on a static address, the private services peering, the prod and dev Cloud SQL instances, the DNS zones, and Artifact Registry | `deploy-runner`, from Actions after approval. A deployer, with `mise run deploy`, when breaking glass. |
13
+ | [`cluster`](stacks/cluster) | The GKE Autopilot cluster, the shared Gateway, its address, certificates, and dev's DNS records, the `dev` and `prod` namespaces with their quotas and network policies, dev's RBAC, the prod Job alerts, and each environment's `platform/outputs.json` | `deploy-runner`, from Actions after approval. A deployer, with `mise run deploy`, when breaking glass. |
14
+ | [`smoke`](stacks/smoke) | One `WebService` in dev, at `smoke.dev.cycsail.team`, for the integration tests | `deploy-dev`, from Actions on every PR. A deployer, with `PULUMI_STACK=dev mise run deploy`, when breaking glass. |
15
+
16
+ ## @cyc-seattle/platform
17
+
18
+ `src/` is the `@cyc-seattle/platform` package, which the stacks here and the apps' stacks import:
19
+
20
+ - `getPlatformOutputs()` reads an environment's `platform/outputs.json` from its state bucket. The
21
+ `cluster` stack writes it. It holds the environment's namespace and domain, the Gateway and its
22
+ address (`gatewayAddress`, for an app's own DNS records), and the Cloud SQL instance's connection
23
+ name and private IP (`sqlHost`). Dev stacks can't read prod's backend, so this replaces a
24
+ StackReference for platform values (cyc-seattle/isthmia#215).
25
+ - `clusterProvider(platform)` builds a Kubernetes provider for the cluster. Its kubeconfig runs
26
+ `gke-gcloud-auth-plugin` with Application Default Credentials, so Pulumi must run under mise,
27
+ where `mise run install` puts the plugin on `PATH`.
28
+ - `Workload` runs a long-lived process with no route: a Deployment, a ServiceAccount, and, when it
29
+ has `ports`, a ClusterIP Service that other pods in the namespace reach at `host`.
30
+ - `WebService` is a `Workload` behind the environment's Gateway at `hostname`. Its Service exposes
31
+ `port` as port 80, and its readiness probe must be an HTTP GET, which the load balancer's health
32
+ check reuses.
33
+ - `ScheduledJob` runs a CronJob on `schedule`, in `America/Los_Angeles` unless `timeZone` says
34
+ otherwise. A run never overlaps the one before it, gets an hour, and doesn't retry, by default.
35
+ - All three run non-root with a read-only root filesystem, no capabilities, and no service account
36
+ token, on Spot pods in dev only. Their limits equal their requests. Their pods get no IAM; grant
37
+ roles to `member`, a Workload Identity principal, or set `serviceAccountAnnotations` to run as a
38
+ Google service account.
39
+ - `enableService` enables a Google Cloud API.
40
+
41
+ `mise run build` builds it into `dist/`, which is all it publishes. `.github/workflows/release.yml`
42
+ releases each merge to `main` with semantic-release, versioned by the conventional commits.
43
+
44
+ ## Environments
45
+
46
+ | Stack | Namespace | Domain | Deploy identity |
47
+ | ------ | --------- | ------------------ | --------------- |
48
+ | `dev` | `dev` | `dev.cycsail.team` | `deploy-dev` |
49
+ | `prod` | `prod` | `cycsail.team` | `deploy-runner` |
50
+
51
+ Each namespace denies ingress from other namespaces except the load balancer's. Dev also admits the
52
+ Kubernetes API's service proxy, which the integration tests use, and denies egress to the mail ports
53
+ (25, 465, 587) outside the cluster. `cluster` writes dev's A records; each prod app writes its own,
54
+ pointing at `gatewayAddress`.
55
+
56
+ `deploy-dev` may administer the `cyc-dev` Cloud SQL instance and read Secret Manager secrets whose IDs
57
+ start with `dev-`. Read them with `gcp.secretmanager.getSecretVersionAccess`, which needs only the
58
+ accessor role.
59
+
60
+ A Job that fails in `prod`, or a CronJob there with no successful Job in 3 hours, emails each address
61
+ in `cluster:alertEmails`.
62
+
63
+ ## Setup
64
+
65
+ [mise](https://mise.jdx.dev/) provides the tools.
66
+
67
+ ```sh
68
+ mise trust
69
+ mise run install
70
+ mise run auth-adc
71
+ ```
72
+
73
+ `mise run auth-adc` logs Application Default Credentials in as your own account. Pulumi uses them
74
+ for GCP and for the state bucket. [docs/manual-setup.md](docs/manual-setup.md) lists the access a
75
+ deployer needs first.
76
+
77
+ ## Deploy
78
+
79
+ ### From Actions
80
+
81
+ `.github/workflows/pull-request.yml` deploys through the org's reusable `deploy.yml`, which
82
+ authenticates with Workload Identity Federation and stores no credentials. Each job runs in a
83
+ GitHub environment that holds its identity and state bucket:
84
+
85
+ | Event | Jobs, in order |
86
+ | -------------- | ----------------------------------------------------------------------------------------- |
87
+ | Pull request | `ci`, then `dev`: `mise run deploy` as `deploy-dev`, then `mise run integration` |
88
+ | Push to `main` | `ci`, `dev`, then `prod-preview`, then `prod`, which waits for the `maintainers` approval |
89
+
90
+ `prod-preview` runs `mise run preview` as `deploy-runner` and writes the diff to the job summary.
91
+ `prod` runs `mise run deploy` on the same commit once approved. A PR from a fork gets no OIDC token,
92
+ so its `dev` job is skipped.
93
+
94
+ `PULUMI_STACK` picks what the tasks run (`scripts/each-stack`): `dev` is `smoke`, and `prod` is
95
+ `cloud`, then `cluster`. `integration` is dev only.
96
+
97
+ `bootstrap` is never deployed from Actions (cyc-seattle/isthmia#118). It holds the identities that
98
+ CI assumes, and a human with project Owner and `gh` `admin:org` applies it with the tasks below.
99
+
100
+ ### From a laptop
101
+
102
+ Local deploys stay as the break-glass path. A deployer applies with the same tasks:
103
+
104
+ ```sh
105
+ mise run preview-bootstrap
106
+ mise run deploy-bootstrap
107
+ mise run preview
108
+ mise run deploy
109
+ PULUMI_STACK=dev mise run deploy
110
+ ```
111
+
112
+ `mise run deploy` applies `cloud`, then `cluster`. Prod stacks read `cloud`'s outputs through a
113
+ StackReference. Dev stacks can't read prod state, so `cluster` writes each environment's platform
114
+ values to `platform/outputs.json` in that environment's state bucket.
115
+
116
+ `bootstrap`'s GitHub provider uses `gh auth token`, so log `gh` in as a cyc-seattle org owner with
117
+ the `admin:org` scope: `gh auth refresh -h github.com -s admin:org`. Deploys refresh first, so they
118
+ delete a label added by hand.
119
+
120
+ ## State
121
+
122
+ Each environment's state lives in its own bucket, `gs://cyc-admin-scripts-pulumi-<stack>`, with its
123
+ secrets encrypted by the `state-<stack>` KMS key. `stacks/bootstrap/state.ts` creates both.
124
+ `mise.toml` picks the bucket from `PULUMI_STACK`, which defaults to `prod`, so stack names are
125
+ `organization/<project>/<stack>`. It sets `GOOGLE_APPLICATION_CREDENTIALS` to the shared `.gcloud/`
126
+ login only when it isn't already set, so Actions' credentials win.
127
+
128
+ `bootstrap`'s own state lives in the bucket it creates. Both the bucket and the key are protected.
129
+
130
+ ## Development
131
+
132
+ ```sh
133
+ mise run ci
134
+ ```
135
+
136
+ Runs the type check, Prettier, ESLint, and the unit tests. Tests mock Pulumi with
137
+ `pulumi.runtime.setMocks` and never call a live API.
138
+
139
+ ```sh
140
+ mise run integration
141
+ ```
142
+
143
+ Runs the Gherkin scenarios in `features/` against dev, after `PULUMI_STACK=dev mise run deploy`. They run as
144
+ whatever identity Application Default Credentials hold. The isolation scenarios expect `deploy-dev`,
145
+ so as a human, log Application Default Credentials in with `--impersonate-service-account` first.
@@ -0,0 +1,6 @@
1
+ export { clusterProvider, type ClusterProviderArgs } from "./kubernetes";
2
+ export { getPlatformOutputs, parsePlatformOutputs, platformOutputsSchema, readPlatformOutputs, stateBucket, type PlatformOutputs, type PlatformOutputsArgs, } from "./outputs";
3
+ export { ScheduledJob, type ScheduledJobArgs } from "./scheduled-job";
4
+ export { enableService } from "./services";
5
+ export { WebService, type WebServiceArgs } from "./web-service";
6
+ export { Workload, type PodArgs, type WorkloadArgs, type WorkloadVolume } from "./workload";
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Workload = exports.WebService = exports.enableService = exports.ScheduledJob = exports.stateBucket = exports.readPlatformOutputs = exports.platformOutputsSchema = exports.parsePlatformOutputs = exports.getPlatformOutputs = exports.clusterProvider = void 0;
4
+ var kubernetes_1 = require("./kubernetes");
5
+ Object.defineProperty(exports, "clusterProvider", { enumerable: true, get: function () { return kubernetes_1.clusterProvider; } });
6
+ var outputs_1 = require("./outputs");
7
+ Object.defineProperty(exports, "getPlatformOutputs", { enumerable: true, get: function () { return outputs_1.getPlatformOutputs; } });
8
+ Object.defineProperty(exports, "parsePlatformOutputs", { enumerable: true, get: function () { return outputs_1.parsePlatformOutputs; } });
9
+ Object.defineProperty(exports, "platformOutputsSchema", { enumerable: true, get: function () { return outputs_1.platformOutputsSchema; } });
10
+ Object.defineProperty(exports, "readPlatformOutputs", { enumerable: true, get: function () { return outputs_1.readPlatformOutputs; } });
11
+ Object.defineProperty(exports, "stateBucket", { enumerable: true, get: function () { return outputs_1.stateBucket; } });
12
+ var scheduled_job_1 = require("./scheduled-job");
13
+ Object.defineProperty(exports, "ScheduledJob", { enumerable: true, get: function () { return scheduled_job_1.ScheduledJob; } });
14
+ var services_1 = require("./services");
15
+ Object.defineProperty(exports, "enableService", { enumerable: true, get: function () { return services_1.enableService; } });
16
+ var web_service_1 = require("./web-service");
17
+ Object.defineProperty(exports, "WebService", { enumerable: true, get: function () { return web_service_1.WebService; } });
18
+ var workload_1 = require("./workload");
19
+ Object.defineProperty(exports, "Workload", { enumerable: true, get: function () { return workload_1.Workload; } });
@@ -0,0 +1,19 @@
1
+ import * as k8s from "@pulumi/kubernetes";
2
+ import * as pulumi from "@pulumi/pulumi";
3
+ import type { PlatformOutputs } from "./outputs";
4
+ export interface ClusterProviderArgs {
5
+ /**
6
+ * Keeps a kubeconfig that is unknown or changes, such as during a cluster update, from replacing
7
+ * the provider and with it every Kubernetes resource it manages.
8
+ */
9
+ clusterIdentifier?: pulumi.Input<string>;
10
+ }
11
+ /**
12
+ * A Kubernetes provider for the environment's cluster. Its kubeconfig runs gke-gcloud-auth-plugin
13
+ * with Application Default Credentials, so it is the same on every run, unlike one that embeds an
14
+ * access token. The plugin must be on PATH: `mise run install` adds it. The cluster stack passes
15
+ * only the endpoint, because it writes the rest.
16
+ */
17
+ export declare function clusterProvider(platform: pulumi.Input<{
18
+ clusterEndpoint: pulumi.Input<PlatformOutputs["clusterEndpoint"]>;
19
+ }>, name?: string, opts?: pulumi.CustomResourceOptions, args?: ClusterProviderArgs): k8s.Provider;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.clusterProvider = clusterProvider;
37
+ const k8s = __importStar(require("@pulumi/kubernetes"));
38
+ const pulumi = __importStar(require("@pulumi/pulumi"));
39
+ /**
40
+ * A Kubernetes provider for the environment's cluster. Its kubeconfig runs gke-gcloud-auth-plugin
41
+ * with Application Default Credentials, so it is the same on every run, unlike one that embeds an
42
+ * access token. The plugin must be on PATH: `mise run install` adds it. The cluster stack passes
43
+ * only the endpoint, because it writes the rest.
44
+ */
45
+ function clusterProvider(platform, name = "cluster", opts, args = {}) {
46
+ // The DNS-based endpoint serves a publicly trusted certificate, so the kubeconfig needs no CA.
47
+ const kubeconfig = pulumi.output(platform).clusterEndpoint.apply((endpoint) => JSON.stringify({
48
+ apiVersion: "v1",
49
+ kind: "Config",
50
+ clusters: [{ name: "cluster", cluster: { server: `https://${endpoint}` } }],
51
+ users: [
52
+ {
53
+ name: "user",
54
+ user: {
55
+ exec: {
56
+ apiVersion: "client.authentication.k8s.io/v1beta1",
57
+ command: "gke-gcloud-auth-plugin",
58
+ args: ["--use_application_default_credentials"],
59
+ installHint: "Run `mise run install`, and run Pulumi under mise.",
60
+ provideClusterInfo: true,
61
+ },
62
+ },
63
+ },
64
+ ],
65
+ contexts: [{ name: "cluster", context: { cluster: "cluster", user: "user" } }],
66
+ "current-context": "cluster",
67
+ }));
68
+ return new k8s.Provider(name, { kubeconfig, clusterIdentifier: args.clusterIdentifier }, opts);
69
+ }
@@ -0,0 +1,36 @@
1
+ import * as pulumi from "@pulumi/pulumi";
2
+ import { z } from "zod";
3
+ export declare const platformOutputsSchema: z.ZodObject<{
4
+ project: z.ZodString;
5
+ projectNumber: z.ZodString;
6
+ region: z.ZodString;
7
+ cluster: z.ZodString;
8
+ clusterEndpoint: z.ZodString;
9
+ namespace: z.ZodString;
10
+ gateway: z.ZodObject<{
11
+ name: z.ZodString;
12
+ namespace: z.ZodString;
13
+ }, z.core.$strip>;
14
+ domain: z.ZodString;
15
+ sqlConnectionName: z.ZodString;
16
+ sqlHost: z.ZodString;
17
+ gatewayAddress: z.ZodString;
18
+ registry: z.ZodString;
19
+ }, z.core.$strip>;
20
+ /** One environment's platform values: where its cluster, Gateway, database, and registry are. */
21
+ export type PlatformOutputs = z.infer<typeof platformOutputsSchema>;
22
+ export declare const outputsObject = "platform/outputs.json";
23
+ /** The state bucket of an environment, as `stacks/bootstrap/state.ts` names it. */
24
+ export declare function stateBucket(project: string, environment: string): string;
25
+ /** Parses and validates the outputs file's text. `source` names the file in error messages. */
26
+ export declare function parsePlatformOutputs(text: string, source: string): PlatformOutputs;
27
+ export interface PlatformOutputsArgs {
28
+ /** The environment, which names the state bucket. Defaults to the stack's name. */
29
+ environment?: string;
30
+ /** The project that holds the state bucket. Defaults to `gcp:project`. */
31
+ project?: string;
32
+ }
33
+ /** Reads this environment's platform values from its state bucket. Most programs want `getPlatformOutputs`. */
34
+ export declare function readPlatformOutputs(args?: PlatformOutputsArgs): Promise<PlatformOutputs>;
35
+ /** Reads this environment's platform values from its state bucket. */
36
+ export declare function getPlatformOutputs(args?: PlatformOutputsArgs): pulumi.Output<PlatformOutputs>;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.outputsObject = exports.platformOutputsSchema = void 0;
37
+ exports.stateBucket = stateBucket;
38
+ exports.parsePlatformOutputs = parsePlatformOutputs;
39
+ exports.readPlatformOutputs = readPlatformOutputs;
40
+ exports.getPlatformOutputs = getPlatformOutputs;
41
+ const gcp = __importStar(require("@pulumi/gcp"));
42
+ const pulumi = __importStar(require("@pulumi/pulumi"));
43
+ const zod_1 = require("zod");
44
+ // The cluster stack writes this object to each environment's state bucket, because a StackReference
45
+ // can't cross from a dev stack into prod's backend (cyc-seattle/isthmia#215).
46
+ exports.platformOutputsSchema = zod_1.z.object({
47
+ project: zod_1.z.string().min(1),
48
+ projectNumber: zod_1.z.string().regex(/^\d+$/),
49
+ region: zod_1.z.string().min(1),
50
+ cluster: zod_1.z.string().min(1),
51
+ clusterEndpoint: zod_1.z.string().min(1),
52
+ namespace: zod_1.z.string().min(1),
53
+ gateway: zod_1.z.object({ name: zod_1.z.string().min(1), namespace: zod_1.z.string().min(1) }),
54
+ domain: zod_1.z.string().min(1),
55
+ sqlConnectionName: zod_1.z.string().min(1),
56
+ /** The environment's Cloud SQL private IP, which pods reach directly. */
57
+ sqlHost: zod_1.z.string().min(1),
58
+ /** The shared Gateway's IPv4 address, for an app's own DNS records. */
59
+ gatewayAddress: zod_1.z.string().min(1),
60
+ registry: zod_1.z.string().min(1),
61
+ });
62
+ exports.outputsObject = "platform/outputs.json";
63
+ /** The state bucket of an environment, as `stacks/bootstrap/state.ts` names it. */
64
+ function stateBucket(project, environment) {
65
+ return `${project}-pulumi-${environment}`;
66
+ }
67
+ /** Parses and validates the outputs file's text. `source` names the file in error messages. */
68
+ function parsePlatformOutputs(text, source) {
69
+ let json;
70
+ try {
71
+ json = JSON.parse(text);
72
+ }
73
+ catch (e) {
74
+ throw new Error(`${source} is not valid JSON: ${e.message}`);
75
+ }
76
+ const result = exports.platformOutputsSchema.safeParse(json);
77
+ if (!result.success) {
78
+ throw new Error(`${source} doesn't hold the platform outputs:\n${zod_1.z.prettifyError(result.error)}`);
79
+ }
80
+ return result.data;
81
+ }
82
+ /** Reads this environment's platform values from its state bucket. Most programs want `getPlatformOutputs`. */
83
+ async function readPlatformOutputs(args = {}) {
84
+ const project = args.project ?? new pulumi.Config("gcp").require("project");
85
+ const bucket = stateBucket(project, args.environment ?? pulumi.getStack());
86
+ const source = `gs://${bucket}/${exports.outputsObject}`;
87
+ let content;
88
+ try {
89
+ ({ content } = await gcp.storage.getBucketObjectContent({ bucket, name: exports.outputsObject }));
90
+ }
91
+ catch (e) {
92
+ throw new Error(`Can't read ${source}. The cluster stack writes it.\n${e.message}`);
93
+ }
94
+ if (!content) {
95
+ throw new Error(`${source} is empty. The cluster stack writes it.`);
96
+ }
97
+ return parsePlatformOutputs(content, source);
98
+ }
99
+ /** Reads this environment's platform values from its state bucket. */
100
+ function getPlatformOutputs(args = {}) {
101
+ return pulumi.output(readPlatformOutputs(args));
102
+ }
@@ -0,0 +1,22 @@
1
+ import * as pulumi from "@pulumi/pulumi";
2
+ import { type PodArgs } from "./workload";
3
+ export interface ScheduledJobArgs extends PodArgs {
4
+ /** A cron schedule, such as `0 * * * *`. */
5
+ schedule: string;
6
+ /** The schedule's time zone. Defaults to `America/Los_Angeles`. */
7
+ timeZone?: string;
8
+ /** How long one run may take, in seconds. Defaults to 3600. */
9
+ activeDeadlineSeconds?: number;
10
+ /** How many times a failed run retries. Defaults to 0, so the next scheduled run is the retry. */
11
+ backoffLimit?: number;
12
+ }
13
+ /**
14
+ * A CronJob with the platform's secure defaults, and a Kubernetes ServiceAccount, both named `name`.
15
+ * A run never overlaps the one before it. Its pods get no IAM; grant roles to `member`.
16
+ */
17
+ export declare class ScheduledJob extends pulumi.ComponentResource {
18
+ /** The pods' Workload Identity principal, for IAM grants. */
19
+ readonly member: pulumi.Output<string>;
20
+ readonly serviceAccountName: pulumi.Output<string>;
21
+ constructor(name: string, args: ScheduledJobArgs, opts?: pulumi.ComponentResourceOptions);
22
+ }
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ScheduledJob = void 0;
37
+ const k8s = __importStar(require("@pulumi/kubernetes"));
38
+ const pulumi = __importStar(require("@pulumi/pulumi"));
39
+ const workload_1 = require("./workload");
40
+ /**
41
+ * A CronJob with the platform's secure defaults, and a Kubernetes ServiceAccount, both named `name`.
42
+ * A run never overlaps the one before it. Its pods get no IAM; grant roles to `member`.
43
+ */
44
+ class ScheduledJob extends pulumi.ComponentResource {
45
+ /** The pods' Workload Identity principal, for IAM grants. */
46
+ member;
47
+ serviceAccountName;
48
+ constructor(name, args, opts) {
49
+ super("cyc-seattle:platform:ScheduledJob", name, {}, opts);
50
+ (0, workload_1.checkRequests)("ScheduledJob", name, args.requests);
51
+ const platform = pulumi.output(args.platform);
52
+ const labels = { "app.kubernetes.io/name": name };
53
+ const child = { parent: this, provider: args.provider };
54
+ const account = (0, workload_1.serviceAccount)(name, args, child);
55
+ new k8s.batch.v1.CronJob(name, {
56
+ metadata: { name, namespace: platform.namespace, labels },
57
+ spec: {
58
+ schedule: args.schedule,
59
+ timeZone: args.timeZone ?? "America/Los_Angeles",
60
+ concurrencyPolicy: "Forbid",
61
+ jobTemplate: {
62
+ metadata: { labels },
63
+ spec: {
64
+ activeDeadlineSeconds: args.activeDeadlineSeconds ?? 3600,
65
+ backoffLimit: args.backoffLimit ?? 0,
66
+ template: {
67
+ metadata: { labels },
68
+ spec: (0, workload_1.podSpec)(name, args, account.metadata.name).apply((spec) => ({
69
+ ...spec,
70
+ restartPolicy: "Never",
71
+ })),
72
+ },
73
+ },
74
+ },
75
+ },
76
+ }, child);
77
+ this.serviceAccountName = account.metadata.name;
78
+ this.member = (0, workload_1.workloadMember)(platform, this.serviceAccountName);
79
+ this.registerOutputs({ member: this.member, serviceAccountName: this.serviceAccountName });
80
+ }
81
+ }
82
+ exports.ScheduledJob = ScheduledJob;
@@ -0,0 +1,8 @@
1
+ import * as gcp from "@pulumi/gcp";
2
+ /**
3
+ * Enables a Google Cloud API, memoized so repeated calls for the same API return the same resource.
4
+ * Returns the {@link gcp.projects.Service} so the resources that need the API can `dependsOn` it and
5
+ * therefore be created only after it is enabled. Enable each API from the file that uses it, rather
6
+ * than maintaining a central list.
7
+ */
8
+ export declare function enableService(service: string): gcp.projects.Service;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.enableService = enableService;
37
+ const gcp = __importStar(require("@pulumi/gcp"));
38
+ const enabled = new Map();
39
+ /**
40
+ * Enables a Google Cloud API, memoized so repeated calls for the same API return the same resource.
41
+ * Returns the {@link gcp.projects.Service} so the resources that need the API can `dependsOn` it and
42
+ * therefore be created only after it is enabled. Enable each API from the file that uses it, rather
43
+ * than maintaining a central list.
44
+ */
45
+ function enableService(service) {
46
+ const existing = enabled.get(service);
47
+ if (existing) {
48
+ return existing;
49
+ }
50
+ const svc = new gcp.projects.Service(`enable-${service}`, {
51
+ service,
52
+ // Leave the API enabled if the resource is torn down — other things may rely on it.
53
+ disableOnDestroy: false,
54
+ });
55
+ enabled.set(service, svc);
56
+ return svc;
57
+ }
@@ -0,0 +1,31 @@
1
+ import * as k8s from "@pulumi/kubernetes";
2
+ import * as pulumi from "@pulumi/pulumi";
3
+ import { type WorkloadArgs } from "./workload";
4
+ type Probe = k8s.types.input.core.v1.Probe;
5
+ export interface WebServiceArgs extends WorkloadArgs {
6
+ /** The public hostname. It must be in the environment's domain. */
7
+ hostname: string;
8
+ /** The port the container serves HTTP on. The Service exposes it as port 80, named `http`. */
9
+ port: number;
10
+ /** An HTTP GET probe. The load balancer's health check uses the same path. */
11
+ readinessProbe: Probe & {
12
+ httpGet: pulumi.Input<k8s.types.input.core.v1.HTTPGetAction>;
13
+ };
14
+ }
15
+ /** Returns `hostname` if it is the environment's domain or a name under it, and throws otherwise. */
16
+ export declare function checkHostname(hostname: string, domain: string): string;
17
+ /**
18
+ * An HTTP service behind the environment's shared Gateway: a `Workload`'s Deployment, Service, and
19
+ * Kubernetes ServiceAccount, plus an HTTPRoute and a HealthCheckPolicy. Its pods get no IAM; grant
20
+ * roles to `member`.
21
+ */
22
+ export declare class WebService extends pulumi.ComponentResource {
23
+ /** The pods' Workload Identity principal, for IAM grants. */
24
+ readonly member: pulumi.Output<string>;
25
+ readonly serviceAccountName: pulumi.Output<string>;
26
+ /** The name other pods in the namespace reach its Service by, on port 80. */
27
+ readonly host: string;
28
+ readonly url: pulumi.Output<string>;
29
+ constructor(name: string, args: WebServiceArgs, opts?: pulumi.ComponentResourceOptions);
30
+ }
31
+ export {};
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.WebService = void 0;
37
+ exports.checkHostname = checkHostname;
38
+ const k8s = __importStar(require("@pulumi/kubernetes"));
39
+ const pulumi = __importStar(require("@pulumi/pulumi"));
40
+ const workload_1 = require("./workload");
41
+ /** Returns `hostname` if it is the environment's domain or a name under it, and throws otherwise. */
42
+ function checkHostname(hostname, domain) {
43
+ const host = hostname.toLowerCase();
44
+ const base = domain.toLowerCase();
45
+ if (host !== base && !host.endsWith(`.${base}`)) {
46
+ throw new Error(`Hostname ${hostname} isn't in the environment's domain, ${domain}.`);
47
+ }
48
+ return hostname;
49
+ }
50
+ /**
51
+ * An HTTP service behind the environment's shared Gateway: a `Workload`'s Deployment, Service, and
52
+ * Kubernetes ServiceAccount, plus an HTTPRoute and a HealthCheckPolicy. Its pods get no IAM; grant
53
+ * roles to `member`.
54
+ */
55
+ class WebService extends pulumi.ComponentResource {
56
+ /** The pods' Workload Identity principal, for IAM grants. */
57
+ member;
58
+ serviceAccountName;
59
+ /** The name other pods in the namespace reach its Service by, on port 80. */
60
+ host;
61
+ url;
62
+ constructor(name, args, opts) {
63
+ super("cyc-seattle:platform:WebService", name, {}, opts);
64
+ (0, workload_1.checkRequests)("WebService", name, args.requests);
65
+ if (!args.readinessProbe?.httpGet) {
66
+ throw new Error(`WebService "${name}" needs an HTTP readiness probe.`);
67
+ }
68
+ const platform = pulumi.output(args.platform);
69
+ // A bad hostname fails the HTTPRoute's registration, so preview fails before anything applies.
70
+ const hostname = platform.domain.apply((domain) => checkHostname(args.hostname, domain));
71
+ const metadata = { name, namespace: platform.namespace, labels: { "app.kubernetes.io/name": name } };
72
+ const child = { parent: this, provider: args.provider };
73
+ const { serviceAccount, service } = (0, workload_1.deployment)(this, name, args, args.port);
74
+ new k8s.apiextensions.CustomResource(name, {
75
+ apiVersion: "gateway.networking.k8s.io/v1",
76
+ kind: "HTTPRoute",
77
+ metadata,
78
+ spec: {
79
+ parentRefs: [{ name: platform.gateway.name, namespace: platform.gateway.namespace }],
80
+ hostnames: [hostname],
81
+ rules: [{ backendRefs: [{ name: service.metadata.name, port: 80 }] }],
82
+ },
83
+ }, child);
84
+ // Without it, the load balancer checks `/` on the serving port, which an app may not answer.
85
+ new k8s.apiextensions.CustomResource(name, {
86
+ apiVersion: "networking.gke.io/v1",
87
+ kind: "HealthCheckPolicy",
88
+ metadata,
89
+ spec: {
90
+ default: {
91
+ config: {
92
+ type: "HTTP",
93
+ httpHealthCheck: {
94
+ portSpecification: "USE_SERVING_PORT",
95
+ requestPath: pulumi.output(args.readinessProbe.httpGet).apply((get) => get?.path ?? "/"),
96
+ },
97
+ },
98
+ },
99
+ targetRef: { group: "", kind: "Service", name: service.metadata.name },
100
+ },
101
+ }, child);
102
+ this.serviceAccountName = serviceAccount.metadata.name;
103
+ this.member = (0, workload_1.workloadMember)(platform, this.serviceAccountName);
104
+ this.host = name;
105
+ this.url = pulumi.interpolate `https://${hostname}/`;
106
+ this.registerOutputs({
107
+ member: this.member,
108
+ serviceAccountName: this.serviceAccountName,
109
+ host: this.host,
110
+ url: this.url,
111
+ });
112
+ }
113
+ }
114
+ exports.WebService = WebService;
@@ -0,0 +1,83 @@
1
+ import * as k8s from "@pulumi/kubernetes";
2
+ import * as pulumi from "@pulumi/pulumi";
3
+ import type { PlatformOutputs } from "./outputs";
4
+ type Probe = k8s.types.input.core.v1.Probe;
5
+ type EnvVar = k8s.types.input.core.v1.EnvVar;
6
+ type EnvFromSource = k8s.types.input.core.v1.EnvFromSource;
7
+ /** A volume and where the container mounts it. Give exactly one of `emptyDir`, `configMap`, or `secret`. */
8
+ export interface WorkloadVolume {
9
+ name: string;
10
+ mountPath: string;
11
+ emptyDir?: {
12
+ sizeLimit?: string;
13
+ };
14
+ /** A ConfigMap's name. */
15
+ configMap?: pulumi.Input<string>;
16
+ /** A Secret's name. */
17
+ secret?: pulumi.Input<string>;
18
+ subPath?: string;
19
+ readOnly?: boolean;
20
+ }
21
+ /** What every pod of `Workload`, `WebService`, and `ScheduledJob` takes. */
22
+ export interface PodArgs {
23
+ /** The environment's platform values, from `getPlatformOutputs`. */
24
+ platform: pulumi.Input<PlatformOutputs>;
25
+ /** The environment's cluster, from `clusterProvider`. Required, so it never uses a local kubeconfig. */
26
+ provider: k8s.Provider;
27
+ image: pulumi.Input<string>;
28
+ command?: string[];
29
+ args?: string[];
30
+ /** The container's requests, which are also its limits. */
31
+ requests: {
32
+ cpu: pulumi.Input<string>;
33
+ memory: pulumi.Input<string>;
34
+ };
35
+ env?: pulumi.Input<EnvVar>[];
36
+ envFrom?: pulumi.Input<EnvFromSource>[];
37
+ volumes?: WorkloadVolume[];
38
+ /** Needed when the image's user is a name, which `runAsNonRoot` can't check. Also sets the group. */
39
+ runAsUser?: number;
40
+ /** Annotations on the Kubernetes ServiceAccount, such as `iam.gke.io/gcp-service-account`. */
41
+ serviceAccountAnnotations?: Record<string, string>;
42
+ }
43
+ export interface WorkloadArgs extends PodArgs {
44
+ /** The container's ports. The Service exposes each at the same number. Without any, there's no Service. */
45
+ ports?: {
46
+ name: string;
47
+ port: number;
48
+ }[];
49
+ readinessProbe?: Probe;
50
+ livenessProbe?: Probe;
51
+ startupProbe?: Probe;
52
+ /** Defaults to 1. */
53
+ replicas?: number;
54
+ }
55
+ /** The pods' Workload Identity principal, for IAM grants. */
56
+ export declare function workloadMember(platform: pulumi.Output<PlatformOutputs>, serviceAccountName: pulumi.Input<string>): pulumi.Output<string>;
57
+ export declare function checkRequests(kind: string, name: string, requests: PodArgs["requests"] | undefined): void;
58
+ /** A ServiceAccount named `name` that mounts no token. */
59
+ export declare function serviceAccount(name: string, args: PodArgs, opts: pulumi.CustomResourceOptions): k8s.core.v1.ServiceAccount;
60
+ /** A pod spec with the platform's secure defaults: non-root, read-only, no token, and Spot in dev only. */
61
+ export declare function podSpec(name: string, args: PodArgs, serviceAccountName: pulumi.Input<string>, container?: Partial<k8s.types.input.core.v1.Container>): pulumi.Output<k8s.types.input.core.v1.PodSpec>;
62
+ export interface DeploymentParts {
63
+ serviceAccount: k8s.core.v1.ServiceAccount;
64
+ service?: k8s.core.v1.Service;
65
+ }
66
+ /**
67
+ * The Deployment, ServiceAccount, and Service of a `Workload` or a `WebService`, as children of
68
+ * `parent`. `http` is a `WebService`'s port, which its Service exposes as port 80.
69
+ */
70
+ export declare function deployment(parent: pulumi.Resource, name: string, args: WorkloadArgs, http?: number): DeploymentParts;
71
+ /**
72
+ * A long-running process with no route: a Deployment, a Kubernetes ServiceAccount, and, when it has
73
+ * ports, a ClusterIP Service, all named `name`. Its pods get no IAM; grant roles to `member`.
74
+ */
75
+ export declare class Workload extends pulumi.ComponentResource {
76
+ /** The pods' Workload Identity principal, for IAM grants. */
77
+ readonly member: pulumi.Output<string>;
78
+ readonly serviceAccountName: pulumi.Output<string>;
79
+ /** The name other pods in the namespace reach its Service by. */
80
+ readonly host: string;
81
+ constructor(name: string, args: WorkloadArgs, opts?: pulumi.ComponentResourceOptions);
82
+ }
83
+ export {};
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.Workload = void 0;
37
+ exports.workloadMember = workloadMember;
38
+ exports.checkRequests = checkRequests;
39
+ exports.serviceAccount = serviceAccount;
40
+ exports.podSpec = podSpec;
41
+ exports.deployment = deployment;
42
+ const k8s = __importStar(require("@pulumi/kubernetes"));
43
+ const pulumi = __importStar(require("@pulumi/pulumi"));
44
+ /** The pods' Workload Identity principal, for IAM grants. */
45
+ function workloadMember(platform, serviceAccountName) {
46
+ return pulumi.interpolate `principal://iam.googleapis.com/projects/${platform.projectNumber}/locations/global/workloadIdentityPools/${platform.project}.svc.id.goog/subject/ns/${platform.namespace}/sa/${serviceAccountName}`;
47
+ }
48
+ function checkRequests(kind, name, requests) {
49
+ // The types already require them, but a JavaScript caller or a cast can skip them.
50
+ if (!requests?.cpu || !requests?.memory) {
51
+ throw new Error(`${kind} "${name}" needs CPU and memory requests.`);
52
+ }
53
+ }
54
+ /** A ServiceAccount named `name` that mounts no token. */
55
+ function serviceAccount(name, args, opts) {
56
+ const platform = pulumi.output(args.platform);
57
+ return new k8s.core.v1.ServiceAccount(name, {
58
+ metadata: {
59
+ name,
60
+ namespace: platform.namespace,
61
+ labels: { "app.kubernetes.io/name": name },
62
+ ...(args.serviceAccountAnnotations && { annotations: args.serviceAccountAnnotations }),
63
+ },
64
+ automountServiceAccountToken: false,
65
+ }, opts);
66
+ }
67
+ /** A pod spec with the platform's secure defaults: non-root, read-only, no token, and Spot in dev only. */
68
+ function podSpec(name, args, serviceAccountName, container = {}) {
69
+ const volumes = args.volumes ?? [];
70
+ // The namespace is the environment's name.
71
+ return pulumi.output(args.platform).namespace.apply((namespace) => ({
72
+ serviceAccountName,
73
+ automountServiceAccountToken: false,
74
+ // Autopilot schedules a pod with this selector on Spot capacity.
75
+ nodeSelector: namespace === "dev" ? { "cloud.google.com/gke-spot": "true" } : {},
76
+ securityContext: {
77
+ runAsNonRoot: true,
78
+ seccompProfile: { type: "RuntimeDefault" },
79
+ ...(args.runAsUser !== undefined && { runAsUser: args.runAsUser, runAsGroup: args.runAsUser }),
80
+ },
81
+ ...(volumes.length > 0 && {
82
+ volumes: volumes.map((v) => ({
83
+ name: v.name,
84
+ ...(v.emptyDir && { emptyDir: v.emptyDir }),
85
+ ...(v.configMap !== undefined && { configMap: { name: v.configMap } }),
86
+ ...(v.secret !== undefined && { secret: { secretName: v.secret } }),
87
+ })),
88
+ }),
89
+ containers: [
90
+ {
91
+ name,
92
+ image: args.image,
93
+ ...(args.command && { command: args.command }),
94
+ ...(args.args && { args: args.args }),
95
+ ...container,
96
+ // A LimitRange's default limit could otherwise sit below the request, which the API refuses.
97
+ resources: { requests: args.requests, limits: args.requests },
98
+ ...(args.env && { env: args.env }),
99
+ ...(args.envFrom && { envFrom: args.envFrom }),
100
+ ...(volumes.length > 0 && {
101
+ volumeMounts: volumes.map((v) => ({
102
+ name: v.name,
103
+ mountPath: v.mountPath,
104
+ ...(v.subPath !== undefined && { subPath: v.subPath }),
105
+ ...(v.readOnly !== undefined && { readOnly: v.readOnly }),
106
+ })),
107
+ }),
108
+ securityContext: {
109
+ allowPrivilegeEscalation: false,
110
+ readOnlyRootFilesystem: true,
111
+ capabilities: { drop: ["ALL"] },
112
+ },
113
+ },
114
+ ],
115
+ }));
116
+ }
117
+ /**
118
+ * The Deployment, ServiceAccount, and Service of a `Workload` or a `WebService`, as children of
119
+ * `parent`. `http` is a `WebService`'s port, which its Service exposes as port 80.
120
+ */
121
+ function deployment(parent, name, args, http) {
122
+ const platform = pulumi.output(args.platform);
123
+ const labels = { "app.kubernetes.io/name": name };
124
+ const metadata = { name, namespace: platform.namespace, labels };
125
+ const child = { parent, provider: args.provider };
126
+ const account = serviceAccount(name, args, child);
127
+ const ports = [...(http !== undefined ? [{ name: "http", port: http }] : []), ...(args.ports ?? [])];
128
+ new k8s.apps.v1.Deployment(name, {
129
+ metadata,
130
+ spec: {
131
+ replicas: args.replicas ?? 1,
132
+ selector: { matchLabels: labels },
133
+ template: {
134
+ metadata: { labels },
135
+ spec: podSpec(name, args, account.metadata.name, {
136
+ ...(ports.length > 0 && { ports: ports.map((p) => ({ name: p.name, containerPort: p.port })) }),
137
+ ...(args.readinessProbe && { readinessProbe: args.readinessProbe }),
138
+ ...(args.livenessProbe && { livenessProbe: args.livenessProbe }),
139
+ ...(args.startupProbe && { startupProbe: args.startupProbe }),
140
+ }),
141
+ },
142
+ },
143
+ }, child);
144
+ if (ports.length === 0) {
145
+ return { serviceAccount: account };
146
+ }
147
+ const service = new k8s.core.v1.Service(name, {
148
+ metadata,
149
+ spec: {
150
+ selector: labels,
151
+ ports: ports.map((p) => ({
152
+ name: p.name,
153
+ port: p.name === "http" && http !== undefined ? 80 : p.port,
154
+ targetPort: p.name,
155
+ })),
156
+ },
157
+ }, child);
158
+ return { serviceAccount: account, service };
159
+ }
160
+ /**
161
+ * A long-running process with no route: a Deployment, a Kubernetes ServiceAccount, and, when it has
162
+ * ports, a ClusterIP Service, all named `name`. Its pods get no IAM; grant roles to `member`.
163
+ */
164
+ class Workload extends pulumi.ComponentResource {
165
+ /** The pods' Workload Identity principal, for IAM grants. */
166
+ member;
167
+ serviceAccountName;
168
+ /** The name other pods in the namespace reach its Service by. */
169
+ host;
170
+ constructor(name, args, opts) {
171
+ super("cyc-seattle:platform:Workload", name, {}, opts);
172
+ checkRequests("Workload", name, args.requests);
173
+ const { serviceAccount } = deployment(this, name, args);
174
+ this.serviceAccountName = serviceAccount.metadata.name;
175
+ this.member = workloadMember(pulumi.output(args.platform), this.serviceAccountName);
176
+ this.host = name;
177
+ this.registerOutputs({ member: this.member, serviceAccountName: this.serviceAccountName, host: this.host });
178
+ }
179
+ }
180
+ exports.Workload = Workload;
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@cyc-seattle/platform",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Pulumi components for CYC's shared Google Cloud platform: WebService, the platform outputs reader, and the stacks that build the platform",
5
+ "author": "CYC Community Sailing Center",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://github.com/cyc-seattle/platform#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/cyc-seattle/platform/issues"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/cyc-seattle/platform.git"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "engines": {
19
+ "node": ">=22"
20
+ },
21
+ "packageManager": "pnpm@10.34.6",
22
+ "prettier": "@cyc-seattle/ts-config/prettier",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.build.json",
35
+ "prepack": "pnpm run build"
36
+ },
37
+ "dependencies": {
38
+ "zod": "4.6.7"
39
+ },
40
+ "peerDependencies": {
41
+ "@pulumi/gcp": "^8",
42
+ "@pulumi/kubernetes": "^4",
43
+ "@pulumi/pulumi": "^3"
44
+ },
45
+ "devDependencies": {
46
+ "@amiceli/vitest-cucumber": "7.0.0",
47
+ "@cyc-seattle/ts-config": "^0.1.2",
48
+ "@pulumi/command": "1.2.1",
49
+ "@pulumi/gcp": "8.41.1",
50
+ "@pulumi/github": "6.15.0",
51
+ "@pulumi/kubernetes": "4.34.2",
52
+ "@pulumi/pulumi": "3.264.0",
53
+ "@types/js-yaml": "4.0.9",
54
+ "@types/node": "^22.19.1",
55
+ "eslint": "^9.39.5",
56
+ "google-auth-library": "^11.3.0",
57
+ "js-yaml": "^5.4.3",
58
+ "prettier": "^3.9.10",
59
+ "typescript": "~5.9.3",
60
+ "vitest": "^4.1.11"
61
+ }
62
+ }