@devries-cameron20 / t3code-1 / commits / 44a7cb1057
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(relay): tunnel recovery no longer drives the Cloudflare API into rate limits (#22059)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 19, 2026 at 20:51 UTC 44a7cb1057b6ef4aedc89760575c2e506669f8a5
16 files changed +2468 -166
infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/migration.sql new
+4
@@ -0,0 +1,4 @@
1 +CREATE TABLE "relay_upstream_api_pauses" (
2 + "api" varchar(64) PRIMARY KEY,
3 + "paused_until_ms" bigint NOT NULL
4 +);
infra/relay/migrations/postgres/20261020013101_upstream_api_pauses/snapshot.json new
+1634
@@ -0,0 +1,1634 @@
1 +{
2 + "version": "8",
3 + "dialect": "postgres",
4 + "id": "f8594baa-6f4a-4a0d-a7f0-0aa717dfe785",
5 + "prevIds": ["7b10c420-1566-4dfc-8e9c-c73efa561d3b"],
6 + "ddl": [
7 + {
8 + "isRlsEnabled": false,
9 + "name": "relay_agent_activity_rows",
10 + "entityType": "tables",
11 + "schema": "public"
12 + },
13 + {
14 + "isRlsEnabled": false,
15 + "name": "relay_delivery_attempts",
16 + "entityType": "tables",
17 + "schema": "public"
18 + },
19 + {
20 + "isRlsEnabled": false,
21 + "name": "relay_dpop_proofs",
22 + "entityType": "tables",
23 + "schema": "public"
24 + },
25 + {
26 + "isRlsEnabled": false,
27 + "name": "relay_environment_credentials",
28 + "entityType": "tables",
29 + "schema": "public"
30 + },
31 + {
32 + "isRlsEnabled": false,
33 + "name": "relay_environment_links",
34 + "entityType": "tables",
35 + "schema": "public"
36 + },
37 + {
38 + "isRlsEnabled": false,
39 + "name": "relay_live_activities",
40 + "entityType": "tables",
41 + "schema": "public"
42 + },
43 + {
44 + "isRlsEnabled": false,
45 + "name": "relay_managed_endpoint_allocations",
46 + "entityType": "tables",
47 + "schema": "public"
48 + },
49 + {
50 + "isRlsEnabled": false,
51 + "name": "relay_managed_tunnel_limits",
52 + "entityType": "tables",
53 + "schema": "public"
54 + },
55 + {
56 + "isRlsEnabled": false,
57 + "name": "relay_mobile_devices",
58 + "entityType": "tables",
59 + "schema": "public"
60 + },
61 + {
62 + "isRlsEnabled": false,
63 + "name": "relay_upstream_api_pauses",
64 + "entityType": "tables",
65 + "schema": "public"
66 + },
67 + {
68 + "type": "varchar(191)",
69 + "typeSchema": null,
70 + "notNull": true,
71 + "dimensions": 0,
72 + "default": null,
73 + "generated": null,
74 + "identity": null,
75 + "name": "environment_id",
76 + "entityType": "columns",
77 + "schema": "public",
78 + "table": "relay_agent_activity_rows"
79 + },
80 + {
81 + "type": "text",
82 + "typeSchema": null,
83 + "notNull": true,
84 + "dimensions": 0,
85 + "default": null,
86 + "generated": null,
87 + "identity": null,
88 + "name": "environment_public_key",
89 + "entityType": "columns",
90 + "schema": "public",
91 + "table": "relay_agent_activity_rows"
92 + },
93 + {
94 + "type": "varchar(512)",
95 + "typeSchema": null,
96 + "notNull": true,
97 + "dimensions": 0,
98 + "default": null,
99 + "generated": null,
100 + "identity": null,
101 + "name": "thread_id",
102 + "entityType": "columns",
103 + "schema": "public",
104 + "table": "relay_agent_activity_rows"
105 + },
106 + {
107 + "type": "jsonb",
108 + "typeSchema": null,
109 + "notNull": true,
110 + "dimensions": 0,
111 + "default": null,
112 + "generated": null,
113 + "identity": null,
114 + "name": "state_json",
115 + "entityType": "columns",
116 + "schema": "public",
117 + "table": "relay_agent_activity_rows"
118 + },
119 + {
120 + "type": "varchar(64)",
121 + "typeSchema": null,
122 + "notNull": true,
123 + "dimensions": 0,
124 + "default": null,
125 + "generated": null,
126 + "identity": null,
127 + "name": "updated_at",
128 + "entityType": "columns",
129 + "schema": "public",
130 + "table": "relay_agent_activity_rows"
131 + },
132 + {
133 + "type": "varchar(64)",
134 + "typeSchema": null,
135 + "notNull": true,
136 + "dimensions": 0,
137 + "default": null,
138 + "generated": null,
139 + "identity": null,
140 + "name": "created_at",
141 + "entityType": "columns",
142 + "schema": "public",
143 + "table": "relay_agent_activity_rows"
144 + },
145 + {
146 + "type": "varchar(36)",
147 + "typeSchema": null,
148 + "notNull": true,
149 + "dimensions": 0,
150 + "default": null,
151 + "generated": null,
152 + "identity": null,
153 + "name": "id",
154 + "entityType": "columns",
155 + "schema": "public",
156 + "table": "relay_delivery_attempts"
157 + },
158 + {
159 + "type": "varchar(64)",
160 + "typeSchema": null,
161 + "notNull": true,
162 + "dimensions": 0,
163 + "default": null,
164 + "generated": null,
165 + "identity": null,
166 + "name": "created_at",
167 + "entityType": "columns",
168 + "schema": "public",
169 + "table": "relay_delivery_attempts"
170 + },
171 + {
172 + "type": "varchar(255)",
173 + "typeSchema": null,
174 + "notNull": false,
175 + "dimensions": 0,
176 + "default": null,
177 + "generated": null,
178 + "identity": null,
179 + "name": "user_id",
180 + "entityType": "columns",
181 + "schema": "public",
182 + "table": "relay_delivery_attempts"
183 + },
184 + {
185 + "type": "varchar(191)",
186 + "typeSchema": null,
187 + "notNull": false,
188 + "dimensions": 0,
189 + "default": null,
190 + "generated": null,
191 + "identity": null,
192 + "name": "environment_id",
193 + "entityType": "columns",
194 + "schema": "public",
195 + "table": "relay_delivery_attempts"
196 + },
197 + {
198 + "type": "varchar(512)",
199 + "typeSchema": null,
200 + "notNull": false,
201 + "dimensions": 0,
202 + "default": null,
203 + "generated": null,
204 + "identity": null,
205 + "name": "thread_id",
206 + "entityType": "columns",
207 + "schema": "public",
208 + "table": "relay_delivery_attempts"
209 + },
210 + {
211 + "type": "varchar(255)",
212 + "typeSchema": null,
213 + "notNull": false,
214 + "dimensions": 0,
215 + "default": null,
216 + "generated": null,
217 + "identity": null,
218 + "name": "device_id",
219 + "entityType": "columns",
220 + "schema": "public",
221 + "table": "relay_delivery_attempts"
222 + },
223 + {
224 + "type": "varchar(64)",
225 + "typeSchema": null,
226 + "notNull": true,
227 + "dimensions": 0,
228 + "default": null,
229 + "generated": null,
230 + "identity": null,
231 + "name": "kind",
232 + "entityType": "columns",
233 + "schema": "public",
234 + "table": "relay_delivery_attempts"
235 + },
236 + {
237 + "type": "varchar(64)",
238 + "typeSchema": null,
239 + "notNull": false,
240 + "dimensions": 0,
241 + "default": null,
242 + "generated": null,
243 + "identity": null,
244 + "name": "source_job_id",
245 + "entityType": "columns",
246 + "schema": "public",
247 + "table": "relay_delivery_attempts"
248 + },
249 + {
250 + "type": "varchar(16)",
251 + "typeSchema": null,
252 + "notNull": false,
253 + "dimensions": 0,
254 + "default": null,
255 + "generated": null,
256 + "identity": null,
257 + "name": "token_suffix",
258 + "entityType": "columns",
259 + "schema": "public",
260 + "table": "relay_delivery_attempts"
261 + },
262 + {
263 + "type": "integer",
264 + "typeSchema": null,
265 + "notNull": false,
266 + "dimensions": 0,
267 + "default": null,
268 + "generated": null,
269 + "identity": null,
270 + "name": "apns_status",
271 + "entityType": "columns",
272 + "schema": "public",
273 + "table": "relay_delivery_attempts"
274 + },
275 + {
276 + "type": "text",
277 + "typeSchema": null,
278 + "notNull": false,
279 + "dimensions": 0,
280 + "default": null,
281 + "generated": null,
282 + "identity": null,
283 + "name": "apns_reason",
284 + "entityType": "columns",
285 + "schema": "public",
286 + "table": "relay_delivery_attempts"
287 + },
288 + {
289 + "type": "varchar(128)",
290 + "typeSchema": null,
291 + "notNull": false,
292 + "dimensions": 0,
293 + "default": null,
294 + "generated": null,
295 + "identity": null,
296 + "name": "apns_id",
297 + "entityType": "columns",
298 + "schema": "public",
299 + "table": "relay_delivery_attempts"
300 + },
301 + {
302 + "type": "text",
303 + "typeSchema": null,
304 + "notNull": false,
305 + "dimensions": 0,
306 + "default": null,
307 + "generated": null,
308 + "identity": null,
309 + "name": "transport_error",
310 + "entityType": "columns",
311 + "schema": "public",
312 + "table": "relay_delivery_attempts"
313 + },
314 + {
315 + "type": "varchar(128)",
316 + "typeSchema": null,
317 + "notNull": true,
318 + "dimensions": 0,
319 + "default": null,
320 + "generated": null,
321 + "identity": null,
322 + "name": "thumbprint",
323 + "entityType": "columns",
324 + "schema": "public",
325 + "table": "relay_dpop_proofs"
326 + },
327 + {
328 + "type": "varchar(255)",
329 + "typeSchema": null,
330 + "notNull": true,
331 + "dimensions": 0,
332 + "default": null,
333 + "generated": null,
334 + "identity": null,
335 + "name": "jti",
336 + "entityType": "columns",
337 + "schema": "public",
338 + "table": "relay_dpop_proofs"
339 + },
340 + {
341 + "type": "integer",
342 + "typeSchema": null,
343 + "notNull": true,
344 + "dimensions": 0,
345 + "default": null,
346 + "generated": null,
347 + "identity": null,
348 + "name": "iat",
349 + "entityType": "columns",
350 + "schema": "public",
351 + "table": "relay_dpop_proofs"
352 + },
353 + {
354 + "type": "varchar(64)",
355 + "typeSchema": null,
356 + "notNull": true,
357 + "dimensions": 0,
358 + "default": null,
359 + "generated": null,
360 + "identity": null,
361 + "name": "expires_at",
362 + "entityType": "columns",
363 + "schema": "public",
364 + "table": "relay_dpop_proofs"
365 + },
366 + {
367 + "type": "varchar(64)",
368 + "typeSchema": null,
369 + "notNull": true,
370 + "dimensions": 0,
371 + "default": null,
372 + "generated": null,
373 + "identity": null,
374 + "name": "created_at",
375 + "entityType": "columns",
376 + "schema": "public",
377 + "table": "relay_dpop_proofs"
378 + },
379 + {
380 + "type": "varchar(64)",
381 + "typeSchema": null,
382 + "notNull": true,
383 + "dimensions": 0,
384 + "default": null,
385 + "generated": null,
386 + "identity": null,
387 + "name": "credential_id",
388 + "entityType": "columns",
389 + "schema": "public",
390 + "table": "relay_environment_credentials"
391 + },
392 + {
393 + "type": "varchar(191)",
394 + "typeSchema": null,
395 + "notNull": true,
396 + "dimensions": 0,
397 + "default": null,
398 + "generated": null,
399 + "identity": null,
400 + "name": "environment_id",
401 + "entityType": "columns",
402 + "schema": "public",
403 + "table": "relay_environment_credentials"
404 + },
405 + {
406 + "type": "text",
407 + "typeSchema": null,
408 + "notNull": true,
409 + "dimensions": 0,
410 + "default": null,
411 + "generated": null,
412 + "identity": null,
413 + "name": "environment_public_key",
414 + "entityType": "columns",
415 + "schema": "public",
416 + "table": "relay_environment_credentials"
417 + },
418 + {
419 + "type": "varchar(191)",
420 + "typeSchema": null,
421 + "notNull": true,
422 + "dimensions": 0,
423 + "default": null,
424 + "generated": null,
425 + "identity": null,
426 + "name": "credential_hash",
427 + "entityType": "columns",
428 + "schema": "public",
429 + "table": "relay_environment_credentials"
430 + },
431 + {
432 + "type": "varchar(64)",
433 + "typeSchema": null,
434 + "notNull": false,
435 + "dimensions": 0,
436 + "default": null,
437 + "generated": null,
438 + "identity": null,
439 + "name": "revoked_at",
440 + "entityType": "columns",
441 + "schema": "public",
442 + "table": "relay_environment_credentials"
443 + },
444 + {
445 + "type": "varchar(64)",
446 + "typeSchema": null,
447 + "notNull": true,
448 + "dimensions": 0,
449 + "default": null,
450 + "generated": null,
451 + "identity": null,
452 + "name": "created_at",
453 + "entityType": "columns",
454 + "schema": "public",
455 + "table": "relay_environment_credentials"
456 + },
457 + {
458 + "type": "varchar(64)",
459 + "typeSchema": null,
460 + "notNull": true,
461 + "dimensions": 0,
462 + "default": null,
463 + "generated": null,
464 + "identity": null,
465 + "name": "updated_at",
466 + "entityType": "columns",
467 + "schema": "public",
468 + "table": "relay_environment_credentials"
469 + },
470 + {
471 + "type": "varchar(191)",
472 + "typeSchema": null,
473 + "notNull": true,
474 + "dimensions": 0,
475 + "default": null,
476 + "generated": null,
477 + "identity": null,
478 + "name": "user_id",
479 + "entityType": "columns",
480 + "schema": "public",
481 + "table": "relay_environment_links"
482 + },
483 + {
484 + "type": "varchar(191)",
485 + "typeSchema": null,
486 + "notNull": true,
487 + "dimensions": 0,
488 + "default": null,
489 + "generated": null,
490 + "identity": null,
491 + "name": "environment_id",
492 + "entityType": "columns",
493 + "schema": "public",
494 + "table": "relay_environment_links"
495 + },
496 + {
497 + "type": "text",
498 + "typeSchema": null,
499 + "notNull": true,
500 + "dimensions": 0,
501 + "default": "'T3 Environment'",
502 + "generated": null,
503 + "identity": null,
504 + "name": "environment_label",
505 + "entityType": "columns",
506 + "schema": "public",
507 + "table": "relay_environment_links"
508 + },
509 + {
510 + "type": "text",
511 + "typeSchema": null,
512 + "notNull": true,
513 + "dimensions": 0,
514 + "default": null,
515 + "generated": null,
516 + "identity": null,
517 + "name": "environment_public_key",
518 + "entityType": "columns",
519 + "schema": "public",
520 + "table": "relay_environment_links"
521 + },
522 + {
523 + "type": "text",
524 + "typeSchema": null,
525 + "notNull": true,
526 + "dimensions": 0,
527 + "default": null,
528 + "generated": null,
529 + "identity": null,
530 + "name": "endpoint_http_base_url",
531 + "entityType": "columns",
532 + "schema": "public",
533 + "table": "relay_environment_links"
534 + },
535 + {
536 + "type": "text",
537 + "typeSchema": null,
538 + "notNull": true,
539 + "dimensions": 0,
540 + "default": null,
541 + "generated": null,
542 + "identity": null,
543 + "name": "endpoint_ws_base_url",
544 + "entityType": "columns",
545 + "schema": "public",
546 + "table": "relay_environment_links"
547 + },
548 + {
549 + "type": "varchar(32)",
550 + "typeSchema": null,
551 + "notNull": true,
552 + "dimensions": 0,
553 + "default": null,
554 + "generated": null,
555 + "identity": null,
556 + "name": "endpoint_provider_kind",
557 + "entityType": "columns",
558 + "schema": "public",
559 + "table": "relay_environment_links"
560 + },
561 + {
562 + "type": "boolean",
563 + "typeSchema": null,
564 + "notNull": true,
565 + "dimensions": 0,
566 + "default": "true",
567 + "generated": null,
568 + "identity": null,
569 + "name": "notifications_enabled",
570 + "entityType": "columns",
571 + "schema": "public",
572 + "table": "relay_environment_links"
573 + },
574 + {
575 + "type": "boolean",
576 + "typeSchema": null,
577 + "notNull": true,
578 + "dimensions": 0,
579 + "default": "true",
580 + "generated": null,
581 + "identity": null,
582 + "name": "live_activities_enabled",
583 + "entityType": "columns",
584 + "schema": "public",
585 + "table": "relay_environment_links"
586 + },
587 + {
588 + "type": "boolean",
589 + "typeSchema": null,
590 + "notNull": true,
591 + "dimensions": 0,
592 + "default": "false",
593 + "generated": null,
594 + "identity": null,
595 + "name": "managed_tunnels_enabled",
596 + "entityType": "columns",
597 + "schema": "public",
598 + "table": "relay_environment_links"
599 + },
600 + {
601 + "type": "boolean",
602 + "typeSchema": null,
603 + "notNull": true,
604 + "dimensions": 0,
605 + "default": "false",
606 + "generated": null,
607 + "identity": null,
608 + "name": "hold_webhooks_while_offline",
609 + "entityType": "columns",
610 + "schema": "public",
611 + "table": "relay_environment_links"
612 + },
613 + {
614 + "type": "varchar(191)",
615 + "typeSchema": null,
616 + "notNull": false,
617 + "dimensions": 0,
618 + "default": null,
619 + "generated": null,
620 + "identity": null,
621 + "name": "created_by_device_id",
622 + "entityType": "columns",
623 + "schema": "public",
624 + "table": "relay_environment_links"
625 + },
626 + {
627 + "type": "varchar(64)",
628 + "typeSchema": null,
629 + "notNull": false,
630 + "dimensions": 0,
631 + "default": null,
632 + "generated": null,
633 + "identity": null,
634 + "name": "revoked_at",
635 + "entityType": "columns",
636 + "schema": "public",
637 + "table": "relay_environment_links"
638 + },
639 + {
640 + "type": "varchar(64)",
641 + "typeSchema": null,
642 + "notNull": true,
643 + "dimensions": 0,
644 + "default": null,
645 + "generated": null,
646 + "identity": null,
647 + "name": "created_at",
648 + "entityType": "columns",
649 + "schema": "public",
650 + "table": "relay_environment_links"
651 + },
652 + {
653 + "type": "varchar(64)",
654 + "typeSchema": null,
655 + "notNull": true,
656 + "dimensions": 0,
657 + "default": null,
658 + "generated": null,
659 + "identity": null,
660 + "name": "updated_at",
661 + "entityType": "columns",
662 + "schema": "public",
663 + "table": "relay_environment_links"
664 + },
665 + {
666 + "type": "varchar(255)",
667 + "typeSchema": null,
668 + "notNull": true,
669 + "dimensions": 0,
670 + "default": null,
671 + "generated": null,
672 + "identity": null,
673 + "name": "user_id",
674 + "entityType": "columns",
675 + "schema": "public",
676 + "table": "relay_live_activities"
677 + },
678 + {
679 + "type": "varchar(255)",
680 + "typeSchema": null,
681 + "notNull": true,
682 + "dimensions": 0,
683 + "default": null,
684 + "generated": null,
685 + "identity": null,
686 + "name": "device_id",
687 + "entityType": "columns",
688 + "schema": "public",
689 + "table": "relay_live_activities"
690 + },
691 + {
692 + "type": "text",
693 + "typeSchema": null,
694 + "notNull": false,
695 + "dimensions": 0,
696 + "default": null,
697 + "generated": null,
698 + "identity": null,
699 + "name": "activity_push_token",
700 + "entityType": "columns",
701 + "schema": "public",
702 + "table": "relay_live_activities"
703 + },
704 + {
705 + "type": "varchar(64)",
706 + "typeSchema": null,
707 + "notNull": false,
708 + "dimensions": 0,
709 + "default": null,
710 + "generated": null,
711 + "identity": null,
712 + "name": "remote_start_queued_at",
713 + "entityType": "columns",
714 + "schema": "public",
715 + "table": "relay_live_activities"
716 + },
717 + {
718 + "type": "varchar(64)",
719 + "typeSchema": null,
720 + "notNull": false,
721 + "dimensions": 0,
722 + "default": null,
723 + "generated": null,
724 + "identity": null,
725 + "name": "remote_started_at",
726 + "entityType": "columns",
727 + "schema": "public",
728 + "table": "relay_live_activities"
729 + },
730 + {
731 + "type": "varchar(64)",
732 + "typeSchema": null,
733 + "notNull": false,
734 + "dimensions": 0,
735 + "default": null,
736 + "generated": null,
737 + "identity": null,
738 + "name": "ended_at",
739 + "entityType": "columns",
740 + "schema": "public",
741 + "table": "relay_live_activities"
742 + },
743 + {
744 + "type": "jsonb",
745 + "typeSchema": null,
746 + "notNull": false,
747 + "dimensions": 0,
748 + "default": null,
749 + "generated": null,
750 + "identity": null,
751 + "name": "last_aggregate_json",
752 + "entityType": "columns",
753 + "schema": "public",
754 + "table": "relay_live_activities"
755 + },
756 + {
757 + "type": "varchar(64)",
758 + "typeSchema": null,
759 + "notNull": false,
760 + "dimensions": 0,
761 + "default": null,
762 + "generated": null,
763 + "identity": null,
764 + "name": "last_live_activity_delivery_at",
765 + "entityType": "columns",
766 + "schema": "public",
767 + "table": "relay_live_activities"
768 + },
769 + {
770 + "type": "varchar(64)",
771 + "typeSchema": null,
772 + "notNull": true,
773 + "dimensions": 0,
774 + "default": null,
775 + "generated": null,
776 + "identity": null,
777 + "name": "created_at",
778 + "entityType": "columns",
779 + "schema": "public",
780 + "table": "relay_live_activities"
781 + },
782 + {
783 + "type": "varchar(64)",
784 + "typeSchema": null,
785 + "notNull": true,
786 + "dimensions": 0,
787 + "default": null,
788 + "generated": null,
789 + "identity": null,
790 + "name": "updated_at",
791 + "entityType": "columns",
792 + "schema": "public",
793 + "table": "relay_live_activities"
794 + },
795 + {
796 + "type": "varchar(191)",
797 + "typeSchema": null,
798 + "notNull": true,
799 + "dimensions": 0,
800 + "default": null,
801 + "generated": null,
802 + "identity": null,
803 + "name": "user_id",
804 + "entityType": "columns",
805 + "schema": "public",
806 + "table": "relay_managed_endpoint_allocations"
807 + },
808 + {
809 + "type": "varchar(191)",
810 + "typeSchema": null,
811 + "notNull": true,
812 + "dimensions": 0,
813 + "default": null,
814 + "generated": null,
815 + "identity": null,
816 + "name": "environment_id",
817 + "entityType": "columns",
818 + "schema": "public",
819 + "table": "relay_managed_endpoint_allocations"
820 + },
821 + {
822 + "type": "text",
823 + "typeSchema": null,
824 + "notNull": true,
825 + "dimensions": 0,
826 + "default": null,
827 + "generated": null,
828 + "identity": null,
829 + "name": "hostname",
830 + "entityType": "columns",
831 + "schema": "public",
832 + "table": "relay_managed_endpoint_allocations"
833 + },
834 + {
835 + "type": "varchar(191)",
836 + "typeSchema": null,
837 + "notNull": false,
838 + "dimensions": 0,
839 + "default": null,
840 + "generated": null,
841 + "identity": null,
842 + "name": "tunnel_id",
843 + "entityType": "columns",
844 + "schema": "public",
845 + "table": "relay_managed_endpoint_allocations"
846 + },
847 + {
848 + "type": "text",
849 + "typeSchema": null,
850 + "notNull": true,
851 + "dimensions": 0,
852 + "default": null,
853 + "generated": null,
854 + "identity": null,
855 + "name": "tunnel_name",
856 + "entityType": "columns",
857 + "schema": "public",
858 + "table": "relay_managed_endpoint_allocations"
859 + },
860 + {
861 + "type": "varchar(191)",
862 + "typeSchema": null,
863 + "notNull": false,
864 + "dimensions": 0,
865 + "default": null,
866 + "generated": null,
867 + "identity": null,
868 + "name": "dns_record_id",
869 + "entityType": "columns",
870 + "schema": "public",
871 + "table": "relay_managed_endpoint_allocations"
872 + },
873 + {
874 + "type": "varchar(64)",
875 + "typeSchema": null,
876 + "notNull": false,
877 + "dimensions": 0,
878 + "default": null,
879 + "generated": null,
880 + "identity": null,
881 + "name": "ready_at",
882 + "entityType": "columns",
883 + "schema": "public",
884 + "table": "relay_managed_endpoint_allocations"
885 + },
886 + {
887 + "type": "varchar(64)",
888 + "typeSchema": null,
889 + "notNull": false,
890 + "dimensions": 0,
891 + "default": null,
892 + "generated": null,
893 + "identity": null,
894 + "name": "recovery_enabled_at",
895 + "entityType": "columns",
896 + "schema": "public",
897 + "table": "relay_managed_endpoint_allocations"
898 + },
899 + {
900 + "type": "text",
901 + "typeSchema": null,
902 + "notNull": false,
903 + "dimensions": 0,
904 + "default": null,
905 + "generated": null,
906 + "identity": null,
907 + "name": "recovery_environment_public_key",
908 + "entityType": "columns",
909 + "schema": "public",
910 + "table": "relay_managed_endpoint_allocations"
911 + },
912 + {
913 + "type": "varchar(64)",
914 + "typeSchema": null,
915 + "notNull": false,
916 + "dimensions": 0,
917 + "default": null,
918 + "generated": null,
919 + "identity": null,
920 + "name": "tunnel_released_at",
921 + "entityType": "columns",
922 + "schema": "public",
923 + "table": "relay_managed_endpoint_allocations"
924 + },
925 + {
926 + "type": "jsonb",
927 + "typeSchema": null,
928 + "notNull": false,
929 + "dimensions": 0,
930 + "default": null,
931 + "generated": null,
932 + "identity": null,
933 + "name": "origin",
934 + "entityType": "columns",
935 + "schema": "public",
936 + "table": "relay_managed_endpoint_allocations"
937 + },
938 + {
939 + "type": "integer",
940 + "typeSchema": null,
941 + "notNull": true,
942 + "dimensions": 0,
943 + "default": "0",
944 + "generated": null,
945 + "identity": null,
946 + "name": "generation",
947 + "entityType": "columns",
948 + "schema": "public",
949 + "table": "relay_managed_endpoint_allocations"
950 + },
951 + {
952 + "type": "varchar(64)",
953 + "typeSchema": null,
954 + "notNull": true,
955 + "dimensions": 0,
956 + "default": null,
957 + "generated": null,
958 + "identity": null,
959 + "name": "created_at",
960 + "entityType": "columns",
961 + "schema": "public",
962 + "table": "relay_managed_endpoint_allocations"
963 + },
964 + {
965 + "type": "varchar(64)",
966 + "typeSchema": null,
967 + "notNull": true,
968 + "dimensions": 0,
969 + "default": null,
970 + "generated": null,
971 + "identity": null,
972 + "name": "updated_at",
973 + "entityType": "columns",
974 + "schema": "public",
975 + "table": "relay_managed_endpoint_allocations"
976 + },
977 + {
978 + "type": "varchar(191)",
979 + "typeSchema": null,
980 + "notNull": true,
981 + "dimensions": 0,
982 + "default": null,
983 + "generated": null,
984 + "identity": null,
985 + "name": "user_id",
986 + "entityType": "columns",
987 + "schema": "public",
988 + "table": "relay_managed_tunnel_limits"
989 + },
990 + {
991 + "type": "integer",
992 + "typeSchema": null,
993 + "notNull": true,
994 + "dimensions": 0,
995 + "default": null,
996 + "generated": null,
997 + "identity": null,
998 + "name": "max_tunnels",
999 + "entityType": "columns",
1000 + "schema": "public",
1001 + "table": "relay_managed_tunnel_limits"
1002 + },
1003 + {
1004 + "type": "varchar(64)",
1005 + "typeSchema": null,
1006 + "notNull": true,
1007 + "dimensions": 0,
1008 + "default": null,
1009 + "generated": null,
1010 + "identity": null,
1011 + "name": "created_at",
1012 + "entityType": "columns",
1013 + "schema": "public",
1014 + "table": "relay_managed_tunnel_limits"
1015 + },
1016 + {
1017 + "type": "varchar(64)",
1018 + "typeSchema": null,
1019 + "notNull": true,
1020 + "dimensions": 0,
1021 + "default": null,
1022 + "generated": null,
1023 + "identity": null,
1024 + "name": "updated_at",
1025 + "entityType": "columns",
1026 + "schema": "public",
1027 + "table": "relay_managed_tunnel_limits"
1028 + },
1029 + {
1030 + "type": "varchar(255)",
1031 + "typeSchema": null,
1032 + "notNull": true,
1033 + "dimensions": 0,
1034 + "default": null,
1035 + "generated": null,
1036 + "identity": null,
1037 + "name": "user_id",
1038 + "entityType": "columns",
1039 + "schema": "public",
1040 + "table": "relay_mobile_devices"
1041 + },
1042 + {
1043 + "type": "varchar(255)",
1044 + "typeSchema": null,
1045 + "notNull": true,
1046 + "dimensions": 0,
1047 + "default": null,
1048 + "generated": null,
1049 + "identity": null,
1050 + "name": "device_id",
1051 + "entityType": "columns",
1052 + "schema": "public",
1053 + "table": "relay_mobile_devices"
1054 + },
1055 + {
1056 + "type": "text",
1057 + "typeSchema": null,
1058 + "notNull": true,
1059 + "dimensions": 0,
1060 + "default": "'iOS device'",
1061 + "generated": null,
1062 + "identity": null,
1063 + "name": "label",
1064 + "entityType": "columns",
1065 + "schema": "public",
1066 + "table": "relay_mobile_devices"
1067 + },
1068 + {
1069 + "type": "varchar(16)",
1070 + "typeSchema": null,
1071 + "notNull": true,
1072 + "dimensions": 0,
1073 + "default": null,
1074 + "generated": null,
1075 + "identity": null,
1076 + "name": "platform",
1077 + "entityType": "columns",
1078 + "schema": "public",
1079 + "table": "relay_mobile_devices"
1080 + },
1081 + {
1082 + "type": "integer",
1083 + "typeSchema": null,
1084 + "notNull": false,
1085 + "dimensions": 0,
1086 + "default": null,
1087 + "generated": null,
1088 + "identity": null,
1089 + "name": "ios_major_version",
1090 + "entityType": "columns",
1091 + "schema": "public",
1092 + "table": "relay_mobile_devices"
1093 + },
1094 + {
1095 + "type": "integer",
1096 + "typeSchema": null,
1097 + "notNull": false,
1098 + "dimensions": 0,
1099 + "default": null,
1100 + "generated": null,
1101 + "identity": null,
1102 + "name": "android_api_level",
1103 + "entityType": "columns",
1104 + "schema": "public",
1105 + "table": "relay_mobile_devices"
1106 + },
1107 + {
1108 + "type": "varchar(64)",
1109 + "typeSchema": null,
1110 + "notNull": false,
1111 + "dimensions": 0,
1112 + "default": null,
1113 + "generated": null,
1114 + "identity": null,
1115 + "name": "app_version",
1116 + "entityType": "columns",
1117 + "schema": "public",
1118 + "table": "relay_mobile_devices"
1119 + },
1120 + {
1121 + "type": "varchar(255)",
1122 + "typeSchema": null,
1123 + "notNull": false,
1124 + "dimensions": 0,
1125 + "default": null,
1126 + "generated": null,
1127 + "identity": null,
1128 + "name": "bundle_id",
1129 + "entityType": "columns",
1130 + "schema": "public",
1131 + "table": "relay_mobile_devices"
1132 + },
1133 + {
1134 + "type": "varchar(16)",
1135 + "typeSchema": null,
1136 + "notNull": false,
1137 + "dimensions": 0,
1138 + "default": null,
1139 + "generated": null,
1140 + "identity": null,
1141 + "name": "aps_environment",
1142 + "entityType": "columns",
1143 + "schema": "public",
1144 + "table": "relay_mobile_devices"
1145 + },
1146 + {
1147 + "type": "text",
1148 + "typeSchema": null,
1149 + "notNull": false,
1150 + "dimensions": 0,
1151 + "default": null,
1152 + "generated": null,
1153 + "identity": null,
1154 + "name": "push_token",
1155 + "entityType": "columns",
1156 + "schema": "public",
1157 + "table": "relay_mobile_devices"
1158 + },
1159 + {
1160 + "type": "text",
1161 + "typeSchema": null,
1162 + "notNull": false,
1163 + "dimensions": 0,
1164 + "default": null,
1165 + "generated": null,
1166 + "identity": null,
1167 + "name": "push_to_start_token",
1168 + "entityType": "columns",
1169 + "schema": "public",
1170 + "table": "relay_mobile_devices"
1171 + },
1172 + {
1173 + "type": "jsonb",
1174 + "typeSchema": null,
1175 + "notNull": true,
1176 + "dimensions": 0,
1177 + "default": null,
1178 + "generated": null,
1179 + "identity": null,
1180 + "name": "preferences_json",
1181 + "entityType": "columns",
1182 + "schema": "public",
1183 + "table": "relay_mobile_devices"
1184 + },
1185 + {
1186 + "type": "varchar(64)",
1187 + "typeSchema": null,
1188 + "notNull": true,
1189 + "dimensions": 0,
1190 + "default": null,
1191 + "generated": null,
1192 + "identity": null,
1193 + "name": "created_at",
1194 + "entityType": "columns",
1195 + "schema": "public",
1196 + "table": "relay_mobile_devices"
1197 + },
1198 + {
1199 + "type": "varchar(64)",
1200 + "typeSchema": null,
1201 + "notNull": true,
1202 + "dimensions": 0,
1203 + "default": null,
1204 + "generated": null,
1205 + "identity": null,
1206 + "name": "updated_at",
1207 + "entityType": "columns",
1208 + "schema": "public",
1209 + "table": "relay_mobile_devices"
1210 + },
1211 + {
1212 + "type": "varchar(64)",
1213 + "typeSchema": null,
1214 + "notNull": true,
1215 + "dimensions": 0,
1216 + "default": null,
1217 + "generated": null,
1218 + "identity": null,
1219 + "name": "api",
1220 + "entityType": "columns",
1221 + "schema": "public",
1222 + "table": "relay_upstream_api_pauses"
1223 + },
1224 + {
1225 + "type": "bigint",
1226 + "typeSchema": null,
1227 + "notNull": true,
1228 + "dimensions": 0,
1229 + "default": null,
1230 + "generated": null,
1231 + "identity": null,
1232 + "name": "paused_until_ms",
1233 + "entityType": "columns",
1234 + "schema": "public",
1235 + "table": "relay_upstream_api_pauses"
1236 + },
1237 + {
1238 + "nameExplicit": true,
1239 + "columns": [
1240 + {
1241 + "value": "updated_at",
1242 + "isExpression": false,
1243 + "asc": true,
1244 + "nullsFirst": false,
1245 + "opclass": null
1246 + }
1247 + ],
1248 + "isUnique": false,
1249 + "where": null,
1250 + "with": "",
1251 + "method": "btree",
1252 + "concurrently": false,
1253 + "name": "idx_relay_agent_activity_rows_updated",
1254 + "entityType": "indexes",
1255 + "schema": "public",
1256 + "table": "relay_agent_activity_rows"
1257 + },
1258 + {
1259 + "nameExplicit": true,
1260 + "columns": [
1261 + {
1262 + "value": "environment_id",
1263 + "isExpression": false,
1264 + "asc": true,
1265 + "nullsFirst": false,
1266 + "opclass": null
1267 + },
1268 + {
1269 + "value": "thread_id",
1270 + "isExpression": false,
1271 + "asc": true,
1272 + "nullsFirst": false,
1273 + "opclass": null
1274 + },
1275 + {
1276 + "value": "created_at",
1277 + "isExpression": false,
1278 + "asc": true,
1279 + "nullsFirst": false,
1280 + "opclass": null
1281 + }
1282 + ],
1283 + "isUnique": false,
1284 + "where": null,
1285 + "with": "",
1286 + "method": "btree",
1287 + "concurrently": false,
1288 + "name": "idx_relay_delivery_attempts_environment",
1289 + "entityType": "indexes",
1290 + "schema": "public",
1291 + "table": "relay_delivery_attempts"
1292 + },
1293 + {
1294 + "nameExplicit": true,
1295 + "columns": [
1296 + {
1297 + "value": "source_job_id",
1298 + "isExpression": false,
1299 + "asc": true,
1300 + "nullsFirst": false,
1301 + "opclass": null
1302 + }
1303 + ],
1304 + "isUnique": true,
1305 + "where": null,
1306 + "with": "",
1307 + "method": "btree",
1308 + "concurrently": false,
1309 + "name": "idx_relay_delivery_attempts_source_job",
1310 + "entityType": "indexes",
1311 + "schema": "public",
1312 + "table": "relay_delivery_attempts"
1313 + },
1314 + {
1315 + "nameExplicit": true,
1316 + "columns": [
1317 + {
1318 + "value": "expires_at",
1319 + "isExpression": false,
1320 + "asc": true,
1321 + "nullsFirst": false,
1322 + "opclass": null
1323 + }
1324 + ],
1325 + "isUnique": false,
1326 + "where": null,
1327 + "with": "",
1328 + "method": "btree",
1329 + "concurrently": false,
1330 + "name": "idx_relay_dpop_proofs_expires_at",
1331 + "entityType": "indexes",
1332 + "schema": "public",
1333 + "table": "relay_dpop_proofs"
1334 + },
1335 + {
1336 + "nameExplicit": true,
1337 + "columns": [
1338 + {
1339 + "value": "credential_hash",
1340 + "isExpression": false,
1341 + "asc": true,
1342 + "nullsFirst": false,
1343 + "opclass": null
1344 + }
1345 + ],
1346 + "isUnique": true,
1347 + "where": null,
1348 + "with": "",
1349 + "method": "btree",
1350 + "concurrently": false,
1351 + "name": "idx_relay_environment_credentials_hash",
1352 + "entityType": "indexes",
1353 + "schema": "public",
1354 + "table": "relay_environment_credentials"
1355 + },
1356 + {
1357 + "nameExplicit": true,
1358 + "columns": [
1359 + {
1360 + "value": "environment_id",
1361 + "isExpression": false,
1362 + "asc": true,
1363 + "nullsFirst": false,
1364 + "opclass": null
1365 + },
1366 + {
1367 + "value": "revoked_at",
1368 + "isExpression": false,
1369 + "asc": true,
1370 + "nullsFirst": false,
1371 + "opclass": null
1372 + }
1373 + ],
1374 + "isUnique": false,
1375 + "where": null,
1376 + "with": "",
1377 + "method": "btree",
1378 + "concurrently": false,
1379 + "name": "idx_relay_environment_credentials_environment",
1380 + "entityType": "indexes",
1381 + "schema": "public",
1382 + "table": "relay_environment_credentials"
1383 + },
1384 + {
1385 + "nameExplicit": true,
1386 + "columns": [
1387 + {
1388 + "value": "environment_id",
1389 + "isExpression": false,
1390 + "asc": true,
1391 + "nullsFirst": false,
1392 + "opclass": null
1393 + },
1394 + {
1395 + "value": "environment_public_key",
1396 + "isExpression": false,
1397 + "asc": true,
1398 + "nullsFirst": false,
1399 + "opclass": null
1400 + },
1401 + {
1402 + "value": "revoked_at",
1403 + "isExpression": false,
1404 + "asc": true,
1405 + "nullsFirst": false,
1406 + "opclass": null
1407 + }
1408 + ],
1409 + "isUnique": false,
1410 + "where": null,
1411 + "with": "",
1412 + "method": "btree",
1413 + "concurrently": false,
1414 + "name": "idx_relay_environment_credentials_environment_key",
1415 + "entityType": "indexes",
1416 + "schema": "public",
1417 + "table": "relay_environment_credentials"
1418 + },
1419 + {
1420 + "nameExplicit": true,
1421 + "columns": [
1422 + {
1423 + "value": "environment_id",
1424 + "isExpression": false,
1425 + "asc": true,
1426 + "nullsFirst": false,
1427 + "opclass": null
1428 + },
1429 + {
1430 + "value": "revoked_at",
1431 + "isExpression": false,
1432 + "asc": true,
1433 + "nullsFirst": false,
1434 + "opclass": null
1435 + }
1436 + ],
1437 + "isUnique": false,
1438 + "where": null,
1439 + "with": "",
1440 + "method": "btree",
1441 + "concurrently": false,
1442 + "name": "idx_relay_environment_links_environment",
1443 + "entityType": "indexes",
1444 + "schema": "public",
1445 + "table": "relay_environment_links"
1446 + },
1447 + {
1448 + "nameExplicit": true,
1449 + "columns": [
1450 + {
1451 + "value": "activity_push_token",
1452 + "isExpression": false,
1453 + "asc": true,
1454 + "nullsFirst": false,
1455 + "opclass": null
1456 + }
1457 + ],
1458 + "isUnique": true,
1459 + "where": null,
1460 + "with": "",
1461 + "method": "btree",
1462 + "concurrently": false,
1463 + "name": "idx_relay_live_activities_activity_push_token",
1464 + "entityType": "indexes",
1465 + "schema": "public",
1466 + "table": "relay_live_activities"
1467 + },
1468 + {
1469 + "nameExplicit": true,
1470 + "columns": [
1471 + {
1472 + "value": "hostname",
1473 + "isExpression": false,
1474 + "asc": true,
1475 + "nullsFirst": false,
1476 + "opclass": null
1477 + }
1478 + ],
1479 + "isUnique": true,
1480 + "where": null,
1481 + "with": "",
1482 + "method": "btree",
1483 + "concurrently": false,
1484 + "name": "idx_relay_managed_endpoint_allocations_hostname",
1485 + "entityType": "indexes",
1486 + "schema": "public",
1487 + "table": "relay_managed_endpoint_allocations"
1488 + },
1489 + {
1490 + "nameExplicit": true,
1491 + "columns": [
1492 + {
1493 + "value": "tunnel_name",
1494 + "isExpression": false,
1495 + "asc": true,
1496 + "nullsFirst": false,
1497 + "opclass": null
1498 + }
1499 + ],
1500 + "isUnique": true,
1501 + "where": null,
1502 + "with": "",
1503 + "method": "btree",
1504 + "concurrently": false,
1505 + "name": "idx_relay_managed_endpoint_allocations_tunnel_name",
1506 + "entityType": "indexes",
1507 + "schema": "public",
1508 + "table": "relay_managed_endpoint_allocations"
1509 + },
1510 + {
1511 + "nameExplicit": true,
1512 + "columns": [
1513 + {
1514 + "value": "push_token",
1515 + "isExpression": false,
1516 + "asc": true,
1517 + "nullsFirst": false,
1518 + "opclass": null
1519 + }
1520 + ],
1521 + "isUnique": true,
1522 + "where": null,
1523 + "with": "",
1524 + "method": "btree",
1525 + "concurrently": false,
1526 + "name": "idx_relay_mobile_devices_push_token",
1527 + "entityType": "indexes",
1528 + "schema": "public",
1529 + "table": "relay_mobile_devices"
1530 + },
1531 + {
1532 + "nameExplicit": true,
1533 + "columns": [
1534 + {
1535 + "value": "push_to_start_token",
1536 + "isExpression": false,
1537 + "asc": true,
1538 + "nullsFirst": false,
1539 + "opclass": null
1540 + }
1541 + ],
1542 + "isUnique": true,
1543 + "where": null,
1544 + "with": "",
1545 + "method": "btree",
1546 + "concurrently": false,
1547 + "name": "idx_relay_mobile_devices_push_to_start_token",
1548 + "entityType": "indexes",
1549 + "schema": "public",
1550 + "table": "relay_mobile_devices"
1551 + },
1552 + {
1553 + "columns": ["environment_id", "environment_public_key", "thread_id"],
1554 + "nameExplicit": false,
1555 + "name": "relay_agent_activity_rows_pkey",
1556 + "entityType": "pks",
1557 + "schema": "public",
1558 + "table": "relay_agent_activity_rows"
1559 + },
1560 + {
1561 + "columns": ["thumbprint", "jti"],
1562 + "nameExplicit": false,
1563 + "name": "relay_dpop_proofs_pkey",
1564 + "entityType": "pks",
1565 + "schema": "public",
1566 + "table": "relay_dpop_proofs"
1567 + },
1568 + {
1569 + "columns": ["user_id", "environment_id"],
1570 + "nameExplicit": false,
1571 + "name": "relay_environment_links_pkey",
1572 + "entityType": "pks",
1573 + "schema": "public",
1574 + "table": "relay_environment_links"
1575 + },
1576 + {
1577 + "columns": ["user_id", "device_id"],
1578 + "nameExplicit": false,
1579 + "name": "relay_live_activities_pkey",
1580 + "entityType": "pks",
1581 + "schema": "public",
1582 + "table": "relay_live_activities"
1583 + },
1584 + {
1585 + "columns": ["user_id", "environment_id"],
1586 + "nameExplicit": false,
1587 + "name": "relay_managed_endpoint_allocations_pkey",
1588 + "entityType": "pks",
1589 + "schema": "public",
1590 + "table": "relay_managed_endpoint_allocations"
1591 + },
1592 + {
1593 + "columns": ["user_id", "device_id"],
1594 + "nameExplicit": false,
1595 + "name": "relay_mobile_devices_pkey",
1596 + "entityType": "pks",
1597 + "schema": "public",
1598 + "table": "relay_mobile_devices"
1599 + },
1600 + {
1601 + "columns": ["id"],
1602 + "nameExplicit": false,
1603 + "name": "relay_delivery_attempts_pkey",
1604 + "schema": "public",
1605 + "table": "relay_delivery_attempts",
1606 + "entityType": "pks"
1607 + },
1608 + {
1609 + "columns": ["credential_id"],
1610 + "nameExplicit": false,
1611 + "name": "relay_environment_credentials_pkey",
1612 + "schema": "public",
1613 + "table": "relay_environment_credentials",
1614 + "entityType": "pks"
1615 + },
1616 + {
1617 + "columns": ["user_id"],
1618 + "nameExplicit": false,
1619 + "name": "relay_managed_tunnel_limits_pkey",
1620 + "schema": "public",
1621 + "table": "relay_managed_tunnel_limits",
1622 + "entityType": "pks"
1623 + },
1624 + {
1625 + "columns": ["api"],
1626 + "nameExplicit": false,
1627 + "name": "relay_upstream_api_pauses_pkey",
1628 + "schema": "public",
1629 + "table": "relay_upstream_api_pauses",
1630 + "entityType": "pks"
1631 + }
1632 + ],
1633 + "renames": []
1634 +}
infra/relay/package.json
+1
@@ -13,6 +13,7 @@
13 },
14 "dependencies": {
15 "@clerk/backend": "catalog:",
16 + "@distilled.cloud/cloudflare": "catalog:",
17 "@effect/sql-pg": "catalog:",
18 "@effect/sql-sqlite-do": "catalog:",
19 "@noble/curves": "catalog:",
infra/relay/src/environments/CloudflareApiPause.test.ts new
+59
@@ -0,0 +1,59 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5 +import * as SqlClient from "effect/sql/SqlClient";
6 +
7 +import * as RelayDb from "../db.ts";
8 +import * as CloudflareApiPause from "./CloudflareApiPause.ts";
9 +
10 +const TransactionConnection = SqlClient.TransactionConnection(7);
11 +
12 +// Like the Worker's alchemy database proxy: every property read returns
13 +// another proxy, never the client's real transaction key.
14 +const lazyProxy = (): unknown => new Proxy(() => {}, { get: () => lazyProxy() });
15 +
16 +// Records whether each statement would have joined the ambient transaction.
17 +function makeFakeDb(joinedTransaction: Array<boolean>) {
18 + const statement = <A>(result: A) =>
19 + Effect.serviceOption(TransactionConnection).pipe(
20 + Effect.tap((connection) =>
21 + Effect.sync(() => joinedTransaction.push(Option.isSome(connection))),
22 + ),
23 + Effect.as(result),
24 + );
25 + return {
26 + $client: lazyProxy(),
27 + select: () => ({
28 + from: () => ({ where: () => ({ limit: () => statement([{ pausedUntilMs: 42 }]) }) }),
29 + }),
30 + insert: () => ({ values: () => ({ onConflictDoUpdate: () => statement([]) }) }),
31 + } as unknown as RelayDb.RelayDb["Service"];
32 +}
33 +
34 +describe("CloudflareApiPause", () => {
35 + it.effect("reads and records the pause outside a surrounding transaction", () => {
36 + const joinedTransaction: Array<boolean> = [];
37 + return Effect.gen(function* () {
38 + const pause = yield* CloudflareApiPause.CloudflareApiPause;
39 + const inTransaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
40 + effect.pipe(
41 + Effect.provideService(TransactionConnection, [
42 + {} as never,
43 + 0,
44 + ] as unknown as SqlClient.TransactionConnection.Service),
45 + );
46 +
47 + expect(yield* inTransaction(pause.pausedUntilMillis)).toBe(42);
48 + yield* inTransaction(pause.pauseUntil(1_000));
49 +
50 + expect(joinedTransaction).toEqual([false, false]);
51 + }).pipe(
52 + Effect.provide(
53 + CloudflareApiPause.layer.pipe(
54 + Layer.provide(Layer.succeed(RelayDb.RelayDb, makeFakeDb(joinedTransaction))),
55 + ),
56 + ),
57 + );
58 + });
59 +});
infra/relay/src/environments/CloudflareApiPause.ts new
+85
@@ -0,0 +1,85 @@
1 +import { eq, sql } from "drizzle-orm";
2 +import * as Context from "effect/Context";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +
6 +import * as RelayDb from "../db.ts";
7 +import { relayUpstreamApiPauses } from "../persistence/schema.ts";
8 +
9 +const CLOUDFLARE_API = "cloudflare";
10 +
11 +// Every SqlClient's transaction connection lives under a key with this prefix.
12 +// Matching by key name instead of `db.$client.transactionService` because the
13 +// relay's database is an alchemy proxy, whose properties are proxies too, not
14 +// the real key.
15 +const SQL_TRANSACTION_KEY_PREFIX = "effect/sql/SqlClient/TransactionConnection/";
16 +
17 +const withoutSqlTransaction = (context: Context.Context<never>): Context.Context<never> =>
18 + Context.makeUnsafe(
19 + new Map(
20 + Array.from(context.mapUnsafe).filter(([key]) => !key.startsWith(SQL_TRANSACTION_KEY_PREFIX)),
21 + ),
22 + );
23 +
24 +/**
25 + * Cloudflare's API rate limit is per account, so a 429 seen by any isolate
26 + * applies to all of them. Both operations fail open: a pause that cannot be
27 + * read or recorded must not block provisioning.
28 + *
29 + * Both also run outside any ambient transaction. Provisioning calls Cloudflare
30 + * while holding an allocation row lock, and a 429 there rolls that transaction
31 + * back, which would drop the recorded pause; a failed read inside it would
32 + * abort the provision's own statements.
33 + */
34 +export class CloudflareApiPause extends Context.Service<
35 + CloudflareApiPause,
36 + {
37 + /** Epoch milliseconds until which calls are paused, or 0. */
38 + readonly pausedUntilMillis: Effect.Effect<number>;
39 + readonly pauseUntil: (untilMillis: number) => Effect.Effect<void>;
40 + }
41 +>()("t3code-relay/environments/CloudflareApiPause") {}
42 +
43 +export const make = Effect.gen(function* () {
44 + const db = yield* RelayDb.RelayDb;
45 + const outsideTransaction = <A, E>(effect: Effect.Effect<A, E>) =>
46 + Effect.updateContext(effect, withoutSqlTransaction);
47 +
48 + return CloudflareApiPause.of({
49 + pausedUntilMillis: db
50 + .select({ pausedUntilMs: relayUpstreamApiPauses.pausedUntilMs })
51 + .from(relayUpstreamApiPauses)
52 + .where(eq(relayUpstreamApiPauses.api, CLOUDFLARE_API))
53 + .limit(1)
54 + .pipe(
55 + Effect.map((rows) => rows[0]?.pausedUntilMs ?? 0),
56 + Effect.catch((cause) =>
57 + Effect.logWarning("Could not read the shared Cloudflare API pause", { cause }).pipe(
58 + Effect.as(0),
59 + ),
60 + ),
61 + outsideTransaction,
62 + Effect.withSpan("relay.cloudflare_api_pause.read"),
63 + ),
64 + pauseUntil: (untilMillis) =>
65 + db
66 + .insert(relayUpstreamApiPauses)
67 + .values({ api: CLOUDFLARE_API, pausedUntilMs: untilMillis })
68 + .onConflictDoUpdate({
69 + target: relayUpstreamApiPauses.api,
70 + set: {
71 + pausedUntilMs: sql`greatest(${relayUpstreamApiPauses.pausedUntilMs}, excluded.paused_until_ms)`,
72 + },
73 + })
74 + .pipe(
75 + Effect.asVoid,
76 + Effect.catch((cause) =>
77 + Effect.logWarning("Could not record the shared Cloudflare API pause", { cause }),
78 + ),
79 + outsideTransaction,
80 + Effect.withSpan("relay.cloudflare_api_pause.record"),
81 + ),
82 + });
83 +});
84 +
85 +export const layer = Layer.effect(CloudflareApiPause, make);
infra/relay/src/environments/ManagedEndpointProvider.test.ts
+196
@@ -3,11 +3,15 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { describe, expect, it } from "@effect/vitest";
4 import * as Alchemy from "alchemy";
5 import * as Cloudflare from "alchemy/Cloudflare";
6 +import * as Deferred from "effect/Deferred";
7 import * as Effect from "effect/Effect";
8 +import * as Fiber from "effect/Fiber";
9 import * as Layer from "effect/Layer";
10 import * as Redacted from "effect/Redacted";
11 +import * as TestClock from "effect/testing/TestClock";
12
13 import * as RelayConfiguration from "../Config.ts";
14 +import * as CloudflareApiPause from "./CloudflareApiPause.ts";
15 import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
16 import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
17 import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";
@@ -364,6 +368,17 @@ function layerProvider(
368 );
369 }
370
371 +function makeSharedCloudflareApiPause() {
372 + let pausedUntilMillis = 0;
373 + return CloudflareApiPause.CloudflareApiPause.of({
374 + pausedUntilMillis: Effect.sync(() => pausedUntilMillis),
375 + pauseUntil: (untilMillis) =>
376 + Effect.sync(() => {
377 + pausedUntilMillis = Math.max(pausedUntilMillis, untilMillis);
378 + }),
379 + });
380 +}
381 +
382 const MANAGED_ENDPOINT_HASHES: Record<string, string> = {
383 "user_ABC:env_ABC": "d101ac68108a423e",
384 "user_ABC:env_shared": "d7e6356aaf8863aa",
@@ -413,6 +428,9 @@ describe("ManagedEndpointProvider", () => {
428 Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()),
429 ),
430 Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())),
431 + Layer.provide(
432 + Layer.succeed(CloudflareApiPause.CloudflareApiPause, makeSharedCloudflareApiPause()),
433 + ),
434 );
435
436 return Effect.gen(function* () {
@@ -754,6 +772,184 @@ describe("ManagedEndpointProvider", () => {
772 }).pipe(Effect.provide(layer));
773 });
774
775 + it.effect("recovers a ready tunnel for the same origin with only reads", () => {
776 + const tunnelCalls: TunnelCall[] = [];
777 + const dnsCalls: DnsCall[] = [];
778 + const allocationCalls: AllocationCall[] = [];
779 + const layer = layerProvider(
780 + makePersistentTunnelClient(tunnelCalls),
781 + makeDnsClient(dnsCalls),
782 + makeAllocations(allocationCalls),
783 + );
784 +
785 + return Effect.gen(function* () {
786 + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
787 + const request = {
788 + userId: "user_ABC",
789 + environmentId: "env_ABC",
790 + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
791 + } as const;
792 + const provisioned = yield* provider.provision(request);
793 + tunnelCalls.length = 0;
794 + dnsCalls.length = 0;
795 + allocationCalls.length = 0;
796 +
797 + const recovered = yield* provider.provision({ ...request, reuseReadyTunnel: true });
798 +
799 + expect(recovered).toEqual(provisioned);
800 + expect(tunnelCalls.map((call) => call.operation)).toEqual(["get", "getToken"]);
801 + expect(dnsCalls).toEqual([]);
802 + expect(allocationCalls.map((call) => call.operation)).toEqual(["reserve"]);
803 + }).pipe(Effect.provide(layer));
804 + });
805 +
806 + it.effect("fully provisions a recovery when the ready tunnel cannot be reused", () => {
807 + const tunnelCalls: TunnelCall[] = [];
808 + const tunnelClient = makePersistentTunnelClient(tunnelCalls);
809 + const layer = layerProvider(tunnelClient);
810 +
811 + return Effect.gen(function* () {
812 + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
813 + const request = {
814 + userId: "user_ABC",
815 + environmentId: "env_ABC",
816 + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
817 + reuseReadyTunnel: true,
818 + } as const;
819 + yield* provider.provision(request);
820 +
821 + tunnelCalls.length = 0;
822 + yield* provider.provision({
823 + ...request,
824 + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 },
825 + });
826 + expect(tunnelCalls.map((call) => call.operation)).toEqual([
827 + "list",
828 + "putConfiguration",
829 + "getToken",
830 + ]);
831 +
832 + yield* tunnelClient.delete("tunnel-id");
833 + tunnelCalls.length = 0;
834 + yield* provider.provision({
835 + ...request,
836 + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 },
837 + });
838 + expect(tunnelCalls.map((call) => call.operation)).toEqual([
839 + "get",
840 + "list",
841 + "create",
842 + "putConfiguration",
843 + "getToken",
844 + ]);
845 + }).pipe(Effect.provide(layer));
846 + });
847 +
848 + it.effect("keeps a pause recorded while a shared pause read was in flight", () => {
849 + let listCalls = 0;
850 + const tunnelClient = {
851 + list: () =>
852 + Effect.suspend(() => {
853 + listCalls += 1;
854 + return Effect.fail({ _tag: "TooManyRequests", message: "Rate limited" });
855 + }),
856 + } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient;
857 +
858 + return Effect.gen(function* () {
859 + const readStarted = yield* Deferred.make<void>();
860 + const releaseRead = yield* Deferred.make<void>();
861 + const layer = ManagedEndpointProvider.layerCloudflareBindings(
862 + tunnelClient,
863 + {} as Cloudflare.DNS.ReadWriteDnsClient,
864 + {} as Alchemy.BaseRuntimeContext,
865 + ).pipe(
866 + Layer.provideMerge(NodeServices.layer),
867 + Layer.provide(RelayConfiguration.layer(config)),
868 + Layer.provide(
869 + Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()),
870 + ),
871 + Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())),
872 + Layer.provide(
873 + Layer.succeed(
874 + CloudflareApiPause.CloudflareApiPause,
875 + CloudflareApiPause.CloudflareApiPause.of({
876 + pausedUntilMillis: Deferred.succeed(readStarted, undefined).pipe(
877 + Effect.andThen(Deferred.await(releaseRead)),
878 + Effect.as(0),
879 + ),
880 + pauseUntil: () => Effect.void,
881 + }),
882 + ),
883 + ),
884 + );
885 +
886 + yield* Effect.gen(function* () {
887 + const tunnels = yield* ManagedEndpointProvider.ManagedEndpointTunnelClient;
888 + const list = tunnels.list({ isDeleted: false }).pipe(Effect.flip);
889 + // The first call starts the shared read; the second hits a 429 meanwhile.
890 + const reading = yield* Effect.forkChild(list);
891 + yield* Deferred.await(readStarted);
892 + yield* list;
893 + yield* Deferred.succeed(releaseRead, undefined);
894 + yield* Fiber.join(reading);
895 + yield* list;
896 + expect(listCalls).toBe(1);
897 + }).pipe(Effect.provide(layer));
898 + });
899 + });
900 +
901 + it.effect("pauses Cloudflare calls in every isolate until a rate limit has passed", () => {
902 + let listCalls = 0;
903 + const tunnelClient = {
904 + list: () =>
905 + Effect.suspend(() => {
906 + listCalls += 1;
907 + return Effect.fail({ _tag: "TooManyRequests", message: "Rate limited" });
908 + }),
909 + } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient;
910 + const sharedPause = makeSharedCloudflareApiPause();
911 + const isolate = () =>
912 + ManagedEndpointProvider.layerCloudflareBindings(
913 + tunnelClient,
914 + {} as Cloudflare.DNS.ReadWriteDnsClient,
915 + {} as Alchemy.BaseRuntimeContext,
916 + ).pipe(
917 + Layer.provideMerge(NodeServices.layer),
918 + Layer.provide(RelayConfiguration.layer(config)),
919 + Layer.provide(
920 + Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()),
921 + ),
922 + Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())),
923 + Layer.provide(Layer.succeed(CloudflareApiPause.CloudflareApiPause, sharedPause)),
924 + );
925 + const provision = ManagedEndpointProvider.ManagedEndpointProvider.pipe(
926 + Effect.flatMap((provider) =>
927 + provider.provision({
928 + userId: "user_ABC",
929 + environmentId: "env_ABC",
930 + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
931 + }),
932 + ),
933 + Effect.flip,
934 + );
935 +
936 + return Effect.gen(function* () {
937 + const rateLimited = yield* provision.pipe(Effect.provide(isolate()));
938 + const pausedElsewhere = yield* provision.pipe(Effect.provide(isolate()));
939 + expect(listCalls).toBe(1);
940 + expect(ManagedEndpointProvider.isCloudflareRateLimited(rateLimited)).toBe(true);
941 + expect(pausedElsewhere).toMatchObject({
942 + _tag: "ManagedEndpointProvisioningFailed",
943 + stage: "ensure-tunnel",
944 + cause: { cause: { _tag: "CloudflareApiPaused" } },
945 + });
946 +
947 + yield* TestClock.adjust("30 seconds");
948 + yield* provision.pipe(Effect.provide(isolate()));
949 + expect(listCalls).toBe(2);
950 + });
951 + });
952 +
953 it.effect("recreates a checkpointed DNS record when it was removed externally", () => {
954 const dnsCalls: DnsCall[] = [];
955 const allocationCalls: AllocationCall[] = [];
infra/relay/src/environments/ManagedEndpointProvider.ts
+335 -144
@@ -1,9 +1,13 @@
1 +import * as CloudflareRetry from "@distilled.cloud/cloudflare/Retry";
2 import * as Alchemy from "alchemy";
3 import * as Cloudflare from "alchemy/Cloudflare";
4 import * as Arr from "effect/Array";
5 +import * as Cause from "effect/Cause";
6 +import * as Clock from "effect/Clock";
7 import * as Context from "effect/Context";
8 import * as Crypto from "effect/Crypto";
9 import * as DateTime from "effect/DateTime";
10 +import * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Hex from "effect/encoding/Hex";
13 import * as Layer from "effect/Layer";
@@ -23,6 +27,7 @@ import {
27 managedEndpointHostname,
28 managedEndpointTunnelName,
29 } from "../deploymentConfig.ts";
30 +import * as CloudflareApiPause from "./CloudflareApiPause.ts";
31 import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
32 import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";
33
@@ -148,6 +153,11 @@ export class ManagedEndpointProvider extends Context.Service<
153 readonly userId: string;
154 readonly environmentId: string;
155 readonly origin: RelayManagedEndpointOrigin;
156 + /**
157 + * Return a ready tunnel that already serves this origin with only a
158 + * liveness check and a fresh token, skipping ingress and DNS repair.
159 + */
160 + readonly reuseReadyTunnel?: boolean;
161 }) => Effect.Effect<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;
162 readonly reconcileOrigin: (input: {
163 readonly userId: string;
@@ -389,6 +399,132 @@ export function isManagedEndpointNotFound(cause: unknown): boolean {
399 return "cause" in cause && isManagedEndpointNotFound(cause.cause);
400 }
401
402 +export class CloudflareApiPaused extends Schema.TaggedError<CloudflareApiPaused>()(
403 + "CloudflareApiPaused",
404 + { retryAfterMillis: Schema.Number },
405 +) {
406 + override get message(): string {
407 + return `Cloudflare API calls are paused for ${this.retryAfterMillis}ms after a rate limit`;
408 + }
409 +}
410 +
411 +export function isCloudflareRateLimited(cause: unknown): boolean {
412 + if (typeof cause !== "object" || cause === null) {
413 + return false;
414 + }
415 + if (
416 + "_tag" in cause &&
417 + (cause._tag === "TooManyRequests" ||
418 + cause._tag === "CloudflareRateLimited" ||
419 + cause._tag === "CloudflareApiPaused")
420 + ) {
421 + return true;
422 + }
423 + if ("status" in cause && cause.status === 429) {
424 + return true;
425 + }
426 + return "cause" in cause && isCloudflareRateLimited(cause.cause);
427 +}
428 +
429 +const CLOUDFLARE_DEFAULT_RATE_LIMIT_PAUSE = Duration.seconds(30);
430 +const CLOUDFLARE_MAX_RATE_LIMIT_PAUSE = Duration.minutes(2);
431 +
432 +function cloudflareRateLimitPauseMillis(cause: unknown): number {
433 + const retryAfter =
434 + typeof cause === "object" && cause !== null && "retryAfter" in cause
435 + ? cause.retryAfter
436 + : undefined;
437 + const pause = Duration.isDuration(retryAfter) ? retryAfter : CLOUDFLARE_DEFAULT_RATE_LIMIT_PAUSE;
438 + return Duration.toMillis(Duration.min(pause, CLOUDFLARE_MAX_RATE_LIMIT_PAUSE));
439 +}
440 +
441 +/**
442 + * How long a caller should wait before retrying, when `cause` is a Cloudflare
443 + * rate limit or a call refused during the pause that follows one.
444 + */
445 +export function cloudflareRetryAfterMillis(cause: unknown): number | undefined {
446 + for (let current = cause, depth = 0; depth < 8; depth++) {
447 + if (typeof current !== "object" || current === null) return undefined;
448 + if ("_tag" in current && current._tag === "CloudflareApiPaused") {
449 + const retryAfterMillis: unknown = Reflect.get(current, "retryAfterMillis");
450 + return typeof retryAfterMillis === "number" ? retryAfterMillis : undefined;
451 + }
452 + if (
453 + ("_tag" in current &&
454 + (current._tag === "TooManyRequests" || current._tag === "CloudflareRateLimited")) ||
455 + ("status" in current && current.status === 429)
456 + ) {
457 + return cloudflareRateLimitPauseMillis(current);
458 + }
459 + if (!("cause" in current)) return undefined;
460 + current = current.cause;
461 + }
462 + return undefined;
463 +}
464 +
465 +// The SDK's default policy sleeps through Retry-After inside the request, which
466 +// held every caller until its timeout and kept the account over its limit.
467 +// Rate limits surface at once instead; other transient failures still retry.
468 +const withoutRateLimitRetries: CloudflareRetry.Factory = (lastError) => {
469 + const defaults = CloudflareRetry.makeDefault(lastError);
470 + return {
471 + ...defaults,
472 + while: (error) => !isCloudflareRateLimited(error) && (defaults.while?.(error) ?? false),
473 + };
474 +};
475 +
476 +// Every isolate rereads the shared pause at most this often, so a quiet
477 +// period costs one query per isolate rather than one per Cloudflare call.
478 +const CLOUDFLARE_PAUSE_REFRESH_MILLIS = 5_000;
479 +
480 +/**
481 + * The rate limit is account-wide, so once one call is rejected every other
482 + * call is too, from any isolate. Failing them without a request leaves the
483 + * account room to recover instead of extending the limit.
484 + */
485 +const makeCloudflareApiGate = (alchemyRuntimeContext: Alchemy.BaseRuntimeContext) => {
486 + let pausedUntilMillis = 0;
487 + let checkedAtMillis = Number.NEGATIVE_INFINITY;
488 + return (pause: CloudflareApiPause.CloudflareApiPause["Service"]) => {
489 + const recordRateLimit = Effect.fn("relay.cloudflare_api_pause.rate_limited")(function* (
490 + cause: unknown,
491 + ) {
492 + const pauseMillis = cloudflareRateLimitPauseMillis(cause);
493 + const until = (yield* Clock.currentTimeMillis) + pauseMillis;
494 + pausedUntilMillis = Math.max(pausedUntilMillis, until);
495 + yield* Effect.annotateCurrentSpan({ "relay.cloudflare.pause_ms": pauseMillis });
496 + yield* pause.pauseUntil(until);
497 + });
498 + return <A, E>(
499 + call: Effect.Effect<A, E, Alchemy.RuntimeContext>,
500 + ): Effect.Effect<A, E | CloudflareApiPaused | Cause.TimeoutError> =>
501 + Effect.gen(function* () {
502 + const now = yield* Clock.currentTimeMillis;
503 + if (now >= pausedUntilMillis && now - checkedAtMillis >= CLOUDFLARE_PAUSE_REFRESH_MILLIS) {
504 + checkedAtMillis = now;
505 + // Read first: a 429 recorded while the read is in flight must win.
506 + const shared = yield* pause.pausedUntilMillis;
507 + pausedUntilMillis = Math.max(pausedUntilMillis, shared);
508 + }
509 + // A paused call never reaches Cloudflare, so it leaves no 429 behind.
510 + // Its own span keeps a storm visible to the rate-limit monitors.
511 + if (now < pausedUntilMillis) {
512 + return yield* new CloudflareApiPaused({ retryAfterMillis: pausedUntilMillis - now }).pipe(
513 + Effect.withSpan("relay.cloudflare_api_pause.rejected"),
514 + );
515 + }
516 + return yield* call.pipe(
517 + Effect.provideService(CloudflareRetry.Retry, withoutRateLimitRetries),
518 + Effect.timeout("8 seconds"),
519 + Effect.tapError((cause) =>
520 + isCloudflareRateLimited(cause) ? recordRateLimit(cause) : Effect.void,
521 + ),
522 + Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
523 + );
524 + });
525 + };
526 +};
527 +
528 /**
529 * Cloudflare refuses to delete a tunnel while a connector is still attached,
530 * either one that has not finished draining or another runtime still serving
@@ -503,6 +639,65 @@ export const make = Effect.gen(function* () {
639 );
640 });
641
642 + // Hosts ask for recovery whenever their connector cannot register, mostly
643 + // for local reasons a fresh provision cannot fix. Those requests outnumber
644 + // every other Cloudflare caller, so a tunnel that is ready for the same
645 + // origin costs two reads instead of a full provision.
646 + const reuseReadyTunnel = Effect.fnUntraced(function* (
647 + allocation: ManagedEndpointAllocations.ManagedEndpointAllocation,
648 + origin: RelayManagedEndpointOrigin,
649 + ) {
650 + const { tunnelId } = allocation;
651 + if (
652 + tunnelId === null ||
653 + allocation.readyAt === null ||
654 + allocation.dnsRecordId === null ||
655 + allocation.tunnelReleasedAt !== null ||
656 + allocation.origin?.localHttpHost !== origin.localHttpHost ||
657 + allocation.origin.localHttpPort !== origin.localHttpPort
658 + ) {
659 + return Option.none<ManagedEndpointProvisioningResult>();
660 + }
661 + const failed = (
662 + stage: "verify-tunnel" | "get-tunnel-token",
663 + cause: ManagedEndpointTunnelClientError,
664 + ) =>
665 + new ManagedEndpointProvisioningFailed({
666 + userId: allocation.userId,
667 + environmentId: allocation.environmentId,
668 + stage,
669 + hostname: allocation.hostname,
670 + tunnelName: allocation.tunnelName,
671 + tunnelId,
672 + cause,
673 + });
674 + const recorded = yield* tunnels.get(tunnelId).pipe(
675 + Effect.asSome,
676 + Effect.catchTags({
677 + ManagedEndpointTunnelClientError: (cause) =>
678 + isManagedEndpointNotFound(cause.cause)
679 + ? Effect.succeedNone
680 + : Effect.fail(failed("verify-tunnel", cause)),
681 + }),
682 + );
683 + if (Option.isNone(recorded) || recorded.value.deletedAt) {
684 + return Option.none<ManagedEndpointProvisioningResult>();
685 + }
686 + const connectorToken = yield* tunnels
687 + .getToken(tunnelId)
688 + .pipe(Effect.mapError((cause) => failed("get-tunnel-token", cause)));
689 + yield* Effect.annotateCurrentSpan({ "relay.managed_endpoint.reused_ready_tunnel": true });
690 + return Option.some<ManagedEndpointProvisioningResult>({
691 + endpoint: managedEndpointForHostname(allocation.hostname),
692 + runtime: {
693 + providerKind: "cloudflare_tunnel",
694 + connectorToken,
695 + tunnelId,
696 + tunnelName: allocation.tunnelName,
697 + },
698 + });
699 + });
700 +
701 const prepareDeprovision = Effect.fn("relay.managed_endpoint_provider.prepare_deprovision")(
702 function* (input: { readonly userId: string; readonly environmentId: string }) {
703 return yield* allocations.get(input).pipe(
@@ -1039,6 +1234,13 @@ export const make = Effect.gen(function* () {
1234 );
1235 const { hostname, tunnelName } = allocation;
1236
1237 + if (input.reuseReadyTunnel === true) {
1238 + const reused = yield* reuseReadyTunnel(allocation, input.origin);
1239 + if (Option.isSome(reused)) {
1240 + return reused.value;
1241 + }
1242 + }
1243 +
1244 const tunnelResponse = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(
1245 Effect.map((tunnels) => tunnels.result),
1246 Effect.map(Arr.findFirst((tunnel) => tunnel.name === tunnelName)),
@@ -1344,153 +1546,142 @@ export const layerCloudflareBindings = (
1546 tunnelClient: Cloudflare.Tunnel.ReadWriteTunnelClient,
1547 dnsClient: Cloudflare.DNS.ReadWriteDnsClient,
1548 alchemyRuntimeContext: Alchemy.BaseRuntimeContext,
1347 -) =>
1348 - layer.pipe(
1549 +) => {
1550 + // Created once per isolate so its cached pause survives layer rebuilds.
1551 + const cloudflare = makeCloudflareApiGate(alchemyRuntimeContext);
1552 + return layer.pipe(
1553 Layer.provideMerge(
1350 - Layer.mergeAll(
1351 - layerTunnelClient({
1352 - get: (tunnelId) =>
1353 - tunnelClient.get(tunnelId).pipe(
1354 - Effect.timeout("8 seconds"),
1355 - Effect.mapError(
1356 - (cause) =>
1357 - new ManagedEndpointTunnelClientError({
1358 - operation: "get",
1359 - tunnelId,
1360 - cause,
1361 - }),
1362 - ),
1363 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1364 - ),
1365 - list: (request) =>
1366 - tunnelClient.list(request).pipe(
1367 - Effect.timeout("8 seconds"),
1368 - Effect.mapError(
1369 - (cause) =>
1370 - new ManagedEndpointTunnelClientError({
1371 - operation: "list",
1372 - ...(request.name === undefined ? {} : { tunnelName: request.name }),
1373 - cause,
1374 - }),
1375 - ),
1376 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1377 - ),
1378 - create: (request) =>
1379 - tunnelClient.create(request).pipe(
1380 - Effect.timeout("8 seconds"),
1381 - Effect.mapError(
1382 - (cause) =>
1383 - new ManagedEndpointTunnelClientError({
1384 - operation: "create",
1385 - tunnelName: request.name,
1386 - cause,
1387 - }),
1388 - ),
1389 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1390 - ),
1391 - putConfiguration: (tunnelId, config) =>
1392 - tunnelClient.putConfiguration(tunnelId, config).pipe(
1393 - Effect.timeout("8 seconds"),
1394 - Effect.mapError(
1395 - (cause) =>
1396 - new ManagedEndpointTunnelClientError({
1397 - operation: "put-configuration",
1398 - tunnelId,
1399 - cause,
1400 - }),
1401 - ),
1402 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1403 - ),
1404 - getToken: (tunnelId) =>
1405 - tunnelClient.getToken(tunnelId).pipe(
1406 - Effect.timeout("8 seconds"),
1407 - Effect.mapError(
1408 - (cause) =>
1409 - new ManagedEndpointTunnelClientError({
1410 - operation: "get-token",
1411 - tunnelId,
1412 - cause,
1413 - }),
1414 - ),
1415 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1416 - ),
1417 - delete: (tunnelId) =>
1418 - tunnelClient.delete(tunnelId).pipe(
1419 - Effect.timeout("8 seconds"),
1420 - Effect.mapError(
1421 - (cause) =>
1422 - new ManagedEndpointTunnelClientError({
1423 - operation: "delete",
1424 - tunnelId,
1425 - cause,
1426 - }),
1427 - ),
1428 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1429 - ),
1430 - }),
1431 - layerDnsClient({
1432 - listRecords: (hostname) =>
1433 - dnsClient.listDnsRecords({ search: hostname }).pipe(
1434 - Effect.timeout("8 seconds"),
1435 - Effect.map((response) =>
1436 - response.result.filter(
1437 - (record): record is typeof record & { readonly id: string } =>
1438 - typeof record.id === "string" &&
1439 - normalizeHostname(record.name) === normalizeHostname(hostname),
1554 + Layer.unwrap(
1555 + Effect.gen(function* () {
1556 + const pause = yield* CloudflareApiPause.CloudflareApiPause;
1557 + const gate = cloudflare(pause);
1558 + return Layer.mergeAll(
1559 + layerTunnelClient({
1560 + get: (tunnelId) =>
1561 + gate(tunnelClient.get(tunnelId)).pipe(
1562 + Effect.mapError(
1563 + (cause) =>
1564 + new ManagedEndpointTunnelClientError({
1565 + operation: "get",
1566 + tunnelId,
1567 + cause,
1568 + }),
1569 + ),
1570 ),
1441 - ),
1442 - Effect.mapError(
1443 - (cause) =>
1444 - new ManagedEndpointDnsClientError({
1445 - operation: "list-records",
1446 - hostname,
1447 - cause,
1448 - }),
1449 - ),
1450 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1451 - ),
1452 - createRecord: (request) =>
1453 - dnsClient.createDnsRecord(request).pipe(
1454 - Effect.timeout("8 seconds"),
1455 - Effect.map((response) => ({ id: response.id })),
1456 - Effect.mapError(
1457 - (cause) =>
1458 - new ManagedEndpointDnsClientError({
1459 - operation: "create-record",
1460 - hostname: request.name,
1461 - cause,
1462 - }),
1463 - ),
1464 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1465 - ),
1466 - updateRecord: (dnsRecordId, request) =>
1467 - dnsClient.updateDnsRecord(dnsRecordId, request).pipe(
1468 - Effect.timeout("8 seconds"),
1469 - Effect.mapError(
1470 - (cause) =>
1471 - new ManagedEndpointDnsClientError({
1472 - operation: "update-record",
1473 - hostname: request.name,
1474 - dnsRecordId,
1475 - cause,
1476 - }),
1477 - ),
1478 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1479 - ),
1480 - deleteRecord: (dnsRecordId) =>
1481 - dnsClient.deleteDnsRecord(dnsRecordId).pipe(
1482 - Effect.timeout("8 seconds"),
1483 - Effect.mapError(
1484 - (cause) =>
1485 - new ManagedEndpointDnsClientError({
1486 - operation: "delete-record",
1487 - dnsRecordId,
1488 - cause,
1489 - }),
1490 - ),
1491 - Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
1492 - ),
1571 + list: (request) =>
1572 + gate(tunnelClient.list(request)).pipe(
1573 + Effect.mapError(
1574 + (cause) =>
1575 + new ManagedEndpointTunnelClientError({
1576 + operation: "list",
1577 + ...(request.name === undefined ? {} : { tunnelName: request.name }),
1578 + cause,
1579 + }),
1580 + ),
1581 + ),
1582 + create: (request) =>
1583 + gate(tunnelClient.create(request)).pipe(
1584 + Effect.mapError(
1585 + (cause) =>
1586 + new ManagedEndpointTunnelClientError({
1587 + operation: "create",
1588 + tunnelName: request.name,
1589 + cause,
1590 + }),
1591 + ),
1592 + ),
1593 + putConfiguration: (tunnelId, config) =>
1594 + gate(tunnelClient.putConfiguration(tunnelId, config)).pipe(
1595 + Effect.mapError(
1596 + (cause) =>
1597 + new ManagedEndpointTunnelClientError({
1598 + operation: "put-configuration",
1599 + tunnelId,
1600 + cause,
1601 + }),
1602 + ),
1603 + ),
1604 + getToken: (tunnelId) =>
1605 + gate(tunnelClient.getToken(tunnelId)).pipe(
1606 + Effect.mapError(
1607 + (cause) =>
1608 + new ManagedEndpointTunnelClientError({
1609 + operation: "get-token",
1610 + tunnelId,
1611 + cause,
1612 + }),
1613 + ),
1614 + ),
1615 + delete: (tunnelId) =>
1616 + gate(tunnelClient.delete(tunnelId)).pipe(
1617 + Effect.mapError(
1618 + (cause) =>
1619 + new ManagedEndpointTunnelClientError({
1620 + operation: "delete",
1621 + tunnelId,
1622 + cause,
1623 + }),
1624 + ),
1625 + ),
1626 + }),
1627 + layerDnsClient({
1628 + listRecords: (hostname) =>
1629 + gate(dnsClient.listDnsRecords({ search: hostname })).pipe(
1630 + Effect.map((response) =>
1631 + response.result.filter(
1632 + (record): record is typeof record & { readonly id: string } =>
1633 + typeof record.id === "string" &&
1634 + normalizeHostname(record.name) === normalizeHostname(hostname),
1635 + ),
1636 + ),
1637 + Effect.mapError(
1638 + (cause) =>
1639 + new ManagedEndpointDnsClientError({
1640 + operation: "list-records",
1641 + hostname,
1642 + cause,
1643 + }),
1644 + ),
1645 + ),
1646 + createRecord: (request) =>
1647 + gate(dnsClient.createDnsRecord(request)).pipe(
1648 + Effect.map((response) => ({ id: response.id })),
1649 + Effect.mapError(
1650 + (cause) =>
1651 + new ManagedEndpointDnsClientError({
1652 + operation: "create-record",
1653 + hostname: request.name,
1654 + cause,
1655 + }),
1656 + ),
1657 + ),
1658 + updateRecord: (dnsRecordId, request) =>
1659 + gate(dnsClient.updateDnsRecord(dnsRecordId, request)).pipe(
1660 + Effect.mapError(
1661 + (cause) =>
1662 + new ManagedEndpointDnsClientError({
1663 + operation: "update-record",
1664 + hostname: request.name,
1665 + dnsRecordId,
1666 + cause,
1667 + }),
1668 + ),
1669 + ),
1670 + deleteRecord: (dnsRecordId) =>
1671 + gate(dnsClient.deleteDnsRecord(dnsRecordId)).pipe(
1672 + Effect.mapError(
1673 + (cause) =>
1674 + new ManagedEndpointDnsClientError({
1675 + operation: "delete-record",
1676 + dnsRecordId,
1677 + cause,
1678 + }),
1679 + ),
1680 + ),
1681 + }),
1682 + );
1683 }),
1684 ),
1685 ),
1686 );
1687 +};
infra/relay/src/environments/ManagedEndpointReaper.test.ts
+11 -3
@@ -66,6 +66,7 @@ function harness(input?: {
66 readonly namespace?: string;
67 readonly failTunnelId?: string;
68 readonly rateLimitedTunnelId?: string;
69 + readonly rateLimitCause?: unknown;
70 readonly failAllDeletes?: boolean;
71 readonly failDeleteWhen?: (tunnelId: string) => boolean;
72 readonly missingOnDeleteTunnelId?: string;
@@ -155,13 +156,13 @@ function harness(input?: {
156 tunnelId === input?.missingOnDeleteTunnelId
157 ? { _tag: "NotFound" }
158 : tunnelId === input?.rateLimitedTunnelId
158 - ? {
159 + ? (input.rateLimitCause ?? {
160 cause: {
161 _tag: "TooManyRequests",
162 message: "Cloudflare rate limit exceeded",
163 retryAfter: 60,
164 },
164 - }
165 + })
166 : "Cloudflare refused the deletion",
167 }),
168 )
@@ -653,7 +654,13 @@ describe("ManagedEndpointReaper", () => {
654 }).pipe(Effect.provide(state.layer));
655 });
656
656 - it.effect("stops the sweep after a structured Cloudflare rate limit error", () => {
657 + it.effect.each([
658 + ["a structured Cloudflare rate limit error", undefined],
659 + [
660 + "a Cloudflare API pause recorded by another isolate",
661 + new ManagedEndpointProvider.CloudflareApiPaused({ retryAfterMillis: 30_000 }),
662 + ],
663 + ] as const)("stops the sweep after %s", ([, rateLimitCause]) => {
664 const state = harness({
665 tunnels: [
666 tunnel({
@@ -674,6 +681,7 @@ describe("ManagedEndpointReaper", () => {
681 allocation({ tunnelId: "next", recoveryEnabled: true }),
682 ],
683 rateLimitedTunnelId: "limited",
684 + rateLimitCause,
685 });
686
687 return Effect.gen(function* () {
infra/relay/src/environments/ManagedEndpointReaper.ts
+1 -14
@@ -110,19 +110,6 @@ function inactiveDaysAt(
110 return (now.epochMilliseconds - timestamp.value.epochMilliseconds) / 86_400_000;
111 }
112
113 -function isRateLimited(cause: unknown): boolean {
114 - if (typeof cause !== "object" || cause === null) {
115 - return false;
116 - }
117 - if ("_tag" in cause && cause._tag === "TooManyRequests") {
118 - return true;
119 - }
120 - if ("status" in cause && cause.status === 429) {
121 - return true;
122 - }
123 - return "cause" in cause && isRateLimited(cause.cause);
124 -}
125 -
113 function rotatedPages(input: {
114 readonly totalCount: number | undefined;
115 readonly slot: number;
@@ -383,7 +370,7 @@ export const make = Effect.gen(function* () {
370 legacy: candidate.legacy,
371 cause: result.failure,
372 });
386 - if (isRateLimited(result.failure)) {
373 + if (ManagedEndpointProvider.isCloudflareRateLimited(result.failure)) {
374 stopDeleting = true;
375 truncated = true;
376 }
infra/relay/src/http/Api.test.ts
+96
@@ -187,6 +187,102 @@ describe("device listing compatibility", () => {
187 });
188 });
189
190 +describe("Cloudflare rate-limit retry hint", () => {
191 + const provisioningFailed = (cause?: unknown) =>
192 + new ManagedEndpointProvider.ManagedEndpointProvisioningFailed({
193 + userId: "user-1",
194 + environmentId: "env-1",
195 + stage: "ensure-tunnel",
196 + ...(cause === undefined
197 + ? {}
198 + : {
199 + cause: new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
200 + operation: "list",
201 + cause,
202 + }),
203 + }),
204 + });
205 +
206 + const linkResponse = (failure: ManagedEndpointProvider.ManagedEndpointProvisioningFailed) => {
207 + const layerHandlers = RelayHttpApi.layerClientApi.pipe(
208 + HttpRouter.provideRequest(
209 + Layer.mergeAll(
210 + Layer.mock(EnvironmentCredentials.EnvironmentCredentials, {}),
211 + Layer.mock(EnvironmentLinks.EnvironmentLinks, {}),
212 + Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}),
213 + Layer.mock(RelayDb.RelayTransactions, {}),
214 + Layer.mock(HookInbox.HookInbox, {}),
215 + ),
216 + ),
217 + Layer.provide(
218 + Layer.mergeAll(
219 + Layer.succeed(RelayConfiguration.RelayConfiguration, relaySettings),
220 + NodeCryptoLayer.layer,
221 + Layer.mock(RelayTokens.RelayTokens, { resolveDpopAccessTokenScopes: () => null }),
222 + Layer.mock(EnvironmentLinker.EnvironmentLinker, { link: () => Effect.fail(failure) }),
223 + Layer.mock(EnvironmentLinks.EnvironmentLinks, {}),
224 + Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}),
225 + Layer.mock(Devices.Devices, {}),
226 + ),
227 + ),
228 + Layer.provideMerge(
229 + Layer.succeed(RelayClientAuth, {
230 + clientBearer: (effect) =>
231 + Effect.provideService(effect, RelayClientPrincipal, {
232 + userId: "user-1",
233 + token: "test-token",
234 + }),
235 + }),
236 + ),
237 + );
238 + return Effect.acquireRelease(
239 + Effect.sync(() =>
240 + HttpRouter.toWebHandler(
241 + HttpApiBuilder.layer(HttpApi.make("RelayApi").add(RelayApi.groups.client)).pipe(
242 + Layer.provide(layerHandlers),
243 + Layer.provide(HttpServer.layerServices),
244 + ),
245 + { disableLogger: true },
246 + ),
247 + ),
248 + (app) => Effect.promise(() => app.dispose()),
249 + ).pipe(
250 + Effect.flatMap((app) =>
251 + Effect.promise(() =>
252 + app.handler(
253 + new Request("https://relay.example.test/v1/client/environment-links", {
254 + method: "POST",
255 + headers: { authorization: "Bearer test-token", "content-type": "application/json" },
256 + body: JSON.stringify({
257 + proof: "signed-proof",
258 + notificationsEnabled: true,
259 + liveActivitiesEnabled: true,
260 + managedTunnelsEnabled: true,
261 + }),
262 + }),
263 + ),
264 + ),
265 + ),
266 + );
267 + };
268 +
269 + it.effect("tells a link refused during a Cloudflare pause when to retry", () =>
270 + Effect.gen(function* () {
271 + const paused = yield* linkResponse(
272 + provisioningFailed(
273 + new ManagedEndpointProvider.CloudflareApiPaused({ retryAfterMillis: 24_100 }),
274 + ),
275 + );
276 + expect(paused.status).toBe(503);
277 + expect(paused.headers.get("retry-after")).toBe("25");
278 +
279 + const other = yield* linkResponse(provisioningFailed());
280 + expect(other.status).toBe(503);
281 + expect(other.headers.get("retry-after")).toBeNull();
282 + }).pipe(Effect.scoped),
283 + );
284 +});
285 +
286 describe("relay client authentication", () => {
287 it.effect("preserves the existing Clerk session JWT path", () =>
288 Effect.gen(function* () {
infra/relay/src/http/Api.ts
+15
@@ -102,6 +102,17 @@ const appendRelayCredentialResponseHeaders = HttpEffect.appendPreResponseHandler
102 ),
103 );
104
105 +// T3 Code hosts never retry sooner than Retry-After, so during a Cloudflare
106 +// rate limit they wait out the pause instead of retrying into it.
107 +const appendCloudflareRetryAfter = (error: unknown) => {
108 + const retryAfterMillis = ManagedEndpointProvider.cloudflareRetryAfterMillis(error);
109 + if (retryAfterMillis === undefined) return Effect.void;
110 + const seconds = String(Math.max(1, Math.ceil(retryAfterMillis / 1000)));
111 + return HttpEffect.appendPreResponseHandler((_request, response) =>
112 + Effect.succeed(HttpServerResponse.setHeader(response, "retry-after", seconds)),
113 + );
114 +};
115 +
116 const appendRelayDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) =>
117 Effect.succeed(
118 response.status === 401
@@ -693,6 +704,7 @@ export const recoverEnvironmentTunnelRecord = Effect.fn(
704 userId: input.userId,
705 environmentId: input.environmentId,
706 origin: input.origin,
707 + reuseReadyTunnel: true,
708 });
709 const recoveredTunnelId = recovered.runtime.tunnelId;
710 if (
@@ -873,6 +885,7 @@ export const layerClientApi = HttpApiBuilder.group(
885 cloudMintPublicKey: config.cloudMintPublicKey,
886 };
887 },
888 + Effect.tapError(appendCloudflareRetryAfter),
889 mapErrorTags({
890 EnvironmentLinkProofExpired: (_error, traceId) =>
891 new RelayEnvironmentLinkProofExpiredError({
@@ -1334,6 +1347,7 @@ export const layerServerApi = HttpApiBuilder.group(
1347 origin: payload.origin,
1348 });
1349 },
1350 + Effect.tapError(appendCloudflareRetryAfter),
1351 Effect.catchTags({
1352 ManagedEndpointOriginNotAllowed: () => Effect.fail(new HttpApiError.Unauthorized({})),
1353 ManagedEndpointProvisioningNotConfigured: () =>
@@ -1369,6 +1383,7 @@ export const layerServerApi = HttpApiBuilder.group(
1383 origin: payload.origin,
1384 });
1385 },
1386 + Effect.tapError(appendCloudflareRetryAfter),
1387 Effect.catchTags({
1388 ManagedEndpointOriginNotAllowed: () => Effect.fail(new HttpApiError.Unauthorized({})),
1389 ManagedEndpointProvisioningNotConfigured: () =>
infra/relay/src/monitoring.ts
+12 -5
@@ -119,9 +119,9 @@ const relayMonitors: ReadonlyArray<RelayMonitor> = [
119 severity: "page",
120 name: "T3 Connect relay: Cloudflare API rate limited",
121 description:
122 - "Cloudflare API 429s per 10 min from tunnel and DNS provisioning. Sustained at this level, links and recoveries stall. Peak before #16810: 1,286; during it: ~11k.",
122 + "Cloudflare API 429s, plus calls the relay refused while paused after one, per 10 min. Sustained at this level, links and recoveries stall. Peak 429s before #16810: 1,286; during it: ~11k.",
123 query: (dataset) =>
124 - `['${dataset}']\n| where ${CLOUDFLARE_API} and ${STATUS} == 429\n| summarize rate_limited = count()`,
124 + `['${dataset}']\n| where (${CLOUDFLARE_API} and ${STATUS} == 429) or name == "relay.cloudflare_api_pause.rejected"\n| summarize rate_limited = count()`,
125 operator: "AboveOrEqual",
126 threshold: 500,
127 rangeMinutes: 10,
@@ -145,9 +145,9 @@ const relayMonitors: ReadonlyArray<RelayMonitor> = [
145 severity: "warn",
146 name: "T3 Connect relay: Cloudflare API near its limit",
147 description:
148 - "Any sustained Cloudflare API 429s. These bursts ran for days before #16810; raise the account limit or cut call volume before they grow.",
148 + "Any sustained Cloudflare API 429s or paused calls. 429 bursts ran for days before #16810; raise the account limit or cut call volume before they grow.",
149 query: (dataset) =>
150 - `['${dataset}']\n| where ${CLOUDFLARE_API} and ${STATUS} == 429\n| summarize rate_limited = count()`,
150 + `['${dataset}']\n| where (${CLOUDFLARE_API} and ${STATUS} == 429) or name == "relay.cloudflare_api_pause.rejected"\n| summarize rate_limited = count()`,
151 operator: "AboveOrEqual",
152 threshold: 20,
153 rangeMinutes: 10,
@@ -250,7 +250,14 @@ const relayDashboardCharts = (dataset: string): ReadonlyArray<QueryChart> => {
250 timeSeries(
251 "cloudflare-api",
252 "Cloudflare API calls by status",
253 - `${source}\n| where ${CLOUDFLARE_API}\n| summarize count() by bin_auto(_time), status = ${STATUS}`,
253 + // Calls refused during a rate-limit pause never reach Cloudflare, so
254 + // they are their own series or a storm would look like a quiet period.
255 + `${source}\n| where ${CLOUDFLARE_API} or name == "relay.cloudflare_api_pause.rejected"\n| summarize count() by bin_auto(_time), status = case(name == "relay.cloudflare_api_pause.rejected", "paused", isnull(${STATUS}), "no response", tostring(${STATUS}))`,
256 + ),
257 + timeSeries(
258 + "provision-paths",
259 + "Tunnel provisions by path",
260 + `${source}\n| where name == "relay.managed_endpoint_provider.provision"\n| summarize reused_ready_tunnel = countif(error != true and tobool(['attributes.custom']['relay.managed_endpoint.reused_ready_tunnel']) == true), full_provision = countif(error != true and isnull(['attributes.custom']['relay.managed_endpoint.reused_ready_tunnel'])), failed = countif(error == true) by bin_auto(_time)`,
261 ),
262 timeSeries(
263 "postgres",
infra/relay/src/persistence/schema.ts
+8
@@ -5,6 +5,7 @@ import type {
5 RelayManagedEndpointOrigin,
6 } from "@t3tools/contracts/relay";
7 import {
8 + bigint,
9 boolean,
10 index,
11 integer,
@@ -111,6 +112,13 @@ export const relayManagedEndpointAllocations = pgTable(
112 ],
113 );
114
115 +// One row per upstream API whose rate limit is shared by every Worker
116 +// isolate, so a 429 seen by one isolate pauses the rest.
117 +export const relayUpstreamApiPauses = pgTable("relay_upstream_api_pauses", {
118 + api: varchar("api", { length: 64 }).primaryKey(),
119 + pausedUntilMs: bigint("paused_until_ms", { mode: "number" }).notNull(),
120 +});
121 +
122 export const relayManagedTunnelLimits = pgTable("relay_managed_tunnel_limits", {
123 userId: varchar("user_id", { length: 191 }).primaryKey(),
124 maxTunnels: integer("max_tunnels").notNull(),
infra/relay/src/worker.ts
+2
@@ -57,6 +57,7 @@ import * as ApnsClient from "./agentActivity/ApnsClient.ts";
57 import * as ApnsProviderTokens from "./agentActivity/ApnsProviderTokens.ts";
58 import * as ApnsDeliveryQueue from "./agentActivity/ApnsDeliveryQueue.ts";
59 import * as ApnsDeliveries from "./agentActivity/ApnsDeliveries.ts";
60 +import * as CloudflareApiPause from "./environments/CloudflareApiPause.ts";
61 import * as EnvironmentConnector from "./environments/EnvironmentConnector.ts";
62 import * as EnvironmentLinker from "./environments/EnvironmentLinker.ts";
63 import * as EnvironmentPublishSignatures from "./environments/EnvironmentPublishSignatures.ts";
@@ -291,6 +292,7 @@ export const layer = Api.make(
292 Layer.provideMerge(EnvironmentCredentials.layer),
293 Layer.provideMerge(
294 Layer.mergeAll(
295 + CloudflareApiPause.layer,
296 EnvironmentLinks.layer,
297 ManagedEndpointAllocations.layer,
298 ManagedTunnelLimits.layer,
pnpm-lock.yaml
+6
@@ -6,6 +6,9 @@ settings:
6
7 catalogs:
8 default:
9 + '@distilled.cloud/cloudflare':
10 + specifier: 1.0.0-rc.13
11 + version: 1.0.0-rc.13
12 '@effect/graphql-generator':
13 specifier: 4.0.5
14 version: 4.0.5
@@ -1064,6 +1067,9 @@ importers:
1067 '@clerk/backend':
1068 specifier: 3.25.0
1069 version: 3.25.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
1070 + '@distilled.cloud/cloudflare':
1071 + specifier: 'catalog:'
1072 + version: 1.0.0-rc.13(effect@4.0.5)
1073 '@effect/sql-pg':
1074 specifier: 4.0.5
1075 version: 4.0.5(effect@4.0.5)
pnpm-workspace.yaml
+3
@@ -34,6 +34,9 @@ catalog:
34 "@clerk/expo": 4.13.0
35 "@clerk/react": 6.17.8
36 "@clerk/shared": 4.40.0
37 + # Must match the version alchemy depends on: the relay overrides its
38 + # Cloudflare retry policy through this package's Retry service.
39 + "@distilled.cloud/cloudflare": 1.0.0-rc.13
40 "@effect/atom-react": 4.0.5
41 "@effect/graphql-generator": 4.0.5
42 "@effect/openapi-generator": 4.0.5