/
remote.tsx
750 lines (698 loc) · 22 KB
/
remote.tsx
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
import path from "node:path";
import { Text } from "ink";
import SelectInput from "ink-select-input";
import React, { useEffect, useRef, useState } from "react";
import { useErrorHandler } from "react-error-boundary";
import { helpIfErrorIsSizeOrScriptStartup } from "../deploy/deploy";
import { printBundleSize } from "../deployment-bundle/bundle-reporter";
import { getBundleType } from "../deployment-bundle/bundle-type";
import { withSourceURLs } from "../deployment-bundle/source-url";
import { getInferredHost } from "../dev";
import { UserError } from "../errors";
import { logger } from "../logger";
import { syncAssets } from "../sites";
import {
getAccountChoices,
requireApiToken,
saveAccountToCache,
} from "../user";
import { getAccessToken } from "../user/access";
import { getZoneIdForPreview } from "../zones";
import {
createPreviewSession,
createWorkerPreview,
} from "./create-worker-preview";
import { startPreviewServer } from "./proxy";
import type { ProxyData } from "../api";
import type { Route } from "../config/environment";
import type {
CfModule,
CfScriptFormat,
CfWorkerContext,
CfWorkerInit,
} from "../deployment-bundle/worker";
import type { ParseError } from "../parse";
import type { AssetPaths } from "../sites";
import type { ChooseAccountItem } from "../user";
import type {
CfAccount,
CfPreviewSession,
CfPreviewToken,
} from "./create-worker-preview";
import type { EsbuildBundle } from "./use-esbuild";
interface RemoteProps {
name: string | undefined;
bundle: EsbuildBundle | undefined;
format: CfScriptFormat | undefined;
isWorkersSite: boolean;
assetPaths: AssetPaths | undefined;
port: number;
ip: string;
localProtocol: "https" | "http";
httpsKeyPath: string | undefined;
httpsCertPath: string | undefined;
inspect: boolean;
inspectorPort: number;
accountId: string | undefined;
bindings: CfWorkerInit["bindings"];
compatibilityDate: string;
compatibilityFlags: string[] | undefined;
usageModel: "bundled" | "unbound" | undefined;
env: string | undefined;
legacyEnv: boolean | undefined;
host: string | undefined;
routes: Route[] | undefined;
onReady?:
| ((ip: string, port: number, proxyData: ProxyData) => void)
| undefined;
sourceMapPath: string | undefined;
sendMetrics: boolean | undefined;
}
export function Remote(props: RemoteProps) {
const [accountId, setAccountId] = useState(props.accountId);
const accountChoicesRef = useRef<Promise<ChooseAccountItem[]>>();
const [accountChoices, setAccountChoices] = useState<ChooseAccountItem[]>();
useWorker({
name: props.name,
bundle: props.bundle,
format: props.format,
modules: props.bundle ? props.bundle.modules : [],
accountId,
bindings: props.bindings,
assetPaths: props.assetPaths,
isWorkersSite: props.isWorkersSite,
compatibilityDate: props.compatibilityDate,
compatibilityFlags: props.compatibilityFlags,
usageModel: props.usageModel,
env: props.env,
legacyEnv: props.legacyEnv,
host: props.host,
routes: props.routes,
onReady: props.onReady,
sendMetrics: props.sendMetrics,
port: props.port,
});
const errorHandler = useErrorHandler();
// This effect handles the async step of fetching the available accounts for the current user.
// If only one account is available then it is just used by calling `setAccountId()`.
useEffect(() => {
if (
accountChoicesRef.current !== undefined ||
props.accountId !== undefined
) {
return;
}
accountChoicesRef.current = getAccountChoices();
accountChoicesRef.current.then(
(accounts) => {
if (accounts.length === 1) {
saveAccountToCache({
id: accounts[0].id,
name: accounts[0].name,
});
setAccountId(accounts[0].id);
} else {
setAccountChoices(accounts);
}
},
(err) => {
errorHandler(err);
}
);
});
// If we have not already chosen an account and there are multiple accounts available
// allow the users to select one.
return accountId === undefined && accountChoices !== undefined ? (
<ChooseAccount
accounts={accountChoices}
onSelect={(selectedAccount) => {
saveAccountToCache(selectedAccount);
setAccountId(selectedAccount.id);
}}
onError={(err) => errorHandler(err)}
></ChooseAccount>
) : null;
}
interface RemoteWorkerProps {
name: string | undefined;
bundle: EsbuildBundle | undefined;
format: CfScriptFormat | undefined;
modules: CfModule[];
accountId: string | undefined;
bindings: CfWorkerInit["bindings"];
assetPaths: AssetPaths | undefined;
isWorkersSite: boolean;
compatibilityDate: string | undefined;
compatibilityFlags: string[] | undefined;
usageModel: "bundled" | "unbound" | undefined;
env: string | undefined;
legacyEnv: boolean | undefined;
host: string | undefined;
routes: Route[] | undefined;
onReady:
| ((ip: string, port: number, proxyData: ProxyData) => void)
| undefined;
sendMetrics: boolean | undefined;
port: number;
}
export function useWorker(
props: RemoteWorkerProps
): CfPreviewToken | undefined {
const [session, setSession] = useState<CfPreviewSession | undefined>();
const [token, setToken] = useState<CfPreviewToken | undefined>();
const [restartCounter, setRestartCounter] = useState<number>(0);
// This is the most reliable way to detect whether
// something's "happened" in our system; We make a ref and
// mark it once we log our initial message. Refs are vars!
const startedRef = useRef(false);
// functions must be destructured before use inside a useEffect, otherwise the entire props object has to be added to the dependency array
const { onReady } = props;
// This effect sets up the preview session
useEffect(() => {
const abortController = new AbortController();
async function start() {
if (props.accountId === undefined) {
return;
}
const { workerAccount, workerContext } = await getWorkerAccountAndContext(
{
accountId: props.accountId,
env: props.env,
legacyEnv: props.legacyEnv,
host: props.host,
routes: props.routes,
sendMetrics: props.sendMetrics,
}
);
setSession(
await createPreviewSession(
workerAccount,
workerContext,
abortController.signal
)
);
}
start().catch((err) => {
// instead of logging the raw API error to the user,
// give them friendly instructions
// for error 10063 (workers.dev subdomain required)
if (err.code === 10063) {
const errorMessage =
"Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
const solutionMessage =
"You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
const onboardingLink = `https://dash.cloudflare.com/${props.accountId}/workers/onboarding`;
logger.error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
} else if (
(err.cause as { code: string; hostname: string })?.code === "ENOTFOUND"
) {
logger.error(
`Could not access \`${err.cause.hostname}\`. Make sure the domain is set up to be proxied by Cloudflare.\nFor more details, refer to https://developers.cloudflare.com/workers/configuration/routing/routes/#set-up-a-route`
);
} else if (err instanceof UserError) {
logger.error(err.message);
}
// we want to log the error, but not end the process
// since it could recover after the developer fixes whatever's wrong
else if ((err as { code: string }).code !== "ABORT_ERR") {
logger.error("Error while creating remote dev session:", err);
}
});
return () => {
abortController.abort();
};
}, [
props.accountId,
props.env,
props.host,
props.legacyEnv,
props.routes,
props.sendMetrics,
restartCounter,
]);
// This effect uses the session to upload the worker and create a preview
useEffect(() => {
const abortController = new AbortController();
async function start() {
if (props.accountId === undefined) {
return;
}
if (session === undefined) {
return;
}
setToken(undefined); // reset token in case we're re-running
if (!props.bundle || !props.format) return;
if (!startedRef.current) {
startedRef.current = true;
} else {
logger.log("⎔ Detected changes, restarted server.");
}
const init = await createRemoteWorkerInit({
bundle: props.bundle,
modules: props.modules,
accountId: props.accountId,
name: props.name,
legacyEnv: props.legacyEnv,
env: props.env,
isWorkersSite: props.isWorkersSite,
assetPaths: props.assetPaths,
format: props.format,
bindings: props.bindings,
compatibilityDate: props.compatibilityDate,
compatibilityFlags: props.compatibilityFlags,
usageModel: props.usageModel,
});
const { workerAccount, workerContext } = await getWorkerAccountAndContext(
{
accountId: props.accountId,
env: props.env,
legacyEnv: props.legacyEnv,
host: props.host,
routes: props.routes,
sendMetrics: props.sendMetrics,
}
);
const workerPreviewToken = await createWorkerPreview(
init,
workerAccount,
workerContext,
session,
abortController.signal
);
setToken(workerPreviewToken);
// TODO: Once we get service bindings working in the
// edge preview server, we can define remote dev service bindings
// and you can uncomment this code.
// https://github.com/cloudflare/workers-sdk/issues/1182
/*
if (name) {
await registerWorker(name, {
mode: "remote",
// upstream protocol is always https (https://github.com/cloudflare/workers-sdk/issues/583)
protocol: "https",
port: undefined,
host: workerPreviewToken.host,
headers: {
"cf-workers-preview-token": workerPreviewToken.value,
host: workerPreviewToken.host,
},
});
}
*/
const accessToken = await getAccessToken(workerPreviewToken.host);
const proxyData: ProxyData = {
userWorkerUrl: {
protocol: "https:",
hostname: workerPreviewToken.host,
port: "443",
},
userWorkerInspectorUrl: {
protocol: workerPreviewToken.inspectorUrl.protocol,
hostname: workerPreviewToken.inspectorUrl.hostname,
port: workerPreviewToken.inspectorUrl.port.toString(),
pathname: workerPreviewToken.inspectorUrl.pathname,
},
userWorkerInnerUrlOverrides: {
hostname: props.host ?? getInferredHost(props.routes),
port: props.port.toString(),
},
headers: {
"cf-workers-preview-token": workerPreviewToken.value,
...(accessToken ? { Cookie: `CF_Authorization=${accessToken}` } : {}),
},
liveReload: false, // liveReload currently disabled in remote-mode, but will be supported with startDevWorker
proxyLogsToController: true,
entrypointAddresses: undefined,
};
onReady?.(
props.host ?? getInferredHost(props.routes) ?? "localhost",
props.port,
proxyData
);
}
start().catch((err) => {
// we want to log the error, but not end the process
// since it could recover after the developer fixes whatever's wrong
// instead of logging the raw API error to the user,
// give them friendly instructions
if ((err as unknown as { code: string }).code !== "ABORT_ERR") {
// code 10049 happens when the preview token expires
if (err.code === 10049) {
logger.log("Preview token expired, fetching a new one");
// since we want a new preview token when this happens,
// lets increment the counter, and trigger a rerun of
// the useEffect above
setRestartCounter((prevCount) => prevCount + 1);
} else if (!handleUserFriendlyError(err, props.accountId)) {
logger.error("Error on remote worker:", err);
}
}
});
return () => {
abortController.abort();
};
}, [
props.name,
props.bundle,
props.format,
props.accountId,
props.assetPaths,
props.isWorkersSite,
props.compatibilityDate,
props.compatibilityFlags,
props.usageModel,
props.bindings,
props.modules,
props.env,
props.legacyEnv,
props.host,
props.routes,
session,
onReady,
props.sendMetrics,
props.port,
]);
return token;
}
export async function startRemoteServer(props: RemoteProps) {
let accountId = props.accountId;
if (accountId === undefined) {
const accountChoices = await getAccountChoices();
if (accountChoices.length === 1) {
saveAccountToCache({
id: accountChoices[0].id,
name: accountChoices[0].name,
});
accountId = accountChoices[0].id;
} else {
const error = new UserError(
"In a non-interactive environment, it is mandatory to specify an account ID, either by assigning its value to CLOUDFLARE_ACCOUNT_ID, or as `account_id` in your `wrangler.toml` file."
);
logger.error(error.message);
throw error;
}
}
const previewToken = await getRemotePreviewToken({
...props,
accountId: accountId,
});
if (previewToken === undefined) {
const error = new Error("Failed to get a previewToken");
logger.error(error.message);
throw error;
}
// start our proxy server
const previewServer = await startPreviewServer({
previewToken,
assetDirectory: props.isWorkersSite
? undefined
: props.assetPaths?.assetDirectory,
localProtocol: props.localProtocol,
customHttpsKeyPath: props.httpsKeyPath,
customHttpsCertPath: props.httpsCertPath,
localPort: props.port,
ip: props.ip,
onReady: async (ip, port) => {
const accessToken = await getAccessToken(previewToken.host);
const proxyData: ProxyData = {
userWorkerUrl: {
protocol: "https:",
hostname: previewToken.host,
port: "443",
},
userWorkerInspectorUrl: {
protocol: previewToken.inspectorUrl.protocol,
hostname: previewToken.inspectorUrl.hostname,
port: previewToken.inspectorUrl.port.toString(),
pathname: previewToken.inspectorUrl.pathname,
},
userWorkerInnerUrlOverrides: {
hostname: props.host,
port: props.port.toString(),
},
headers: {
"cf-workers-preview-token": previewToken.value,
...(accessToken ? { Cookie: `CF_Authorization=${accessToken}` } : {}),
},
liveReload: false, // liveReload currently disabled in remote-mode, but will be supported with startDevWorker
proxyLogsToController: true,
entrypointAddresses: undefined,
};
props.onReady?.(ip, port, proxyData);
},
});
if (!previewServer) {
const error = new Error("Failed to start remote server");
logger.error(error);
throw error;
}
return { stop: previewServer.stop };
}
/**
* getRemotePreviewToken is a react-free version of `useWorker`.
* It returns a preview token, which we then use in our proxy server
*/
export async function getRemotePreviewToken(props: RemoteProps) {
//setup the preview session
async function start() {
if (props.accountId === undefined) {
const error = new Error("no accountId provided");
logger.error(error.message);
throw error;
}
const abortController = new AbortController();
const { workerAccount, workerContext } = await getWorkerAccountAndContext({
accountId: props.accountId,
env: props.env,
legacyEnv: props.legacyEnv,
host: props.host,
routes: props.routes,
sendMetrics: props.sendMetrics,
});
const session = await createPreviewSession(
workerAccount,
workerContext,
abortController.signal
);
//use the session to upload the worker, and create a preview
if (session === undefined) {
const error = new Error("Failed to start a session");
logger.error(error.message);
throw error;
}
if (!props.bundle || !props.format) return;
const init = await createRemoteWorkerInit({
bundle: props.bundle,
modules: props.bundle ? props.bundle.modules : [],
accountId: props.accountId,
name: props.name,
legacyEnv: props.legacyEnv,
env: props.env,
isWorkersSite: props.isWorkersSite,
assetPaths: props.assetPaths,
format: props.format,
bindings: props.bindings,
compatibilityDate: props.compatibilityDate,
compatibilityFlags: props.compatibilityFlags,
usageModel: props.usageModel,
});
const workerPreviewToken = await createWorkerPreview(
init,
workerAccount,
workerContext,
session,
abortController.signal
);
return workerPreviewToken;
}
return start().catch((err) => {
// we want to log the error, but not end the process
// since it could recover after the developer fixes whatever's wrong
// instead of logging the raw API error to the user,
// give them friendly instructions
if ((err as unknown as { code: string })?.code !== "ABORT_ERR") {
// code 10049 happens when the preview token expires
if (err.code === 10049) {
logger.log("Preview token expired, restart server to fetch a new one");
} else if (!handleUserFriendlyError(err, props.accountId)) {
helpIfErrorIsSizeOrScriptStartup(err, props.bundle?.dependencies || {});
logger.error("Error on remote worker:", err);
}
}
});
}
async function createRemoteWorkerInit(props: {
bundle: EsbuildBundle;
modules: CfModule[];
accountId: string;
name: string | undefined;
legacyEnv: boolean | undefined;
env: string | undefined;
isWorkersSite: boolean;
assetPaths: AssetPaths | undefined;
format: CfScriptFormat;
bindings: CfWorkerInit["bindings"];
compatibilityDate: string | undefined;
compatibilityFlags: string[] | undefined;
usageModel: "bundled" | "unbound" | undefined;
}) {
const { entrypointSource: content, modules } = withSourceURLs(
props.bundle.path,
props.modules
);
// TODO: For Dev we could show the reporter message in the interactive box.
void printBundleSize(
{ name: path.basename(props.bundle.path), content: content },
props.modules
);
const assets = await syncAssets(
props.accountId,
// When we're using the newer service environments, we wouldn't
// have added the env name on to the script name. However, we must
// include it in the kv namespace name regardless (since there's no
// concept of service environments for kv namespaces yet).
props.name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
props.isWorkersSite ? props.assetPaths : undefined,
true,
false,
undefined
); // TODO: cancellable?
if (assets.manifest) {
modules.push({
name: "__STATIC_CONTENT_MANIFEST",
filePath: undefined,
content: JSON.stringify(assets.manifest),
type: "text",
});
}
const init: CfWorkerInit = {
name: props.name,
main: {
name: path.basename(props.bundle.path),
filePath: props.bundle.path,
type: getBundleType(props.format, path.basename(props.bundle.path)),
content,
},
modules,
bindings: {
...props.bindings,
kv_namespaces: (props.bindings.kv_namespaces || []).concat(
assets.namespace
? { binding: "__STATIC_CONTENT", id: assets.namespace }
: []
),
text_blobs: {
...props.bindings.text_blobs,
...(assets.manifest &&
props.format === "service-worker" && {
__STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
}),
},
},
migrations: undefined, // no migrations in dev
compatibility_date: props.compatibilityDate,
compatibility_flags: props.compatibilityFlags,
usage_model: props.usageModel,
keepVars: true,
keepSecrets: true,
logpush: false,
sourceMaps: undefined,
placement: undefined, // no placement in dev
tail_consumers: undefined, // no tail consumers in dev - TODO revisit?
limits: undefined, // no limits in preview - not supported yet but can be added
};
return init;
}
export async function getWorkerAccountAndContext(props: {
accountId: string;
env?: string;
legacyEnv?: boolean;
host?: string;
routes: Route[] | undefined;
sendMetrics?: boolean;
}): Promise<{ workerAccount: CfAccount; workerContext: CfWorkerContext }> {
const workerAccount: CfAccount = {
accountId: props.accountId,
apiToken: requireApiToken(),
};
// What zone should the realish preview for this Worker run on?
const zoneId = await getZoneIdForPreview(props.host, props.routes);
const workerContext: CfWorkerContext = {
env: props.env,
legacyEnv: props.legacyEnv,
zone: zoneId,
host: props.host ?? getInferredHost(props.routes),
routes: props.routes,
sendMetrics: props.sendMetrics,
};
return { workerAccount, workerContext };
}
/**
* A component that allows the user to select from a list of available accounts.
*/
function ChooseAccount(props: {
accounts: ChooseAccountItem[];
onSelect: (account: { name: string; id: string }) => void;
onError: (error: Error) => void;
}) {
return (
<>
<Text bold>Select an account from below:</Text>
<SelectInput
items={props.accounts.map((item) => ({
key: item.id,
label: item.name,
value: item,
}))}
onSelect={(item) => {
logger.log(`Using account: "${item.value.name} - ${item.value.id}"`);
props.onSelect({ id: item.value.id, name: item.value.name });
}}
/>
</>
);
}
/**
* A switch for handling thrown error mappings to user friendly
* messages, does not perform any logic other than logging errors.
* @returns if the error was handled or not
*/
function handleUserFriendlyError(error: ParseError, accountId?: string) {
switch ((error as unknown as { code: number }).code) {
// code 10021 is a validation error
case 10021: {
// if it is the following message, give a more user friendly
// error, otherwise do not handle this error in this function
if (
error.notes[0].text ===
"binding DB of type d1 must have a valid `id` specified [code: 10021]"
) {
const errorMessage =
"Error: You must use a real database in the preview_database_id configuration.";
const solutionMessage =
"You can find your databases using 'wrangler d1 list', or read how to develop locally with D1 here:";
const documentationLink = `https://developers.cloudflare.com/d1/configuration/local-development`;
logger.error(
`${errorMessage}\n${solutionMessage}\n${documentationLink}`
);
return true;
}
return false;
}
// for error 10063 (workers.dev subdomain required)
case 10063: {
const errorMessage =
"Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
const solutionMessage =
"You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
const onboardingLink = accountId
? `https://dash.cloudflare.com/${accountId}/workers/onboarding`
: "https://dash.cloudflare.com/?to=/:account/workers/onboarding";
logger.error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
return true;
}
default: {
return false;
}
}
}