-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathprepare.ts
More file actions
224 lines (212 loc) · 8.79 KB
/
prepare.ts
File metadata and controls
224 lines (212 loc) · 8.79 KB
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
import * as path from "path";
import {
doSetupSourceDeploy,
ensureAppHostingComputeServiceAccount,
ensureRequiredApisEnabled,
} from "../../apphosting/backend";
import { AppHostingMultiple, AppHostingSingle } from "../../firebaseConfig";
import { ensureApiEnabled, listBackends, parseBackendName } from "../../gcp/apphosting";
import { getGitRepositoryLink, parseGitRepositoryLinkName } from "../../gcp/devConnect";
import { Options } from "../../options";
import { needProjectId } from "../../projectUtils";
import { checkbox, confirm } from "../../prompt";
import { logLabeledBullet, logLabeledWarning } from "../../utils";
import { localBuild } from "../../apphosting/localbuilds";
import * as experiments from "../../experiments";
import { Context } from "./args";
import { FirebaseError } from "../../error";
/**
* Prepare backend targets to deploy from source. Checks that all required APIs are enabled,
* and that the App Hosting Compute Service Account exists and has the necessary IAM roles.
*/
export default async function (context: Context, options: Options): Promise<void> {
const projectId = needProjectId(options);
await ensureApiEnabled(options);
await ensureRequiredApisEnabled(projectId);
await ensureAppHostingComputeServiceAccount(projectId, /* serviceAccount= */ "");
context.backendConfigs = {};
context.backendLocations = {};
context.backendStorageUris = {};
context.backendLocalBuilds = {};
const configs = getBackendConfigs(options);
const { backends } = await listBackends(projectId, "-");
const foundBackends: AppHostingSingle[] = [];
const notFoundBackends: AppHostingSingle[] = [];
const ambiguousBackends: AppHostingSingle[] = [];
const skippedBackends: AppHostingSingle[] = [];
for (const cfg of configs) {
const filteredBackends = backends.filter(
(backend) => parseBackendName(backend.name).id === cfg.backendId,
);
if (filteredBackends.length === 0) {
notFoundBackends.push(cfg);
} else if (filteredBackends.length === 1) {
foundBackends.push(cfg);
} else {
ambiguousBackends.push(cfg);
}
}
// log warning for each ambiguous backend
for (const cfg of ambiguousBackends) {
const filteredBackends = backends.filter(
(backend) => parseBackendName(backend.name).id === cfg.backendId,
);
const locations = filteredBackends.map((b) => parseBackendName(b.name).location);
logLabeledWarning(
"apphosting",
`You have multiple backends with the same ${cfg.backendId} ID in regions: ${locations.join(", ")}. This is not allowed until we can support more locations. ` +
"Please delete and recreate any backends that share an ID with another backend.",
);
}
if (foundBackends.length > 0) {
logLabeledBullet(
"apphosting",
`Found backend(s) ${foundBackends.map((cfg) => cfg.backendId).join(", ")}`,
);
}
for (const cfg of foundBackends) {
const filteredBackends = backends.filter(
(backend) => parseBackendName(backend.name).id === cfg.backendId,
);
if (cfg.alwaysDeployFromSource === false) {
skippedBackends.push(cfg);
continue;
}
const backend = filteredBackends[0];
const { location } = parseBackendName(backend.name);
// We prompt the user for confirmation if they are attempting to deploy from source
// when the backend already has a remote repo connected. We force deploy if the command
// is run with the --force flag.
if (cfg.alwaysDeployFromSource === undefined && backend.codebase?.repository) {
const { connectionName, id } = parseGitRepositoryLinkName(backend.codebase.repository);
const gitRepositoryLink = await getGitRepositoryLink(projectId, location, connectionName, id);
if (!options.force) {
const confirmDeploy = await confirm({
default: true,
message: `${cfg.backendId} is linked to the remote repository at ${gitRepositoryLink.cloneUri}. Are you sure you want to deploy your local source?`,
});
cfg.alwaysDeployFromSource = confirmDeploy;
const configPath = path.join(options.projectRoot || "", "firebase.json");
options.config.writeProjectFile(configPath, options.config.src);
logLabeledBullet(
"apphosting",
`On future invocations of "firebase deploy", your local source will ${!confirmDeploy ? "not " : ""}be deployed to ${cfg.backendId}. You can edit this setting in your firebase.json at any time.`,
);
if (!confirmDeploy) {
skippedBackends.push(cfg);
continue;
}
}
}
context.backendConfigs[cfg.backendId] = cfg;
context.backendLocations[cfg.backendId] = location;
}
if (notFoundBackends.length > 0) {
if (options.force) {
logLabeledWarning(
"apphosting",
`Skipping deployments of backend(s) ${notFoundBackends.map((cfg) => cfg.backendId).join(", ")}; ` +
"the backend(s) do not exist yet and we cannot create them for you because you must choose primary regions for each one. " +
"Please run 'firebase deploy' without the --force flag, or 'firebase apphosting:backends:create' to create the backend, " +
"then retry deployment.",
);
return;
}
const confirmCreate = await confirm({
default: true,
message: `Did not find backend(s) ${notFoundBackends.map((cfg) => cfg.backendId).join(", ")}. Do you want to create them (you'll have the option to select which to create in the next step)?`,
});
if (confirmCreate) {
const selected = await checkbox<string>({
message: "Which backends do you want to create and deploy to?",
choices: notFoundBackends.map((cfg) => cfg.backendId),
});
const selectedBackends = selected.map((id) =>
notFoundBackends.find((backend) => backend.backendId === id),
) as AppHostingSingle[];
for (const cfg of selectedBackends) {
logLabeledBullet("apphosting", `Creating a new backend ${cfg.backendId}...`);
const { location } = await doSetupSourceDeploy(projectId, cfg.backendId);
context.backendConfigs[cfg.backendId] = cfg;
context.backendLocations[cfg.backendId] = location;
}
} else {
skippedBackends.push(...notFoundBackends);
}
}
if (skippedBackends.length > 0) {
logLabeledWarning(
"apphosting",
`Skipping deployment of backend(s) ${skippedBackends.map((cfg) => cfg.backendId).join(", ")}.`,
);
}
for (const cfg of Object.values(context.backendConfigs)) {
if (!cfg.localBuild) {
continue;
}
experiments.assertEnabled("apphostinglocalbuilds", "locally build App Hosting backends");
logLabeledBullet("apphosting", `Starting local build for backend ${cfg.backendId}`);
try {
const { outputFiles, annotations, buildConfig } = await localBuild(
options.projectRoot || "./",
"nextjs",
);
if (outputFiles.length !== 1) {
throw new FirebaseError(
`Local build for backend ${cfg.backendId} failed: No output files found.`,
);
}
context.backendLocalBuilds[cfg.backendId] = {
// TODO(9114): This only works for nextjs.
buildDir: outputFiles[0],
buildConfig,
annotations,
};
} catch (e: unknown) {
const errorMsg = e instanceof Error ? e.message : String(e);
throw new FirebaseError(`Local Build for backend ${cfg.backendId} failed: ${errorMsg}`);
}
}
}
/**
* Exported for unit testing. Filters backend configs based on user input.
*/
export function getBackendConfigs(options: Options): AppHostingMultiple {
if (!options.config.src.apphosting) {
return [];
}
const backendConfigs = Array.isArray(options.config.src.apphosting)
? options.config.src.apphosting
: [options.config.src.apphosting];
// If no --only specifier is passed, return all backend configs
if (!options.only) {
return backendConfigs;
}
const selectors = options.only.split(",");
const backendIds: string[] = [];
for (const selector of selectors) {
// if the user passes the "apphosting" selector, we default to deploying all backends
// listed in the user's firebase.json App Hosting config.
if (selector === "apphosting") {
return backendConfigs;
}
if (selector.startsWith("apphosting:")) {
const backendId = selector.replace("apphosting:", "");
if (backendId.length > 0) {
backendIds.push(backendId);
}
}
}
if (backendIds.length === 0) {
return [];
}
const filteredConfigs = backendConfigs.filter((cfg) => backendIds.includes(cfg.backendId));
const foundIds = filteredConfigs.map((cfg) => cfg.backendId);
const missingIds = backendIds.filter((id) => !foundIds.includes(id));
if (missingIds.length > 0) {
throw new FirebaseError(
`App Hosting backend IDs ${missingIds.join(",")} not detected in firebase.json`,
);
}
return filteredConfigs;
}