-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mts
225 lines (207 loc) · 6.07 KB
/
index.mts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import * as pulumi from "@pulumi/pulumi";
import * as gcp from "@pulumi/gcp";
import * as dockerbuild from "@pulumi/docker-build";
import * as random from "@pulumi/random";
import * as fs from "fs";
import * as path from "path";
import * as crypto from "crypto";
import * as command from "@pulumi/command";
import { fileURLToPath } from "node:url";
// Import the program's configuration settings.
const config = new pulumi.Config();
const imageName = config.require("imageName");
const appPath = config.require("appPath");
const containerPort = config.requireNumber("containerPort");
const cpu = config.requireNumber("cpu");
const memory = config.require("memory");
const concurrency = config.requireNumber("concurrency");
// Import the provider's configuration settings.
const gcpConfig = new pulumi.Config("gcp");
const location = gcpConfig.require("region");
const project = gcpConfig.require("project");
// Generate a unique Artifact Registry repository ID
const uniqueString = new random.RandomString("unique-string", {
length: 4,
lower: true,
upper: false,
numeric: true,
special: false,
});
let repoId = uniqueString.result.apply((result) => "repo-" + result);
// Create an Artifact Registry repository
const repository =
(await gcp.artifactregistry
.getRepository({
location,
repositoryId: "docker",
})
.then((res) => {
return res;
})
.catch((err) => {
console.log(`Failed to find repository with error:\n${err}\ncreating...`);
return undefined;
})) ??
new gcp.artifactregistry.Repository("docker", {
project,
description: undefined,
format: "Docker",
location: location,
repositoryId: "docker",
});
// Form the repository URL
let repoUrl = pulumi.concat(location, "-docker.pkg.dev/", project, "/", repository.repositoryId);
const tagName = pulumi.concat(repoUrl, "/", imageName, ":latest");
// Create a container image for the service.
// Before running `pulumi up`, configure Docker for authentication to Artifact Registry
// as described here: https://cloud.google.com/artifact-registry/docs/docker/authentication
const image = new dockerbuild.Image(
"web",
{
tags: [tagName],
context: {
location: appPath,
},
// Cloud Run currently requires x86_64 images
// https://cloud.google.com/run/docs/container-contract#languages
platforms: ["linux/amd64"],
// cacheTo: [
// {
// registry: {
// ref: tagName,
// },
// },
// ],
// cacheFrom: [
// {
// registry: {
// ref: tagName,
// },
// },
// ],
push: true,
},
{
customTimeouts: {
create: "15m",
},
},
);
// Create a Cloud Run service definition.
const service = new gcp.cloudrunv2.Service("web", {
location,
name: "web",
template: {
containers: [
{
image: image.ref,
resources: {
limits: {
memory,
cpu: cpu.toString(),
},
},
ports: {
containerPort,
},
envs: [
{
name: "NODE_ENV",
value: "production",
},
// this breaks routing, not very clever am i
// {
// name: "BASE",
// value: "https://codyduong.dev/",
// },
],
startupProbe: {
timeoutSeconds: 60,
periodSeconds: 60,
failureThreshold: 1,
tcpSocket: {
port: containerPort,
},
},
},
],
maxInstanceRequestConcurrency: concurrency,
timeout: "60s",
scaling: {
minInstanceCount: 0,
maxInstanceCount: 5,
}
},
});
// Create an IAM member to allow the service to be publicly accessible.
const invoker = new gcp.cloudrun.IamMember("invoker", {
location,
service: service.name,
role: "roles/run.invoker",
member: "allUsers",
});
// Export the URL of the service.
// export const url = service.statuses.apply((statuses) => statuses[0]?.url);
// const site = new gcp.firebase.HostingSite("codyduongweb", {
// project,
// });
// // Set up hosting configuration
// const hostingConfig = new gcp.firebase.HostingVersion("codyduongweb", {
// siteId: site.name,
// config: {
// rewrites: [
// {
// glob: "**",
// run: {
// serviceId: "web",
// region: "us-central1",
// },
// },
// ],
// },
// });
const directories = [appPath] as const;
function hashDirectories(dirs: readonly string[] | string[]): string {
const hash = crypto.createHash("sha256");
for (const dir of dirs) {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isFile()) {
const content = fs.readFileSync(filePath);
hash.update(content);
} else if (stat.isDirectory()) {
hash.update(hashDirectories([filePath]));
}
}
}
return hash.digest("hex");
}
const directoryHash: string = hashDirectories(directories);
const deploy = new command.local.Command(
`Firebase Deploy: ${directoryHash}`,
{
create: pulumi.runtime.isDryRun()
? pulumi.interpolate`echo "[Preview] Skipping firebase deploy for hash: ${directoryHash}"`
: pulumi.interpolate`firebase deploy --project ${project} --only hosting --message "${directoryHash}"`,
environment: {
// FIREBASE_AUTH_TOKEN: firebaseToken,
GOOGLE_APPLICATION_CREDENTIALS: path.resolve(
fileURLToPath(import.meta.url),
"/application_default_credentials.json",
),
},
dir: appPath,
triggers: [image],
},
{
dependsOn: [image, service, invoker],
},
);
// Deploy the new hosting configuration
// const hostingRelease = new gcp.firebase.HostingRelease(`version-${directoryHash}`, {
// siteId: site.name,
// versionName: hostingConfig.name,
// type: "DEPLOY",
// });