Repository navigation
Expand file tree
/
Copy pathdeployments.test.ts
More file actions
1041 lines (947 loc) · 31.5 KB
/
Copy pathdeployments.test.ts
File metadata and controls
1041 lines (947 loc) · 31.5 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
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ci from "ci-info";
import dedent from "ts-dedent";
import { fetch } from "undici";
import {
afterAll,
afterEach,
assert,
beforeAll,
beforeEach,
describe,
type ExpectStatic,
it,
} from "vitest";
import { CLOUDFLARE_ACCOUNT_ID } from "./helpers/account-id";
import { WranglerE2ETestHelper } from "./helpers/e2e-wrangler-test";
import { generateResourceName } from "./helpers/generate-resource-name";
import { normalizeOutput, validateAssetUploadLogs } from "./helpers/normalize";
import { retry } from "./helpers/retry";
import { waitForLong } from "./helpers/wait-for";
import { waitForWorkersDev } from "./helpers/wait-for-workers-dev";
const TIMEOUT = 90_000;
describe.skipIf(!CLOUDFLARE_ACCOUNT_ID)(
"deployments",
{ timeout: TIMEOUT },
() => {
// Note that we are sharing the workerName and helper across all these tests,
// which means that these tests are not isolated from each other.
// Seeded files will leak between tests.
const workerName = generateResourceName();
const helper = new WranglerE2ETestHelper();
afterAll(async () => {
// clean up user Worker after all tests
await helper.bestEffortRun(`wrangler delete`);
});
it("deploys a Worker", async ({ expect }) => {
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
main = "src/index.ts"
compatibility_date = "2023-01-01"
`,
"src/index.ts": dedent`
export default {
fetch(request) {
return new Response("Hello World!")
}
}`,
"package.json": dedent`
{
"name": "${workerName}",
"version": "0.0.0",
"private": true
}
`,
});
const output = await helper.run(`wrangler deploy`);
const deployedUrl = getDeployedUrl(output);
const response = await waitForWorkersDev(
deployedUrl,
async (candidate) => (await candidate.clone().text()) === "Hello World!"
);
expect(await response.text()).toEqual("Hello World!");
});
it("lists 1 deployment", async ({ expect }) => {
const output = await helper.run(`wrangler deployments list`);
expect(normalizeOutput(output.stdout)).toMatchInlineSnapshot(`
"Created: TIMESTAMP
Author: person@example.com
Source: Upload
Message: Automatic deployment on upload.
Version(s): (100%) 00000000-0000-0000-0000-000000000000
Created: TIMESTAMP
Tag: -
Message: -"
`);
});
it("modifies & deploys a Worker", async ({ expect }) => {
await helper.seed({
"src/index.ts": dedent`
export default {
fetch(request) {
return new Response("Updated Worker!")
}
}`,
});
const output = await helper.run(`wrangler deploy`);
const deployedUrl = getDeployedUrl(output);
const response = await waitForWorkersDev(
deployedUrl,
async (candidate) =>
(await candidate.clone().text()) === "Updated Worker!"
);
expect(await response.text()).toEqual("Updated Worker!");
});
it("lists 2 deployments", async ({ expect }) => {
const dep = await helper.run(`wrangler deployments list`);
expect(normalizeOutput(dep.stdout)).toMatchInlineSnapshot(`
"Created: TIMESTAMP
Author: person@example.com
Source: Upload
Message: Automatic deployment on upload.
Version(s): (100%) 00000000-0000-0000-0000-000000000000
Created: TIMESTAMP
Tag: -
Message: -
Created: TIMESTAMP
Author: person@example.com
Source: Unknown (deployment)
Message: -
Version(s): (100%) 00000000-0000-0000-0000-000000000000
Created: TIMESTAMP
Tag: -
Message: -"
`);
});
it("rolls back", async ({ expect }) => {
const output = await helper.run(
`wrangler rollback --message "A test message"`
);
expect(normalizeOutput(output.stdout)).toMatchInlineSnapshot(`
"├ Fetching latest deployment
│
├ Your current deployment has 1 version(s):
│
│ (100%) 00000000-0000-0000-0000-000000000000
│ Created: TIMESTAMP
│ Tag: -
│ Message: -
│
├ Finding latest stable Worker Version to rollback to
│
│
? Please provide an optional message for this rollback (120 characters max)
🤖 Using default value in non-interactive context: A test message
│
├ WARNING You are about to rollback to Worker Version 00000000-0000-0000-0000-000000000000.
│ This will immediately replace the current deployment and become the active deployment across all your deployed triggers.
│ However, your local development environment will not be affected by this rollback.
│ Rolling back to a previous deployment will not rollback any of the bound resources (Durable Object, D1, R2, KV, etc).
│
│ (100%) 00000000-0000-0000-0000-000000000000
│ Created: TIMESTAMP
│ Tag: -
│ Message: -
│
? Are you sure you want to deploy this Worker Version to 100% of traffic?
🤖 Using fallback value in non-interactive context: yes
Performing rollback...
│
╰ SUCCESS Worker Version 00000000-0000-0000-0000-000000000000 has been deployed to 100% of traffic.
Current Version ID: 00000000-0000-0000-0000-000000000000"
`);
});
it("lists deployments", async ({ expect }) => {
const dep = await helper.run(`wrangler deployments list`);
expect(normalizeOutput(dep.stdout)).toMatchInlineSnapshot(`
"Created: TIMESTAMP
Author: person@example.com
Source: Upload
Message: Automatic deployment on upload.
Version(s): (100%) 00000000-0000-0000-0000-000000000000
Created: TIMESTAMP
Tag: -
Message: -
Created: TIMESTAMP
Author: person@example.com
Source: Unknown (deployment)
Message: -
Version(s): (100%) 00000000-0000-0000-0000-000000000000
Created: TIMESTAMP
Tag: -
Message: -
Created: TIMESTAMP
Author: person@example.com
Source: Unknown (deployment)
Message: A test message
Version(s): (100%) 00000000-0000-0000-0000-000000000000
Created: TIMESTAMP
Tag: -
Message: -"
`);
});
}
);
type AssetTestCase = {
path: string;
content?: string;
redirect?: string;
};
function generateInitialAssets(workerName: string) {
return {
"public/index.html": dedent`
<h1>index.html</h1>`,
"public/[boop].html": dedent`
<h1>[boop].html</h1>`,
"public/404.html": dedent`
<h1>404.html</h1>`,
"package.json": dedent`
{
"name": "${workerName}",
"version": "0.0.0",
"private": true
}`,
};
}
async function checkAssets(
expect: ExpectStatic,
testCases: AssetTestCase[],
deployedUrl: string
) {
for (const testCase of testCases) {
await waitForLong(
async () => {
const r = await fetch(new URL(testCase.path, deployedUrl));
const text = await r.text();
const url = r.url;
if (testCase.content) {
expect(
text,
`expected content for ${testCase.path} to be ${testCase.content}`
).toContain(testCase.content);
}
if (testCase.redirect) {
expect(
new URL(url).pathname,
`expected redirect for ${testCase.path} to be ${testCase.redirect}`
).toEqual(new URL(testCase.redirect, deployedUrl).pathname);
} else {
expect(
new URL(url).pathname,
`unexpected pathname for ${testCase.path}`
).toEqual(new URL(testCase.path, deployedUrl).pathname);
}
},
{ timeout: 40_000 }
);
}
}
describe.skipIf(!CLOUDFLARE_ACCOUNT_ID)("Workers + Assets deployment", () => {
let helper: WranglerE2ETestHelper;
let workerName: string;
beforeEach(() => {
// We are recreating the helper on each test to ensure they are isolated from each other.
helper = new WranglerE2ETestHelper();
// Use a new user Worker in each test
workerName = generateResourceName();
});
describe("Workers", () => {
afterEach(async () => {
// clean up user Worker after each test
await helper.bestEffortRun(`wrangler delete`);
});
it("deploys a Workers + Assets project with assets only, logging each uploaded asset", async ({
expect,
}) => {
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
compatibility_date = "2023-01-01"
[assets]
directory = "public"
`,
...generateInitialAssets(workerName),
});
// Deploy the user Worker && verify output.
// `debug: true` is load-bearing: the per-file `✨ <path>` upload logs
// asserted by `includeDebug` are only emitted at `WRANGLER_LOG=debug`.
const output = await helper.run(`wrangler deploy`, { debug: true });
validateAssetUploadLogs(
expect,
output,
["/404.html", "/index.html", "/[boop].html"],
{ includeDebug: true }
);
const deployedUrl = getDeployedUrl(output);
const testCases: AssetTestCase[] = [
// Tests html_handling = "auto_trailing_slash" (default):
{
path: "/",
content: "<h1>index.html</h1>",
},
{
path: "/index.html",
content: "<h1>index.html</h1>",
redirect: "/",
},
{
path: "/[boop]",
content: "<h1>[boop].html</h1>",
redirect: "/%5Bboop%5D",
},
];
await checkAssets(expect, testCases, deployedUrl);
// Test 404 handling:
// even though 404.html has been uploaded, because not_found_handling is set to "none"
// we expect to get an empty response
const { text } = await retry(
(s) => s.status !== 404,
async () => {
const r = await fetch(new URL("/try-404", deployedUrl));
const temp = { text: await r.text(), status: r.status };
return temp;
}
);
expect(text).toBeFalsy();
});
it("deploys a Worker with static assets and user Worker", async ({
expect,
}) => {
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
main = "src/index.ts"
compatibility_date = "2023-01-01"
[assets]
directory = "public"
binding = "ASSETS"
html_handling = "none"
not_found_handling = "404-page"
`,
"src/index.ts": dedent`
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname === "/binding") {
return await env.ASSETS.fetch(new URL("index.html", request.url));
} else if (url.pathname === "/try-404") {
return await env.ASSETS.fetch(request.url);
}
return new Response("Hello World!")
}
}`,
...generateInitialAssets(workerName),
});
// deploy user Worker && verify output
const output = await helper.run(`wrangler deploy`);
validateAssetUploadLogs(expect, output, [
"/404.html",
"/index.html",
"/[boop].html",
]);
const deployedUrl = getDeployedUrl(output);
const testCases: AssetTestCase[] = [
// because html handling has now been set to "none", only exact matches will be served
{
path: "/index.html",
content: "<h1>index.html</h1>",
},
// 404s should fall through to the user worker, and "/" is not an exact match
// so we should expect the UW response
{ path: "/", content: "Hello World!" },
{
path: "/binding",
content: "<h1>index.html</h1>",
},
{
path: "/worker",
content: "Hello World!",
},
];
await checkAssets(expect, testCases, deployedUrl);
// unlike before, not_found_handling has been set to "404-page" instead of the default "none"
// note that with a user worker, the request must be passed back to the asset worker via the ASSET binding
// in order to return the 404 page
const { text } = await retry(
// Retry while the status isn't 404 OR the content hasn't propagated yet.
// Before assets are live the platform may return its own 404 page (status 200)
// instead of the user's 404.html asset.
(s) => s.status !== 404 || !s.text.includes("<h1>404.html</h1>"),
async () => {
const r = await fetch(new URL("/try-404", deployedUrl));
const temp = { text: await r.text(), status: r.status };
return temp;
}
);
expect(text).toContain("<h1>404.html</h1>");
});
it("serves assets only beneath the configured base path", async ({
expect,
}) => {
const assetName = `base-path-${workerName}.txt`;
const assetBody = `asset response from ${workerName}`;
const workerBody = `user Worker response from ${workerName}`;
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
main = "src/index.ts"
compatibility_date = "2023-01-01"
workers_dev = true
[assets]
directory = "public"
base_path = "/blog/"
`,
"src/index.ts": dedent`
export default {
fetch() {
return new Response("${workerBody}")
}
}`,
[`public/${assetName}`]: assetBody,
"package.json": dedent`
{
"name": "${workerName}",
"version": "0.0.0",
"private": true
}`,
});
const output = await helper.run(`wrangler deploy`);
validateAssetUploadLogs(expect, output, [`/${assetName}`]);
const deployedUrl = getDeployedUrl(output);
const assetResponse = await waitForWorkersDev(
new URL(`/blog/${assetName}`, deployedUrl).href,
async (candidate) =>
candidate.status === 200 &&
(await candidate.clone().text()) === assetBody
);
expect(assetResponse.status).toBe(200);
expect(await assetResponse.text()).toBe(assetBody);
const workerResponse = await waitForWorkersDev(
new URL(`/${assetName}`, deployedUrl).href,
async (candidate) =>
candidate.status === 200 &&
(await candidate.clone().text()) === workerBody
);
expect(workerResponse.status).toBe(200);
expect(await workerResponse.text()).toBe(workerBody);
});
it("runs the user Worker ahead of matching assets when run_worker_first = true", async ({
expect,
}) => {
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
main = "src/index.ts"
compatibility_date = "2023-01-01"
[assets]
directory = "public"
binding = "ASSETS"
html_handling = "none"
not_found_handling = "404-page"
run_worker_first = true
`,
"src/index.ts": dedent`
export default {
async fetch(request, env) {
return new Response("Hello World from User Worker!")
}
}`,
...generateInitialAssets(workerName),
});
// deploy user Worker && verify output
const output = await helper.run(`wrangler deploy`);
validateAssetUploadLogs(expect, output, [
"/404.html",
"/index.html",
"/[boop].html",
]);
const deployedUrl = getDeployedUrl(output);
const testCases: AssetTestCase[] = [
{
path: "/index.html",
content: "Hello World from User Worker!",
},
{
path: "/",
content: "Hello World from User Worker!",
},
{
path: "/worker",
content: "Hello World from User Worker!",
},
];
await checkAssets(expect, testCases, deployedUrl);
});
it("runs the user Worker ahead of matching assets for matching run_worker_first routes", async ({
expect,
}) => {
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
main = "src/index.ts"
compatibility_date = "2023-01-01"
[assets]
directory = "public"
binding = "ASSETS"
html_handling = "none"
not_found_handling = "404-page"
run_worker_first = ["/api/*", "!/api/assets/*"]
`,
"src/index.ts": dedent`
export default {
async fetch(request, env) {
return new Response("Hello World from User Worker!")
}
}`,
...generateInitialAssets(workerName),
"public/api/index.html": "<h1>api/index.html</h1>",
"public/api/assets/test.html": "<h1>api/assets/test.html</h1>",
});
// deploy user Worker && verify output
const output = await helper.run(`wrangler deploy`);
validateAssetUploadLogs(expect, output, [
"/404.html",
"/api/index.html",
"/index.html",
"/api/assets/test.html",
"/[boop].html",
]);
const deployedUrl = getDeployedUrl(output);
const testCases: AssetTestCase[] = [
{ path: "/index.html", content: "<h1>index.html</h1>" },
{ path: "/missing.html", content: "<h1>404.html</h1>" },
{ path: "/api/", content: "Hello World from User Worker!" },
{ path: "/api/foo.html", content: "Hello World from User Worker!" },
{ path: "/api/assets/missing", content: "404.html" },
{ path: "/api/assets/test.html", content: "api/assets/test.html" },
];
await checkAssets(expect, testCases, deployedUrl);
});
});
describe("Workers for Platforms", () => {
let dispatchNamespaceName: string;
let dispatchWorkerName: string;
beforeEach(async () => {
// set up a new dispatch Worker in each test
dispatchNamespaceName = generateResourceName("dispatch");
dispatchWorkerName = generateResourceName();
await helper.seed({
"dispatch-worker/wrangler.toml": dedent`
name = "${dispatchWorkerName}"
main = "./src/index.js"
compatibility_date = "2023-01-01"
[[dispatch_namespaces]]
binding = "DISPATCH"
namespace = "${dispatchNamespaceName}"
`,
"dispatch-worker/src/index.js": dedent`
export default {
async fetch(request, env, ctx) {
const stub = env.DISPATCH.get("${workerName}");
return stub.fetch(request);
}
}
`,
});
});
afterEach(async () => {
// clean up dispatch Worker
await helper.bestEffortRun(
`wrangler delete -c dispatch-worker/wrangler.toml`
);
await helper.bestEffortRun(
`wrangler dispatch-namespace delete ${dispatchNamespaceName}`
);
});
it("deploys a Workers + Assets project with assets only", async ({
expect,
}) => {
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
compatibility_date = "2023-01-01"
[assets]
directory = "public"
`,
...generateInitialAssets(workerName),
});
// create a dispatch namespace && verify output
let output = await helper.run(
`wrangler dispatch-namespace create ${dispatchNamespaceName}`
);
let normalizedStdout = normalizeOutput(output.stdout);
expect(normalizedStdout).toContain(
`Created dispatch namespace "tmp-e2e-dispatch-00000000-0000-0000-0000-000000000000" with ID "00000000-0000-0000-0000-000000000000"`
);
// upload user Worker to the dispatch namespace && verify output
output = await helper.run(
`wrangler deploy --dispatch-namespace ${dispatchNamespaceName}`
);
validateAssetUploadLogs(expect, output, [
"/404.html",
"/index.html",
"/[boop].html",
]);
// deploy dispatch Worker && verify output
output = await helper.run(
`wrangler deploy -c dispatch-worker/wrangler.toml`
);
normalizedStdout = normalizeOutput(output.stdout);
expect(normalizedStdout).toEqual(`Total Upload: xx KiB / gzip: xx KiB
Your Worker has access to the following bindings:
Binding Resource
env.DISPATCH (tmp-e2e-dispatch-00000000-0000-0000-0000-000000000000) Dispatch Namespace
Uploaded tmp-e2e-worker-00000000-0000-0000-0000-000000000000 (TIMINGS)
Deployed tmp-e2e-worker-00000000-0000-0000-0000-000000000000 triggers (TIMINGS)
https://tmp-e2e-worker-00000000-0000-0000-0000-000000000000.SUBDOMAIN.workers.dev
Current Version ID: 00000000-0000-0000-0000-000000000000`);
const deployedUrl = getDeployedUrl(output);
const testCases: AssetTestCase[] = [
// Tests html_handling = "auto_trailing_slash" (default):
{
path: "/",
content: "<h1>index.html</h1>",
},
{
path: "/index.html",
content: "<h1>index.html</h1>",
redirect: "/",
},
{
path: "/[boop]",
content: "<h1>[boop].html</h1>",
redirect: "/%5Bboop%5D",
},
];
await checkAssets(expect, testCases, deployedUrl);
// Test 404 handling:
// even though 404.html has been uploaded, because not_found_handling is set to "none"
// we expect to get an empty response
const { text } = await retry(
(s) => s.status !== 404,
async () => {
const r = await fetch(new URL("/try-404", deployedUrl));
const temp = { text: await r.text(), status: r.status };
return temp;
}
);
expect(text).toBeFalsy();
});
it("deploys a Worker with static assets and user Worker", async ({
expect,
}) => {
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
main = "src/index.ts"
compatibility_date = "2023-01-01"
[assets]
directory = "public"
binding = "ASSETS"
html_handling = "none"
not_found_handling = "404-page"
`,
"src/index.ts": dedent`
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname === "/binding") {
return await env.ASSETS.fetch(new URL("index.html", request.url));
} else if (url.pathname === "/try-404") {
return await env.ASSETS.fetch(request.url);
}
return new Response("Hello World!")
}
}`,
...generateInitialAssets(workerName),
});
// create a dispatch namespace && verify output
let output = await helper.run(
`wrangler dispatch-namespace create ${dispatchNamespaceName}`
);
let normalizedStdout = normalizeOutput(output.stdout);
expect(normalizedStdout).toContain(
`Created dispatch namespace "tmp-e2e-dispatch-00000000-0000-0000-0000-000000000000" with ID "00000000-0000-0000-0000-000000000000"`
);
// upload user Worker to the dispatch namespace && verify output
output = await helper.run(
`wrangler deploy --dispatch-namespace ${dispatchNamespaceName}`
);
validateAssetUploadLogs(expect, output, [
"/404.html",
"/index.html",
"/[boop].html",
]);
// deploy dispatch Worker && verify output
output = await helper.run(
`wrangler deploy -c dispatch-worker/wrangler.toml`
);
normalizedStdout = normalizeOutput(output.stdout);
expect(normalizedStdout).toEqual(`Total Upload: xx KiB / gzip: xx KiB
Your Worker has access to the following bindings:
Binding Resource
env.DISPATCH (tmp-e2e-dispatch-00000000-0000-0000-0000-000000000000) Dispatch Namespace
Uploaded tmp-e2e-worker-00000000-0000-0000-0000-000000000000 (TIMINGS)
Deployed tmp-e2e-worker-00000000-0000-0000-0000-000000000000 triggers (TIMINGS)
https://tmp-e2e-worker-00000000-0000-0000-0000-000000000000.SUBDOMAIN.workers.dev
Current Version ID: 00000000-0000-0000-0000-000000000000`);
const deployedUrl = getDeployedUrl(output);
const testCases: AssetTestCase[] = [
// because html handling has now been set to "none", only exact matches will be served
{
path: "/index.html",
content: "<h1>index.html</h1>",
},
// 404s should fall through to the user worker, and "/" is not an exact match
// so we should expect the UW response
{ path: "/", content: "Hello World!" },
{
path: "/binding",
content: "<h1>index.html</h1>",
},
{
path: "/worker",
content: "Hello World!",
},
];
await checkAssets(expect, testCases, deployedUrl);
// unlike before, not_found_handling has been set to "404-page"
// instead of the default "none"
// note that with a user Worker, the request must be passed back to
// the asset worker via the ASSET binding in order to return the 404
// page
const { text } = await retry(
// Retry while the status isn't 404 OR the content hasn't propagated yet.
// Before assets are live the platform may return its own 404 page (status 200)
// instead of the user's 404.html asset.
(s) => s.status !== 404 || !s.text.includes("<h1>404.html</h1>"),
async () => {
const r = await fetch(new URL("/try-404", deployedUrl));
const temp = { text: await r.text(), status: r.status };
return temp;
}
);
expect(text).toContain("<h1>404.html</h1>");
});
it("runs the user Worker ahead of matching assets when run_worker_first = true", async ({
expect,
}) => {
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
main = "src/index.ts"
compatibility_date = "2023-01-01"
[assets]
directory = "public"
binding = "ASSETS"
html_handling = "none"
not_found_handling = "404-page"
run_worker_first = true
`,
"src/index.ts": dedent`
export default {
async fetch(request, env) {
return new Response("Hello World from User Worker!")
}
}`,
...generateInitialAssets(workerName),
});
// create a dispatch namespace && verify output
let output = await helper.run(
`wrangler dispatch-namespace create ${dispatchNamespaceName}`
);
let normalizedStdout = normalizeOutput(output.stdout);
expect(normalizedStdout).toContain(
`Created dispatch namespace "tmp-e2e-dispatch-00000000-0000-0000-0000-000000000000" with ID "00000000-0000-0000-0000-000000000000"`
);
// upload user Worker to the dispatch namespace && verify output
output = await helper.run(
`wrangler deploy --dispatch-namespace ${dispatchNamespaceName}`
);
validateAssetUploadLogs(expect, output, [
"/404.html",
"/index.html",
"/[boop].html",
]);
// deploy dispatch Worker && verify output
output = await helper.run(
`wrangler deploy -c dispatch-worker/wrangler.toml`
);
normalizedStdout = normalizeOutput(output.stdout);
expect(normalizedStdout).toEqual(`Total Upload: xx KiB / gzip: xx KiB
Your Worker has access to the following bindings:
Binding Resource
env.DISPATCH (tmp-e2e-dispatch-00000000-0000-0000-0000-000000000000) Dispatch Namespace
Uploaded tmp-e2e-worker-00000000-0000-0000-0000-000000000000 (TIMINGS)
Deployed tmp-e2e-worker-00000000-0000-0000-0000-000000000000 triggers (TIMINGS)
https://tmp-e2e-worker-00000000-0000-0000-0000-000000000000.SUBDOMAIN.workers.dev
Current Version ID: 00000000-0000-0000-0000-000000000000`);
const deployedUrl = getDeployedUrl(output);
const testCases: AssetTestCase[] = [
{
path: "/index.html",
content: "Hello World from User Worker!",
},
{
path: "/",
content: "Hello World from User Worker!",
},
{
path: "/worker",
content: "Hello World from User Worker!",
},
];
await checkAssets(expect, testCases, deployedUrl);
});
});
});
const skipContainersTest =
!CLOUDFLARE_ACCOUNT_ID || (ci.isCI && process.platform !== "linux");
describe.skipIf(skipContainersTest)("containers", () => {
let helper: WranglerE2ETestHelper;
let workerName: string;
let applicationId: string | undefined;
let deployedUrl: string;
beforeAll(async () => {
helper = new WranglerE2ETestHelper();
workerName = generateResourceName();
await helper.seed({
"wrangler.toml": dedent`
name = "${workerName}"
main = "src/index.ts"
compatibility_date = "2023-01-01"
[durable_objects]
bindings = [
{ name = "MY_DO", class_name = "MyDurableObject" }
]
[[containers]]
name = "e2e-test-${workerName}"
class_name = "MyDurableObject"
image = "./Dockerfile"
max_instances = 1
[[migrations]]
tag = "v1"
new_sqlite_classes = ["MyDurableObject"]
[observability]
enabled = true
`,
"container/index.js": dedent`
const { createServer } = require("http");
const server = createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('hello from container');
});
server.listen(80, () => {
console.log('Server running on port 80');
});
`,
Dockerfile: dedent`
FROM node:18-slim
WORKDIR /app
COPY container/index.js .
CMD ["node", "index.js"]
EXPOSE 80
`,
"src/index.ts": dedent`
export default {
async fetch(req, env) {
const url = new URL(req.url)
if (url.pathname === "/do") {
const id = env.MY_DO.idFromName(url.pathname);
const stub = env.MY_DO.get(id);
try {
return await stub.fetch(req);
} catch (err) {
return new Response("Error fetching from stub: " + err.message, { status: 400 });
}
}
return new Response("not found", { status: 404 });
},
};
export class MyDurableObject implements DurableObject {
constructor(ctx) {
this.ctx = ctx;
}
async fetch(_request: Request) {
if (!this.ctx.container) {
return new Response('this.ctx.container not defined', { status: 500 });
}
if (!this.ctx.container.running) {
this.ctx.container.start();
this.monitor = this.ctx.container.monitor();
}
return this.ctx.container.getTcpPort(80).fetch(new Request("http://foo"));
}
}`,
});
});
afterAll(async () => {
// clean up user Worker after each test
const deleteWorker = helper.bestEffortRun(`wrangler delete`);
const deleteContainer = helper.bestEffortRun(
`wrangler containers delete ${applicationId}`
);
await Promise.allSettled([deleteWorker, deleteContainer]);
}, 30_000);
it(
"can deploy a digest-pinned Dockerfile container and skip unchanged rebuilds",
{ timeout: 60 * 2 * 1000 },
async ({ expect }) => {
const outputOne = await helper.run(`wrangler deploy`);
deployedUrl = getDeployedUrl(outputOne);
const matchApplicationId = outputOne.stdout.match(
/([(]Application ID: (?<applicationId>.+?)[)])/
);
applicationId = matchApplicationId?.groups?.applicationId;
assert(matchApplicationId?.groups);
assert(applicationId);
assert(CLOUDFLARE_ACCOUNT_ID);
const containerInfo = await helper.run(
`wrangler containers info ${applicationId}`
);
const application = JSON.parse(containerInfo.stdout) as {
configuration?: {
image?: unknown;
};
};
const image = application.configuration?.image;
assert(typeof image === "string");
const expectedImagePrefix = `registry.cloudflare.com/${CLOUDFLARE_ACCOUNT_ID}/e2e-test-${workerName}@sha256:`;
expect(image.startsWith(expectedImagePrefix)).toBe(true);

