@geekmidas/constructs 10.0.0-alpha.16 → 10.0.0-alpha.161
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +246 -158
- package/dist/Construct-127M7yrl.d.cts +231 -0
- package/dist/Construct-127M7yrl.d.cts.map +1 -0
- package/dist/Construct-BMk_CRSD.d.mts +231 -0
- package/dist/Construct-BMk_CRSD.d.mts.map +1 -0
- package/dist/{Construct-BeYVu_QF.mjs → Construct-CGuc_Ijk.mjs} +8 -9
- package/dist/Construct-CGuc_Ijk.mjs.map +1 -0
- package/dist/{Construct-DqdlARxq.cjs → Construct-DorKS0Ua.cjs} +8 -9
- package/dist/Construct-DorKS0Ua.cjs.map +1 -0
- package/dist/{Cron-l4Wlz6G9.d.mts → Cron-D6Y7BBt3.d.mts} +15 -8
- package/dist/Cron-D6Y7BBt3.d.mts.map +1 -0
- package/dist/{Cron-zsoSAwZo.d.cts → Cron-D_sfaMGz.d.cts} +14 -7
- package/dist/Cron-D_sfaMGz.d.cts.map +1 -0
- package/dist/CronBuilder-4BZhkChG.d.mts +47 -0
- package/dist/CronBuilder-4BZhkChG.d.mts.map +1 -0
- package/dist/{CronBuilder-D_0HNBTr.mjs → CronBuilder-BJ5LoadF.mjs} +28 -11
- package/dist/CronBuilder-BJ5LoadF.mjs.map +1 -0
- package/dist/{CronBuilder-BdnI6lxF.cjs → CronBuilder-B_NSP-Y5.cjs} +27 -10
- package/dist/CronBuilder-B_NSP-Y5.cjs.map +1 -0
- package/dist/CronBuilder-C91MVLSr.d.cts +47 -0
- package/dist/CronBuilder-C91MVLSr.d.cts.map +1 -0
- package/dist/Endpoint-52z1P0Ue.cjs +581 -0
- package/dist/Endpoint-52z1P0Ue.cjs.map +1 -0
- package/dist/{Endpoint-oS-Fe3d_.d.mts → Endpoint-BUoDD96P.d.mts} +104 -23
- package/dist/Endpoint-BUoDD96P.d.mts.map +1 -0
- package/dist/{Endpoint-DBflWAe4.d.cts → Endpoint-YYwjqtS1.d.cts} +101 -20
- package/dist/Endpoint-YYwjqtS1.d.cts.map +1 -0
- package/dist/Endpoint-sUOU7uLx.mjs +552 -0
- package/dist/Endpoint-sUOU7uLx.mjs.map +1 -0
- package/dist/{index-Cc4kKPag.d.mts → EndpointFactory-BbVOeryo.d.mts} +189 -106
- package/dist/EndpointFactory-BbVOeryo.d.mts.map +1 -0
- package/dist/{EndpointFactory-Bm3aKRdV.mjs → EndpointFactory-Bzi9Sl7r.mjs} +269 -53
- package/dist/EndpointFactory-Bzi9Sl7r.mjs.map +1 -0
- package/dist/{EndpointFactory-CLvWuHyt.cjs → EndpointFactory-Cf_Cs1ym.cjs} +309 -51
- package/dist/EndpointFactory-Cf_Cs1ym.cjs.map +1 -0
- package/dist/{index-C1ZwNOOk.d.cts → EndpointFactory-Hh1r6J_C.d.cts} +187 -104
- package/dist/EndpointFactory-Hh1r6J_C.d.cts.map +1 -0
- package/dist/Function-BIEsY0Hm.d.cts +76 -0
- package/dist/Function-BIEsY0Hm.d.cts.map +1 -0
- package/dist/Function-BKReud5p.d.mts +76 -0
- package/dist/Function-BKReud5p.d.mts.map +1 -0
- package/dist/{HonoEndpointAdaptor-92zavCsV.cjs → HonoEndpointAdaptor-BTbqfSaa.cjs} +115 -41
- package/dist/HonoEndpointAdaptor-BTbqfSaa.cjs.map +1 -0
- package/dist/{HonoEndpointAdaptor-yYaU7jVJ.mjs → HonoEndpointAdaptor-CBVey2cY.mjs} +112 -38
- package/dist/HonoEndpointAdaptor-CBVey2cY.mjs.map +1 -0
- package/dist/ObjectSubscriberBuilder-DfzXQEKW.d.mts +129 -0
- package/dist/ObjectSubscriberBuilder-DfzXQEKW.d.mts.map +1 -0
- package/dist/ObjectSubscriberBuilder-LWkey_oq.d.cts +129 -0
- package/dist/ObjectSubscriberBuilder-LWkey_oq.d.cts.map +1 -0
- package/dist/ProcessorBuilder-D4oYvZeG.d.mts +216 -0
- package/dist/ProcessorBuilder-D4oYvZeG.d.mts.map +1 -0
- package/dist/ProcessorBuilder-_jdZlbfW.d.cts +216 -0
- package/dist/ProcessorBuilder-_jdZlbfW.d.cts.map +1 -0
- package/dist/{Queue-D9X6OoON.d.mts → Queue-B8HGg439.d.mts} +42 -41
- package/dist/Queue-B8HGg439.d.mts.map +1 -0
- package/dist/{Queue-DYPB2KWL.d.cts → Queue-C4rijiM7.d.cts} +43 -42
- package/dist/Queue-C4rijiM7.d.cts.map +1 -0
- package/dist/Queue-D4Iaidrs.cjs +109 -0
- package/dist/Queue-D4Iaidrs.cjs.map +1 -0
- package/dist/Queue-u8w8_HpE.mjs +104 -0
- package/dist/Queue-u8w8_HpE.mjs.map +1 -0
- package/dist/QueueBuilder-2wP5lEC8.mjs +118 -0
- package/dist/QueueBuilder-2wP5lEC8.mjs.map +1 -0
- package/dist/QueueBuilder-BxsZ9o5z.cjs +135 -0
- package/dist/QueueBuilder-BxsZ9o5z.cjs.map +1 -0
- package/dist/QueueBuilder-CVS_qPuo.d.mts +75 -0
- package/dist/QueueBuilder-CVS_qPuo.d.mts.map +1 -0
- package/dist/QueueBuilder-SQli59An.d.cts +75 -0
- package/dist/QueueBuilder-SQli59An.d.cts.map +1 -0
- package/dist/Subscriber-5rCX1Nph.d.cts +83 -0
- package/dist/Subscriber-5rCX1Nph.d.cts.map +1 -0
- package/dist/Subscriber-CtQXhcL7.d.mts +83 -0
- package/dist/Subscriber-CtQXhcL7.d.mts.map +1 -0
- package/dist/SubscriberBuilder-CpFhShTJ.mjs +238 -0
- package/dist/SubscriberBuilder-CpFhShTJ.mjs.map +1 -0
- package/dist/SubscriberBuilder-DJEvNRdD.cjs +261 -0
- package/dist/SubscriberBuilder-DJEvNRdD.cjs.map +1 -0
- package/dist/Topic-DN2gYJ-p.mjs +99 -0
- package/dist/Topic-DN2gYJ-p.mjs.map +1 -0
- package/dist/Topic-Dp9Q7Lj2.cjs +104 -0
- package/dist/Topic-Dp9Q7Lj2.cjs.map +1 -0
- package/dist/adaptors/aws.cjs +147 -168
- package/dist/adaptors/aws.cjs.map +1 -1
- package/dist/adaptors/aws.d.cts +57 -48
- package/dist/adaptors/aws.d.cts.map +1 -1
- package/dist/adaptors/aws.d.mts +58 -49
- package/dist/adaptors/aws.d.mts.map +1 -1
- package/dist/adaptors/aws.mjs +142 -164
- package/dist/adaptors/aws.mjs.map +1 -1
- package/dist/adaptors/awsWebsocket.cjs +354 -0
- package/dist/adaptors/awsWebsocket.cjs.map +1 -0
- package/dist/adaptors/awsWebsocket.d.cts +156 -0
- package/dist/adaptors/awsWebsocket.d.cts.map +1 -0
- package/dist/adaptors/awsWebsocket.d.mts +156 -0
- package/dist/adaptors/awsWebsocket.d.mts.map +1 -0
- package/dist/adaptors/awsWebsocket.mjs +347 -0
- package/dist/adaptors/awsWebsocket.mjs.map +1 -0
- package/dist/adaptors/hono.cjs +1 -1
- package/dist/adaptors/hono.d.cts +8 -7
- package/dist/adaptors/hono.d.cts.map +1 -1
- package/dist/adaptors/hono.d.mts +10 -9
- package/dist/adaptors/hono.d.mts.map +1 -1
- package/dist/adaptors/hono.mjs +1 -1
- package/dist/adaptors/testing.cjs +1174 -41
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts +517 -40
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts +517 -40
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +1140 -36
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/auth-BqWz2JxC.d.cts +274 -0
- package/dist/auth-BqWz2JxC.d.cts.map +1 -0
- package/dist/auth-DnB9H9KL.d.mts +274 -0
- package/dist/auth-DnB9H9KL.d.mts.map +1 -0
- package/dist/auth.cjs +308 -23
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +2 -104
- package/dist/auth.d.mts +2 -104
- package/dist/auth.mjs +304 -25
- package/dist/auth.mjs.map +1 -1
- package/dist/cache-CCHcO9Oo.d.mts +44 -0
- package/dist/cache-CCHcO9Oo.d.mts.map +1 -0
- package/dist/cache-CQjMNPrC.d.cts +44 -0
- package/dist/cache-CQjMNPrC.d.cts.map +1 -0
- package/dist/cache.cjs +3 -19
- package/dist/cache.cjs.map +1 -1
- package/dist/cache.d.cts +2 -43
- package/dist/cache.d.mts +2 -43
- package/dist/cache.mjs +2 -18
- package/dist/cache.mjs.map +1 -1
- package/dist/cipher-C1lEFX63.mjs +225 -0
- package/dist/cipher-C1lEFX63.mjs.map +1 -0
- package/dist/cipher-CVxfwLjk.cjs +332 -0
- package/dist/cipher-CVxfwLjk.cjs.map +1 -0
- package/dist/cipher-DSDxPRIp.d.cts +106 -0
- package/dist/cipher-DSDxPRIp.d.cts.map +1 -0
- package/dist/cipher-DSDxPRIp.d.mts +106 -0
- package/dist/cipher-DSDxPRIp.d.mts.map +1 -0
- package/dist/{construct-interface-DPlxfpoS.d.mts → construct-interface-CSA9VeWM.d.mts} +47 -8
- package/dist/construct-interface-CSA9VeWM.d.mts.map +1 -0
- package/dist/{construct-interface-DgXTJcOD.d.cts → construct-interface-DugP0E5q.d.cts} +47 -8
- package/dist/construct-interface-DugP0E5q.d.cts.map +1 -0
- package/dist/construct-interface.cjs +38 -4
- package/dist/construct-interface.cjs.map +1 -1
- package/dist/construct-interface.d.cts +2 -2
- package/dist/construct-interface.d.mts +2 -2
- package/dist/construct-interface.mjs +37 -5
- package/dist/construct-interface.mjs.map +1 -1
- package/dist/credential-DYymbp_7.cjs +257 -0
- package/dist/credential-DYymbp_7.cjs.map +1 -0
- package/dist/credential-DfSAOOdY.mjs +222 -0
- package/dist/credential-DfSAOOdY.mjs.map +1 -0
- package/dist/credential.cjs +7 -129
- package/dist/credential.d.cts +2 -58
- package/dist/credential.d.mts +2 -58
- package/dist/credential.mjs +2 -128
- package/dist/crons/index.cjs +127 -1
- package/dist/crons/index.cjs.map +1 -1
- package/dist/crons/index.d.cts +43 -3
- package/dist/crons/index.d.cts.map +1 -1
- package/dist/crons/index.d.mts +43 -3
- package/dist/crons/index.d.mts.map +1 -1
- package/dist/crons/index.mjs +126 -2
- package/dist/crons/index.mjs.map +1 -1
- package/dist/database/kysely.cjs +3 -194
- package/dist/database/kysely.d.cts +2 -149
- package/dist/database/kysely.d.mts +2 -149
- package/dist/database/kysely.mjs +2 -192
- package/dist/email.cjs +4 -16
- package/dist/email.cjs.map +1 -1
- package/dist/email.d.cts +1 -1
- package/dist/email.d.cts.map +1 -1
- package/dist/email.d.mts +2 -2
- package/dist/email.d.mts.map +1 -1
- package/dist/email.mjs +2 -14
- package/dist/email.mjs.map +1 -1
- package/dist/encryption/kms.cjs +95 -0
- package/dist/encryption/kms.cjs.map +1 -0
- package/dist/encryption/kms.d.cts +7 -0
- package/dist/encryption/kms.d.cts.map +1 -0
- package/dist/encryption/kms.d.mts +7 -0
- package/dist/encryption/kms.d.mts.map +1 -0
- package/dist/encryption/kms.mjs +93 -0
- package/dist/encryption/kms.mjs.map +1 -0
- package/dist/encryption.cjs +116 -0
- package/dist/encryption.cjs.map +1 -0
- package/dist/encryption.d.cts +37 -0
- package/dist/encryption.d.cts.map +1 -0
- package/dist/encryption.d.mts +37 -0
- package/dist/encryption.d.mts.map +1 -0
- package/dist/encryption.mjs +101 -0
- package/dist/encryption.mjs.map +1 -0
- package/dist/endpoints/index.cjs +32 -10
- package/dist/endpoints/index.d.cts +106 -3
- package/dist/endpoints/index.d.cts.map +1 -0
- package/dist/endpoints/index.d.mts +106 -3
- package/dist/endpoints/index.d.mts.map +1 -0
- package/dist/endpoints/index.mjs +6 -4
- package/dist/expire-C586zznE.d.cts +38 -0
- package/dist/expire-C586zznE.d.cts.map +1 -0
- package/dist/expire-C586zznE.d.mts +38 -0
- package/dist/expire-C586zznE.d.mts.map +1 -0
- package/dist/expire-CieftS01.cjs +67 -0
- package/dist/expire-CieftS01.cjs.map +1 -0
- package/dist/expire-CpzUAfr9.mjs +50 -0
- package/dist/expire-CpzUAfr9.mjs.map +1 -0
- package/dist/external-api.cjs +106 -0
- package/dist/external-api.cjs.map +1 -0
- package/dist/external-api.d.cts +2 -0
- package/dist/external-api.d.mts +2 -0
- package/dist/external-api.mjs +103 -0
- package/dist/external-api.mjs.map +1 -0
- package/dist/fake-BqhP8RRQ.d.mts +201 -0
- package/dist/fake-BqhP8RRQ.d.mts.map +1 -0
- package/dist/fake-DqieDYYA.d.cts +201 -0
- package/dist/fake-DqieDYYA.d.cts.map +1 -0
- package/dist/file-server.cjs +123 -30
- package/dist/file-server.cjs.map +1 -1
- package/dist/file-server.d.cts +115 -1
- package/dist/file-server.d.cts.map +1 -1
- package/dist/file-server.d.mts +115 -1
- package/dist/file-server.d.mts.map +1 -1
- package/dist/file-server.mjs +122 -32
- package/dist/file-server.mjs.map +1 -1
- package/dist/functions/index.cjs +1 -1
- package/dist/functions/index.d.cts +2 -1
- package/dist/functions/index.d.mts +2 -1
- package/dist/functions/index.mjs +1 -1
- package/dist/{functions-C53GW2eQ.mjs → functions-BvIDQKAA.mjs} +117 -22
- package/dist/functions-BvIDQKAA.mjs.map +1 -0
- package/dist/{functions-B6qCvfmy.cjs → functions-DLF6-IK8.cjs} +122 -18
- package/dist/functions-DLF6-IK8.cjs.map +1 -0
- package/dist/inbox-CR3L1fOI.d.cts +195 -0
- package/dist/inbox-CR3L1fOI.d.cts.map +1 -0
- package/dist/inbox-YOdxlyfj.d.mts +195 -0
- package/dist/inbox-YOdxlyfj.d.mts.map +1 -0
- package/dist/inbox.cjs +291 -0
- package/dist/inbox.cjs.map +1 -0
- package/dist/inbox.d.cts +2 -0
- package/dist/inbox.d.mts +2 -0
- package/dist/inbox.mjs +283 -0
- package/dist/inbox.mjs.map +1 -0
- package/dist/index-BoQ3-M-K.d.mts +115 -0
- package/dist/index-BoQ3-M-K.d.mts.map +1 -0
- package/dist/index-DPTHa6Ud.d.cts +115 -0
- package/dist/index-DPTHa6Ud.d.cts.map +1 -0
- package/dist/{index-CeEtxDmK.d.cts → index-DdRjYhiJ.d.cts} +42 -2
- package/dist/{index-CeEtxDmK.d.cts.map → index-DdRjYhiJ.d.cts.map} +1 -1
- package/dist/{index-CeEtxDmK.d.mts → index-DdRjYhiJ.d.mts} +42 -2
- package/dist/{index-CeEtxDmK.d.mts.map → index-DdRjYhiJ.d.mts.map} +1 -1
- package/dist/index.cjs +4 -1
- package/dist/index.d.cts +26 -3
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +26 -3
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +3 -2
- package/dist/kysely-CebjCWTl.d.cts +216 -0
- package/dist/kysely-CebjCWTl.d.cts.map +1 -0
- package/dist/kysely-Cs4uPO8k.mjs +371 -0
- package/dist/kysely-Cs4uPO8k.mjs.map +1 -0
- package/dist/kysely-CukArHJ0.cjs +384 -0
- package/dist/kysely-CukArHJ0.cjs.map +1 -0
- package/dist/kysely-De5rAC-E.d.mts +216 -0
- package/dist/kysely-De5rAC-E.d.mts.map +1 -0
- package/dist/{telemetry-DGcFlVpB.d.cts → lambdaTelemetry-8vnmVZQ5.d.cts} +2 -2
- package/dist/lambdaTelemetry-8vnmVZQ5.d.cts.map +1 -0
- package/dist/{telemetry-DGcFlVpB.d.mts → lambdaTelemetry-8vnmVZQ5.d.mts} +2 -2
- package/dist/lambdaTelemetry-8vnmVZQ5.d.mts.map +1 -0
- package/dist/mobile-app.cjs +74 -0
- package/dist/mobile-app.cjs.map +1 -0
- package/dist/mobile-app.d.cts +73 -0
- package/dist/mobile-app.d.cts.map +1 -0
- package/dist/mobile-app.d.mts +73 -0
- package/dist/mobile-app.d.mts.map +1 -0
- package/dist/mobile-app.mjs +73 -0
- package/dist/mobile-app.mjs.map +1 -0
- package/dist/object-storage.cjs +8 -1
- package/dist/object-storage.cjs.map +1 -1
- package/dist/object-storage.d.cts +10 -1
- package/dist/object-storage.d.cts.map +1 -1
- package/dist/object-storage.d.mts +10 -1
- package/dist/object-storage.d.mts.map +1 -1
- package/dist/object-storage.mjs +7 -2
- package/dist/object-storage.mjs.map +1 -1
- package/dist/optionalPeers-D7Wt6dnF.mjs +140 -0
- package/dist/optionalPeers-D7Wt6dnF.mjs.map +1 -0
- package/dist/optionalPeers-DuNQXXe1.cjs +223 -0
- package/dist/optionalPeers-DuNQXXe1.cjs.map +1 -0
- package/dist/origins-BjxYht13.cjs +96 -0
- package/dist/origins-BjxYht13.cjs.map +1 -0
- package/dist/origins-Boc9qbo-.mjs +73 -0
- package/dist/origins-Boc9qbo-.mjs.map +1 -0
- package/dist/pattern-C1CEcglD.mjs +241 -0
- package/dist/pattern-C1CEcglD.mjs.map +1 -0
- package/dist/pattern-QFaUIr77.cjs +288 -0
- package/dist/pattern-QFaUIr77.cjs.map +1 -0
- package/dist/privateAddress-Bg5fUsbp.mjs +21 -0
- package/dist/privateAddress-Bg5fUsbp.mjs.map +1 -0
- package/dist/privateAddress-CqGyuFHn.cjs +26 -0
- package/dist/privateAddress-CqGyuFHn.cjs.map +1 -0
- package/dist/processors/index.cjs +214 -0
- package/dist/processors/index.cjs.map +1 -0
- package/dist/processors/index.d.cts +78 -0
- package/dist/processors/index.d.cts.map +1 -0
- package/dist/processors/index.d.mts +78 -0
- package/dist/processors/index.d.mts.map +1 -0
- package/dist/processors/index.mjs +193 -0
- package/dist/processors/index.mjs.map +1 -0
- package/dist/queue/index.cjs +5 -192
- package/dist/queue/index.d.cts +3 -53
- package/dist/queue/index.d.mts +3 -53
- package/dist/queue/index.mjs +3 -190
- package/dist/random-password.cjs +86 -0
- package/dist/random-password.cjs.map +1 -0
- package/dist/random-password.d.cts +30 -0
- package/dist/random-password.d.cts.map +1 -0
- package/dist/random-password.d.mts +30 -0
- package/dist/random-password.d.mts.map +1 -0
- package/dist/random-password.mjs +84 -0
- package/dist/random-password.mjs.map +1 -0
- package/dist/readRequestBody-BmKnPl0a.mjs +293 -0
- package/dist/readRequestBody-BmKnPl0a.mjs.map +1 -0
- package/dist/{lazyAccessors-Dx9NLwJZ.cjs → readRequestBody-CN9GVdeE.cjs} +141 -47
- package/dist/readRequestBody-CN9GVdeE.cjs.map +1 -0
- package/dist/{processAudits-D_2W5x8k.cjs → requestLogger-CnoYd-Ah.cjs} +63 -3
- package/dist/requestLogger-CnoYd-Ah.cjs.map +1 -0
- package/dist/{processAudits-BpRlPQMW.mjs → requestLogger-D2JS7pPM.mjs} +51 -3
- package/dist/requestLogger-D2JS7pPM.mjs.map +1 -0
- package/dist/rest-api.cjs +85 -70
- package/dist/rest-api.cjs.map +1 -1
- package/dist/rest-api.d.cts +77 -59
- package/dist/rest-api.d.cts.map +1 -1
- package/dist/rest-api.d.mts +77 -59
- package/dist/rest-api.d.mts.map +1 -1
- package/dist/rest-api.mjs +87 -72
- package/dist/rest-api.mjs.map +1 -1
- package/dist/runSubscriber-HEqXkin1.mjs +117 -0
- package/dist/runSubscriber-HEqXkin1.mjs.map +1 -0
- package/dist/runSubscriber-sVJfLA0-.cjs +134 -0
- package/dist/runSubscriber-sVJfLA0-.cjs.map +1 -0
- package/dist/shutdown-BMJmAhSt.cjs +38 -0
- package/dist/shutdown-BMJmAhSt.cjs.map +1 -0
- package/dist/shutdown-C7xa8x9S.mjs +27 -0
- package/dist/shutdown-C7xa8x9S.mjs.map +1 -0
- package/dist/site.cjs +104 -8
- package/dist/site.cjs.map +1 -1
- package/dist/site.d.cts +132 -2
- package/dist/site.d.cts.map +1 -1
- package/dist/site.d.mts +132 -2
- package/dist/site.d.mts.map +1 -1
- package/dist/site.mjs +102 -11
- package/dist/site.mjs.map +1 -1
- package/dist/stages-DaTaoQei.d.cts +73 -0
- package/dist/stages-DaTaoQei.d.cts.map +1 -0
- package/dist/stages-DaTaoQei.d.mts +73 -0
- package/dist/stages-DaTaoQei.d.mts.map +1 -0
- package/dist/subscribers/index.cjs +134 -1
- package/dist/subscribers/index.cjs.map +1 -0
- package/dist/subscribers/index.d.cts +74 -3
- package/dist/subscribers/index.d.cts.map +1 -0
- package/dist/subscribers/index.d.mts +74 -3
- package/dist/subscribers/index.d.mts.map +1 -0
- package/dist/subscribers/index.mjs +132 -2
- package/dist/subscribers/index.mjs.map +1 -0
- package/dist/telemetry-C1oqncFY.d.cts +40 -0
- package/dist/telemetry-C1oqncFY.d.cts.map +1 -0
- package/dist/telemetry-CObow3Dn.d.mts +40 -0
- package/dist/telemetry-CObow3Dn.d.mts.map +1 -0
- package/dist/telemetry.cjs +56 -0
- package/dist/telemetry.cjs.map +1 -0
- package/dist/telemetry.d.cts +2 -0
- package/dist/telemetry.d.mts +2 -0
- package/dist/telemetry.mjs +55 -0
- package/dist/telemetry.mjs.map +1 -0
- package/dist/topic/index.cjs +2 -134
- package/dist/topic/index.d.cts +2 -3
- package/dist/topic/index.d.mts +2 -3
- package/dist/topic/index.mjs +2 -132
- package/dist/tracing-Bbj1uoFJ.mjs +127 -0
- package/dist/tracing-Bbj1uoFJ.mjs.map +1 -0
- package/dist/tracing-C0ooU0V2.cjs +150 -0
- package/dist/tracing-C0ooU0V2.cjs.map +1 -0
- package/dist/websocket-api-Bg9SowJ5.mjs +1710 -0
- package/dist/websocket-api-Bg9SowJ5.mjs.map +1 -0
- package/dist/websocket-api-CPEzJyDt.d.mts +1201 -0
- package/dist/websocket-api-CPEzJyDt.d.mts.map +1 -0
- package/dist/websocket-api-DkF8Hva-.d.cts +1201 -0
- package/dist/websocket-api-DkF8Hva-.d.cts.map +1 -0
- package/dist/websocket-api-czxhekGG.cjs +1889 -0
- package/dist/websocket-api-czxhekGG.cjs.map +1 -0
- package/dist/websocket-api.cjs +35 -0
- package/dist/websocket-api.d.cts +2 -0
- package/dist/websocket-api.d.mts +2 -0
- package/dist/websocket-api.mjs +3 -0
- package/dist/worker.cjs +174 -32
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +147 -47
- package/dist/worker.d.cts.map +1 -1
- package/dist/worker.d.mts +147 -47
- package/dist/worker.d.mts.map +1 -1
- package/dist/worker.mjs +175 -33
- package/dist/worker.mjs.map +1 -1
- package/package.json +180 -43
- package/dist/Construct-BeYVu_QF.mjs.map +0 -1
- package/dist/Construct-DfbwIntp.d.cts +0 -115
- package/dist/Construct-DfbwIntp.d.cts.map +0 -1
- package/dist/Construct-DqdlARxq.cjs.map +0 -1
- package/dist/Construct-l5aOn_jv.d.mts +0 -115
- package/dist/Construct-l5aOn_jv.d.mts.map +0 -1
- package/dist/Cron-l4Wlz6G9.d.mts.map +0 -1
- package/dist/Cron-zsoSAwZo.d.cts.map +0 -1
- package/dist/CronBuilder-BdnI6lxF.cjs.map +0 -1
- package/dist/CronBuilder-CyT71Nzg.d.cts +0 -41
- package/dist/CronBuilder-CyT71Nzg.d.cts.map +0 -1
- package/dist/CronBuilder-D_0HNBTr.mjs.map +0 -1
- package/dist/CronBuilder-UoNgFe8S.d.mts +0 -41
- package/dist/CronBuilder-UoNgFe8S.d.mts.map +0 -1
- package/dist/Endpoint-BpZHtJ2W.cjs +0 -1689
- package/dist/Endpoint-BpZHtJ2W.cjs.map +0 -1
- package/dist/Endpoint-DBflWAe4.d.cts.map +0 -1
- package/dist/Endpoint-ONsly_dq.mjs +0 -1671
- package/dist/Endpoint-ONsly_dq.mjs.map +0 -1
- package/dist/Endpoint-oS-Fe3d_.d.mts.map +0 -1
- package/dist/EndpointFactory-Bm3aKRdV.mjs.map +0 -1
- package/dist/EndpointFactory-CLvWuHyt.cjs.map +0 -1
- package/dist/HonoEndpointAdaptor-92zavCsV.cjs.map +0 -1
- package/dist/HonoEndpointAdaptor-yYaU7jVJ.mjs.map +0 -1
- package/dist/Queue-D9X6OoON.d.mts.map +0 -1
- package/dist/Queue-DYPB2KWL.d.cts.map +0 -1
- package/dist/Subscriber-C4heaAyO.d.mts +0 -51
- package/dist/Subscriber-C4heaAyO.d.mts.map +0 -1
- package/dist/Subscriber-CotDUELC.d.cts +0 -51
- package/dist/Subscriber-CotDUELC.d.cts.map +0 -1
- package/dist/SubscriberBuilder-BEv0eoHy.d.cts +0 -59
- package/dist/SubscriberBuilder-BEv0eoHy.d.cts.map +0 -1
- package/dist/SubscriberBuilder-C0ZEtGDI.cjs +0 -125
- package/dist/SubscriberBuilder-C0ZEtGDI.cjs.map +0 -1
- package/dist/SubscriberBuilder-h7B_cHMr.mjs +0 -114
- package/dist/SubscriberBuilder-h7B_cHMr.mjs.map +0 -1
- package/dist/SubscriberBuilder-tyH5yTk5.d.mts +0 -59
- package/dist/SubscriberBuilder-tyH5yTk5.d.mts.map +0 -1
- package/dist/Topic-DEVGo0Dm.d.cts +0 -89
- package/dist/Topic-DEVGo0Dm.d.cts.map +0 -1
- package/dist/Topic-zk_6Gthr.d.mts +0 -89
- package/dist/Topic-zk_6Gthr.d.mts.map +0 -1
- package/dist/auth.d.cts.map +0 -1
- package/dist/auth.d.mts.map +0 -1
- package/dist/cache.d.cts.map +0 -1
- package/dist/cache.d.mts.map +0 -1
- package/dist/construct-interface-DPlxfpoS.d.mts.map +0 -1
- package/dist/construct-interface-DgXTJcOD.d.cts.map +0 -1
- package/dist/credential.cjs.map +0 -1
- package/dist/credential.d.cts.map +0 -1
- package/dist/credential.d.mts.map +0 -1
- package/dist/credential.mjs.map +0 -1
- package/dist/database/kysely.cjs.map +0 -1
- package/dist/database/kysely.d.cts.map +0 -1
- package/dist/database/kysely.d.mts.map +0 -1
- package/dist/database/kysely.mjs.map +0 -1
- package/dist/functions-B6qCvfmy.cjs.map +0 -1
- package/dist/functions-C53GW2eQ.mjs.map +0 -1
- package/dist/index-B2urf3YI.d.cts +0 -26
- package/dist/index-B2urf3YI.d.cts.map +0 -1
- package/dist/index-C1ZwNOOk.d.cts.map +0 -1
- package/dist/index-Cc4kKPag.d.mts.map +0 -1
- package/dist/index-DMCDvnsM.d.mts +0 -26
- package/dist/index-DMCDvnsM.d.mts.map +0 -1
- package/dist/index-D_frT6MP.d.cts +0 -165
- package/dist/index-D_frT6MP.d.cts.map +0 -1
- package/dist/index-DcyIYbDS.d.mts +0 -165
- package/dist/index-DcyIYbDS.d.mts.map +0 -1
- package/dist/lazyAccessors-BHtcqgz2.mjs +0 -211
- package/dist/lazyAccessors-BHtcqgz2.mjs.map +0 -1
- package/dist/lazyAccessors-Dx9NLwJZ.cjs.map +0 -1
- package/dist/processAudits-BpRlPQMW.mjs.map +0 -1
- package/dist/processAudits-D_2W5x8k.cjs.map +0 -1
- package/dist/queue/index.cjs.map +0 -1
- package/dist/queue/index.d.cts.map +0 -1
- package/dist/queue/index.d.mts.map +0 -1
- package/dist/queue/index.mjs.map +0 -1
- package/dist/telemetry-DGcFlVpB.d.cts.map +0 -1
- package/dist/telemetry-DGcFlVpB.d.mts.map +0 -1
- package/dist/topic/index.cjs.map +0 -1
- package/dist/topic/index.mjs.map +0 -1
|
@@ -0,0 +1,1889 @@
|
|
|
1
|
+
const require_shutdown = require("./shutdown-BMJmAhSt.cjs");
|
|
2
|
+
const require_construct_interface = require("./construct-interface.cjs");
|
|
3
|
+
const require_optionalPeers = require("./optionalPeers-DuNQXXe1.cjs");
|
|
4
|
+
const require_privateAddress = require("./privateAddress-CqGyuFHn.cjs");
|
|
5
|
+
const require_surfaceEnv = require("./surfaceEnv-CNimK76p.cjs");
|
|
6
|
+
const require_origins = require("./origins-BjxYht13.cjs");
|
|
7
|
+
let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
8
|
+
let _geekmidas_logger_console = require("@geekmidas/logger/console");
|
|
9
|
+
let node_crypto = require("node:crypto");
|
|
10
|
+
let _geekmidas_services = require("@geekmidas/services");
|
|
11
|
+
let _geekmidas_errors = require("@geekmidas/errors");
|
|
12
|
+
let _geekmidas_schema_conversion = require("@geekmidas/schema/conversion");
|
|
13
|
+
//#region src/websocket/frame.ts
|
|
14
|
+
/**
|
|
15
|
+
* The shape a surface's frames take on the wire.
|
|
16
|
+
*
|
|
17
|
+
* By default a frame is `{ "action": …, "id"?: …, "data": … }` — API
|
|
18
|
+
* Gateway's shape. A surface that names a discriminator — `frame: {
|
|
19
|
+
* discriminator: 'type' }` — sends and reads flat frames instead: the action
|
|
20
|
+
* under that key, and the data's own fields beside it.
|
|
21
|
+
*
|
|
22
|
+
* ```json
|
|
23
|
+
* {"type":"chat.message.created","chatId":"c1","message":{…}}
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* A flat frame has no `id` of its own: every field but the discriminator is
|
|
27
|
+
* the data, so a reply is paired by its action, not an echoed id.
|
|
28
|
+
*/
|
|
29
|
+
/** A declared message whose schema does not describe an object. */
|
|
30
|
+
var WebSocketMessageNotAnObject = class extends Error {
|
|
31
|
+
surface;
|
|
32
|
+
action;
|
|
33
|
+
discriminator;
|
|
34
|
+
constructor(surface, action, discriminator) {
|
|
35
|
+
super(`${surface} sends flat frames, keyed by '${discriminator}', so each message's fields sit beside it — but '${action}' is not an object schema. Declare it as an object (z.object({ … })), or drop \`frame\` to send { action, data }.`);
|
|
36
|
+
this.surface = surface;
|
|
37
|
+
this.action = action;
|
|
38
|
+
this.discriminator = discriminator;
|
|
39
|
+
this.name = "WebSocketMessageNotAnObject";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
/** A declared message whose schema has a field named the discriminator. */
|
|
43
|
+
var WebSocketMessageDeclaresDiscriminator = class extends Error {
|
|
44
|
+
surface;
|
|
45
|
+
action;
|
|
46
|
+
discriminator;
|
|
47
|
+
constructor(surface, action, discriminator) {
|
|
48
|
+
super(`${surface}'s '${action}' message declares a '${discriminator}' field, which is where its flat frames keep the action. Rename the field, or give \`frame.discriminator\` a key no message uses.`);
|
|
49
|
+
this.surface = surface;
|
|
50
|
+
this.action = action;
|
|
51
|
+
this.discriminator = discriminator;
|
|
52
|
+
this.name = "WebSocketMessageDeclaresDiscriminator";
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
/** Data sent in a flat frame that is not an object. */
|
|
56
|
+
var WebSocketDataNotAnObject = class extends Error {
|
|
57
|
+
surface;
|
|
58
|
+
action;
|
|
59
|
+
discriminator;
|
|
60
|
+
constructor(surface, action, discriminator) {
|
|
61
|
+
super(`${surface} sends flat frames, keyed by '${discriminator}', and '${action}''s data is not an object, so it has no fields to put beside it. Send an object. Nothing was sent.`);
|
|
62
|
+
this.surface = surface;
|
|
63
|
+
this.action = action;
|
|
64
|
+
this.discriminator = discriminator;
|
|
65
|
+
this.name = "WebSocketDataNotAnObject";
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
/** Data sent in a flat frame that carries the discriminator itself. */
|
|
69
|
+
var WebSocketDataHasDiscriminator = class extends Error {
|
|
70
|
+
surface;
|
|
71
|
+
action;
|
|
72
|
+
discriminator;
|
|
73
|
+
constructor(surface, action, discriminator) {
|
|
74
|
+
super(`'${action}''s data on ${surface} has a '${discriminator}' field, which is where its flat frames keep the action. Rename the field. Nothing was sent.`);
|
|
75
|
+
this.surface = surface;
|
|
76
|
+
this.action = action;
|
|
77
|
+
this.discriminator = discriminator;
|
|
78
|
+
this.name = "WebSocketDataHasDiscriminator";
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
/** How one surface writes and reads its frames. */
|
|
82
|
+
var FrameShape = class {
|
|
83
|
+
surface;
|
|
84
|
+
discriminator;
|
|
85
|
+
constructor(surface, discriminator) {
|
|
86
|
+
this.surface = surface;
|
|
87
|
+
this.discriminator = discriminator;
|
|
88
|
+
}
|
|
89
|
+
/** The key an inbound frame names its action under. */
|
|
90
|
+
get key() {
|
|
91
|
+
return this.discriminator ?? "action";
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The frame for `action`'s `data`, serialised.
|
|
95
|
+
*
|
|
96
|
+
* @throws {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator} for
|
|
97
|
+
* a flat frame whose data cannot sit beside the discriminator.
|
|
98
|
+
*/
|
|
99
|
+
encode(action, data, id) {
|
|
100
|
+
const { discriminator } = this;
|
|
101
|
+
if (discriminator === void 0) return JSON.stringify({
|
|
102
|
+
action,
|
|
103
|
+
...id !== void 0 ? { id } : {},
|
|
104
|
+
data
|
|
105
|
+
});
|
|
106
|
+
if (!isRecord(data)) throw new WebSocketDataNotAnObject(this.surface, action, discriminator);
|
|
107
|
+
if (Object.hasOwn(data, discriminator)) throw new WebSocketDataHasDiscriminator(this.surface, action, discriminator);
|
|
108
|
+
return JSON.stringify({
|
|
109
|
+
[discriminator]: action,
|
|
110
|
+
...data
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** A parsed frame's action, id and data — `undefined` when it names none. */
|
|
114
|
+
decode(frame) {
|
|
115
|
+
if (!isRecord(frame)) return void 0;
|
|
116
|
+
const { discriminator } = this;
|
|
117
|
+
if (discriminator === void 0) {
|
|
118
|
+
if (typeof frame.action !== "string") return void 0;
|
|
119
|
+
return {
|
|
120
|
+
action: frame.action,
|
|
121
|
+
...isId(frame.id) ? { id: frame.id } : {},
|
|
122
|
+
data: frame.data
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const { [discriminator]: action, ...data } = frame;
|
|
126
|
+
if (typeof action !== "string") return void 0;
|
|
127
|
+
return {
|
|
128
|
+
action,
|
|
129
|
+
data
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** The id a frame that names no action carried, to echo on its error. */
|
|
133
|
+
idOf(frame) {
|
|
134
|
+
if (this.discriminator !== void 0 || !isRecord(frame)) return void 0;
|
|
135
|
+
return isId(frame.id) ? frame.id : void 0;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Refuse a declared message a flat frame cannot carry: one that is not an
|
|
139
|
+
* object, or that has a field named the discriminator.
|
|
140
|
+
*
|
|
141
|
+
* @throws {WebSocketMessageNotAnObject}, {WebSocketMessageDeclaresDiscriminator}
|
|
142
|
+
*/
|
|
143
|
+
check(messages) {
|
|
144
|
+
const { discriminator } = this;
|
|
145
|
+
if (discriminator === void 0) return;
|
|
146
|
+
for (const [action, schema] of Object.entries(messages)) {
|
|
147
|
+
const shape = objectShape((0, _geekmidas_schema_conversion.toJsonSchema)(schema));
|
|
148
|
+
if (!shape) throw new WebSocketMessageNotAnObject(this.surface, action, discriminator);
|
|
149
|
+
if (shape.has(discriminator)) throw new WebSocketMessageDeclaresDiscriminator(this.surface, action, discriminator);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
/**
|
|
154
|
+
* The fields a JSON Schema's object declares, or `undefined` when it is not
|
|
155
|
+
* an object. A union or intersection is one when each of its members is.
|
|
156
|
+
*/
|
|
157
|
+
function objectShape(schema) {
|
|
158
|
+
if (!isRecord(schema)) return void 0;
|
|
159
|
+
const members = schema.anyOf ?? schema.oneOf ?? schema.allOf;
|
|
160
|
+
if (Array.isArray(members) && members.length > 0) {
|
|
161
|
+
const fields = /* @__PURE__ */ new Set();
|
|
162
|
+
for (const member of members) {
|
|
163
|
+
const shape = objectShape(member);
|
|
164
|
+
if (!shape) return void 0;
|
|
165
|
+
for (const field of shape) fields.add(field);
|
|
166
|
+
}
|
|
167
|
+
return fields;
|
|
168
|
+
}
|
|
169
|
+
if (schema.type !== "object") return void 0;
|
|
170
|
+
return new Set(isRecord(schema.properties) ? Object.keys(schema.properties) : []);
|
|
171
|
+
}
|
|
172
|
+
function isRecord(value) {
|
|
173
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
174
|
+
}
|
|
175
|
+
function isId(value) {
|
|
176
|
+
return typeof value === "string" || typeof value === "number";
|
|
177
|
+
}
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region src/websocket/publisher.ts
|
|
180
|
+
/** A message sent on an action the surface does not declare. */
|
|
181
|
+
var UnknownWebSocketMessage = class extends Error {
|
|
182
|
+
surface;
|
|
183
|
+
action;
|
|
184
|
+
declared;
|
|
185
|
+
constructor(surface, action, declared) {
|
|
186
|
+
super(`${surface} sends no '${action}' message. It declares ${declared.map((a) => `'${a}'`).join(", ")} — send one of them, or add '${action}' to its messages.`);
|
|
187
|
+
this.surface = surface;
|
|
188
|
+
this.action = action;
|
|
189
|
+
this.declared = declared;
|
|
190
|
+
this.name = "UnknownWebSocketMessage";
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
/** A message whose data its action's schema refused. */
|
|
194
|
+
var InvalidWebSocketMessage = class extends Error {
|
|
195
|
+
surface;
|
|
196
|
+
action;
|
|
197
|
+
issues;
|
|
198
|
+
constructor(surface, action, issues) {
|
|
199
|
+
super(`${surface}'s '${action}' message was refused by its schema: ${issues.map((issue) => issue.message).join("; ")}. Nothing was sent.`);
|
|
200
|
+
this.surface = surface;
|
|
201
|
+
this.action = action;
|
|
202
|
+
this.issues = issues;
|
|
203
|
+
this.name = "InvalidWebSocketMessage";
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
/**
|
|
207
|
+
* How anything reaches a socket — `services.realtime` in an endpoint, and
|
|
208
|
+
* `sockets` in a route of the surface itself.
|
|
209
|
+
*
|
|
210
|
+
* A message is `{ action, data }`, the shape a client's frames arrive in —
|
|
211
|
+
* or, where the surface names a `frame.discriminator`, flat: `{ [key]: action,
|
|
212
|
+
* ...data }`.
|
|
213
|
+
* Where the surface declares its messages, `action` is one of them and
|
|
214
|
+
* `data` is typed and checked by its schema before anything is sent; where it
|
|
215
|
+
* declares none, any action and any JSON value go. A message is serialised
|
|
216
|
+
* once, whatever the number of sockets it goes to. An id whose process has
|
|
217
|
+
* gone is dropped silently, as API Gateway's `postToConnection` to a closed
|
|
218
|
+
* connection is a no-op the sender rarely wants to handle.
|
|
219
|
+
*/
|
|
220
|
+
var WebSocketPublisher = class {
|
|
221
|
+
sink;
|
|
222
|
+
declared;
|
|
223
|
+
frame;
|
|
224
|
+
constructor(sink, declared, frame = new FrameShape(declared?.surface ?? "")) {
|
|
225
|
+
this.sink = sink;
|
|
226
|
+
this.declared = declared;
|
|
227
|
+
this.frame = frame;
|
|
228
|
+
}
|
|
229
|
+
/** Send `action`'s message to each connection. */
|
|
230
|
+
async send(ids, action, data) {
|
|
231
|
+
const payload = await this.payload(action, data);
|
|
232
|
+
await this.sink.send(listOf(ids), payload);
|
|
233
|
+
}
|
|
234
|
+
/** Send `action`'s message to every open connection, on every process. */
|
|
235
|
+
async broadcast(action, data, options = {}) {
|
|
236
|
+
const payload = await this.payload(action, data);
|
|
237
|
+
await this.sink.broadcast(payload, options.except?.length ? options.except : void 0);
|
|
238
|
+
}
|
|
239
|
+
/** Close each connection, with a close code and reason its client sees. */
|
|
240
|
+
async close(ids, code = 1e3, reason = "") {
|
|
241
|
+
await this.sink.close(listOf(ids), code, reason);
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* The frame, checked by the action's schema where the surface declares
|
|
245
|
+
* its messages.
|
|
246
|
+
*
|
|
247
|
+
* @throws {UnknownWebSocketMessage}, {InvalidWebSocketMessage}, and for a
|
|
248
|
+
* flat frame {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator}
|
|
249
|
+
*/
|
|
250
|
+
async payload(action, data) {
|
|
251
|
+
if (!this.declared) return this.frame.encode(action, data);
|
|
252
|
+
const { surface, messages } = this.declared;
|
|
253
|
+
const schema = messages[action];
|
|
254
|
+
if (!schema) throw new UnknownWebSocketMessage(surface, action, Object.keys(messages));
|
|
255
|
+
const result = await schema["~standard"].validate(data);
|
|
256
|
+
if (result.issues) throw new InvalidWebSocketMessage(surface, action, result.issues);
|
|
257
|
+
return this.frame.encode(action, result.value);
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
function listOf(ids) {
|
|
261
|
+
return typeof ids === "string" ? [ids] : ids;
|
|
262
|
+
}
|
|
263
|
+
//#endregion
|
|
264
|
+
//#region src/websocket/core.ts
|
|
265
|
+
/** Two routes answer one action. */
|
|
266
|
+
var DuplicateWebSocketRoute = class extends Error {
|
|
267
|
+
surface;
|
|
268
|
+
action;
|
|
269
|
+
constructor(surface, action) {
|
|
270
|
+
super(`Two routes on ${surface} answer '${action}'. Each action has one handler — rename one of them.`);
|
|
271
|
+
this.surface = surface;
|
|
272
|
+
this.action = action;
|
|
273
|
+
this.name = "DuplicateWebSocketRoute";
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
var WebSocketCore = class {
|
|
277
|
+
options;
|
|
278
|
+
surface;
|
|
279
|
+
/** How frames are read and written — what an adaptor decodes replies by. */
|
|
280
|
+
frame;
|
|
281
|
+
/** `sockets` in every handler. */
|
|
282
|
+
sockets;
|
|
283
|
+
routes = /* @__PURE__ */ new Map();
|
|
284
|
+
lifecycle = {};
|
|
285
|
+
/**
|
|
286
|
+
* @throws {DuplicateWebSocketRoute} when two routes answer one action, and
|
|
287
|
+
* the frame checks of `FrameShape.check` for declared messages.
|
|
288
|
+
*/
|
|
289
|
+
constructor(options) {
|
|
290
|
+
this.options = options;
|
|
291
|
+
this.surface = options.surface;
|
|
292
|
+
for (const route of options.routes) {
|
|
293
|
+
if (route.surface.id !== options.surface) continue;
|
|
294
|
+
if (route.kind === "message") {
|
|
295
|
+
if (this.routes.has(route.action)) throw new DuplicateWebSocketRoute(options.surface, route.action);
|
|
296
|
+
this.routes.set(route.action, route);
|
|
297
|
+
} else {
|
|
298
|
+
if (this.lifecycle[route.kind]) throw new DuplicateWebSocketRoute(options.surface, route.action);
|
|
299
|
+
this.lifecycle[route.kind] = route;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
this.frame = new FrameShape(options.surface, options.frame?.discriminator);
|
|
303
|
+
if (options.messages) this.frame.check(options.messages);
|
|
304
|
+
this.sockets = new WebSocketPublisher(options.sink, options.messages ? {
|
|
305
|
+
surface: options.surface,
|
|
306
|
+
messages: options.messages
|
|
307
|
+
} : void 0, this.frame);
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Run the connect handler for a handshake: accepted with the connection's
|
|
311
|
+
* `data` (what the handler returned, `{}` for nothing), or refused with
|
|
312
|
+
* the status of the `HttpError` it threw — 500 for anything else. A surface
|
|
313
|
+
* with no connect handler accepts every handshake, and verifies no session.
|
|
314
|
+
*/
|
|
315
|
+
async connect(request, options = {}) {
|
|
316
|
+
const { connectionId, headers, query } = request;
|
|
317
|
+
const route = this.lifecycle.connect;
|
|
318
|
+
if (!route) return {
|
|
319
|
+
accepted: true,
|
|
320
|
+
connection: {
|
|
321
|
+
id: connectionId,
|
|
322
|
+
data: {}
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
try {
|
|
326
|
+
const session = "session" in request ? request.session : this.options.authenticator ? await this.options.authenticator.verify(headers, this.options.envParser) : null;
|
|
327
|
+
const returned = await this.run(route, connectionId, (base) => ({
|
|
328
|
+
...base,
|
|
329
|
+
connectionId,
|
|
330
|
+
headers,
|
|
331
|
+
query,
|
|
332
|
+
session
|
|
333
|
+
}), options);
|
|
334
|
+
return {
|
|
335
|
+
accepted: true,
|
|
336
|
+
connection: {
|
|
337
|
+
id: connectionId,
|
|
338
|
+
data: returned && typeof returned === "object" ? returned : {}
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
} catch (error) {
|
|
342
|
+
if (error instanceof _geekmidas_errors.HttpError) return {
|
|
343
|
+
accepted: false,
|
|
344
|
+
status: error.statusCode,
|
|
345
|
+
statusText: error.statusMessage,
|
|
346
|
+
error
|
|
347
|
+
};
|
|
348
|
+
this.options.logger.error({
|
|
349
|
+
err: error,
|
|
350
|
+
connectionId
|
|
351
|
+
}, "WebSocket connect handler failed");
|
|
352
|
+
return {
|
|
353
|
+
accepted: false,
|
|
354
|
+
status: 500,
|
|
355
|
+
statusText: "Internal Server Error",
|
|
356
|
+
error
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Parse, validate and run one inbound frame. The reply — the handler's
|
|
362
|
+
* return, encoded — and every `$error` are written with `write`; an error
|
|
363
|
+
* is a frame, never a close. A binary frame is refused: frames are text.
|
|
364
|
+
*/
|
|
365
|
+
async message(connection, raw, write, options = {}) {
|
|
366
|
+
if (typeof raw !== "string") return this.error(write, {}, "Frames are JSON text.");
|
|
367
|
+
let parsed;
|
|
368
|
+
try {
|
|
369
|
+
parsed = JSON.parse(raw);
|
|
370
|
+
} catch {
|
|
371
|
+
return this.error(write, {}, "Frames are JSON.");
|
|
372
|
+
}
|
|
373
|
+
const frame = this.frame.decode(parsed);
|
|
374
|
+
if (!frame) return this.error(write, { id: this.frame.idOf(parsed) }, `A frame names its \`${this.frame.key}\`.`);
|
|
375
|
+
const { action, id } = frame;
|
|
376
|
+
const route = this.routes.get(action) ?? this.routes.get("$default");
|
|
377
|
+
if (!route) return this.error(write, {
|
|
378
|
+
action,
|
|
379
|
+
id
|
|
380
|
+
}, `No route answers '${action}'.`);
|
|
381
|
+
let body = frame.data;
|
|
382
|
+
if (route.schema) {
|
|
383
|
+
const result = await route.schema["~standard"].validate(frame.data);
|
|
384
|
+
if (result.issues) return this.error(write, {
|
|
385
|
+
action,
|
|
386
|
+
id
|
|
387
|
+
}, "The frame was invalid.", result.issues);
|
|
388
|
+
body = result.value;
|
|
389
|
+
}
|
|
390
|
+
try {
|
|
391
|
+
const returned = await this.run(route, connection.id, (base) => ({
|
|
392
|
+
...base,
|
|
393
|
+
connection,
|
|
394
|
+
body,
|
|
395
|
+
reply: (message) => write(JSON.stringify(message))
|
|
396
|
+
}), options);
|
|
397
|
+
if (returned !== void 0) write(this.frame.encode(action, returned, id));
|
|
398
|
+
return {
|
|
399
|
+
ok: true,
|
|
400
|
+
action,
|
|
401
|
+
...id !== void 0 ? { id } : {},
|
|
402
|
+
returned
|
|
403
|
+
};
|
|
404
|
+
} catch (error) {
|
|
405
|
+
if (error instanceof _geekmidas_errors.HttpError) return this.error(write, {
|
|
406
|
+
action,
|
|
407
|
+
id
|
|
408
|
+
}, error.message, void 0, error);
|
|
409
|
+
this.options.logger.error({
|
|
410
|
+
err: error,
|
|
411
|
+
connectionId: connection.id,
|
|
412
|
+
action
|
|
413
|
+
}, "WebSocket route failed");
|
|
414
|
+
return this.error(write, {
|
|
415
|
+
action,
|
|
416
|
+
id
|
|
417
|
+
}, "The route failed.", void 0, error);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Run the disconnect handler for a connection that has closed. What it
|
|
422
|
+
* throws is logged and returned, never thrown: the socket is gone either
|
|
423
|
+
* way.
|
|
424
|
+
*/
|
|
425
|
+
async disconnect(connection, close, options = {}) {
|
|
426
|
+
const route = this.lifecycle.disconnect;
|
|
427
|
+
if (!route) return { ok: true };
|
|
428
|
+
try {
|
|
429
|
+
await this.run(route, connection.id, (base) => ({
|
|
430
|
+
...base,
|
|
431
|
+
connection,
|
|
432
|
+
...close
|
|
433
|
+
}), options);
|
|
434
|
+
return { ok: true };
|
|
435
|
+
} catch (error) {
|
|
436
|
+
this.options.logger.error({
|
|
437
|
+
err: error,
|
|
438
|
+
connectionId: connection.id
|
|
439
|
+
}, "WebSocket disconnect handler failed");
|
|
440
|
+
return {
|
|
441
|
+
ok: false,
|
|
442
|
+
error
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
/** Run a handler with its services, inside a request context of its own. */
|
|
447
|
+
async run(route, connectionId, context, options) {
|
|
448
|
+
const logger = this.options.logger.child({
|
|
449
|
+
connectionId,
|
|
450
|
+
action: route.action
|
|
451
|
+
});
|
|
452
|
+
return (0, _geekmidas_services.runWithRequestContext)({
|
|
453
|
+
logger,
|
|
454
|
+
requestId: connectionId,
|
|
455
|
+
startTime: Date.now(),
|
|
456
|
+
operation: `ws ${route.action}`
|
|
457
|
+
}, async () => {
|
|
458
|
+
const services = await this.services(route, options.services);
|
|
459
|
+
return route.handler(context({
|
|
460
|
+
services,
|
|
461
|
+
logger,
|
|
462
|
+
sockets: this.sockets
|
|
463
|
+
}));
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
/** The route's services: the overrides it names, the rest registered. */
|
|
467
|
+
async services(route, overrides = {}) {
|
|
468
|
+
const given = {};
|
|
469
|
+
const wanted = route.services.filter((service) => {
|
|
470
|
+
if (!Object.hasOwn(overrides, service.serviceName)) return true;
|
|
471
|
+
given[service.serviceName] = overrides[service.serviceName];
|
|
472
|
+
return false;
|
|
473
|
+
});
|
|
474
|
+
return {
|
|
475
|
+
...wanted.length ? await _geekmidas_services.ServiceDiscovery.getInstance(this.options.envParser).register([...wanted]) : {},
|
|
476
|
+
...given
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
error(write, at, message, issues, error) {
|
|
480
|
+
write(this.frame.encode("$error", {
|
|
481
|
+
message,
|
|
482
|
+
...issues ? { issues } : {}
|
|
483
|
+
}, at.id));
|
|
484
|
+
return {
|
|
485
|
+
ok: false,
|
|
486
|
+
...at.action !== void 0 ? { action: at.action } : {},
|
|
487
|
+
...at.id !== void 0 ? { id: at.id } : {},
|
|
488
|
+
message,
|
|
489
|
+
...issues ? { issues } : {},
|
|
490
|
+
...error !== void 0 ? { error } : {}
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
//#endregion
|
|
495
|
+
//#region src/websocket/limits.ts
|
|
496
|
+
/** Close codes the limits close a socket with. */
|
|
497
|
+
const LIMIT_CLOSE = {
|
|
498
|
+
/** Policy violation: it kept sending past its rate, or its identity has too many sockets. */
|
|
499
|
+
policy: 1008 };
|
|
500
|
+
const DEFAULT_WEBSOCKET_LIMITS = {
|
|
501
|
+
handshakesPerMinute: 120,
|
|
502
|
+
inFlightHandshakes: 16,
|
|
503
|
+
connectionsPerIp: 256,
|
|
504
|
+
messagesPerSecond: 50,
|
|
505
|
+
burst: 100,
|
|
506
|
+
maxConnections: 16
|
|
507
|
+
};
|
|
508
|
+
/** A limit that is not a whole number of at least one. */
|
|
509
|
+
var InvalidWebSocketLimit = class extends Error {
|
|
510
|
+
surface;
|
|
511
|
+
limit;
|
|
512
|
+
value;
|
|
513
|
+
constructor(surface, limit, value) {
|
|
514
|
+
super(`${surface} sets limits.${limit} to ${String(value)}. A limit is a whole number of 1 or more — or false, to lift it.`);
|
|
515
|
+
this.surface = surface;
|
|
516
|
+
this.limit = limit;
|
|
517
|
+
this.value = value;
|
|
518
|
+
this.name = "InvalidWebSocketLimit";
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
/**
|
|
522
|
+
* Fill in the defaults.
|
|
523
|
+
*
|
|
524
|
+
* @throws {InvalidWebSocketLimit} for a limit that is not a positive integer.
|
|
525
|
+
*/
|
|
526
|
+
function resolveLimits(surface, limits = {}) {
|
|
527
|
+
const pick = (name, value) => {
|
|
528
|
+
if (value === false) return void 0;
|
|
529
|
+
const resolved = value ?? DEFAULT_WEBSOCKET_LIMITS[name];
|
|
530
|
+
if (!Number.isInteger(resolved) || resolved < 1) throw new InvalidWebSocketLimit(surface, name, value);
|
|
531
|
+
return resolved;
|
|
532
|
+
};
|
|
533
|
+
const messagesPerSecond = pick("messagesPerSecond", limits.messagesPerSecond);
|
|
534
|
+
return {
|
|
535
|
+
...optional("handshakesPerMinute", pick("handshakesPerMinute", limits.handshakesPerMinute)),
|
|
536
|
+
...optional("inFlightHandshakes", pick("inFlightHandshakes", limits.inFlightHandshakes)),
|
|
537
|
+
...optional("connectionsPerIp", pick("connectionsPerIp", limits.connectionsPerIp)),
|
|
538
|
+
...optional("messagesPerSecond", messagesPerSecond),
|
|
539
|
+
burst: pick("burst", limits.burst) ?? DEFAULT_WEBSOCKET_LIMITS.burst,
|
|
540
|
+
...limits.maxConnectionsPer ? { maxConnectionsPer: limits.maxConnectionsPer } : {},
|
|
541
|
+
maxConnections: pick("maxConnections", limits.maxConnections) ?? DEFAULT_WEBSOCKET_LIMITS.maxConnections,
|
|
542
|
+
overflow: limits.overflow ?? "refuse"
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
function optional(key, value) {
|
|
546
|
+
return value === void 0 ? {} : { [key]: value };
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* In one process. Two servers on one `memory://` channel — replicas in a
|
|
550
|
+
* test — share it, as they share the channel.
|
|
551
|
+
*/
|
|
552
|
+
var MemoryLimitStore = class {
|
|
553
|
+
windows = /* @__PURE__ */ new Map();
|
|
554
|
+
/** key → member → [opened, expires] */
|
|
555
|
+
sets = /* @__PURE__ */ new Map();
|
|
556
|
+
async hit(key, windowMs) {
|
|
557
|
+
const now = Date.now();
|
|
558
|
+
let window = this.windows.get(key);
|
|
559
|
+
if (!window || window.resetAt <= now) {
|
|
560
|
+
window = {
|
|
561
|
+
count: 0,
|
|
562
|
+
resetAt: now + windowMs
|
|
563
|
+
};
|
|
564
|
+
this.windows.set(key, window);
|
|
565
|
+
}
|
|
566
|
+
window.count++;
|
|
567
|
+
return {
|
|
568
|
+
count: window.count,
|
|
569
|
+
resetMs: window.resetAt - now
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
async hold(key, member, ttlMs) {
|
|
573
|
+
const now = Date.now();
|
|
574
|
+
let set = this.sets.get(key);
|
|
575
|
+
if (!set) {
|
|
576
|
+
set = /* @__PURE__ */ new Map();
|
|
577
|
+
this.sets.set(key, set);
|
|
578
|
+
}
|
|
579
|
+
for (const [held, [, expires]] of set) if (expires <= now) set.delete(held);
|
|
580
|
+
const opened = set.get(member)?.[0] ?? now;
|
|
581
|
+
set.set(member, [opened, now + ttlMs]);
|
|
582
|
+
return [...set].sort((a, b) => a[1][0] - b[1][0]).map(([held]) => held);
|
|
583
|
+
}
|
|
584
|
+
async release(key, member) {
|
|
585
|
+
const set = this.sets.get(key);
|
|
586
|
+
set?.delete(member);
|
|
587
|
+
if (set?.size === 0) this.sets.delete(key);
|
|
588
|
+
}
|
|
589
|
+
async renew(held, ttlMs) {
|
|
590
|
+
const expires = Date.now() + ttlMs;
|
|
591
|
+
for (const { key, member } of held) {
|
|
592
|
+
const entry = this.sets.get(key)?.get(member);
|
|
593
|
+
if (entry) entry[1] = expires;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
const HIT = `
|
|
598
|
+
local count = redis.call('INCR', KEYS[1])
|
|
599
|
+
if count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
|
|
600
|
+
local ttl = redis.call('PTTL', KEYS[1])
|
|
601
|
+
if ttl < 0 then
|
|
602
|
+
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
|
603
|
+
ttl = tonumber(ARGV[1])
|
|
604
|
+
end
|
|
605
|
+
return { count, ttl }
|
|
606
|
+
`;
|
|
607
|
+
const HOLD = `
|
|
608
|
+
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1])
|
|
609
|
+
redis.call('ZADD', KEYS[1], ARGV[2], ARGV[3])
|
|
610
|
+
redis.call('PEXPIRE', KEYS[1], ARGV[4])
|
|
611
|
+
return redis.call('ZRANGE', KEYS[1], 0, -1)
|
|
612
|
+
`;
|
|
613
|
+
const RENEW = `
|
|
614
|
+
for i, key in ipairs(KEYS) do
|
|
615
|
+
redis.call('ZADD', key, 'XX', ARGV[1], ARGV[i + 2])
|
|
616
|
+
redis.call('PEXPIRE', key, ARGV[2])
|
|
617
|
+
end
|
|
618
|
+
return 0
|
|
619
|
+
`;
|
|
620
|
+
/**
|
|
621
|
+
* Over Redis — the transport's own — so every replica counts in one place.
|
|
622
|
+
* Each operation is one script, so concurrent handshakes on any replica are
|
|
623
|
+
* each counted.
|
|
624
|
+
*/
|
|
625
|
+
var RedisLimitStore = class {
|
|
626
|
+
client;
|
|
627
|
+
prefix;
|
|
628
|
+
/** member as handed in → member as stored, with its opening time. */
|
|
629
|
+
stored = /* @__PURE__ */ new Map();
|
|
630
|
+
constructor(client, prefix) {
|
|
631
|
+
this.client = client;
|
|
632
|
+
this.prefix = prefix;
|
|
633
|
+
}
|
|
634
|
+
key(key) {
|
|
635
|
+
return `${this.prefix}:limits:${key}`;
|
|
636
|
+
}
|
|
637
|
+
storedAs(key, member) {
|
|
638
|
+
const id = `${key}\n${member}`;
|
|
639
|
+
let stored = this.stored.get(id);
|
|
640
|
+
if (!stored) {
|
|
641
|
+
stored = `${Date.now().toString(36).padStart(9, "0")}|${member}`;
|
|
642
|
+
this.stored.set(id, stored);
|
|
643
|
+
}
|
|
644
|
+
return stored;
|
|
645
|
+
}
|
|
646
|
+
async hit(key, windowMs) {
|
|
647
|
+
const [count, resetMs] = await this.client.eval(HIT, 1, this.key(key), windowMs);
|
|
648
|
+
return {
|
|
649
|
+
count: Number(count),
|
|
650
|
+
resetMs: Number(resetMs)
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
async hold(key, member, ttlMs) {
|
|
654
|
+
const now = Date.now();
|
|
655
|
+
return (await this.client.eval(HOLD, 1, this.key(key), now, now + ttlMs, this.storedAs(key, member), ttlMs)).sort().map((stored) => stored.slice(stored.indexOf("|") + 1));
|
|
656
|
+
}
|
|
657
|
+
async release(key, member) {
|
|
658
|
+
const id = `${key}\n${member}`;
|
|
659
|
+
const stored = this.stored.get(id);
|
|
660
|
+
this.stored.delete(id);
|
|
661
|
+
if (!stored) return;
|
|
662
|
+
await this.client.eval("return redis.call('ZREM', KEYS[1], ARGV[1])", 1, this.key(key), stored);
|
|
663
|
+
}
|
|
664
|
+
async renew(held, ttlMs) {
|
|
665
|
+
const known = held.flatMap(({ key, member }) => {
|
|
666
|
+
const stored = this.stored.get(`${key}\n${member}`);
|
|
667
|
+
return stored ? [{
|
|
668
|
+
key: this.key(key),
|
|
669
|
+
stored
|
|
670
|
+
}] : [];
|
|
671
|
+
});
|
|
672
|
+
if (known.length === 0) return;
|
|
673
|
+
await this.client.eval(RENEW, known.length, ...known.map(({ key }) => key), Date.now() + ttlMs, ttlMs, ...known.map(({ stored }) => stored));
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
/**
|
|
677
|
+
* A socket's inbound budget: `burst` frames at once, refilled at `rate` a
|
|
678
|
+
* second.
|
|
679
|
+
*/
|
|
680
|
+
var TokenBucket = class {
|
|
681
|
+
rate;
|
|
682
|
+
burst;
|
|
683
|
+
tokens;
|
|
684
|
+
at = Date.now();
|
|
685
|
+
constructor(rate, burst) {
|
|
686
|
+
this.rate = rate;
|
|
687
|
+
this.burst = burst;
|
|
688
|
+
this.tokens = burst;
|
|
689
|
+
}
|
|
690
|
+
/** Spend one token, if there is one. */
|
|
691
|
+
take(now = Date.now()) {
|
|
692
|
+
this.tokens = Math.min(this.burst, this.tokens + (now - this.at) / 1e3 * this.rate);
|
|
693
|
+
this.at = now;
|
|
694
|
+
if (this.tokens < 1) return false;
|
|
695
|
+
this.tokens -= 1;
|
|
696
|
+
return true;
|
|
697
|
+
}
|
|
698
|
+
/** Whether it has refilled completely since it last ran dry. */
|
|
699
|
+
get full() {
|
|
700
|
+
return this.tokens >= this.burst - 1;
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
/**
|
|
704
|
+
* The client a handshake is counted against. Behind the stack's edge — a
|
|
705
|
+
* private peer — the address the edge put last in `X-Forwarded-For`, the one
|
|
706
|
+
* it saw; Traefik and Caddy both replace what an outside client sent there.
|
|
707
|
+
* From anywhere else, the peer itself: a header a client could set never
|
|
708
|
+
* picks the bucket it is counted in.
|
|
709
|
+
*/
|
|
710
|
+
function clientAddress(request) {
|
|
711
|
+
const peer = request.socket.remoteAddress ?? "unknown";
|
|
712
|
+
const forwarded = request.headers["x-forwarded-for"];
|
|
713
|
+
if (!forwarded || !require_privateAddress.isPrivateAddress(peer)) return peer;
|
|
714
|
+
return (Array.isArray(forwarded) ? forwarded.join(",") : forwarded).split(",").map((hop) => hop.trim()).filter(Boolean).at(-1) ?? peer;
|
|
715
|
+
}
|
|
716
|
+
//#endregion
|
|
717
|
+
//#region src/websocket/testing.ts
|
|
718
|
+
/**
|
|
719
|
+
* A sink that keeps what it is handed, decoded by the surface's frame shape,
|
|
720
|
+
* and sends it nowhere.
|
|
721
|
+
*/
|
|
722
|
+
var RecordingSink = class {
|
|
723
|
+
frame;
|
|
724
|
+
sent = [];
|
|
725
|
+
broadcasts = [];
|
|
726
|
+
closed = [];
|
|
727
|
+
constructor(frame) {
|
|
728
|
+
this.frame = frame;
|
|
729
|
+
}
|
|
730
|
+
async send(ids, payload) {
|
|
731
|
+
this.sent.push({
|
|
732
|
+
ids: [...ids],
|
|
733
|
+
...this.decode(payload)
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
async broadcast(payload, except) {
|
|
737
|
+
this.broadcasts.push({
|
|
738
|
+
except: [...except ?? []],
|
|
739
|
+
...this.decode(payload)
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
async close(ids, code, reason) {
|
|
743
|
+
this.closed.push({
|
|
744
|
+
ids: [...ids],
|
|
745
|
+
code,
|
|
746
|
+
reason
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
clear() {
|
|
750
|
+
this.sent.length = 0;
|
|
751
|
+
this.broadcasts.length = 0;
|
|
752
|
+
this.closed.length = 0;
|
|
753
|
+
}
|
|
754
|
+
decode(payload) {
|
|
755
|
+
const frame = JSON.parse(payload);
|
|
756
|
+
const { action, data } = this.frame.decode(frame);
|
|
757
|
+
return {
|
|
758
|
+
action,
|
|
759
|
+
data,
|
|
760
|
+
frame
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
/**
|
|
765
|
+
* A surface's publisher that records rather than sends — what
|
|
766
|
+
* `surface.testPublisher()` returns, of the type `services.<surface>` is.
|
|
767
|
+
*
|
|
768
|
+
* Every send is still checked by the declared `messages` and encoded by the
|
|
769
|
+
* surface's `frame`, so an invalid push fails the spec as it would fail
|
|
770
|
+
* deployed, and `frame` on each record is what the client would parse.
|
|
771
|
+
*/
|
|
772
|
+
var TestWebSocketPublisher = class extends WebSocketPublisher {
|
|
773
|
+
/** Where the records are kept — what `route.request()` builds its core on. */
|
|
774
|
+
recording;
|
|
775
|
+
constructor(frame, declared) {
|
|
776
|
+
const recording = new RecordingSink(frame);
|
|
777
|
+
super(recording, declared, frame);
|
|
778
|
+
this.recording = recording;
|
|
779
|
+
}
|
|
780
|
+
/** Each `send(ids, action, data)`, in order. */
|
|
781
|
+
get sent() {
|
|
782
|
+
return this.recording.sent;
|
|
783
|
+
}
|
|
784
|
+
/** Each `broadcast(action, data, { except })`, in order. */
|
|
785
|
+
get broadcasts() {
|
|
786
|
+
return this.recording.broadcasts;
|
|
787
|
+
}
|
|
788
|
+
/** Each `close(ids, code, reason)`, in order. */
|
|
789
|
+
get closed() {
|
|
790
|
+
return this.recording.closed;
|
|
791
|
+
}
|
|
792
|
+
/** Forget everything recorded so far. */
|
|
793
|
+
clear() {
|
|
794
|
+
this.recording.clear();
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
/** A frame `route.request()` sent was refused before its handler ran. */
|
|
798
|
+
var InvalidWebSocketRequest = class extends Error {
|
|
799
|
+
surface;
|
|
800
|
+
action;
|
|
801
|
+
reason;
|
|
802
|
+
issues;
|
|
803
|
+
constructor(surface, action, reason, issues) {
|
|
804
|
+
super(`${surface}'s '${action}' route refused the request: ${reason}${issues?.length ? ` ${issues.map((issue) => issue.message).join("; ")}.` : ""} Send a body its schema accepts.`);
|
|
805
|
+
this.surface = surface;
|
|
806
|
+
this.action = action;
|
|
807
|
+
this.reason = reason;
|
|
808
|
+
this.issues = issues;
|
|
809
|
+
this.name = "InvalidWebSocketRequest";
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
let issued = 0;
|
|
813
|
+
/** A connection id no other test call is using. */
|
|
814
|
+
function nextConnectionId() {
|
|
815
|
+
issued += 1;
|
|
816
|
+
return `test.${issued}`;
|
|
817
|
+
}
|
|
818
|
+
function connectionOf(given) {
|
|
819
|
+
return {
|
|
820
|
+
id: given?.id ?? nextConnectionId(),
|
|
821
|
+
data: given?.data ?? {}
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
function coreFor(route, surface, sockets) {
|
|
825
|
+
return surface.core({
|
|
826
|
+
envParser: surface.envParser,
|
|
827
|
+
sink: (sockets ?? surface.testPublisher()).recording,
|
|
828
|
+
modules: [{ route }]
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
/** `connect.request()`: the connection's `data`, or what refused it. */
|
|
832
|
+
async function requestConnect(route, surface, request = {}) {
|
|
833
|
+
const outcome = await coreFor(route, surface, request.sockets).connect({
|
|
834
|
+
connectionId: request.connectionId ?? nextConnectionId(),
|
|
835
|
+
headers: new Headers(request.headers),
|
|
836
|
+
query: new URLSearchParams(request.query),
|
|
837
|
+
..."session" in request ? { session: request.session } : {}
|
|
838
|
+
}, request.services ? { services: request.services } : {});
|
|
839
|
+
if (!outcome.accepted) throw outcome.error;
|
|
840
|
+
return outcome.connection.data;
|
|
841
|
+
}
|
|
842
|
+
/** A message route's `fullRequest()`: what it returned and wrote. */
|
|
843
|
+
async function requestMessage(route, surface, request) {
|
|
844
|
+
const core = coreFor(route, surface, request.sockets);
|
|
845
|
+
const frames = [];
|
|
846
|
+
const outcome = await core.message(connectionOf(request.connection), core.frame.encode(route.action, request.body, request.id), (payload) => frames.push(JSON.parse(payload)), request.services ? { services: request.services } : {});
|
|
847
|
+
if (outcome.ok) return {
|
|
848
|
+
returned: outcome.returned,
|
|
849
|
+
frames
|
|
850
|
+
};
|
|
851
|
+
if ("error" in outcome) throw outcome.error;
|
|
852
|
+
throw new InvalidWebSocketRequest(surface.id, route.action, outcome.message, outcome.issues);
|
|
853
|
+
}
|
|
854
|
+
/** `disconnect.request()`: resolves once the handler has run. */
|
|
855
|
+
async function requestDisconnect(route, surface, request = {}) {
|
|
856
|
+
const outcome = await coreFor(route, surface, request.sockets).disconnect(connectionOf(request.connection), {
|
|
857
|
+
code: request.code ?? 1e3,
|
|
858
|
+
reason: request.reason ?? ""
|
|
859
|
+
}, request.services ? { services: request.services } : {});
|
|
860
|
+
if (!outcome.ok) throw outcome.error;
|
|
861
|
+
}
|
|
862
|
+
//#endregion
|
|
863
|
+
//#region src/websocket/route.ts
|
|
864
|
+
/**
|
|
865
|
+
* A handler bound to a WebSocket surface — what `realtime.route('chat.send')
|
|
866
|
+
* …handle()` returns, and what a file exports.
|
|
867
|
+
*
|
|
868
|
+
* Carries `surface` and `constructs` the way an endpoint does, so discovery
|
|
869
|
+
* records what its process reaches without knowing what a route is.
|
|
870
|
+
*/
|
|
871
|
+
var WebSocketRoute = class {
|
|
872
|
+
kind;
|
|
873
|
+
action;
|
|
874
|
+
surface;
|
|
875
|
+
services;
|
|
876
|
+
constructs;
|
|
877
|
+
handler;
|
|
878
|
+
schema;
|
|
879
|
+
__IS_WEBSOCKET_ROUTE__ = true;
|
|
880
|
+
static isRoute(value) {
|
|
881
|
+
return Boolean(value && value.__IS_WEBSOCKET_ROUTE__ === true);
|
|
882
|
+
}
|
|
883
|
+
constructor(kind, action, surface, services, constructs, handler, schema) {
|
|
884
|
+
this.kind = kind;
|
|
885
|
+
this.action = action;
|
|
886
|
+
this.surface = surface;
|
|
887
|
+
this.services = services;
|
|
888
|
+
this.constructs = constructs;
|
|
889
|
+
this.handler = handler;
|
|
890
|
+
this.schema = schema;
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* Run the handler as its surface would, with no server and no socket —
|
|
894
|
+
* as `endpoint.request()` runs an endpoint.
|
|
895
|
+
*
|
|
896
|
+
* - `connect`: resolves with the connection's `data`, or rejects with what
|
|
897
|
+
* refused it (an `UnauthorizedError` stays a 401).
|
|
898
|
+
* - a message route: `body` is encoded as a frame and checked by the
|
|
899
|
+
* route's schema; resolves with the handler's return, or rejects with
|
|
900
|
+
* what it threw or an `InvalidWebSocketRequest`.
|
|
901
|
+
* - `disconnect`: resolves once the handler has run, or rejects with what
|
|
902
|
+
* it threw.
|
|
903
|
+
*/
|
|
904
|
+
request(...[request]) {
|
|
905
|
+
const route = this;
|
|
906
|
+
const given = request ?? {};
|
|
907
|
+
if (this.kind === "connect") return requestConnect(route, this.surface, given);
|
|
908
|
+
if (this.kind === "disconnect") return requestDisconnect(route, this.surface, given);
|
|
909
|
+
return requestMessage(route, this.surface, given).then(({ returned }) => returned);
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* A message route's `request()`, with every frame it wrote back to the
|
|
913
|
+
* connection — each `reply()` and the reply itself — beside its return.
|
|
914
|
+
*/
|
|
915
|
+
fullRequest(request) {
|
|
916
|
+
return requestMessage(this, this.surface, request);
|
|
917
|
+
}
|
|
918
|
+
};
|
|
919
|
+
/** The builder `connect()`, `disconnect()` and `route()` start. */
|
|
920
|
+
var WebSocketRouteBuilder = class WebSocketRouteBuilder {
|
|
921
|
+
kind;
|
|
922
|
+
action;
|
|
923
|
+
surface;
|
|
924
|
+
_services;
|
|
925
|
+
_constructs;
|
|
926
|
+
schema;
|
|
927
|
+
constructor(kind, action, surface, _services = [], _constructs = [], schema) {
|
|
928
|
+
this.kind = kind;
|
|
929
|
+
this.action = action;
|
|
930
|
+
this.surface = surface;
|
|
931
|
+
this._services = _services;
|
|
932
|
+
this._constructs = _constructs;
|
|
933
|
+
this.schema = schema;
|
|
934
|
+
}
|
|
935
|
+
/** The schema a frame's `data` must satisfy before the handler runs. */
|
|
936
|
+
body(schema) {
|
|
937
|
+
return new WebSocketRouteBuilder(this.kind, this.action, this.surface, this._services, this._constructs, schema);
|
|
938
|
+
}
|
|
939
|
+
/** What the handler reaches, as `services.<id>` — per route, as an endpoint's. */
|
|
940
|
+
dependsOn(constructs) {
|
|
941
|
+
return new WebSocketRouteBuilder(this.kind, this.action, this.surface, [...this._services, ...require_construct_interface.servicesOf(constructs)], require_construct_interface.idsOf(constructs, this._constructs), this.schema);
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* The handler. A message handler's return value, when there is one, is
|
|
945
|
+
* sent back to the connection as the reply to that frame; a connect
|
|
946
|
+
* handler's is kept as the connection's `data`.
|
|
947
|
+
*/
|
|
948
|
+
handle(handler) {
|
|
949
|
+
return new WebSocketRoute(this.kind, this.action, this.surface, this._services, this._constructs, handler, this.schema);
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
/** The instance a connection id was issued by: everything before its dot. */
|
|
953
|
+
function instanceOf(connectionId) {
|
|
954
|
+
const dot = connectionId.indexOf(".");
|
|
955
|
+
return dot > 0 ? connectionId.slice(0, dot) : void 0;
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* A publisher's sink over a transport: a send goes to the instance each
|
|
959
|
+
* connection id names, a broadcast to every instance. What `services.<id>`
|
|
960
|
+
* sends through, and what the Node adaptor's own `sockets` do.
|
|
961
|
+
*/
|
|
962
|
+
var TransportSink = class {
|
|
963
|
+
transport;
|
|
964
|
+
local;
|
|
965
|
+
constructor(transport, local) {
|
|
966
|
+
this.transport = transport;
|
|
967
|
+
this.local = local;
|
|
968
|
+
}
|
|
969
|
+
send(ids, payload) {
|
|
970
|
+
return this.each(ids, (group) => ({
|
|
971
|
+
kind: "send",
|
|
972
|
+
ids: group,
|
|
973
|
+
payload
|
|
974
|
+
}));
|
|
975
|
+
}
|
|
976
|
+
async broadcast(payload, except) {
|
|
977
|
+
await this.transport.publish("*", {
|
|
978
|
+
kind: "broadcast",
|
|
979
|
+
payload,
|
|
980
|
+
...except?.length ? { except } : {}
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
close(ids, code, reason) {
|
|
984
|
+
return this.each(ids, (group) => ({
|
|
985
|
+
kind: "close",
|
|
986
|
+
ids: group,
|
|
987
|
+
code,
|
|
988
|
+
reason
|
|
989
|
+
}));
|
|
990
|
+
}
|
|
991
|
+
/** One delivery per process that holds any of `ids`. */
|
|
992
|
+
async each(ids, delivery) {
|
|
993
|
+
const byInstance = /* @__PURE__ */ new Map();
|
|
994
|
+
for (const id of ids) {
|
|
995
|
+
const instance = instanceOf(id);
|
|
996
|
+
if (!instance) continue;
|
|
997
|
+
const group = byInstance.get(instance) ?? [];
|
|
998
|
+
group.push(id);
|
|
999
|
+
byInstance.set(instance, group);
|
|
1000
|
+
}
|
|
1001
|
+
await Promise.all([...byInstance].map(([instance, group]) => this.local?.instance === instance ? this.local.deliver(delivery(group)) : this.transport.publish(instance, delivery(group))));
|
|
1002
|
+
}
|
|
1003
|
+
};
|
|
1004
|
+
/** A connection string names no transport this package knows. */
|
|
1005
|
+
var UnsupportedWebSocketTransport = class extends Error {
|
|
1006
|
+
connectionString;
|
|
1007
|
+
constructor(connectionString) {
|
|
1008
|
+
super(`'${redact(connectionString)}' is not a WebSocket publisher connection string. Use redis://, rediss:// or memory:// — gkm composes it as <ID>_PUBLISHER_CONNECTION_STRING.`);
|
|
1009
|
+
this.connectionString = connectionString;
|
|
1010
|
+
this.name = "UnsupportedWebSocketTransport";
|
|
1011
|
+
}
|
|
1012
|
+
};
|
|
1013
|
+
/** The scheme alone, so an error never prints a password. */
|
|
1014
|
+
function redact(connectionString) {
|
|
1015
|
+
const scheme = connectionString.split("://")[0];
|
|
1016
|
+
return scheme && scheme !== connectionString ? `${scheme}://…` : connectionString.slice(0, 12);
|
|
1017
|
+
}
|
|
1018
|
+
const key = Symbol.for("@geekmidas/constructs/websocket/memory");
|
|
1019
|
+
const registry = globalThis;
|
|
1020
|
+
registry[key] ??= /* @__PURE__ */ new Map();
|
|
1021
|
+
const channels = registry[key];
|
|
1022
|
+
const limitsKey = Symbol.for("@geekmidas/constructs/websocket/memory-limits");
|
|
1023
|
+
const limitRegistry = globalThis;
|
|
1024
|
+
limitRegistry[limitsKey] ??= /* @__PURE__ */ new Map();
|
|
1025
|
+
const limitStores = limitRegistry[limitsKey];
|
|
1026
|
+
/**
|
|
1027
|
+
* In one process: the server and whoever sends meet in a map, keyed by the
|
|
1028
|
+
* channel the connection string names.
|
|
1029
|
+
*/
|
|
1030
|
+
var MemoryTransport = class {
|
|
1031
|
+
channel;
|
|
1032
|
+
subscribed = /* @__PURE__ */ new Set();
|
|
1033
|
+
constructor(channel) {
|
|
1034
|
+
this.channel = channel;
|
|
1035
|
+
}
|
|
1036
|
+
async publish(instance, delivery) {
|
|
1037
|
+
const instances = channels.get(this.channel);
|
|
1038
|
+
if (!instances) return;
|
|
1039
|
+
if (instance === "*") {
|
|
1040
|
+
for (const receive of instances.values()) receive(delivery);
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
instances.get(instance)?.(delivery);
|
|
1044
|
+
}
|
|
1045
|
+
async subscribe(instance, receive) {
|
|
1046
|
+
let instances = channels.get(this.channel);
|
|
1047
|
+
if (!instances) {
|
|
1048
|
+
instances = /* @__PURE__ */ new Map();
|
|
1049
|
+
channels.set(this.channel, instances);
|
|
1050
|
+
}
|
|
1051
|
+
instances.set(instance, receive);
|
|
1052
|
+
this.subscribed.add(instance);
|
|
1053
|
+
}
|
|
1054
|
+
async close() {
|
|
1055
|
+
const instances = channels.get(this.channel);
|
|
1056
|
+
for (const instance of this.subscribed) instances?.delete(instance);
|
|
1057
|
+
this.subscribed.clear();
|
|
1058
|
+
if (!instances?.size) limitStores.delete(this.channel);
|
|
1059
|
+
}
|
|
1060
|
+
limits() {
|
|
1061
|
+
let store = limitStores.get(this.channel);
|
|
1062
|
+
if (!store) {
|
|
1063
|
+
store = new MemoryLimitStore();
|
|
1064
|
+
limitStores.set(this.channel, store);
|
|
1065
|
+
}
|
|
1066
|
+
return store;
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
/**
|
|
1070
|
+
* Over Redis pub/sub: one channel per instance and one for broadcasts, under
|
|
1071
|
+
* a prefix that keeps two surfaces — or two projects on one Redis — apart.
|
|
1072
|
+
* Channels are not scoped by database index, so the prefix is what does it.
|
|
1073
|
+
*
|
|
1074
|
+
* Publishing and subscribing take separate connections, because a connection
|
|
1075
|
+
* that has subscribed can do nothing else.
|
|
1076
|
+
*/
|
|
1077
|
+
var RedisTransport = class {
|
|
1078
|
+
client;
|
|
1079
|
+
prefix;
|
|
1080
|
+
subscriber;
|
|
1081
|
+
closed;
|
|
1082
|
+
constructor(client, prefix) {
|
|
1083
|
+
this.client = client;
|
|
1084
|
+
this.prefix = prefix;
|
|
1085
|
+
}
|
|
1086
|
+
channel(instance) {
|
|
1087
|
+
return `${this.prefix}:${instance}`;
|
|
1088
|
+
}
|
|
1089
|
+
async publish(instance, delivery) {
|
|
1090
|
+
await this.client.publish(this.channel(instance), JSON.stringify(delivery));
|
|
1091
|
+
}
|
|
1092
|
+
async subscribe(instance, receive) {
|
|
1093
|
+
const subscriber = this.client.duplicate();
|
|
1094
|
+
this.subscriber = subscriber;
|
|
1095
|
+
const own = this.channel(instance);
|
|
1096
|
+
const every = this.channel("*");
|
|
1097
|
+
subscriber.on("message", (channel, message) => {
|
|
1098
|
+
if (channel !== own && channel !== every) return;
|
|
1099
|
+
receive(JSON.parse(message));
|
|
1100
|
+
});
|
|
1101
|
+
await subscriber.subscribe(own, every);
|
|
1102
|
+
}
|
|
1103
|
+
/** Counted in this Redis, under the transport's prefix. */
|
|
1104
|
+
limits() {
|
|
1105
|
+
return new RedisLimitStore(this.client, this.prefix);
|
|
1106
|
+
}
|
|
1107
|
+
/** Idempotent: the server and a shutdown hook may both close it. */
|
|
1108
|
+
close() {
|
|
1109
|
+
this.closed ??= Promise.all([this.subscriber?.quit(), this.client.quit()]).then(() => void 0);
|
|
1110
|
+
return this.closed;
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
/**
|
|
1114
|
+
* The transport a connection string names.
|
|
1115
|
+
*
|
|
1116
|
+
* `redis://` and `rediss://` take an optional `channel` query parameter, the
|
|
1117
|
+
* prefix every channel is named under; `memory://<channel>` is in-process.
|
|
1118
|
+
* Absent, the channel is `fallback` — the surface's own.
|
|
1119
|
+
*/
|
|
1120
|
+
async function transportFromConnectionString(connectionString, fallback) {
|
|
1121
|
+
if (connectionString.startsWith("memory://")) return new MemoryTransport(connectionString.slice(9) || fallback);
|
|
1122
|
+
const url = URL.canParse(connectionString) ? new URL(connectionString) : void 0;
|
|
1123
|
+
if (!url) throw new UnsupportedWebSocketTransport(connectionString);
|
|
1124
|
+
if (url.protocol === "redis:" || url.protocol === "rediss:") {
|
|
1125
|
+
const channel = url.searchParams.get("channel") || fallback;
|
|
1126
|
+
url.searchParams.delete("channel");
|
|
1127
|
+
const { Redis } = await require_optionalPeers.loadIoredis();
|
|
1128
|
+
return new RedisTransport(new Redis(url.toString(), {
|
|
1129
|
+
maxRetriesPerRequest: null,
|
|
1130
|
+
lazyConnect: false
|
|
1131
|
+
}), channel);
|
|
1132
|
+
}
|
|
1133
|
+
throw new UnsupportedWebSocketTransport(connectionString);
|
|
1134
|
+
}
|
|
1135
|
+
//#endregion
|
|
1136
|
+
//#region src/websocket/server.ts
|
|
1137
|
+
/**
|
|
1138
|
+
* The Node adaptor: the process that holds a WebSocket surface's sockets.
|
|
1139
|
+
*
|
|
1140
|
+
* Node's own `http` server and `ws`, nothing between them. This owns what
|
|
1141
|
+
* only a real socket has — the upgrade, the Origin check, connection ids,
|
|
1142
|
+
* the heartbeat, backpressure, and the limits on what one client may ask of
|
|
1143
|
+
* it (`limits.ts`) — and hands the rest to the surface's `WebSocketCore`: a
|
|
1144
|
+
* handshake to `connect()`, each frame to `message()`, a close to
|
|
1145
|
+
* `disconnect()`. The HTTP server is whatever the entry started — the
|
|
1146
|
+
* generated one serves `/health` on the same port — and this attaches to its
|
|
1147
|
+
* `upgrade` event.
|
|
1148
|
+
*/
|
|
1149
|
+
/** Close codes a client sees. */
|
|
1150
|
+
const CLOSE = {
|
|
1151
|
+
normal: 1e3,
|
|
1152
|
+
/**
|
|
1153
|
+
* It kept sending past its message rate, or its identity opened more
|
|
1154
|
+
* sockets than `limits.maxConnections` and this was the oldest.
|
|
1155
|
+
*/
|
|
1156
|
+
policy: LIMIT_CLOSE.policy,
|
|
1157
|
+
/** The process is stopping; reconnect and land on another. */
|
|
1158
|
+
serviceRestart: 1012,
|
|
1159
|
+
/** It stopped reading, and what was queued for it passed the limit. */
|
|
1160
|
+
tooSlow: 1013
|
|
1161
|
+
};
|
|
1162
|
+
/** A handshake is counted as in flight for at most this long. */
|
|
1163
|
+
const IN_FLIGHT_TTL_MS = 3e4;
|
|
1164
|
+
var WebSocketSurfaceServer = class WebSocketSurfaceServer {
|
|
1165
|
+
wss;
|
|
1166
|
+
options;
|
|
1167
|
+
/** This process, as connection ids name it. */
|
|
1168
|
+
instance = (0, node_crypto.randomBytes)(6).toString("hex");
|
|
1169
|
+
/** Where each handshake, frame and close is handed. */
|
|
1170
|
+
core;
|
|
1171
|
+
held = /* @__PURE__ */ new Map();
|
|
1172
|
+
heartbeat;
|
|
1173
|
+
heartbeatMs;
|
|
1174
|
+
trusted;
|
|
1175
|
+
sink;
|
|
1176
|
+
limits;
|
|
1177
|
+
store;
|
|
1178
|
+
next = 0;
|
|
1179
|
+
closing = false;
|
|
1180
|
+
constructor(wss, options) {
|
|
1181
|
+
this.wss = wss;
|
|
1182
|
+
this.options = options;
|
|
1183
|
+
this.sink = new TransportSink(options.transport, {
|
|
1184
|
+
instance: this.instance,
|
|
1185
|
+
deliver: (delivery) => this.deliver(delivery)
|
|
1186
|
+
});
|
|
1187
|
+
this.core = options.core(this.sink);
|
|
1188
|
+
this.trusted = [...options.trustedOrigins, ...require_origins.ownOrigins(options.url)];
|
|
1189
|
+
this.limits = options.limits ?? resolveLimits(this.core.surface);
|
|
1190
|
+
this.store = options.transport.limits?.() ?? new MemoryLimitStore();
|
|
1191
|
+
this.heartbeatMs = options.heartbeatMs ?? 3e4;
|
|
1192
|
+
this.heartbeat = setInterval(() => this.beat(), this.heartbeatMs);
|
|
1193
|
+
this.heartbeat.unref();
|
|
1194
|
+
}
|
|
1195
|
+
static async start(options) {
|
|
1196
|
+
const { WebSocketServer } = await require_optionalPeers.loadWs();
|
|
1197
|
+
const wss = new WebSocketServer({
|
|
1198
|
+
noServer: true,
|
|
1199
|
+
maxPayload: options.maxPayload ?? 1048576,
|
|
1200
|
+
perMessageDeflate: false,
|
|
1201
|
+
clientTracking: false
|
|
1202
|
+
});
|
|
1203
|
+
const server = new WebSocketSurfaceServer(wss, options);
|
|
1204
|
+
await options.transport.subscribe(server.instance, (delivery) => server.deliver(delivery));
|
|
1205
|
+
return server;
|
|
1206
|
+
}
|
|
1207
|
+
/** `sockets` in a route: local sends skip the transport. */
|
|
1208
|
+
get publisher() {
|
|
1209
|
+
return this.core.sockets;
|
|
1210
|
+
}
|
|
1211
|
+
/** How many sockets this process holds. */
|
|
1212
|
+
get size() {
|
|
1213
|
+
return this.held.size;
|
|
1214
|
+
}
|
|
1215
|
+
/** Take over `server`'s upgrades. */
|
|
1216
|
+
attach(server) {
|
|
1217
|
+
server.on("upgrade", (request, socket, head) => {
|
|
1218
|
+
this.upgrade(request, socket, head);
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* Upgrade one request, or refuse it with a status line. The cheap checks
|
|
1223
|
+
* come first — the Origin, the client's handshake rate, its handshakes in
|
|
1224
|
+
* flight and its open sockets — so a flood is refused before the connect
|
|
1225
|
+
* handler, and the session lookup it makes, runs.
|
|
1226
|
+
*/
|
|
1227
|
+
async upgrade(request, socket, head) {
|
|
1228
|
+
if (this.closing) return refuse(socket, 503, "Service Unavailable");
|
|
1229
|
+
const origin = request.headers.origin;
|
|
1230
|
+
if (origin ? !(0, _geekmidas_manifest.trustsOrigin)(origin, this.trusted) : this.options.requireOrigin) return refuse(socket, 403, "Forbidden");
|
|
1231
|
+
const { limits } = this;
|
|
1232
|
+
const client = clientAddress(request);
|
|
1233
|
+
const connectionId = `${this.instance}.${(this.next++).toString(36)}`;
|
|
1234
|
+
if (limits.handshakesPerMinute) {
|
|
1235
|
+
const window = await this.guard(() => this.store.hit(`handshakes:${client}`, 6e4));
|
|
1236
|
+
if (window && window.count > limits.handshakesPerMinute) return tooMany(socket, window.resetMs);
|
|
1237
|
+
}
|
|
1238
|
+
const inFlight = {
|
|
1239
|
+
key: `in-flight:${client}`,
|
|
1240
|
+
member: connectionId
|
|
1241
|
+
};
|
|
1242
|
+
if (limits.inFlightHandshakes && !await this.claim(inFlight, limits.inFlightHandshakes, IN_FLIGHT_TTL_MS)) return tooMany(socket);
|
|
1243
|
+
const leases = [];
|
|
1244
|
+
const releaseAll = () => {
|
|
1245
|
+
for (const lease of leases.splice(0)) this.release(lease);
|
|
1246
|
+
};
|
|
1247
|
+
try {
|
|
1248
|
+
if (limits.connectionsPerIp) {
|
|
1249
|
+
const lease = {
|
|
1250
|
+
key: `ip:${client}`,
|
|
1251
|
+
member: connectionId
|
|
1252
|
+
};
|
|
1253
|
+
if (!await this.claim(lease, limits.connectionsPerIp)) return tooMany(socket);
|
|
1254
|
+
leases.push(lease);
|
|
1255
|
+
}
|
|
1256
|
+
const outcome = await this.core.connect({
|
|
1257
|
+
connectionId,
|
|
1258
|
+
headers: headersOf(request),
|
|
1259
|
+
query: new URL(request.url ?? "/", "http://localhost").searchParams
|
|
1260
|
+
});
|
|
1261
|
+
if (!outcome.accepted) {
|
|
1262
|
+
releaseAll();
|
|
1263
|
+
return refuse(socket, outcome.status, outcome.statusText);
|
|
1264
|
+
}
|
|
1265
|
+
const identity = limits.maxConnectionsPer?.(outcome.connection.data);
|
|
1266
|
+
if (identity !== void 0) {
|
|
1267
|
+
const lease = {
|
|
1268
|
+
key: `identity:${identity}`,
|
|
1269
|
+
member: connectionId
|
|
1270
|
+
};
|
|
1271
|
+
leases.push(lease);
|
|
1272
|
+
const held = await this.guard(() => this.store.hold(lease.key, lease.member, this.connectionTtl));
|
|
1273
|
+
if (held && held.length > limits.maxConnections) {
|
|
1274
|
+
if (limits.overflow === "refuse") {
|
|
1275
|
+
releaseAll();
|
|
1276
|
+
return tooMany(socket);
|
|
1277
|
+
}
|
|
1278
|
+
const oldest = held.filter((id) => id !== connectionId).slice(0, held.length - limits.maxConnections);
|
|
1279
|
+
for (const id of oldest) this.release({
|
|
1280
|
+
key: lease.key,
|
|
1281
|
+
member: id
|
|
1282
|
+
});
|
|
1283
|
+
await this.guard(() => this.sink.close(oldest, CLOSE.policy, "Too many connections"));
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
if (socket.destroyed) return releaseAll();
|
|
1287
|
+
const opened = leases.splice(0);
|
|
1288
|
+
this.wss.handleUpgrade(request, socket, head, (ws) => this.open(ws, outcome.connection, opened));
|
|
1289
|
+
} finally {
|
|
1290
|
+
if (limits.inFlightHandshakes) this.release(inFlight);
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
open(socket, connection, leases) {
|
|
1294
|
+
const { messagesPerSecond, burst } = this.limits;
|
|
1295
|
+
const held = {
|
|
1296
|
+
socket,
|
|
1297
|
+
connection,
|
|
1298
|
+
alive: true,
|
|
1299
|
+
leases,
|
|
1300
|
+
warned: false,
|
|
1301
|
+
...messagesPerSecond ? { bucket: new TokenBucket(messagesPerSecond, burst) } : {}
|
|
1302
|
+
};
|
|
1303
|
+
this.held.set(connection.id, held);
|
|
1304
|
+
const write = (payload) => this.write(held, payload);
|
|
1305
|
+
socket.on("pong", () => {
|
|
1306
|
+
held.alive = true;
|
|
1307
|
+
});
|
|
1308
|
+
socket.on("message", (raw, isBinary) => {
|
|
1309
|
+
held.alive = true;
|
|
1310
|
+
if (!this.admit(held)) return;
|
|
1311
|
+
this.core.message(connection, isBinary ? bytesOf(raw) : raw.toString(), write);
|
|
1312
|
+
});
|
|
1313
|
+
socket.on("error", () => socket.terminate());
|
|
1314
|
+
socket.on("close", (code, reason) => {
|
|
1315
|
+
this.held.delete(connection.id);
|
|
1316
|
+
for (const lease of held.leases.splice(0)) this.release(lease);
|
|
1317
|
+
this.core.disconnect(connection, {
|
|
1318
|
+
code,
|
|
1319
|
+
reason: reason.toString()
|
|
1320
|
+
});
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Whether a frame is within its socket's budget. The first past it is
|
|
1325
|
+
* answered with one `$error`; another before the budget has refilled
|
|
1326
|
+
* closes the socket with 1008.
|
|
1327
|
+
*/
|
|
1328
|
+
admit(held) {
|
|
1329
|
+
const { bucket } = held;
|
|
1330
|
+
if (!bucket) return true;
|
|
1331
|
+
if (bucket.take()) {
|
|
1332
|
+
if (held.warned && bucket.full) held.warned = false;
|
|
1333
|
+
return true;
|
|
1334
|
+
}
|
|
1335
|
+
if (held.socket.readyState !== held.socket.OPEN) return false;
|
|
1336
|
+
if (held.warned) {
|
|
1337
|
+
held.socket.close(CLOSE.policy, "Too many messages");
|
|
1338
|
+
return false;
|
|
1339
|
+
}
|
|
1340
|
+
held.warned = true;
|
|
1341
|
+
this.write(held, this.core.frame.encode("$error", { message: `Too many messages: at most ${this.limits.messagesPerSecond} a second, ${this.limits.burst} at once. Frames are dropped until the socket slows down, and it is closed if it keeps sending.` }));
|
|
1342
|
+
return false;
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Take a place in `lease`'s count — or none, when that would put it past
|
|
1346
|
+
* `max`. A store that cannot be reached lets the handshake through.
|
|
1347
|
+
*/
|
|
1348
|
+
async claim(lease, max, ttlMs = this.connectionTtl) {
|
|
1349
|
+
const held = await this.guard(() => this.store.hold(lease.key, lease.member, ttlMs));
|
|
1350
|
+
if (!held || held.length <= max) return true;
|
|
1351
|
+
this.release(lease);
|
|
1352
|
+
return false;
|
|
1353
|
+
}
|
|
1354
|
+
release(lease) {
|
|
1355
|
+
this.guard(() => this.store.release(lease.key, lease.member));
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* How long a socket's place in a count outlives its process, should it
|
|
1359
|
+
* die without giving it back: three heartbeats, each of which renews it.
|
|
1360
|
+
*/
|
|
1361
|
+
get connectionTtl() {
|
|
1362
|
+
return this.heartbeatMs * 3;
|
|
1363
|
+
}
|
|
1364
|
+
/** The store's answer — or nothing, logged, when it fails. */
|
|
1365
|
+
async guard(call) {
|
|
1366
|
+
try {
|
|
1367
|
+
return await call();
|
|
1368
|
+
} catch (err) {
|
|
1369
|
+
this.options.logger?.warn({ err }, "WebSocket limit store failed; the limit was not applied");
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
/** Write, unless the socket has stopped reading and its queue is full. */
|
|
1374
|
+
write(held, payload) {
|
|
1375
|
+
const { socket } = held;
|
|
1376
|
+
if (socket.readyState !== socket.OPEN) return;
|
|
1377
|
+
if (socket.bufferedAmount > (this.options.maxBufferedBytes ?? 4194304)) {
|
|
1378
|
+
socket.close(CLOSE.tooSlow, "Too slow");
|
|
1379
|
+
return;
|
|
1380
|
+
}
|
|
1381
|
+
socket.send(payload);
|
|
1382
|
+
}
|
|
1383
|
+
/** What the transport, or a local publisher, asked of this process. */
|
|
1384
|
+
deliver(delivery) {
|
|
1385
|
+
switch (delivery.kind) {
|
|
1386
|
+
case "send":
|
|
1387
|
+
for (const id of delivery.ids) {
|
|
1388
|
+
const held = this.held.get(id);
|
|
1389
|
+
if (held) this.write(held, delivery.payload);
|
|
1390
|
+
}
|
|
1391
|
+
return;
|
|
1392
|
+
case "broadcast": {
|
|
1393
|
+
const except = delivery.except ? new Set(delivery.except) : void 0;
|
|
1394
|
+
for (const [id, held] of this.held) if (!except?.has(id)) this.write(held, delivery.payload);
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1397
|
+
case "close":
|
|
1398
|
+
for (const id of delivery.ids) this.held.get(id)?.socket.close(delivery.code, delivery.reason);
|
|
1399
|
+
return;
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* Drop every socket that missed the last ping, and ping the rest — whose
|
|
1404
|
+
* places in the limits' counts are renewed.
|
|
1405
|
+
*/
|
|
1406
|
+
beat() {
|
|
1407
|
+
const renewed = [];
|
|
1408
|
+
for (const [id, held] of this.held) {
|
|
1409
|
+
if (!held.alive) {
|
|
1410
|
+
held.socket.terminate();
|
|
1411
|
+
this.held.delete(id);
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
held.alive = false;
|
|
1415
|
+
held.socket.ping();
|
|
1416
|
+
renewed.push(...held.leases);
|
|
1417
|
+
}
|
|
1418
|
+
if (renewed.length > 0) this.guard(() => this.store.renew(renewed, this.connectionTtl));
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Stop: refuse new upgrades, close every socket with `code` — 1012 tells
|
|
1422
|
+
* a client to reconnect, and it lands on a process that is still up — and
|
|
1423
|
+
* leave the transport.
|
|
1424
|
+
*/
|
|
1425
|
+
async close(code = CLOSE.serviceRestart, reason = "Restarting") {
|
|
1426
|
+
if (this.closing) return;
|
|
1427
|
+
this.closing = true;
|
|
1428
|
+
clearInterval(this.heartbeat);
|
|
1429
|
+
const closed = [...this.held.values()].map(({ socket }) => new Promise((resolve) => {
|
|
1430
|
+
if (socket.readyState === socket.CLOSED) return resolve();
|
|
1431
|
+
socket.once("close", () => resolve());
|
|
1432
|
+
socket.close(code, reason);
|
|
1433
|
+
setTimeout(() => {
|
|
1434
|
+
socket.terminate();
|
|
1435
|
+
resolve();
|
|
1436
|
+
}, 2e3).unref();
|
|
1437
|
+
}));
|
|
1438
|
+
await Promise.all(closed);
|
|
1439
|
+
await this.options.transport.close();
|
|
1440
|
+
this.wss.close();
|
|
1441
|
+
}
|
|
1442
|
+
};
|
|
1443
|
+
/** A binary frame's bytes, however `ws` delivered them. */
|
|
1444
|
+
function bytesOf(raw) {
|
|
1445
|
+
if (Array.isArray(raw)) return Buffer.concat(raw);
|
|
1446
|
+
return raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw;
|
|
1447
|
+
}
|
|
1448
|
+
function headersOf(request) {
|
|
1449
|
+
const headers = new Headers();
|
|
1450
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
1451
|
+
if (value === void 0) continue;
|
|
1452
|
+
for (const one of Array.isArray(value) ? value : [value]) headers.append(name, one);
|
|
1453
|
+
}
|
|
1454
|
+
return headers;
|
|
1455
|
+
}
|
|
1456
|
+
function refuse(socket, status, message, headers = {}) {
|
|
1457
|
+
if (!socket.destroyed) {
|
|
1458
|
+
const extra = Object.entries(headers).map(([name, value]) => `${name}: ${value}\r\n`).join("");
|
|
1459
|
+
socket.end(`HTTP/1.1 ${status} ${message}\r\n${extra}Connection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
/** 429 — with when to come back, where a window says. */
|
|
1463
|
+
function tooMany(socket, retryAfterMs) {
|
|
1464
|
+
refuse(socket, 429, "Too Many Requests", retryAfterMs === void 0 ? {} : { "Retry-After": String(Math.max(1, Math.ceil(retryAfterMs / 1e3))) });
|
|
1465
|
+
}
|
|
1466
|
+
//#endregion
|
|
1467
|
+
//#region src/websocket-api.ts
|
|
1468
|
+
/** A replica count that is not a whole number of at least one. */
|
|
1469
|
+
var InvalidReplicaCount = class extends Error {
|
|
1470
|
+
id;
|
|
1471
|
+
replicas;
|
|
1472
|
+
constructor(id, replicas) {
|
|
1473
|
+
super(`${id} asks for ${replicas} replicas. A surface runs on at least one process — give a whole number of 1 or more.`);
|
|
1474
|
+
this.id = id;
|
|
1475
|
+
this.replicas = replicas;
|
|
1476
|
+
this.name = "InvalidReplicaCount";
|
|
1477
|
+
}
|
|
1478
|
+
};
|
|
1479
|
+
var WebSocketApi = class WebSocketApi {
|
|
1480
|
+
config;
|
|
1481
|
+
authenticator;
|
|
1482
|
+
id;
|
|
1483
|
+
keys;
|
|
1484
|
+
logger;
|
|
1485
|
+
envParser;
|
|
1486
|
+
telemetry;
|
|
1487
|
+
/**
|
|
1488
|
+
* The shape its frames take — `{ action, data }`, or flat under
|
|
1489
|
+
* `discriminator`. What a client of the surface decodes by.
|
|
1490
|
+
*/
|
|
1491
|
+
frame;
|
|
1492
|
+
/** What one client may ask of it, defaults filled in. */
|
|
1493
|
+
limits;
|
|
1494
|
+
/**
|
|
1495
|
+
* The surface as a dependency: `services.<id>` is its publisher, so an
|
|
1496
|
+
* endpoint sends to a socket the way a route beside it does.
|
|
1497
|
+
*/
|
|
1498
|
+
service;
|
|
1499
|
+
constructor(id, config, authenticator) {
|
|
1500
|
+
this.config = config;
|
|
1501
|
+
this.authenticator = authenticator;
|
|
1502
|
+
const canonical = (0, _geekmidas_manifest.canonicalId)(id);
|
|
1503
|
+
this.id = canonical;
|
|
1504
|
+
const replicas = config.replicas ?? 1;
|
|
1505
|
+
if (!Number.isInteger(replicas) || replicas < 1) throw new InvalidReplicaCount(canonical, replicas);
|
|
1506
|
+
const frame = new FrameShape(canonical, config.frame?.discriminator);
|
|
1507
|
+
if (config.messages) frame.check(config.messages);
|
|
1508
|
+
this.frame = config.frame ? { discriminator: config.frame.discriminator } : {};
|
|
1509
|
+
this.limits = resolveLimits(canonical, config.limits);
|
|
1510
|
+
this.keys = {
|
|
1511
|
+
url: (0, _geekmidas_manifest.provideKey)(canonical, "url"),
|
|
1512
|
+
trustedOrigins: (0, _geekmidas_manifest.provideKey)(canonical, "trustedOrigins"),
|
|
1513
|
+
publisherConnectionString: (0, _geekmidas_manifest.provideKey)(canonical, "publisherConnectionString")
|
|
1514
|
+
};
|
|
1515
|
+
this.logger = config.logger ?? _geekmidas_logger_console.DEFAULT_LOGGER;
|
|
1516
|
+
this.telemetry = config.telemetry;
|
|
1517
|
+
this.envParser = require_surfaceEnv.envParserFor(config.envParser ? {
|
|
1518
|
+
id: canonical,
|
|
1519
|
+
envParser: config.envParser
|
|
1520
|
+
} : void 0);
|
|
1521
|
+
const envVar = this.keys.publisherConnectionString;
|
|
1522
|
+
const channel = channelOf(canonical);
|
|
1523
|
+
this.service = {
|
|
1524
|
+
serviceName: (0, _geekmidas_manifest.serviceKey)(canonical),
|
|
1525
|
+
register: async ({ envParser }) => {
|
|
1526
|
+
const { connectionString } = envParser.create((get) => ({ connectionString: get(envVar).string() })).parse();
|
|
1527
|
+
return this.publisher(await sinkFromConnectionString(this.id, connectionString, channel));
|
|
1528
|
+
}
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
/** The handler a connection's upgrade runs: refuse it, or say who it is. */
|
|
1532
|
+
connect() {
|
|
1533
|
+
return new WebSocketRouteBuilder("connect", "$connect", this);
|
|
1534
|
+
}
|
|
1535
|
+
/** The handler a closed connection runs. */
|
|
1536
|
+
disconnect() {
|
|
1537
|
+
return new WebSocketRouteBuilder("disconnect", "$disconnect", this);
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* The handler for frames whose `action` — or, for flat frames, whose
|
|
1541
|
+
* discriminator — is `action`. `$default` answers
|
|
1542
|
+
* any action nothing else does.
|
|
1543
|
+
*/
|
|
1544
|
+
route(action) {
|
|
1545
|
+
return new WebSocketRouteBuilder("message", action, this);
|
|
1546
|
+
}
|
|
1547
|
+
/** What authenticates a connection — its session reaches `connect()`. */
|
|
1548
|
+
auth(construct) {
|
|
1549
|
+
return new WebSocketApi(this.id, this.config, construct);
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* Serve it: the routes exported by `modules` that were built from this
|
|
1553
|
+
* surface, on whatever HTTP server `attach` is handed.
|
|
1554
|
+
*
|
|
1555
|
+
* `app` answers plain HTTP — the generated entry puts `/health` in front
|
|
1556
|
+
* of it — and `attach` takes over the server's upgrades. The sockets are
|
|
1557
|
+
* closed with 1012 when the server shuts down.
|
|
1558
|
+
*/
|
|
1559
|
+
async server(options) {
|
|
1560
|
+
const { Hono } = await require_optionalPeers.loadHono("A WebSocketApi");
|
|
1561
|
+
const { connectionString, origins, url } = options.envParser.create((get) => ({
|
|
1562
|
+
connectionString: get(this.keys.publisherConnectionString).string().default(`memory://${channelOf(this.id)}`),
|
|
1563
|
+
origins: get(this.keys.trustedOrigins).string().default("").transform((value) => value.split(",").map((origin) => origin.trim()).filter(Boolean)),
|
|
1564
|
+
url: get(this.keys.url).string().optional()
|
|
1565
|
+
})).parse();
|
|
1566
|
+
const server = await WebSocketSurfaceServer.start({
|
|
1567
|
+
core: (sink) => this.core({
|
|
1568
|
+
envParser: options.envParser,
|
|
1569
|
+
sink,
|
|
1570
|
+
...options.modules ? { modules: options.modules } : {}
|
|
1571
|
+
}),
|
|
1572
|
+
transport: await transportFromConnectionString(connectionString, channelOf(this.id)),
|
|
1573
|
+
trustedOrigins: origins,
|
|
1574
|
+
...this.config.requireOrigin ? { requireOrigin: true } : {},
|
|
1575
|
+
limits: this.limits,
|
|
1576
|
+
logger: this.logger,
|
|
1577
|
+
...url ? { url } : {},
|
|
1578
|
+
...this.config.heartbeat ? { heartbeatMs: this.config.heartbeat * 1e3 } : {},
|
|
1579
|
+
...this.config.maxPayload ? { maxPayload: this.config.maxPayload } : {}
|
|
1580
|
+
});
|
|
1581
|
+
require_shutdown.onShutdown(() => server.close());
|
|
1582
|
+
const app = new Hono();
|
|
1583
|
+
app.get("/health", (c) => c.json({
|
|
1584
|
+
status: "ok",
|
|
1585
|
+
connections: server.size
|
|
1586
|
+
}));
|
|
1587
|
+
app.get("/", (c) => c.json({
|
|
1588
|
+
surface: this.id,
|
|
1589
|
+
connections: server.size
|
|
1590
|
+
}, 426, { Upgrade: "websocket" }));
|
|
1591
|
+
return {
|
|
1592
|
+
app,
|
|
1593
|
+
attach: (http) => server.attach(http),
|
|
1594
|
+
release: () => server.close(),
|
|
1595
|
+
server
|
|
1596
|
+
};
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* The surface with no socket in it — what every runtime serves. The
|
|
1600
|
+
* routes exported by `modules` that were built from this surface answer
|
|
1601
|
+
* its frames; `sink` is where its handlers' `sockets` send.
|
|
1602
|
+
*
|
|
1603
|
+
* `server()` is the Node adaptor over it. Another runtime (a Lambda
|
|
1604
|
+
* behind API Gateway, a test) builds one with a sink of its own and
|
|
1605
|
+
* calls `connect()`, `message()` and `disconnect()` per connection id.
|
|
1606
|
+
*
|
|
1607
|
+
* @throws {DuplicateWebSocketRoute} when two routes answer one action.
|
|
1608
|
+
*/
|
|
1609
|
+
core(options) {
|
|
1610
|
+
return new WebSocketCore({
|
|
1611
|
+
surface: this.id,
|
|
1612
|
+
routes: (options.modules ?? []).flatMap((module) => Object.values(module).filter(WebSocketRoute.isRoute)),
|
|
1613
|
+
sink: options.sink,
|
|
1614
|
+
envParser: options.envParser,
|
|
1615
|
+
logger: this.logger,
|
|
1616
|
+
...this.config.frame ? { frame: this.config.frame } : {},
|
|
1617
|
+
...this.declared ? { messages: this.declared.messages } : {},
|
|
1618
|
+
...this.authenticator ? { authenticator: this.authenticator } : {}
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
/**
|
|
1622
|
+
* The surface's publisher over `sink` — typed, checked and encoded as
|
|
1623
|
+
* `services.<id>` is. What an adaptor with a sink of its own (MSW, a
|
|
1624
|
+
* Lambda) hands the code that sends to its connections.
|
|
1625
|
+
*/
|
|
1626
|
+
publisher(sink) {
|
|
1627
|
+
return new WebSocketPublisher(sink, this.declared, new FrameShape(this.id, this.config.frame?.discriminator));
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* A publisher of the type `services.<id>` is, that records rather than
|
|
1631
|
+
* sends — hand it to an endpoint's spec, or to a route's `request()` as
|
|
1632
|
+
* `sockets`, and assert on `sent`, `broadcasts` and `closed`.
|
|
1633
|
+
*
|
|
1634
|
+
* Every send is checked by the declared `messages` and encoded by `frame`,
|
|
1635
|
+
* as deployed: an invalid push rejects, and each record carries the
|
|
1636
|
+
* frame a client would parse.
|
|
1637
|
+
*
|
|
1638
|
+
* ```ts
|
|
1639
|
+
* const realtime = surface.testPublisher();
|
|
1640
|
+
* await sendMessage.request({ services: { realtime }, … });
|
|
1641
|
+
* expect(realtime.sent).toEqual([
|
|
1642
|
+
* { ids: ['a.1'], action: 'chat.sent', data: { text: 'hi' }, frame: … },
|
|
1643
|
+
* ]);
|
|
1644
|
+
* ```
|
|
1645
|
+
*/
|
|
1646
|
+
testPublisher() {
|
|
1647
|
+
return new TestWebSocketPublisher(new FrameShape(this.id, this.config.frame?.discriminator), this.declared);
|
|
1648
|
+
}
|
|
1649
|
+
/**
|
|
1650
|
+
* The per-address limits the edge in front of it enforces too, so a
|
|
1651
|
+
* flood is refused before it reaches a replica.
|
|
1652
|
+
*/
|
|
1653
|
+
get edgeLimits() {
|
|
1654
|
+
const { handshakesPerMinute, connectionsPerIp } = this.limits;
|
|
1655
|
+
if (!handshakesPerMinute && !connectionsPerIp) return void 0;
|
|
1656
|
+
return {
|
|
1657
|
+
...handshakesPerMinute ? { handshakesPerMinute } : {},
|
|
1658
|
+
...connectionsPerIp ? { connectionsPerIp } : {}
|
|
1659
|
+
};
|
|
1660
|
+
}
|
|
1661
|
+
/** The declared messages, with the surface they are checked for. */
|
|
1662
|
+
get declared() {
|
|
1663
|
+
return this.config.messages ? {
|
|
1664
|
+
surface: this.id,
|
|
1665
|
+
messages: this.config.messages
|
|
1666
|
+
} : void 0;
|
|
1667
|
+
}
|
|
1668
|
+
declare() {
|
|
1669
|
+
return [{
|
|
1670
|
+
kind: "websocket-api",
|
|
1671
|
+
id: this.id,
|
|
1672
|
+
path: this.config.path,
|
|
1673
|
+
...this.config.subdomain ? { subdomain: this.config.subdomain } : {},
|
|
1674
|
+
...this.config.frame?.discriminator ? { discriminator: this.config.frame.discriminator } : {},
|
|
1675
|
+
...this.authenticator ? { auth: require_construct_interface.edgeTo(this.authenticator) } : {},
|
|
1676
|
+
...this.config.telemetry ? { telemetry: this.config.telemetry.id } : {},
|
|
1677
|
+
...this.config.replicas && this.config.replicas > 1 ? { replicas: this.config.replicas } : {},
|
|
1678
|
+
...this.edgeLimits ? { limits: this.edgeLimits } : {},
|
|
1679
|
+
provides: [
|
|
1680
|
+
this.keys.url,
|
|
1681
|
+
this.keys.trustedOrigins,
|
|
1682
|
+
this.keys.publisherConnectionString
|
|
1683
|
+
]
|
|
1684
|
+
}];
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
/**
|
|
1688
|
+
* Where `services.<surface>` sends, by the publisher string's scheme: a
|
|
1689
|
+
* registered driver's sink — API Gateway's management API on an AWS stage,
|
|
1690
|
+
* registered by the build's entry — or else whichever process holds the
|
|
1691
|
+
* sockets (`redis://`, `memory://`).
|
|
1692
|
+
*
|
|
1693
|
+
* @throws {UnregisteredWebSocketScheme} for `apigateway://` with no driver.
|
|
1694
|
+
*/
|
|
1695
|
+
async function sinkFromConnectionString(surface, connectionString, channel) {
|
|
1696
|
+
const driver = require_origins.webSocketSinkDriverFor(connectionString);
|
|
1697
|
+
if (driver) return driver.sink(connectionString);
|
|
1698
|
+
if (connectionString.startsWith(_geekmidas_manifest.API_GATEWAY_WEBSOCKET_SCHEME)) throw new require_origins.UnregisteredWebSocketScheme(surface, _geekmidas_manifest.API_GATEWAY_WEBSOCKET_SCHEME);
|
|
1699
|
+
const transport = await transportFromConnectionString(connectionString, channel);
|
|
1700
|
+
require_shutdown.onShutdown(() => transport.close());
|
|
1701
|
+
return new TransportSink(transport);
|
|
1702
|
+
}
|
|
1703
|
+
/** The prefix a surface's channels are named under. */
|
|
1704
|
+
function channelOf(id) {
|
|
1705
|
+
return `gkm:ws:${id}`;
|
|
1706
|
+
}
|
|
1707
|
+
//#endregion
|
|
1708
|
+
Object.defineProperty(exports, "CLOSE", {
|
|
1709
|
+
enumerable: true,
|
|
1710
|
+
get: function() {
|
|
1711
|
+
return CLOSE;
|
|
1712
|
+
}
|
|
1713
|
+
});
|
|
1714
|
+
Object.defineProperty(exports, "DEFAULT_WEBSOCKET_LIMITS", {
|
|
1715
|
+
enumerable: true,
|
|
1716
|
+
get: function() {
|
|
1717
|
+
return DEFAULT_WEBSOCKET_LIMITS;
|
|
1718
|
+
}
|
|
1719
|
+
});
|
|
1720
|
+
Object.defineProperty(exports, "DuplicateWebSocketRoute", {
|
|
1721
|
+
enumerable: true,
|
|
1722
|
+
get: function() {
|
|
1723
|
+
return DuplicateWebSocketRoute;
|
|
1724
|
+
}
|
|
1725
|
+
});
|
|
1726
|
+
Object.defineProperty(exports, "InvalidReplicaCount", {
|
|
1727
|
+
enumerable: true,
|
|
1728
|
+
get: function() {
|
|
1729
|
+
return InvalidReplicaCount;
|
|
1730
|
+
}
|
|
1731
|
+
});
|
|
1732
|
+
Object.defineProperty(exports, "InvalidWebSocketLimit", {
|
|
1733
|
+
enumerable: true,
|
|
1734
|
+
get: function() {
|
|
1735
|
+
return InvalidWebSocketLimit;
|
|
1736
|
+
}
|
|
1737
|
+
});
|
|
1738
|
+
Object.defineProperty(exports, "InvalidWebSocketMessage", {
|
|
1739
|
+
enumerable: true,
|
|
1740
|
+
get: function() {
|
|
1741
|
+
return InvalidWebSocketMessage;
|
|
1742
|
+
}
|
|
1743
|
+
});
|
|
1744
|
+
Object.defineProperty(exports, "InvalidWebSocketRequest", {
|
|
1745
|
+
enumerable: true,
|
|
1746
|
+
get: function() {
|
|
1747
|
+
return InvalidWebSocketRequest;
|
|
1748
|
+
}
|
|
1749
|
+
});
|
|
1750
|
+
Object.defineProperty(exports, "LIMIT_CLOSE", {
|
|
1751
|
+
enumerable: true,
|
|
1752
|
+
get: function() {
|
|
1753
|
+
return LIMIT_CLOSE;
|
|
1754
|
+
}
|
|
1755
|
+
});
|
|
1756
|
+
Object.defineProperty(exports, "MemoryLimitStore", {
|
|
1757
|
+
enumerable: true,
|
|
1758
|
+
get: function() {
|
|
1759
|
+
return MemoryLimitStore;
|
|
1760
|
+
}
|
|
1761
|
+
});
|
|
1762
|
+
Object.defineProperty(exports, "MemoryTransport", {
|
|
1763
|
+
enumerable: true,
|
|
1764
|
+
get: function() {
|
|
1765
|
+
return MemoryTransport;
|
|
1766
|
+
}
|
|
1767
|
+
});
|
|
1768
|
+
Object.defineProperty(exports, "RecordingSink", {
|
|
1769
|
+
enumerable: true,
|
|
1770
|
+
get: function() {
|
|
1771
|
+
return RecordingSink;
|
|
1772
|
+
}
|
|
1773
|
+
});
|
|
1774
|
+
Object.defineProperty(exports, "RedisLimitStore", {
|
|
1775
|
+
enumerable: true,
|
|
1776
|
+
get: function() {
|
|
1777
|
+
return RedisLimitStore;
|
|
1778
|
+
}
|
|
1779
|
+
});
|
|
1780
|
+
Object.defineProperty(exports, "RedisTransport", {
|
|
1781
|
+
enumerable: true,
|
|
1782
|
+
get: function() {
|
|
1783
|
+
return RedisTransport;
|
|
1784
|
+
}
|
|
1785
|
+
});
|
|
1786
|
+
Object.defineProperty(exports, "TestWebSocketPublisher", {
|
|
1787
|
+
enumerable: true,
|
|
1788
|
+
get: function() {
|
|
1789
|
+
return TestWebSocketPublisher;
|
|
1790
|
+
}
|
|
1791
|
+
});
|
|
1792
|
+
Object.defineProperty(exports, "TokenBucket", {
|
|
1793
|
+
enumerable: true,
|
|
1794
|
+
get: function() {
|
|
1795
|
+
return TokenBucket;
|
|
1796
|
+
}
|
|
1797
|
+
});
|
|
1798
|
+
Object.defineProperty(exports, "TransportSink", {
|
|
1799
|
+
enumerable: true,
|
|
1800
|
+
get: function() {
|
|
1801
|
+
return TransportSink;
|
|
1802
|
+
}
|
|
1803
|
+
});
|
|
1804
|
+
Object.defineProperty(exports, "UnknownWebSocketMessage", {
|
|
1805
|
+
enumerable: true,
|
|
1806
|
+
get: function() {
|
|
1807
|
+
return UnknownWebSocketMessage;
|
|
1808
|
+
}
|
|
1809
|
+
});
|
|
1810
|
+
Object.defineProperty(exports, "UnsupportedWebSocketTransport", {
|
|
1811
|
+
enumerable: true,
|
|
1812
|
+
get: function() {
|
|
1813
|
+
return UnsupportedWebSocketTransport;
|
|
1814
|
+
}
|
|
1815
|
+
});
|
|
1816
|
+
Object.defineProperty(exports, "WebSocketApi", {
|
|
1817
|
+
enumerable: true,
|
|
1818
|
+
get: function() {
|
|
1819
|
+
return WebSocketApi;
|
|
1820
|
+
}
|
|
1821
|
+
});
|
|
1822
|
+
Object.defineProperty(exports, "WebSocketCore", {
|
|
1823
|
+
enumerable: true,
|
|
1824
|
+
get: function() {
|
|
1825
|
+
return WebSocketCore;
|
|
1826
|
+
}
|
|
1827
|
+
});
|
|
1828
|
+
Object.defineProperty(exports, "WebSocketDataHasDiscriminator", {
|
|
1829
|
+
enumerable: true,
|
|
1830
|
+
get: function() {
|
|
1831
|
+
return WebSocketDataHasDiscriminator;
|
|
1832
|
+
}
|
|
1833
|
+
});
|
|
1834
|
+
Object.defineProperty(exports, "WebSocketDataNotAnObject", {
|
|
1835
|
+
enumerable: true,
|
|
1836
|
+
get: function() {
|
|
1837
|
+
return WebSocketDataNotAnObject;
|
|
1838
|
+
}
|
|
1839
|
+
});
|
|
1840
|
+
Object.defineProperty(exports, "WebSocketMessageDeclaresDiscriminator", {
|
|
1841
|
+
enumerable: true,
|
|
1842
|
+
get: function() {
|
|
1843
|
+
return WebSocketMessageDeclaresDiscriminator;
|
|
1844
|
+
}
|
|
1845
|
+
});
|
|
1846
|
+
Object.defineProperty(exports, "WebSocketMessageNotAnObject", {
|
|
1847
|
+
enumerable: true,
|
|
1848
|
+
get: function() {
|
|
1849
|
+
return WebSocketMessageNotAnObject;
|
|
1850
|
+
}
|
|
1851
|
+
});
|
|
1852
|
+
Object.defineProperty(exports, "WebSocketPublisher", {
|
|
1853
|
+
enumerable: true,
|
|
1854
|
+
get: function() {
|
|
1855
|
+
return WebSocketPublisher;
|
|
1856
|
+
}
|
|
1857
|
+
});
|
|
1858
|
+
Object.defineProperty(exports, "WebSocketRoute", {
|
|
1859
|
+
enumerable: true,
|
|
1860
|
+
get: function() {
|
|
1861
|
+
return WebSocketRoute;
|
|
1862
|
+
}
|
|
1863
|
+
});
|
|
1864
|
+
Object.defineProperty(exports, "WebSocketRouteBuilder", {
|
|
1865
|
+
enumerable: true,
|
|
1866
|
+
get: function() {
|
|
1867
|
+
return WebSocketRouteBuilder;
|
|
1868
|
+
}
|
|
1869
|
+
});
|
|
1870
|
+
Object.defineProperty(exports, "WebSocketSurfaceServer", {
|
|
1871
|
+
enumerable: true,
|
|
1872
|
+
get: function() {
|
|
1873
|
+
return WebSocketSurfaceServer;
|
|
1874
|
+
}
|
|
1875
|
+
});
|
|
1876
|
+
Object.defineProperty(exports, "resolveLimits", {
|
|
1877
|
+
enumerable: true,
|
|
1878
|
+
get: function() {
|
|
1879
|
+
return resolveLimits;
|
|
1880
|
+
}
|
|
1881
|
+
});
|
|
1882
|
+
Object.defineProperty(exports, "transportFromConnectionString", {
|
|
1883
|
+
enumerable: true,
|
|
1884
|
+
get: function() {
|
|
1885
|
+
return transportFromConnectionString;
|
|
1886
|
+
}
|
|
1887
|
+
});
|
|
1888
|
+
|
|
1889
|
+
//# sourceMappingURL=websocket-api-czxhekGG.cjs.map
|