@ultrst-armada/krnl 1.0.2 → 1.0.4
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 +67 -65
- package/package.json +15 -8
- package/packages/cli/dist/bin/krnl.cjs +808 -331
- package/packages/cli/dist/bin/krnl.js +50 -65
- package/packages/cli/dist/chunk-GHWYEAPD.js +1642 -0
- package/packages/cli/dist/index.cjs +761 -263
- package/packages/cli/dist/index.d.cts +45 -2
- package/packages/cli/dist/index.d.ts +45 -2
- package/packages/cli/dist/index.js +5 -1
- package/packages/cli/package.json +17 -10
- package/packages/core/dist/index.cjs +2912 -140
- package/packages/core/dist/index.d.cts +614 -27
- package/packages/core/dist/index.d.ts +614 -27
- package/packages/core/dist/index.js +2903 -140
- package/packages/core/package.json +15 -6
- package/packages/create-krnl/dist/index.cjs +102 -65
- package/packages/create-krnl/dist/index.js +102 -65
- package/packages/create-krnl/package.json +5 -3
- package/packages/eslint-plugin/dist/index.cjs +17 -55
- package/packages/eslint-plugin/dist/index.d.cts +8 -43
- package/packages/eslint-plugin/dist/index.d.ts +8 -43
- package/packages/eslint-plugin/dist/index.js +17 -55
- package/packages/eslint-plugin/package.json +5 -4
- package/packages/validate/dist/index.cjs +378 -85
- package/packages/validate/dist/index.d.cts +11 -1
- package/packages/validate/dist/index.d.ts +11 -1
- package/packages/validate/dist/index.js +375 -82
- package/packages/validate/package.json +14 -7
- package/packages/cli/dist/K_ENT_Entity-PQ5MURQY-ZG6FZXXX.js +0 -13
- package/packages/cli/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-K4CRQYA5.js +0 -8
- package/packages/cli/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-LNPXZYOE.js +0 -110
- package/packages/cli/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-3ALZPNX4.js +0 -11
- package/packages/cli/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-PJTICYSW.js +0 -11
- package/packages/cli/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-M5TYU55O.js +0 -8
- package/packages/cli/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-H6STOXRK.js +0 -20
- package/packages/cli/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-XPJXSF7D.js +0 -19
- package/packages/cli/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-CUYGTWOW.js +0 -7
- package/packages/cli/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-VR6T4N6J.js +0 -17
- package/packages/cli/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-RLJ4QWDP.js +0 -58
- package/packages/cli/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-BOQGUASC.js +0 -22
- package/packages/cli/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-XJI7KIT5.js +0 -8
- package/packages/cli/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-K5VCWAFW.js +0 -9
- package/packages/cli/dist/chunk-3TRM6CYL.js +0 -152
- package/packages/cli/dist/chunk-5JDK35TG.js +0 -3872
- package/packages/cli/dist/chunk-63PTK33I.js +0 -997
- package/packages/cli/dist/chunk-6NIKAMUZ.js +0 -82
- package/packages/cli/dist/chunk-BOXWWXQG.js +0 -400
- package/packages/cli/dist/chunk-EEKLK7QJ.js +0 -565
- package/packages/cli/dist/chunk-EG7T2IAD.js +0 -107
- package/packages/cli/dist/chunk-ESTKOQ7T.js +0 -1146
- package/packages/cli/dist/chunk-F5EHXE2O.js +0 -1036
- package/packages/cli/dist/chunk-F65ANSQG.js +0 -269
- package/packages/cli/dist/chunk-FDNCADFE.js +0 -71
- package/packages/cli/dist/chunk-FZ6X7PHR.js +0 -1146
- package/packages/cli/dist/chunk-GDLRMDAN.js +0 -127
- package/packages/cli/dist/chunk-HWMTCMOS.js +0 -656
- package/packages/cli/dist/chunk-I74QIQOD.js +0 -5536
- package/packages/cli/dist/chunk-JTLSTO25.js +0 -71
- package/packages/cli/dist/chunk-JULBBJ27.js +0 -1033
- package/packages/cli/dist/chunk-OHVMVRBP.js +0 -117
- package/packages/cli/dist/chunk-P2PCLEKX.js +0 -666
- package/packages/cli/dist/chunk-PJQIUOX2.js +0 -7767
- package/packages/cli/dist/chunk-PPOF3DJW.js +0 -471
- package/packages/cli/dist/chunk-Q45257P6.js +0 -173
- package/packages/cli/dist/chunk-QNROWGBI.js +0 -1036
- package/packages/cli/dist/chunk-RJNYUXZD.js +0 -977
- package/packages/cli/dist/chunk-SRTOPJ5W.js +0 -104
- package/packages/cli/dist/chunk-TCEX3MPS.js +0 -702
- package/packages/cli/dist/chunk-TNOAJO2J.js +0 -675
- package/packages/cli/dist/chunk-UR2SUCSF.js +0 -701
- package/packages/cli/dist/chunk-X5LOIFM7.js +0 -68
- package/packages/cli/dist/chunk-XIRFOO3H.js +0 -589
- package/packages/cli/dist/chunk-ZAAV3JXQ.js +0 -809
- package/packages/core/dist/K_ENT_Entity-4MB7CU4A.js +0 -12
- package/packages/core/dist/K_ENT_Entity-DEJGIDGH.js +0 -12
- package/packages/core/dist/K_ENT_Entity-FXZO5UZ2.js +0 -12
- package/packages/core/dist/K_ENT_Entity-HDSCXC5F.js +0 -12
- package/packages/core/dist/K_ENT_Entity-JILABHLW.js +0 -12
- package/packages/core/dist/K_ENT_Entity-PQ5MURQY.js +0 -13
- package/packages/core/dist/K_ENT_Entity-ROAKDIHW.js +0 -12
- package/packages/core/dist/K_ENT_Entity-TBVFSKDV.js +0 -12
- package/packages/core/dist/K_ENT_Entity-ZFLKG3JO.js +0 -12
- package/packages/core/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW.js +0 -8
- package/packages/core/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF.js +0 -110
- package/packages/core/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF.js +0 -9
- package/packages/core/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X.js +0 -9
- package/packages/core/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW.js +0 -8
- package/packages/core/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2.js +0 -20
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-4C6GBQAG.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-6V23A6F6.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK.js +0 -19
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-DYLLC5G2.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-F4FOFAUP.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-FBOXXMI3.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-Q73BWLNP.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QM2C4MVA.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QUGI6SMP.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RGMTBHNP.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RWR7UNDW.js +0 -18
- package/packages/core/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7.js +0 -7
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-32MFJJ5Z.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-4J4CEWRY.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-A366YHF2.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-LK4LYJHI.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-NW3K63II.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-QDHTI5ZV.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-VHCT6VIW.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-WBRKF24R.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-XKYQYT6Q.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-Z2PWZYDZ.js +0 -17
- package/packages/core/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5.js +0 -58
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-2EZU7QF4.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-6G3AQNAV.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-B2NZMQUG.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-C2RABMZP.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-HHE3NZ4F.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-LHFGR6WK.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-M74BLM3N.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-PT6ZA6EA.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-SP52V3CX.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF.js +0 -22
- package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-YNSEUHJJ.js +0 -21
- package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-M6SBHIVA.js +0 -8
- package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG.js +0 -8
- package/packages/core/dist/K_LIB_Krnl_Telemetry-77FRZ3KV.js +0 -9
- package/packages/core/dist/chunk-33L2J7V7.js +0 -82
- package/packages/core/dist/chunk-3ES4K2ZP.js +0 -817
- package/packages/core/dist/chunk-3SMHVVLL.js +0 -82
- package/packages/core/dist/chunk-3UEZ7JQA.js +0 -4877
- package/packages/core/dist/chunk-3XIE6KBD.js +0 -4877
- package/packages/core/dist/chunk-46ZLCML6.js +0 -107
- package/packages/core/dist/chunk-4UEL3DWJ.js +0 -107
- package/packages/core/dist/chunk-54GWZ5PC.js +0 -82
- package/packages/core/dist/chunk-6QCYRS5L.js +0 -127
- package/packages/core/dist/chunk-6ULMHNXR.js +0 -104
- package/packages/core/dist/chunk-7WUETJEV.js +0 -117
- package/packages/core/dist/chunk-A5KRAYDB.js +0 -107
- package/packages/core/dist/chunk-ANEAZ3PO.js +0 -107
- package/packages/core/dist/chunk-BE76RL6F.js +0 -82
- package/packages/core/dist/chunk-CIARVYDO.js +0 -107
- package/packages/core/dist/chunk-CR2ANE62.js +0 -107
- package/packages/core/dist/chunk-DI27MOR7.js +0 -173
- package/packages/core/dist/chunk-E6RLFHM5.js +0 -596
- package/packages/core/dist/chunk-EELAPMNV.js +0 -4877
- package/packages/core/dist/chunk-ENZ2RQVJ.js +0 -107
- package/packages/core/dist/chunk-F2U6CX4F.js +0 -4877
- package/packages/core/dist/chunk-FKG64OHL.js +0 -82
- package/packages/core/dist/chunk-FYAZJYM5.js +0 -772
- package/packages/core/dist/chunk-G4NP4RDQ.js +0 -82
- package/packages/core/dist/chunk-GADIRLRS.js +0 -473
- package/packages/core/dist/chunk-GR6CSLQJ.js +0 -772
- package/packages/core/dist/chunk-HDS7AT6O.js +0 -772
- package/packages/core/dist/chunk-HIMEZUU2.js +0 -71
- package/packages/core/dist/chunk-IB4UHG5I.js +0 -596
- package/packages/core/dist/chunk-J7ZYNVRS.js +0 -772
- package/packages/core/dist/chunk-JVLZU4K7.js +0 -604
- package/packages/core/dist/chunk-JYXXI7Q3.js +0 -82
- package/packages/core/dist/chunk-K54K2KZW.js +0 -192
- package/packages/core/dist/chunk-K6VHLBNH.js +0 -3316
- package/packages/core/dist/chunk-KCBP7ZYA.js +0 -596
- package/packages/core/dist/chunk-KFQGP6VL.js +0 -33
- package/packages/core/dist/chunk-KIUEUI7K.js +0 -82
- package/packages/core/dist/chunk-LB67NIZP.js +0 -949
- package/packages/core/dist/chunk-LDTYFUNW.js +0 -596
- package/packages/core/dist/chunk-MLVWARD4.js +0 -596
- package/packages/core/dist/chunk-MPYVXHKO.js +0 -2777
- package/packages/core/dist/chunk-MRQ3MITU.js +0 -772
- package/packages/core/dist/chunk-MVUN7I7O.js +0 -107
- package/packages/core/dist/chunk-NDDOIRW7.js +0 -596
- package/packages/core/dist/chunk-O3KDB5MH.js +0 -3330
- package/packages/core/dist/chunk-OEINUDSE.js +0 -400
- package/packages/core/dist/chunk-OPDENPT4.js +0 -4877
- package/packages/core/dist/chunk-P6XEM2LA.js +0 -429
- package/packages/core/dist/chunk-QKMRSQV4.js +0 -82
- package/packages/core/dist/chunk-R6CCWALL.js +0 -4877
- package/packages/core/dist/chunk-RAMMOO73.js +0 -774
- package/packages/core/dist/chunk-S3FTZFG6.js +0 -772
- package/packages/core/dist/chunk-T2ZVN434.js +0 -4877
- package/packages/core/dist/chunk-TFHLDMIA.js +0 -107
- package/packages/core/dist/chunk-TI3QUCIJ.js +0 -107
- package/packages/core/dist/chunk-TR2BAIGI.js +0 -107
- package/packages/core/dist/chunk-UGVVJKC6.js +0 -4877
- package/packages/core/dist/chunk-V2DX7YIU.js +0 -984
- package/packages/core/dist/chunk-W4IHYUYD.js +0 -772
- package/packages/core/dist/chunk-W6WBG5OY.js +0 -4877
- package/packages/core/dist/chunk-WN3M7O7H.js +0 -3312
- package/packages/core/dist/chunk-WR3NCU7U.js +0 -4877
- package/packages/core/dist/chunk-XC6B6L27.js +0 -82
- package/packages/core/dist/chunk-XNSE64ZY.js +0 -3316
- package/packages/core/dist/chunk-XROES2WN.js +0 -634
- package/packages/core/dist/chunk-XSCKNRCZ.js +0 -5020
- package/packages/core/dist/chunk-XVABPAUZ.js +0 -82
- package/packages/core/dist/chunk-YOBCB5C5.js +0 -596
- package/packages/core/dist/chunk-YUK6Q563.js +0 -666
- package/packages/core/dist/chunk-YXGL3ZEU.js +0 -1030
- package/packages/core/dist/chunk-ZINJ5OUX.js +0 -596
- package/packages/core/dist/chunk-ZPFD4BIQ.js +0 -604
- package/packages/core/dist/chunk-ZQZBFG6F.js +0 -4826
- package/packages/core/dist/chunk-ZZFRJGXM.js +0 -4877
- package/packages/create-krnl/dist/K_ENT_Entity-PQ5MURQY-R2OH4VXE.js +0 -14
- package/packages/create-krnl/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-AZM5HF4M.js +0 -9
- package/packages/create-krnl/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-X5N6SV2S.js +0 -111
- package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-5PFHF4JU.js +0 -12
- package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-ED33OQPH.js +0 -12
- package/packages/create-krnl/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-YGQLVR4P.js +0 -9
- package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-VM7CTU2L.js +0 -21
- package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-Y2GQFJ7I.js +0 -21
- package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-L3JQWO54.js +0 -8
- package/packages/create-krnl/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-KQARASPR.js +0 -19
- package/packages/create-krnl/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-OF3IGLVL.js +0 -59
- package/packages/create-krnl/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-JOLHKOEX.js +0 -24
- package/packages/create-krnl/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-L46LSHKQ.js +0 -10
- package/packages/create-krnl/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-4JUPRR3X.js +0 -10
- package/packages/create-krnl/dist/chunk-3TRM6CYL.js +0 -152
- package/packages/create-krnl/dist/chunk-3URCB3QS.js +0 -127
- package/packages/create-krnl/dist/chunk-5JDK35TG.js +0 -3872
- package/packages/create-krnl/dist/chunk-A2XAXDOW.js +0 -812
- package/packages/create-krnl/dist/chunk-AN6TMQHG.js +0 -1033
- package/packages/create-krnl/dist/chunk-BOXWWXQG.js +0 -400
- package/packages/create-krnl/dist/chunk-BPTBREBG.js +0 -38
- package/packages/create-krnl/dist/chunk-FDNCADFE.js +0 -71
- package/packages/create-krnl/dist/chunk-JTLSTO25.js +0 -71
- package/packages/create-krnl/dist/chunk-M3NCUIPL.js +0 -107
- package/packages/create-krnl/dist/chunk-N2EONSOC.js +0 -7769
- package/packages/create-krnl/dist/chunk-OHVMVRBP.js +0 -117
- package/packages/create-krnl/dist/chunk-Q45257P6.js +0 -173
- package/packages/create-krnl/dist/chunk-QGM4M3NI.js +0 -37
- package/packages/create-krnl/dist/chunk-RJNYUXZD.js +0 -977
- package/packages/create-krnl/dist/chunk-SRTOPJ5W.js +0 -104
- package/packages/create-krnl/dist/chunk-UPBIGEC3.js +0 -666
- package/packages/create-krnl/dist/chunk-V2DB7UD7.js +0 -82
- package/packages/create-krnl/dist/chunk-WMHLIUI6.js +0 -3644
- package/packages/create-krnl/dist/chunk-XIRFOO3H.js +0 -589
- package/packages/create-krnl/dist/chunk-Y2CEEVZP.js +0 -5536
- package/packages/create-krnl/dist/main-DXUMPBND.js +0 -2217
- package/packages/create-krnl/dist/wrapper-SDF2VKX3.js +0 -31
|
@@ -30,14 +30,18 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
30
30
|
// src/index.ts
|
|
31
31
|
var index_exports = {};
|
|
32
32
|
__export(index_exports, {
|
|
33
|
+
FunctionalityOrchestration: () => FunctionalityOrchestration,
|
|
33
34
|
HttpProtocolAdapter: () => HttpProtocolAdapter,
|
|
34
35
|
KrnlPackageReconciler: () => KrnlPackageReconciler,
|
|
36
|
+
KrnlQueue: () => KrnlQueue,
|
|
37
|
+
KrnlWorkerPool: () => KrnlWorkerPool,
|
|
35
38
|
LifecycleManager: () => LifecycleManager,
|
|
36
39
|
MemoryTransport: () => MemoryTransport,
|
|
37
40
|
P2PProtocolAdapter: () => P2PProtocolAdapter,
|
|
38
41
|
ProtocolResolver: () => ProtocolResolver,
|
|
39
42
|
ServiceDiscovery: () => ServiceDiscovery,
|
|
40
43
|
ServiceEventBus: () => ServiceEventBus,
|
|
44
|
+
ServiceFacade: () => ServiceFacade,
|
|
41
45
|
ServiceInstance: () => ServiceInstance,
|
|
42
46
|
ServiceProxy: () => ServiceProxy,
|
|
43
47
|
ServiceRegistry: () => ServiceRegistry,
|
|
@@ -45,9 +49,14 @@ __export(index_exports, {
|
|
|
45
49
|
ServiceStateStore: () => ServiceStateStore,
|
|
46
50
|
UdpProtocolAdapter: () => UdpProtocolAdapter,
|
|
47
51
|
WebSocketProtocolAdapter: () => WebSocketProtocolAdapter,
|
|
52
|
+
WorkerExecutionBoundary: () => WorkerExecutionBoundary,
|
|
48
53
|
createService: () => createService,
|
|
49
54
|
createServiceDefinition: () => createServiceDefinition,
|
|
50
|
-
|
|
55
|
+
createServiceFacade: () => createServiceFacade,
|
|
56
|
+
createServiceProxy: () => createServiceProxy,
|
|
57
|
+
gutts: () => gutts,
|
|
58
|
+
validateOrchestrationDAG: () => validateOrchestrationDAG,
|
|
59
|
+
validateServiceDefinition: () => validateServiceDefinition
|
|
51
60
|
});
|
|
52
61
|
module.exports = __toCommonJS(index_exports);
|
|
53
62
|
|
|
@@ -109,171 +118,2541 @@ var ServiceEventBus = class {
|
|
|
109
118
|
};
|
|
110
119
|
|
|
111
120
|
// src/lifecycle/LifecycleManager.ts
|
|
121
|
+
var TRANSITIONS = {
|
|
122
|
+
uninitialized: ["initializing"],
|
|
123
|
+
initializing: ["ready", "uninitialized"],
|
|
124
|
+
ready: ["starting"],
|
|
125
|
+
starting: ["running", "ready"],
|
|
126
|
+
running: ["stopping"],
|
|
127
|
+
stopping: ["stopped", "running"],
|
|
128
|
+
stopped: ["starting"]
|
|
129
|
+
};
|
|
112
130
|
var LifecycleManager = class {
|
|
113
131
|
status = "uninitialized";
|
|
114
132
|
getStatus() {
|
|
115
133
|
return this.status;
|
|
116
134
|
}
|
|
117
|
-
|
|
135
|
+
canTransitionTo(next) {
|
|
136
|
+
return TRANSITIONS[this.status].includes(next);
|
|
137
|
+
}
|
|
138
|
+
transitionTo(next) {
|
|
139
|
+
if (!this.canTransitionTo(next)) {
|
|
140
|
+
throw new Error("[Lifecycle] Invalid transition '" + this.status + "' -> '" + next + "'.");
|
|
141
|
+
}
|
|
118
142
|
this.status = next;
|
|
119
143
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
144
|
+
setStatus(next) {
|
|
145
|
+
this.transitionTo(next);
|
|
146
|
+
}
|
|
147
|
+
assertRunning(serviceName) {
|
|
148
|
+
if (this.status !== "running") {
|
|
149
|
+
throw new Error(
|
|
150
|
+
"[Service:" + serviceName + "] Cannot invoke operation while status is '" + this.status + "' (expected 'running')."
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// src/services/ServiceInstance.ts
|
|
157
|
+
var ServiceInstance = class {
|
|
158
|
+
constructor(definition) {
|
|
159
|
+
this.definition = definition;
|
|
160
|
+
this.id = definition.id;
|
|
161
|
+
this.name = definition.name;
|
|
162
|
+
this.version = definition.version;
|
|
163
|
+
this.lifecycle = new LifecycleManager();
|
|
164
|
+
this.eventBus = new ServiceEventBus();
|
|
165
|
+
if (definition.state) {
|
|
166
|
+
this.stateStore = new ServiceStateStore(definition.state.initial);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
definition;
|
|
170
|
+
id;
|
|
171
|
+
name;
|
|
172
|
+
version;
|
|
173
|
+
stateStore;
|
|
174
|
+
eventBus;
|
|
175
|
+
lifecycle;
|
|
176
|
+
initialized = false;
|
|
177
|
+
disposed = false;
|
|
178
|
+
getDefinition() {
|
|
179
|
+
return this.definition;
|
|
180
|
+
}
|
|
181
|
+
getStatus() {
|
|
182
|
+
return this.lifecycle.getStatus();
|
|
183
|
+
}
|
|
184
|
+
async start() {
|
|
185
|
+
if (this.disposed) throw new Error("[Service:" + this.name + "] Cannot start a disposed service.");
|
|
186
|
+
const current = this.lifecycle.getStatus();
|
|
187
|
+
if (current === "running") return;
|
|
188
|
+
if (current === "initializing" || current === "starting" || current === "stopping") {
|
|
189
|
+
throw new Error("[Service:" + this.name + "] Cannot start while status is '" + current + "'.");
|
|
190
|
+
}
|
|
191
|
+
if (!this.initialized) {
|
|
192
|
+
this.lifecycle.transitionTo("initializing");
|
|
193
|
+
try {
|
|
194
|
+
await this.definition.lifecycle?.onInit?.();
|
|
195
|
+
this.initialized = true;
|
|
196
|
+
this.lifecycle.transitionTo("ready");
|
|
197
|
+
} catch (error) {
|
|
198
|
+
this.lifecycle.transitionTo("uninitialized");
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
this.lifecycle.transitionTo("starting");
|
|
203
|
+
try {
|
|
204
|
+
await this.definition.lifecycle?.onStart?.();
|
|
205
|
+
this.lifecycle.transitionTo("running");
|
|
206
|
+
} catch (error) {
|
|
207
|
+
this.lifecycle.transitionTo("ready");
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
async stop() {
|
|
212
|
+
const current = this.lifecycle.getStatus();
|
|
213
|
+
if (current === "stopped") return;
|
|
214
|
+
if (current !== "running") {
|
|
215
|
+
throw new Error("[Service:" + this.name + "] Cannot stop while status is '" + current + "'.");
|
|
216
|
+
}
|
|
217
|
+
this.lifecycle.transitionTo("stopping");
|
|
218
|
+
try {
|
|
219
|
+
await this.definition.lifecycle?.onStop?.();
|
|
220
|
+
this.lifecycle.transitionTo("stopped");
|
|
221
|
+
} catch (error) {
|
|
222
|
+
this.lifecycle.transitionTo("running");
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async dispose() {
|
|
227
|
+
if (this.disposed) return;
|
|
228
|
+
if (this.lifecycle.getStatus() === "running") await this.stop();
|
|
229
|
+
await this.definition.lifecycle?.onDispose?.();
|
|
230
|
+
this.disposed = true;
|
|
231
|
+
}
|
|
232
|
+
async call(op, input, ctx = {}) {
|
|
233
|
+
this.lifecycle.assertRunning(this.name);
|
|
234
|
+
const operation = this.definition.operations[op];
|
|
235
|
+
if (!operation) {
|
|
236
|
+
throw new Error("[Service:" + this.name + "] Operation '" + op + "' not found.");
|
|
237
|
+
}
|
|
238
|
+
return await operation.handler(input, ctx);
|
|
239
|
+
}
|
|
240
|
+
getState() {
|
|
241
|
+
return this.stateStore?.getState() ?? Object.freeze({});
|
|
242
|
+
}
|
|
243
|
+
setState(mutation) {
|
|
244
|
+
if (!this.stateStore) {
|
|
245
|
+
this.stateStore = new ServiceStateStore({ ...mutation });
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
this.stateStore.setState(mutation);
|
|
249
|
+
}
|
|
250
|
+
on(event, handler) {
|
|
251
|
+
return this.eventBus.on(event, handler);
|
|
252
|
+
}
|
|
253
|
+
emit(event, payload) {
|
|
254
|
+
this.eventBus.emit(event, payload);
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
// src/services/ServiceProxy.ts
|
|
259
|
+
var ServiceProxy = class {
|
|
260
|
+
constructor(definition, adapter, endpoint) {
|
|
261
|
+
this.definition = definition;
|
|
262
|
+
this.adapter = adapter;
|
|
263
|
+
this.endpoint = endpoint;
|
|
264
|
+
if (!definition) {
|
|
265
|
+
throw new Error("[ServiceProxy] Missing service definition.");
|
|
266
|
+
}
|
|
267
|
+
if (!adapter || typeof adapter.send !== "function") {
|
|
268
|
+
throw new Error("[ServiceProxy:" + (definition.name || "unknown") + "] Missing or invalid protocol adapter.");
|
|
269
|
+
}
|
|
270
|
+
if (!endpoint || typeof endpoint.address !== "string" || endpoint.address.length === 0) {
|
|
271
|
+
throw new Error("[ServiceProxy:" + (definition.name || "unknown") + "] Missing or invalid endpoint descriptor.");
|
|
272
|
+
}
|
|
273
|
+
this.id = definition.id;
|
|
274
|
+
this.name = definition.name;
|
|
275
|
+
this.version = definition.version;
|
|
276
|
+
this.stateCache = { ...definition.state?.initial ?? {} };
|
|
277
|
+
}
|
|
278
|
+
definition;
|
|
279
|
+
adapter;
|
|
280
|
+
endpoint;
|
|
281
|
+
id;
|
|
282
|
+
name;
|
|
283
|
+
version;
|
|
284
|
+
stateCache;
|
|
285
|
+
eventHandlers = /* @__PURE__ */ new Map();
|
|
286
|
+
lifecycle = new LifecycleManager();
|
|
287
|
+
disposed = false;
|
|
288
|
+
getDefinition() {
|
|
289
|
+
return this.definition;
|
|
290
|
+
}
|
|
291
|
+
getStatus() {
|
|
292
|
+
return this.lifecycle.getStatus();
|
|
293
|
+
}
|
|
294
|
+
async start() {
|
|
295
|
+
if (this.disposed) {
|
|
296
|
+
throw new Error("[ServiceProxy:" + this.name + "] Cannot start a disposed service proxy.");
|
|
297
|
+
}
|
|
298
|
+
const status = this.lifecycle.getStatus();
|
|
299
|
+
if (status === "running") return;
|
|
300
|
+
if (status === "stopping" || status === "starting" || status === "initializing") {
|
|
301
|
+
throw new Error("[ServiceProxy:" + this.name + "] Cannot start while status is '" + status + "'.");
|
|
302
|
+
}
|
|
303
|
+
if (status === "uninitialized") {
|
|
304
|
+
this.lifecycle.transitionTo("initializing");
|
|
305
|
+
this.lifecycle.transitionTo("ready");
|
|
306
|
+
}
|
|
307
|
+
this.lifecycle.transitionTo("starting");
|
|
308
|
+
this.lifecycle.transitionTo("running");
|
|
309
|
+
}
|
|
310
|
+
async stop() {
|
|
311
|
+
const status = this.lifecycle.getStatus();
|
|
312
|
+
if (status === "stopped") return;
|
|
313
|
+
if (status !== "running") {
|
|
314
|
+
throw new Error("[ServiceProxy:" + this.name + "] Cannot stop while status is '" + status + "'.");
|
|
315
|
+
}
|
|
316
|
+
this.lifecycle.transitionTo("stopping");
|
|
317
|
+
this.lifecycle.transitionTo("stopped");
|
|
318
|
+
}
|
|
319
|
+
async dispose() {
|
|
320
|
+
if (this.disposed) return;
|
|
321
|
+
if (this.lifecycle.getStatus() === "running") await this.stop();
|
|
322
|
+
this.disposed = true;
|
|
323
|
+
}
|
|
324
|
+
async call(op, input, ctx = {}) {
|
|
325
|
+
if (!this.definition.operations[op]) {
|
|
326
|
+
throw new Error("[ServiceProxy:" + this.name + "] Operation '" + op + "' not found.");
|
|
327
|
+
}
|
|
328
|
+
if (this.lifecycle.getStatus() !== "running") {
|
|
329
|
+
await this.start();
|
|
330
|
+
}
|
|
331
|
+
if (!this.adapter.send) {
|
|
332
|
+
throw new Error("[ServiceProxy:" + this.name + "] Adapter does not support send().");
|
|
333
|
+
}
|
|
334
|
+
const envelope = {
|
|
335
|
+
id: "req-" + Date.now() + "-" + Math.random().toString(36).slice(2, 7),
|
|
336
|
+
type: "request",
|
|
337
|
+
operation: op,
|
|
338
|
+
payload: input,
|
|
339
|
+
timestamp: Date.now()
|
|
340
|
+
};
|
|
341
|
+
const response = await this.adapter.send(this.endpoint, envelope);
|
|
342
|
+
if (response.error) {
|
|
343
|
+
throw new Error("[ServiceProxy:" + this.name + "] Remote error: " + response.error);
|
|
344
|
+
}
|
|
345
|
+
return response.payload;
|
|
346
|
+
}
|
|
347
|
+
getState() {
|
|
348
|
+
return Object.freeze({ ...this.stateCache });
|
|
349
|
+
}
|
|
350
|
+
setState(mutation) {
|
|
351
|
+
this.stateCache = { ...this.stateCache, ...mutation };
|
|
352
|
+
}
|
|
353
|
+
on(event, handler) {
|
|
354
|
+
if (!this.eventHandlers.has(event)) this.eventHandlers.set(event, /* @__PURE__ */ new Set());
|
|
355
|
+
const handlers = this.eventHandlers.get(event);
|
|
356
|
+
handlers.add(handler);
|
|
357
|
+
return () => handlers.delete(handler);
|
|
358
|
+
}
|
|
359
|
+
emit(event, payload) {
|
|
360
|
+
const handlers = this.eventHandlers.get(event);
|
|
361
|
+
if (!handlers) return;
|
|
362
|
+
for (const handler of Array.from(handlers)) {
|
|
363
|
+
try {
|
|
364
|
+
handler(payload);
|
|
365
|
+
} catch (error) {
|
|
366
|
+
console.error("[ServiceProxy:" + this.name + "] Event handler error for '" + event + "':", error);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
// src/services/ServiceGenerators.ts
|
|
373
|
+
function assertRecord(value, field) {
|
|
374
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
375
|
+
throw new Error("[KrnlTS] Invalid service definition: '" + field + "' must be an object.");
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
function assertNonEmptyString(value, field) {
|
|
379
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
380
|
+
throw new Error("[KrnlTS] Invalid service definition: '" + field + "' must be a non-empty string.");
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
function validateServiceDefinition(definition) {
|
|
384
|
+
if (!definition || typeof definition !== "object") {
|
|
385
|
+
throw new Error("[KrnlTS] Invalid service definition: expected an object.");
|
|
386
|
+
}
|
|
387
|
+
assertNonEmptyString(definition.id, "id");
|
|
388
|
+
assertNonEmptyString(definition.name, "name");
|
|
389
|
+
assertNonEmptyString(definition.version, "version");
|
|
390
|
+
if (!definition.operations || typeof definition.operations !== "object") {
|
|
391
|
+
throw new Error("[Service:" + definition.name + "] Invalid operations: expected an object.");
|
|
392
|
+
}
|
|
393
|
+
for (const [key, operation] of Object.entries(definition.operations)) {
|
|
394
|
+
if (!operation || typeof operation !== "object") {
|
|
395
|
+
throw new Error("[Service:" + definition.name + "] Invalid operation '" + key + "'.");
|
|
396
|
+
}
|
|
397
|
+
assertNonEmptyString(operation.id, "operations." + key + ".id");
|
|
398
|
+
assertNonEmptyString(operation.name, "operations." + key + ".name");
|
|
399
|
+
if (operation.inputSchema !== void 0) assertRecord(operation.inputSchema, "operations." + key + ".inputSchema");
|
|
400
|
+
if (operation.outputSchema !== void 0) assertRecord(operation.outputSchema, "operations." + key + ".outputSchema");
|
|
401
|
+
if (typeof operation.handler !== "function") {
|
|
402
|
+
throw new Error("[Service:" + definition.name + "] Operation '" + key + "' must define a handler.");
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
for (const [key, event] of Object.entries(definition.events ?? {})) {
|
|
406
|
+
if (!event || typeof event !== "object") {
|
|
407
|
+
throw new Error("[Service:" + definition.name + "] Invalid event '" + key + "'.");
|
|
408
|
+
}
|
|
409
|
+
assertNonEmptyString(event.name, "events." + key + ".name");
|
|
410
|
+
}
|
|
411
|
+
for (const [key, schema] of Object.entries(definition.inputs ?? {})) assertRecord(schema, "inputs." + key);
|
|
412
|
+
for (const [key, schema] of Object.entries(definition.outputs ?? {})) assertRecord(schema, "outputs." + key);
|
|
413
|
+
if (definition.state?.schema !== void 0) assertRecord(definition.state.schema, "state.schema");
|
|
414
|
+
for (const capability of definition.capabilities ?? []) {
|
|
415
|
+
assertNonEmptyString(capability.id, "capability.id");
|
|
416
|
+
assertNonEmptyString(capability.name, "capability.name");
|
|
417
|
+
if (!Array.isArray(capability.protocols)) {
|
|
418
|
+
throw new Error("[Service:" + definition.name + "] Capability '" + capability.name + "' protocols must be an array.");
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
for (const dependency of definition.dependencies ?? []) {
|
|
422
|
+
assertNonEmptyString(dependency.serviceId, "dependency.serviceId");
|
|
423
|
+
}
|
|
424
|
+
return definition;
|
|
425
|
+
}
|
|
426
|
+
function createServiceDefinition(definition) {
|
|
427
|
+
return validateServiceDefinition(definition);
|
|
428
|
+
}
|
|
429
|
+
function createService(definition) {
|
|
430
|
+
return new ServiceInstance(validateServiceDefinition(definition));
|
|
431
|
+
}
|
|
432
|
+
function createServiceProxy(definition, adapter, endpoint) {
|
|
433
|
+
validateServiceDefinition(definition);
|
|
434
|
+
if (!adapter || typeof adapter.send !== "function") {
|
|
435
|
+
throw new Error("[ServiceProxy:" + definition.name + "] Adapter must implement send().");
|
|
436
|
+
}
|
|
437
|
+
if (!endpoint || typeof endpoint.address !== "string" || endpoint.address.length === 0) {
|
|
438
|
+
throw new Error("[ServiceProxy:" + definition.name + "] Endpoint must have an address.");
|
|
439
|
+
}
|
|
440
|
+
return new ServiceProxy(definition, adapter, endpoint);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// ../../node_modules/.pnpm/p-queue@10.0.0/node_modules/p-queue/dist/lower-bound.js
|
|
444
|
+
function lowerBound(array, value, comparator) {
|
|
445
|
+
let first = 0;
|
|
446
|
+
let count = array.length;
|
|
447
|
+
while (count > 0) {
|
|
448
|
+
const step = Math.trunc(count / 2);
|
|
449
|
+
let it = first + step;
|
|
450
|
+
if (comparator(array[it], value) <= 0) {
|
|
451
|
+
first = ++it;
|
|
452
|
+
count -= step + 1;
|
|
453
|
+
} else {
|
|
454
|
+
count = step;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return first;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ../../node_modules/.pnpm/p-queue@10.0.0/node_modules/p-queue/dist/priority-queue.js
|
|
461
|
+
var compactionThreshold = 100;
|
|
462
|
+
var PriorityQueue = class {
|
|
463
|
+
// The slots before `#head` are `undefined`.
|
|
464
|
+
#queue = [];
|
|
465
|
+
// The queue is stored as a sorted array, but dequeued slots are left before `#head` until compaction. Only items from `#head` onward are live, which keeps repeated dequeues amortized O(1).
|
|
466
|
+
#head = 0;
|
|
467
|
+
#compact() {
|
|
468
|
+
if (this.#head === 0) {
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
this.#queue.splice(0, this.#head);
|
|
472
|
+
this.#head = 0;
|
|
473
|
+
}
|
|
474
|
+
// Only the live items, because a dequeued item with the same id or function is no longer part of the queue.
|
|
475
|
+
#findIndex(isMatch) {
|
|
476
|
+
for (let index = this.#head; index < this.#queue.length; index++) {
|
|
477
|
+
if (isMatch(this.#queue[index])) {
|
|
478
|
+
return index;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return -1;
|
|
482
|
+
}
|
|
483
|
+
// Not `dequeue()`, which a subclass can override, because `remove()` also uses it.
|
|
484
|
+
#removeFirst() {
|
|
485
|
+
const item = this.#queue[this.#head];
|
|
486
|
+
this.#queue[this.#head] = void 0;
|
|
487
|
+
this.#head++;
|
|
488
|
+
if (this.#head === this.#queue.length) {
|
|
489
|
+
this.#queue.length = 0;
|
|
490
|
+
this.#head = 0;
|
|
491
|
+
} else if (this.#head > compactionThreshold && this.#head > this.#queue.length / 2) {
|
|
492
|
+
this.#compact();
|
|
493
|
+
}
|
|
494
|
+
return item.run;
|
|
495
|
+
}
|
|
496
|
+
enqueue(run, options) {
|
|
497
|
+
const { priority = 0, id } = options ?? {};
|
|
498
|
+
const { size } = this;
|
|
499
|
+
const element = {
|
|
500
|
+
priority,
|
|
501
|
+
id,
|
|
502
|
+
run
|
|
503
|
+
};
|
|
504
|
+
if (size === 0) {
|
|
505
|
+
this.#queue.length = 0;
|
|
506
|
+
this.#head = 0;
|
|
507
|
+
this.#queue.push(element);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
if (this.#queue.at(-1).priority >= priority) {
|
|
511
|
+
this.#queue.push(element);
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
this.#compact();
|
|
515
|
+
const index = lowerBound(this.#queue, element, (a, b) => a.priority === b.priority ? 0 : b.priority - a.priority);
|
|
516
|
+
this.#queue.splice(index, 0, element);
|
|
517
|
+
}
|
|
518
|
+
setPriority(id, priority) {
|
|
519
|
+
const index = this.#findIndex((element) => element.id === id);
|
|
520
|
+
if (index === -1) {
|
|
521
|
+
throw new ReferenceError(`No promise function with the id "${id}" exists in the queue.`);
|
|
522
|
+
}
|
|
523
|
+
if (this.#queue[index].priority === priority) {
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
const [item] = this.#queue.splice(index, 1);
|
|
527
|
+
this.enqueue(item.run, { priority, id });
|
|
528
|
+
}
|
|
529
|
+
remove(idOrRun) {
|
|
530
|
+
const index = this.#findIndex((element) => (typeof idOrRun === "string" ? element.id : element.run) === idOrRun);
|
|
531
|
+
if (index === this.#head) {
|
|
532
|
+
this.#removeFirst();
|
|
533
|
+
} else if (index !== -1) {
|
|
534
|
+
this.#queue.splice(index, 1);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
dequeue() {
|
|
538
|
+
return this.#head === this.#queue.length ? void 0 : this.#removeFirst();
|
|
539
|
+
}
|
|
540
|
+
filter(options) {
|
|
541
|
+
const result = [];
|
|
542
|
+
for (let index = this.#head; index < this.#queue.length; index++) {
|
|
543
|
+
const element = this.#queue[index];
|
|
544
|
+
if (element.priority === options.priority) {
|
|
545
|
+
result.push(element.run);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return result;
|
|
549
|
+
}
|
|
550
|
+
get size() {
|
|
551
|
+
return this.#queue.length - this.#head;
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
// ../../node_modules/.pnpm/p-queue@10.0.0/node_modules/p-queue/dist/index.js
|
|
556
|
+
var maximumTimerDelay = 2147483647;
|
|
557
|
+
var asyncHooks = globalThis.process?.getBuiltinModule?.("node:async_hooks");
|
|
558
|
+
var bindAsyncContext = (function_) => {
|
|
559
|
+
if (asyncHooks === void 0) {
|
|
560
|
+
return function_;
|
|
561
|
+
}
|
|
562
|
+
const asyncResource = new asyncHooks.AsyncResource("PQueueTask");
|
|
563
|
+
return () => asyncResource.runInAsyncScope(function_);
|
|
564
|
+
};
|
|
565
|
+
var validateTimeout = (timeout) => {
|
|
566
|
+
if (timeout !== void 0 && !(Number.isFinite(timeout) && timeout > 0 && timeout <= maximumTimerDelay)) {
|
|
567
|
+
throw new TypeError(`Expected \`timeout\` to be a positive finite number up to ${maximumTimerDelay}, got \`${timeout}\` (${typeof timeout})`);
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
var validateLimit = (name, value) => {
|
|
571
|
+
if (!(typeof value === "number" && value >= 1 && (value === Infinity || Number.isInteger(value)))) {
|
|
572
|
+
throw new TypeError(`Expected \`${name}\` to be an integer from 1 and up or \`Infinity\`, got \`${String(value)}\` (${typeof value})`);
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
var validateRateLimit = (interval, intervalCap, isStrict) => {
|
|
576
|
+
validateLimit("intervalCap", intervalCap);
|
|
577
|
+
if (!(Number.isFinite(interval) && interval >= 0)) {
|
|
578
|
+
throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${String(interval)}\` (${typeof interval})`);
|
|
579
|
+
}
|
|
580
|
+
if (intervalCap !== Infinity && interval > maximumTimerDelay) {
|
|
581
|
+
throw new TypeError(`Expected \`interval\` to be at most ${maximumTimerDelay} with an \`intervalCap\`, got \`${interval}\``);
|
|
582
|
+
}
|
|
583
|
+
if (isStrict && interval === 0) {
|
|
584
|
+
throw new TypeError("The `strict` option requires a non-zero `interval`");
|
|
585
|
+
}
|
|
586
|
+
if (isStrict && intervalCap === Infinity) {
|
|
587
|
+
throw new TypeError("The `strict` option requires a finite `intervalCap`");
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
var PQueue = class extends EventTarget {
|
|
591
|
+
#carryoverIntervalCount;
|
|
592
|
+
#isIntervalIgnored;
|
|
593
|
+
#intervalCount = 0;
|
|
594
|
+
#intervalCap;
|
|
595
|
+
#rateLimitedInInterval = false;
|
|
596
|
+
#rateLimitFlushScheduled = false;
|
|
597
|
+
#interval;
|
|
598
|
+
/*
|
|
599
|
+
Timestamp when the current interval window ends. Kept accurate at every window transition: `#initializeIntervalIfNeeded` sets it when a window starts and `#onInterval` advances it as the recurring timer rolls into each new window. This is the source of truth for whether a task added after the queue goes idle belongs to a fresh window, so it must not go stale.
|
|
600
|
+
*/
|
|
601
|
+
#intervalEnd = 0;
|
|
602
|
+
// Recurring timer that drives windows while the queue is actively processing. Absent (`undefined`) once the queue goes idle.
|
|
603
|
+
#intervalId;
|
|
604
|
+
// One-shot timer used while idle to resume at the next window boundary, since `#intervalId` is cleared when idle.
|
|
605
|
+
#timeoutId;
|
|
606
|
+
#strict;
|
|
607
|
+
// Circular buffer implementation for better performance
|
|
608
|
+
#strictTicks = [];
|
|
609
|
+
#strictTicksStartIndex = 0;
|
|
610
|
+
#queue;
|
|
611
|
+
#queueClass;
|
|
612
|
+
#pending = 0;
|
|
613
|
+
// The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
|
|
614
|
+
#concurrency;
|
|
615
|
+
#isPaused;
|
|
616
|
+
// Use to assign a unique identifier to a promise function, if not explicitly specified
|
|
617
|
+
#idAssigner = 1n;
|
|
618
|
+
// Track currently running tasks for debugging
|
|
619
|
+
#runningTasks = /* @__PURE__ */ new Set();
|
|
620
|
+
// The `abort` listener of each signal, with the callbacks of the tasks that use the signal.
|
|
621
|
+
#abortListeners = /* @__PURE__ */ new Map();
|
|
622
|
+
// The waiting tasks, so that `.clear()` can reject their promises.
|
|
623
|
+
#waitingTasks = /* @__PURE__ */ new Set();
|
|
624
|
+
#timeout;
|
|
625
|
+
constructor(options) {
|
|
626
|
+
super();
|
|
627
|
+
globalThis.process?.getBuiltinModule?.("node:events")?.setMaxListeners(Infinity, this);
|
|
628
|
+
const { carryoverIntervalCount = false, intervalCap = Infinity, interval = 0, concurrency = Infinity, autoStart = true, queueClass = PriorityQueue, strict = false, timeout } = options ?? {};
|
|
629
|
+
validateRateLimit(interval, intervalCap, strict);
|
|
630
|
+
this.#carryoverIntervalCount = carryoverIntervalCount;
|
|
631
|
+
this.#isIntervalIgnored = intervalCap === Infinity || interval === 0;
|
|
632
|
+
this.#intervalCap = intervalCap;
|
|
633
|
+
this.#interval = interval;
|
|
634
|
+
this.#strict = strict;
|
|
635
|
+
this.#queueClass = queueClass;
|
|
636
|
+
this.#queue = new this.#queueClass();
|
|
637
|
+
this.concurrency = concurrency;
|
|
638
|
+
this.timeout = timeout;
|
|
639
|
+
this.#isPaused = !autoStart;
|
|
640
|
+
this.#setupRateLimitTracking();
|
|
641
|
+
}
|
|
642
|
+
// Calls `callback` when `signal` aborts, and returns a function that stops it. The tasks that share a signal share one listener on it, because Node.js searches all the listeners of a signal to add or remove one, so a listener for each task takes O(n²) time with many tasks.
|
|
643
|
+
#onAbort(signal, callback) {
|
|
644
|
+
let listener = this.#abortListeners.get(signal);
|
|
645
|
+
if (!listener) {
|
|
646
|
+
const callbacks = /* @__PURE__ */ new Set();
|
|
647
|
+
const dispatch = () => {
|
|
648
|
+
this.#abortListeners.delete(signal);
|
|
649
|
+
for (const abortCallback of callbacks) {
|
|
650
|
+
abortCallback();
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
listener = { callbacks, dispatch };
|
|
654
|
+
this.#abortListeners.set(signal, listener);
|
|
655
|
+
signal.addEventListener("abort", dispatch, { once: true });
|
|
656
|
+
}
|
|
657
|
+
const currentListener = listener;
|
|
658
|
+
currentListener.callbacks.add(callback);
|
|
659
|
+
return () => {
|
|
660
|
+
currentListener.callbacks.delete(callback);
|
|
661
|
+
if (currentListener.callbacks.size > 0 || this.#abortListeners.get(signal) !== currentListener) {
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
this.#abortListeners.delete(signal);
|
|
665
|
+
signal.removeEventListener("abort", currentListener.dispatch);
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
#emit(event, detail) {
|
|
669
|
+
this.dispatchEvent(new CustomEvent(event, { detail }));
|
|
670
|
+
}
|
|
671
|
+
async #onEvent(events, shouldHandle) {
|
|
672
|
+
const eventList = Array.isArray(events) ? events : [events];
|
|
673
|
+
return new Promise((resolve) => {
|
|
674
|
+
const controller = new AbortController();
|
|
675
|
+
const listener = () => {
|
|
676
|
+
if (shouldHandle && !shouldHandle()) {
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
controller.abort();
|
|
680
|
+
resolve();
|
|
681
|
+
};
|
|
682
|
+
for (const event of eventList) {
|
|
683
|
+
this.addEventListener(event, listener, { signal: controller.signal });
|
|
684
|
+
}
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
// From the current state. `#rateLimitedInInterval` is what the events last reported, and it updates in a microtask.
|
|
688
|
+
get #isRateLimitedNow() {
|
|
689
|
+
if (this.#isIntervalIgnored || this.#queue.size === 0) {
|
|
690
|
+
return false;
|
|
691
|
+
}
|
|
692
|
+
const now = Date.now();
|
|
693
|
+
if (this.#strict) {
|
|
694
|
+
this.#cleanupStrictTicks(now);
|
|
695
|
+
return this.#getActiveTicksCount() >= this.#intervalCap;
|
|
696
|
+
}
|
|
697
|
+
const isWindowOver = this.#intervalId === void 0 && this.#intervalEnd <= now;
|
|
698
|
+
const count = isWindowOver ? this.#intervalCountAtWindowStart : this.#intervalCount;
|
|
699
|
+
return count >= this.#intervalCap;
|
|
700
|
+
}
|
|
701
|
+
// The tasks that still run count against the new window with `carryoverIntervalCount`.
|
|
702
|
+
get #intervalCountAtWindowStart() {
|
|
703
|
+
return this.#carryoverIntervalCount ? this.#pending : 0;
|
|
704
|
+
}
|
|
705
|
+
#updateRateLimitState() {
|
|
706
|
+
const shouldBeRateLimited = this.#isRateLimitedNow;
|
|
707
|
+
if (shouldBeRateLimited === this.#rateLimitedInInterval) {
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
this.#rateLimitedInInterval = shouldBeRateLimited;
|
|
711
|
+
this.#emit(shouldBeRateLimited ? "rateLimit" : "rateLimitCleared");
|
|
712
|
+
}
|
|
713
|
+
#rollbackIntervalConsumption() {
|
|
714
|
+
if (this.#isIntervalIgnored) {
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
this.#rollbackIntervalSlot();
|
|
718
|
+
this.#scheduleRateLimitUpdate();
|
|
719
|
+
}
|
|
720
|
+
#scheduleRateLimitUpdate() {
|
|
721
|
+
if (this.#isIntervalIgnored || this.#rateLimitFlushScheduled) {
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
this.#rateLimitFlushScheduled = true;
|
|
725
|
+
queueMicrotask(() => {
|
|
726
|
+
this.#rateLimitFlushScheduled = false;
|
|
727
|
+
this.#updateRateLimitState();
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
#setupRateLimitTracking() {
|
|
731
|
+
if (this.#isIntervalIgnored) {
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
this.addEventListener("add", () => {
|
|
735
|
+
if (this.#queue.size > 0) {
|
|
736
|
+
this.#scheduleRateLimitUpdate();
|
|
737
|
+
}
|
|
738
|
+
});
|
|
739
|
+
this.addEventListener("next", () => {
|
|
740
|
+
this.#scheduleRateLimitUpdate();
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
#cleanupStrictTicks(now) {
|
|
744
|
+
while (this.#strictTicksStartIndex < this.#strictTicks.length) {
|
|
745
|
+
const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];
|
|
746
|
+
if (oldestTick !== void 0 && now - oldestTick >= this.#interval) {
|
|
747
|
+
this.#strictTicksStartIndex++;
|
|
748
|
+
} else {
|
|
749
|
+
break;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
const shouldCompact = this.#strictTicksStartIndex > 100 && this.#strictTicksStartIndex > this.#strictTicks.length / 2 || this.#strictTicksStartIndex === this.#strictTicks.length;
|
|
753
|
+
if (!shouldCompact) {
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
this.#strictTicks = this.#strictTicks.slice(this.#strictTicksStartIndex);
|
|
757
|
+
this.#strictTicksStartIndex = 0;
|
|
758
|
+
}
|
|
759
|
+
// Helper methods for interval consumption
|
|
760
|
+
#consumeIntervalSlot(now) {
|
|
761
|
+
if (this.#strict) {
|
|
762
|
+
this.#strictTicks.push(now);
|
|
763
|
+
} else {
|
|
764
|
+
this.#intervalCount++;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
#rollbackIntervalSlot() {
|
|
768
|
+
if (this.#strict) {
|
|
769
|
+
if (this.#strictTicks.length > this.#strictTicksStartIndex) {
|
|
770
|
+
this.#strictTicks.pop();
|
|
771
|
+
}
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
if (this.#intervalCount > 0) {
|
|
775
|
+
this.#intervalCount--;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
#getActiveTicksCount() {
|
|
779
|
+
return this.#strictTicks.length - this.#strictTicksStartIndex;
|
|
780
|
+
}
|
|
781
|
+
get #doesIntervalAllowAnother() {
|
|
782
|
+
if (this.#isIntervalIgnored) {
|
|
783
|
+
return true;
|
|
784
|
+
}
|
|
785
|
+
const count = this.#strict ? this.#getActiveTicksCount() : this.#intervalCount;
|
|
786
|
+
return count < this.#intervalCap;
|
|
787
|
+
}
|
|
788
|
+
get #doesConcurrentAllowAnother() {
|
|
789
|
+
return this.#pending < this.#concurrency;
|
|
790
|
+
}
|
|
791
|
+
#next() {
|
|
792
|
+
this.#pending--;
|
|
793
|
+
if (this.#pending === 0) {
|
|
794
|
+
this.#emit("pendingZero");
|
|
795
|
+
}
|
|
796
|
+
this.#processQueue();
|
|
797
|
+
this.#emit("next");
|
|
798
|
+
}
|
|
799
|
+
#onResumeInterval() {
|
|
800
|
+
this.#timeoutId = void 0;
|
|
801
|
+
this.#onInterval();
|
|
802
|
+
if (!this.#isPaused) {
|
|
803
|
+
this.#initializeIntervalIfNeeded();
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
#isIntervalPausedAt(now) {
|
|
807
|
+
if (this.#strict) {
|
|
808
|
+
this.#cleanupStrictTicks(now);
|
|
809
|
+
const activeTicksCount = this.#getActiveTicksCount();
|
|
810
|
+
if (activeTicksCount >= this.#intervalCap) {
|
|
811
|
+
const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];
|
|
812
|
+
const delay = this.#interval - (now - oldestTick);
|
|
813
|
+
this.#createIntervalTimeout(delay);
|
|
814
|
+
return true;
|
|
815
|
+
}
|
|
816
|
+
return false;
|
|
817
|
+
}
|
|
818
|
+
if (this.#intervalId === void 0) {
|
|
819
|
+
const delay = this.#intervalEnd - now;
|
|
820
|
+
if (delay <= 0) {
|
|
821
|
+
this.#intervalCount = this.#intervalCountAtWindowStart;
|
|
822
|
+
} else {
|
|
823
|
+
this.#createIntervalTimeout(delay);
|
|
824
|
+
return true;
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
return false;
|
|
828
|
+
}
|
|
829
|
+
#createIntervalTimeout(delay) {
|
|
830
|
+
if (this.#timeoutId !== void 0) {
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
this.#timeoutId = setTimeout(() => {
|
|
834
|
+
this.#onResumeInterval();
|
|
835
|
+
}, delay);
|
|
836
|
+
}
|
|
837
|
+
#clearIntervalTimer() {
|
|
838
|
+
if (this.#intervalId === void 0) {
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
clearInterval(this.#intervalId);
|
|
842
|
+
this.#intervalId = void 0;
|
|
843
|
+
}
|
|
844
|
+
#clearTimeoutTimer() {
|
|
845
|
+
if (this.#timeoutId === void 0) {
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
clearTimeout(this.#timeoutId);
|
|
849
|
+
this.#timeoutId = void 0;
|
|
850
|
+
}
|
|
851
|
+
// Emits `empty`, and `idle` when no tasks run. For when the queue has no waiting tasks.
|
|
852
|
+
#emitEmptyAndIdle() {
|
|
853
|
+
this.#clearIntervalTimer();
|
|
854
|
+
this.#emit("empty");
|
|
855
|
+
if (this.#pending > 0 || this.#queue.size > 0) {
|
|
856
|
+
return;
|
|
857
|
+
}
|
|
858
|
+
this.#clearTimeoutTimer();
|
|
859
|
+
if (this.#strict) {
|
|
860
|
+
this.#cleanupStrictTicks(Date.now());
|
|
861
|
+
}
|
|
862
|
+
this.#emit("idle");
|
|
863
|
+
}
|
|
864
|
+
#tryToStartAnother() {
|
|
865
|
+
let isStarted;
|
|
866
|
+
do {
|
|
867
|
+
isStarted = this.#startNextTask();
|
|
868
|
+
} while (isStarted === void 0);
|
|
869
|
+
return isStarted;
|
|
870
|
+
}
|
|
871
|
+
// Returns `undefined` when it skipped a task whose signal aborted while it waited.
|
|
872
|
+
#startNextTask() {
|
|
873
|
+
if (this.#queue.size === 0) {
|
|
874
|
+
this.#emitEmptyAndIdle();
|
|
875
|
+
return false;
|
|
876
|
+
}
|
|
877
|
+
if (this.#isPaused) {
|
|
878
|
+
if (!this.#doesIntervalAllowAnother) {
|
|
879
|
+
this.#isIntervalPausedAt(Date.now());
|
|
880
|
+
}
|
|
881
|
+
return false;
|
|
882
|
+
}
|
|
883
|
+
const now = Date.now();
|
|
884
|
+
const canInitializeInterval = !this.#isIntervalPausedAt(now);
|
|
885
|
+
if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {
|
|
886
|
+
const job = this.#queue.dequeue();
|
|
887
|
+
if (!this.#isIntervalIgnored) {
|
|
888
|
+
this.#consumeIntervalSlot(now);
|
|
889
|
+
this.#scheduleRateLimitUpdate();
|
|
890
|
+
}
|
|
891
|
+
if (canInitializeInterval) {
|
|
892
|
+
this.#initializeIntervalIfNeeded();
|
|
893
|
+
}
|
|
894
|
+
const pendingBefore = this.#pending;
|
|
895
|
+
job();
|
|
896
|
+
if (this.#pending === pendingBefore) {
|
|
897
|
+
this.#emit("next");
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
this.#emit("active");
|
|
901
|
+
return true;
|
|
902
|
+
}
|
|
903
|
+
return false;
|
|
904
|
+
}
|
|
905
|
+
#initializeIntervalIfNeeded() {
|
|
906
|
+
if (this.#isIntervalIgnored || this.#intervalId !== void 0 || this.#strict) {
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
this.#clearTimeoutTimer();
|
|
910
|
+
this.#intervalId = setInterval(() => {
|
|
911
|
+
this.#onInterval();
|
|
912
|
+
}, this.#interval);
|
|
913
|
+
this.#intervalEnd = Date.now() + this.#interval;
|
|
914
|
+
}
|
|
915
|
+
#onInterval() {
|
|
916
|
+
if (!this.#strict) {
|
|
917
|
+
if (this.#intervalId !== void 0) {
|
|
918
|
+
if (this.#intervalCount === 0 && this.#pending === 0) {
|
|
919
|
+
this.#clearIntervalTimer();
|
|
920
|
+
} else {
|
|
921
|
+
this.#intervalEnd = Date.now() + this.#interval;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
this.#intervalCount = this.#intervalCountAtWindowStart;
|
|
925
|
+
}
|
|
926
|
+
this.#processQueue();
|
|
927
|
+
this.#scheduleRateLimitUpdate();
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
Executes all queued functions until it reaches the limit.
|
|
931
|
+
*/
|
|
932
|
+
#processQueue() {
|
|
933
|
+
while (this.#tryToStartAnother()) {
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
// On an empty queue, `#processQueue()` emits `empty` and `idle`. An `idle` listener that sets `concurrency` or calls `.start()` would then recurse without end.
|
|
937
|
+
#processWaitingTasks() {
|
|
938
|
+
if (this.#queue.size > 0) {
|
|
939
|
+
this.#processQueue();
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
async #add(function_, options, waitingTask) {
|
|
943
|
+
const id = options.id ?? (this.#idAssigner++).toString();
|
|
944
|
+
options = {
|
|
945
|
+
timeout: this.#timeout,
|
|
946
|
+
...options,
|
|
947
|
+
id
|
|
948
|
+
};
|
|
949
|
+
validateTimeout(options.timeout);
|
|
950
|
+
if (options.priority !== void 0 && (typeof options.priority !== "number" || Number.isNaN(options.priority))) {
|
|
951
|
+
throw new TypeError(`Expected \`priority\` to be a number, got \`${String(options.priority)}\` (${typeof options.priority})`);
|
|
952
|
+
}
|
|
953
|
+
waitingTask.id = id;
|
|
954
|
+
waitingTask.priority = options.priority ?? 0;
|
|
955
|
+
return new Promise((resolve, reject) => {
|
|
956
|
+
if (options.signal?.aborted) {
|
|
957
|
+
reject(options.signal.reason);
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
const run = bindAsyncContext(async () => {
|
|
961
|
+
waitingTask.stopListeningForAbort?.();
|
|
962
|
+
this.#waitingTasks.delete(waitingTask);
|
|
963
|
+
if (options.signal?.aborted) {
|
|
964
|
+
this.#rollbackIntervalConsumption();
|
|
965
|
+
reject(options.signal.reason);
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
this.#pending++;
|
|
969
|
+
const runningTask = {
|
|
970
|
+
id,
|
|
971
|
+
priority: waitingTask.priority,
|
|
972
|
+
startTime: Date.now(),
|
|
973
|
+
timeout: options.timeout
|
|
974
|
+
};
|
|
975
|
+
this.#runningTasks.add(runningTask);
|
|
976
|
+
let { signal } = options;
|
|
977
|
+
let stopListeningForAbort;
|
|
978
|
+
let stopForwardingAbort;
|
|
979
|
+
let timeoutId;
|
|
980
|
+
try {
|
|
981
|
+
if (options.timeout !== void 0) {
|
|
982
|
+
const { signal: userSignal, timeout } = options;
|
|
983
|
+
const taskController = new AbortController();
|
|
984
|
+
timeoutId = setTimeout(() => {
|
|
985
|
+
taskController.abort(new TimeoutError(`Task timed out after ${timeout}ms (queue has ${this.#pending} running, ${this.#queue.size} waiting)`));
|
|
986
|
+
}, timeout);
|
|
987
|
+
if (userSignal) {
|
|
988
|
+
stopForwardingAbort = this.#onAbort(userSignal, () => {
|
|
989
|
+
taskController.abort(userSignal.reason);
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
signal = taskController.signal;
|
|
993
|
+
}
|
|
994
|
+
let operation;
|
|
995
|
+
if (signal) {
|
|
996
|
+
const abortSignal = signal;
|
|
997
|
+
const abortPromise = new Promise((_resolve, rejectWithReason) => {
|
|
998
|
+
stopListeningForAbort = this.#onAbort(abortSignal, () => {
|
|
999
|
+
rejectWithReason(abortSignal.reason);
|
|
1000
|
+
});
|
|
1001
|
+
});
|
|
1002
|
+
operation = Promise.race([abortPromise, (async () => function_({ signal }))()]);
|
|
1003
|
+
} else {
|
|
1004
|
+
try {
|
|
1005
|
+
operation = function_({ signal });
|
|
1006
|
+
} catch (error) {
|
|
1007
|
+
operation = Promise.reject(error);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
const result = await operation;
|
|
1011
|
+
resolve(result);
|
|
1012
|
+
this.#emit("completed", result);
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
reject(error);
|
|
1015
|
+
this.#emit("error", error);
|
|
1016
|
+
} finally {
|
|
1017
|
+
clearTimeout(timeoutId);
|
|
1018
|
+
stopListeningForAbort?.();
|
|
1019
|
+
stopForwardingAbort?.();
|
|
1020
|
+
this.#runningTasks.delete(runningTask);
|
|
1021
|
+
queueMicrotask(() => {
|
|
1022
|
+
this.#next();
|
|
1023
|
+
});
|
|
1024
|
+
}
|
|
1025
|
+
});
|
|
1026
|
+
const hasWaitingTasks = this.#queue.size > 0;
|
|
1027
|
+
this.#queue.enqueue(run, options);
|
|
1028
|
+
waitingTask.reject = reject;
|
|
1029
|
+
this.#waitingTasks.add(waitingTask);
|
|
1030
|
+
if (options.signal) {
|
|
1031
|
+
const { signal } = options;
|
|
1032
|
+
waitingTask.stopListeningForAbort = this.#onAbort(signal, () => {
|
|
1033
|
+
this.#waitingTasks.delete(waitingTask);
|
|
1034
|
+
if (this.#queue instanceof PriorityQueue) {
|
|
1035
|
+
this.#queue.remove(run);
|
|
1036
|
+
} else {
|
|
1037
|
+
this.#queue.remove(id);
|
|
1038
|
+
}
|
|
1039
|
+
reject(signal.reason);
|
|
1040
|
+
this.#processQueue();
|
|
1041
|
+
this.#emit("next");
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
this.#emit("add");
|
|
1045
|
+
if (hasWaitingTasks) {
|
|
1046
|
+
this.#processQueue();
|
|
1047
|
+
} else {
|
|
1048
|
+
this.#tryToStartAnother();
|
|
1049
|
+
}
|
|
1050
|
+
});
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
Get or set the default timeout. A change applies to tasks added after it.
|
|
1054
|
+
|
|
1055
|
+
@example
|
|
1056
|
+
```
|
|
1057
|
+
const queue = new PQueue({timeout: 5000});
|
|
1058
|
+
|
|
1059
|
+
queue.timeout = 10000;
|
|
1060
|
+
```
|
|
1061
|
+
*/
|
|
1062
|
+
get timeout() {
|
|
1063
|
+
return this.#timeout;
|
|
1064
|
+
}
|
|
1065
|
+
// Validated here, not only in `.add()`, so that an invalid value throws where it is set, instead of making every later `.add()` reject.
|
|
1066
|
+
set timeout(timeout) {
|
|
1067
|
+
validateTimeout(timeout);
|
|
1068
|
+
this.#timeout = timeout;
|
|
1069
|
+
}
|
|
1070
|
+
get concurrency() {
|
|
1071
|
+
return this.#concurrency;
|
|
1072
|
+
}
|
|
1073
|
+
set concurrency(newConcurrency) {
|
|
1074
|
+
validateLimit("concurrency", newConcurrency);
|
|
1075
|
+
this.#concurrency = newConcurrency;
|
|
1076
|
+
this.#processWaitingTasks();
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
Changes the priority of a waiting task, found by its `id`. Throws a `ReferenceError` if no waiting task has that `id`, for example because it already started. Throws a `TypeError` if `priority` is not a finite number. Tasks only wait when the queue has a `concurrency` limit, is paused, or is rate-limited.
|
|
1080
|
+
|
|
1081
|
+
@example
|
|
1082
|
+
```
|
|
1083
|
+
// Raise the priority to run a task earlier
|
|
1084
|
+
import PQueue from 'p-queue';
|
|
1085
|
+
|
|
1086
|
+
const queue = new PQueue({concurrency: 1});
|
|
1087
|
+
|
|
1088
|
+
queue.add(async () => '🦄', {priority: 1});
|
|
1089
|
+
queue.add(async () => '🦀', {priority: 0, id: '🦀'});
|
|
1090
|
+
queue.add(async () => '🦄', {priority: 1});
|
|
1091
|
+
queue.add(async () => '🦄', {priority: 1});
|
|
1092
|
+
|
|
1093
|
+
queue.setPriority('🦀', 2);
|
|
1094
|
+
// '🦀' runs second
|
|
1095
|
+
```
|
|
1096
|
+
|
|
1097
|
+
@example
|
|
1098
|
+
```
|
|
1099
|
+
// Lower the priority to run a task later
|
|
1100
|
+
import PQueue from 'p-queue';
|
|
1101
|
+
|
|
1102
|
+
const queue = new PQueue({concurrency: 1});
|
|
1103
|
+
|
|
1104
|
+
queue.add(async () => '🦄', {priority: 1});
|
|
1105
|
+
queue.add(async () => '🦀', {priority: 1, id: '🦀'});
|
|
1106
|
+
queue.add(async () => '🦄');
|
|
1107
|
+
queue.add(async () => '🦄', {priority: 0});
|
|
1108
|
+
|
|
1109
|
+
queue.setPriority('🦀', -1);
|
|
1110
|
+
// '🦀' runs last
|
|
1111
|
+
```
|
|
1112
|
+
*/
|
|
1113
|
+
setPriority(id, priority) {
|
|
1114
|
+
if (typeof priority !== "number" || !Number.isFinite(priority)) {
|
|
1115
|
+
throw new TypeError(`Expected \`priority\` to be a finite number, got \`${priority}\` (${typeof priority})`);
|
|
1116
|
+
}
|
|
1117
|
+
for (const waitingTask of this.#waitingTasks) {
|
|
1118
|
+
if (waitingTask.id === id) {
|
|
1119
|
+
this.#queue.setPriority(id, priority);
|
|
1120
|
+
waitingTask.priority = priority;
|
|
1121
|
+
return;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
throw new ReferenceError(`No promise function with the id "${id}" exists in the queue.`);
|
|
1125
|
+
}
|
|
1126
|
+
/**
|
|
1127
|
+
Adds a sync or async task to the queue.
|
|
1128
|
+
|
|
1129
|
+
Returns a promise that settles with the result of `fn` when the task completes, not when it is added. The function gets `{signal}` as its first argument. The signal is set when the task has a `signal` or a `timeout`, and aborts when either one does. Pass it on, for example to `fetch()`, to stop the work. The function runs in the async context of the `.add()` call (in Node.js 22.3 and later, Deno, and Bun), so it sees the [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) values of the caller, also when it starts later.
|
|
1130
|
+
|
|
1131
|
+
If you `await` each `.add()` call before the next, the tasks run one after the other, whatever the `concurrency`.
|
|
1132
|
+
|
|
1133
|
+
Handle rejections of the returned promise. Otherwise, they are unhandled rejections, which can make the process exit.
|
|
1134
|
+
*/
|
|
1135
|
+
add(function_, options = {}) {
|
|
1136
|
+
const waitingTask = {};
|
|
1137
|
+
const promise = this.#add(function_, options, waitingTask);
|
|
1138
|
+
waitingTask.promise = promise;
|
|
1139
|
+
if (waitingTask.isCleared) {
|
|
1140
|
+
promise.catch(() => void 0);
|
|
1141
|
+
}
|
|
1142
|
+
return promise;
|
|
1143
|
+
}
|
|
1144
|
+
async addAll(functions, options) {
|
|
1145
|
+
return Promise.all(functions.map(async (function_) => this.add(function_, options)));
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
Starts (or resumes) running queued tasks. Only needed if the queue is paused, with `autoStart: false` or `.pause()`.
|
|
1149
|
+
|
|
1150
|
+
@returns `this` (the instance).
|
|
1151
|
+
*/
|
|
1152
|
+
start() {
|
|
1153
|
+
if (!this.#isPaused) {
|
|
1154
|
+
return this;
|
|
1155
|
+
}
|
|
1156
|
+
this.#isPaused = false;
|
|
1157
|
+
this.#processWaitingTasks();
|
|
1158
|
+
return this;
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
Stops starting new tasks. Running tasks continue.
|
|
1162
|
+
*/
|
|
1163
|
+
pause() {
|
|
1164
|
+
this.#isPaused = true;
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
Removes all waiting tasks. Running tasks continue.
|
|
1168
|
+
|
|
1169
|
+
The promises returned by `.add()` for the removed tasks reject with an `AbortError`, which is a `DOMException`. The removed tasks do not run, and they do not emit the `error` event.
|
|
1170
|
+
|
|
1171
|
+
If you ignore such a promise, its rejection is not reported as unhandled. This does not apply to a promise made from it, like the one from `queue.add(fn).then(…)` or from `.addAll()`, so handle the rejection of that promise.
|
|
1172
|
+
|
|
1173
|
+
@example
|
|
1174
|
+
```
|
|
1175
|
+
import PQueue from 'p-queue';
|
|
1176
|
+
|
|
1177
|
+
const queue = new PQueue({concurrency: 1});
|
|
1178
|
+
|
|
1179
|
+
queue.add(() => doWork());
|
|
1180
|
+
const promise = queue.add(() => doWork());
|
|
1181
|
+
|
|
1182
|
+
queue.clear();
|
|
1183
|
+
|
|
1184
|
+
try {
|
|
1185
|
+
await promise;
|
|
1186
|
+
} catch (error) {
|
|
1187
|
+
console.log(error.name);
|
|
1188
|
+
//=> 'AbortError'
|
|
1189
|
+
}
|
|
1190
|
+
```
|
|
1191
|
+
*/
|
|
1192
|
+
clear() {
|
|
1193
|
+
if (this.#queue.size === 0) {
|
|
1194
|
+
return;
|
|
1195
|
+
}
|
|
1196
|
+
this.#queue = new this.#queueClass();
|
|
1197
|
+
const error = new DOMException("The queue was cleared", "AbortError");
|
|
1198
|
+
for (const waitingTask of this.#waitingTasks) {
|
|
1199
|
+
waitingTask.stopListeningForAbort?.();
|
|
1200
|
+
waitingTask.isCleared = true;
|
|
1201
|
+
waitingTask.promise?.catch(() => void 0);
|
|
1202
|
+
waitingTask.reject(error);
|
|
1203
|
+
}
|
|
1204
|
+
this.#waitingTasks.clear();
|
|
1205
|
+
this.#emitEmptyAndIdle();
|
|
1206
|
+
this.#updateRateLimitState();
|
|
1207
|
+
this.#emit("next");
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
Returns a promise that resolves when the queue is empty. Tasks can still be running.
|
|
1211
|
+
|
|
1212
|
+
The promise resolves once. Call `.onEmpty()` again to wait for the next time, or use the `empty` event to get every time.
|
|
1213
|
+
*/
|
|
1214
|
+
async onEmpty() {
|
|
1215
|
+
if (this.#queue.size === 0) {
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
await this.#onEvent(["empty", "active"], () => this.#queue.size === 0);
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
Returns a promise that resolves when `queue.size < limit`.
|
|
1222
|
+
|
|
1223
|
+
Await it before you add a task, to keep the queue from growing beyond a size. It counts only waiting tasks, not running tasks.
|
|
1224
|
+
*/
|
|
1225
|
+
async onSizeLessThan(limit) {
|
|
1226
|
+
if (this.#queue.size < limit) {
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
await this.#onEvent(["next", "active"], () => this.#queue.size < limit);
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
Returns a promise that resolves when the queue is empty and all tasks have completed: `queue.size === 0 && queue.pending === 0`.
|
|
1233
|
+
|
|
1234
|
+
Unlike `.onEmpty()`, it waits for running tasks to finish.
|
|
1235
|
+
|
|
1236
|
+
The promise resolves once. Call `.onIdle()` again to wait for the next time, or use the `idle` event to get every time.
|
|
1237
|
+
*/
|
|
1238
|
+
async onIdle() {
|
|
1239
|
+
if (this.#pending === 0 && this.#queue.size === 0) {
|
|
1240
|
+
return;
|
|
1241
|
+
}
|
|
1242
|
+
await this.#onEvent("idle");
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
Returns a promise that resolves when no tasks are running: `queue.pending === 0`.
|
|
1246
|
+
|
|
1247
|
+
Unlike `.onIdle()`, it ignores queued tasks. Use it to let running tasks finish before you change shared state. A task that timed out, or whose `signal` aborted while it ran, no longer counts, although its function can still run.
|
|
1248
|
+
|
|
1249
|
+
@example
|
|
1250
|
+
```
|
|
1251
|
+
queue.pause();
|
|
1252
|
+
await queue.onPendingZero();
|
|
1253
|
+
// No tasks are running, but the queue can still have tasks
|
|
1254
|
+
```
|
|
1255
|
+
*/
|
|
1256
|
+
async onPendingZero() {
|
|
1257
|
+
if (this.#pending === 0) {
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
await this.#onEvent("pendingZero");
|
|
1261
|
+
}
|
|
1262
|
+
/**
|
|
1263
|
+
Returns a promise that resolves when the queue becomes rate-limited by `intervalCap`. If the queue is already rate-limited, it resolves immediately.
|
|
1264
|
+
|
|
1265
|
+
Useful for backpressure, when tasks are added faster than they run.
|
|
1266
|
+
|
|
1267
|
+
@example
|
|
1268
|
+
```
|
|
1269
|
+
const queue = new PQueue({intervalCap: 5, interval: 1000});
|
|
1270
|
+
|
|
1271
|
+
for (let index = 0; index < 10; index++) {
|
|
1272
|
+
queue.add(() => someTask());
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
await queue.onRateLimit();
|
|
1276
|
+
console.log('The queue is rate-limited');
|
|
1277
|
+
```
|
|
1278
|
+
*/
|
|
1279
|
+
async onRateLimit() {
|
|
1280
|
+
this.#updateRateLimitState();
|
|
1281
|
+
if (this.isRateLimited) {
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
await this.#onEvent("rateLimit");
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
Returns a promise that resolves when the queue is no longer rate-limited. If the queue is not rate-limited, it resolves immediately.
|
|
1288
|
+
|
|
1289
|
+
@example
|
|
1290
|
+
```
|
|
1291
|
+
const queue = new PQueue({intervalCap: 5, interval: 1000});
|
|
1292
|
+
|
|
1293
|
+
for (let index = 0; index < 10; index++) {
|
|
1294
|
+
queue.add(() => someTask());
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
await queue.onRateLimitCleared();
|
|
1298
|
+
console.log('The rate limit is cleared');
|
|
1299
|
+
```
|
|
1300
|
+
*/
|
|
1301
|
+
async onRateLimitCleared() {
|
|
1302
|
+
this.#updateRateLimitState();
|
|
1303
|
+
if (!this.isRateLimited) {
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
await this.#onEvent("rateLimitCleared");
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
Returns a promise that rejects when a task fails: it throws, times out, or its `signal` aborts while it runs. It rejects with the error of the task, or with `null` if the error is `undefined`, like the `error` event.
|
|
1310
|
+
|
|
1311
|
+
Use `Promise.race([queue.onError(), queue.onIdle()])` to stop at the first error, and to resolve normally when the queue becomes idle. Each call adds an `error` listener that stays until a task fails, so to get every error, for example in a loop, use the `error` event instead.
|
|
1312
|
+
|
|
1313
|
+
Important: The promises returned by `.add()` still reject. Handle each of them (for example with `.catch(() => {})`) to prevent unhandled rejections.
|
|
1314
|
+
|
|
1315
|
+
@example
|
|
1316
|
+
```
|
|
1317
|
+
import PQueue from 'p-queue';
|
|
1318
|
+
|
|
1319
|
+
const queue = new PQueue({concurrency: 2});
|
|
1320
|
+
|
|
1321
|
+
// Do not start the remaining tasks. Pause in an `error` listener, because it runs before the next task starts, and the code after `await` runs later.
|
|
1322
|
+
queue.addEventListener('error', () => {
|
|
1323
|
+
queue.pause();
|
|
1324
|
+
}, {once: true});
|
|
1325
|
+
|
|
1326
|
+
queue.add(() => fetchData(1)).catch(() => {});
|
|
1327
|
+
queue.add(() => fetchData(2)).catch(() => {});
|
|
1328
|
+
queue.add(() => fetchData(3)).catch(() => {});
|
|
1329
|
+
|
|
1330
|
+
try {
|
|
1331
|
+
await Promise.race([
|
|
1332
|
+
queue.onError(),
|
|
1333
|
+
queue.onIdle()
|
|
1334
|
+
]);
|
|
1335
|
+
} catch (error) {
|
|
1336
|
+
console.error('Queue failed:', error);
|
|
1337
|
+
}
|
|
1338
|
+
```
|
|
1339
|
+
*/
|
|
1340
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
1341
|
+
onError() {
|
|
1342
|
+
return new Promise((_resolve, reject) => {
|
|
1343
|
+
this.addEventListener("error", (event) => {
|
|
1344
|
+
reject(event.detail);
|
|
1345
|
+
}, { once: true });
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
/**
|
|
1349
|
+
The number of tasks waiting to run.
|
|
1350
|
+
*/
|
|
1351
|
+
get size() {
|
|
1352
|
+
return this.#queue.size;
|
|
1353
|
+
}
|
|
1354
|
+
/**
|
|
1355
|
+
The number of waiting tasks with the given `priority`.
|
|
1356
|
+
|
|
1357
|
+
@example
|
|
1358
|
+
```
|
|
1359
|
+
import PQueue from 'p-queue';
|
|
1360
|
+
|
|
1361
|
+
const queue = new PQueue();
|
|
1362
|
+
|
|
1363
|
+
// Paused, so the tasks stay queued. Without it they all start synchronously and the queue is empty by the time `sizeBy` reads it.
|
|
1364
|
+
queue.pause();
|
|
1365
|
+
|
|
1366
|
+
queue.add(async () => '🦄', {priority: 1});
|
|
1367
|
+
queue.add(async () => '🦄', {priority: 0});
|
|
1368
|
+
queue.add(async () => '🦄', {priority: 1});
|
|
1369
|
+
|
|
1370
|
+
console.log(queue.sizeBy({priority: 1}));
|
|
1371
|
+
//=> 2
|
|
1372
|
+
|
|
1373
|
+
console.log(queue.sizeBy({priority: 0}));
|
|
1374
|
+
//=> 1
|
|
1375
|
+
```
|
|
1376
|
+
*/
|
|
1377
|
+
sizeBy(options) {
|
|
1378
|
+
return this.#queue.filter(options).length;
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
The number of running tasks.
|
|
1382
|
+
*/
|
|
1383
|
+
get pending() {
|
|
1384
|
+
return this.#pending;
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
Whether the queue is paused.
|
|
1388
|
+
*/
|
|
1389
|
+
get isPaused() {
|
|
1390
|
+
return this.#isPaused;
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
Whether the queue is rate-limited: the number of tasks started in the current interval, plus the tasks still running from earlier intervals with `carryoverIntervalCount`, has reached `intervalCap`, and tasks are waiting.
|
|
1394
|
+
*/
|
|
1395
|
+
get isRateLimited() {
|
|
1396
|
+
return this.#isRateLimitedNow;
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
Whether tasks are waiting because all concurrency slots are in use, or because the queue is rate-limited.
|
|
1400
|
+
|
|
1401
|
+
Useful to detect backpressure and tasks that hang.
|
|
1402
|
+
|
|
1403
|
+
@example
|
|
1404
|
+
```
|
|
1405
|
+
import PQueue from 'p-queue';
|
|
1406
|
+
|
|
1407
|
+
const queue = new PQueue({concurrency: 2});
|
|
1408
|
+
|
|
1409
|
+
// Backpressure
|
|
1410
|
+
if (queue.isSaturated) {
|
|
1411
|
+
await queue.onSizeLessThan(queue.concurrency);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
// Monitoring
|
|
1415
|
+
setInterval(() => {
|
|
1416
|
+
if (queue.isSaturated) {
|
|
1417
|
+
console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`);
|
|
1418
|
+
}
|
|
1419
|
+
}, 60000);
|
|
1420
|
+
```
|
|
1421
|
+
*/
|
|
1422
|
+
get isSaturated() {
|
|
1423
|
+
return this.#queue.size > 0 && (this.#pending >= this.#concurrency || this.isRateLimited);
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
An array with the running tasks. Each task has its `id`, `priority`, `startTime`, `timeout`, and `timeoutRemaining` (the milliseconds until it times out). Without a timeout, `timeout` and `timeoutRemaining` are `undefined`.
|
|
1427
|
+
|
|
1428
|
+
@example
|
|
1429
|
+
```
|
|
1430
|
+
import PQueue from 'p-queue';
|
|
1431
|
+
|
|
1432
|
+
const queue = new PQueue({concurrency: 2, timeout: 10000});
|
|
1433
|
+
|
|
1434
|
+
queue.add(() => fetchUser(123), {id: 'user-123'});
|
|
1435
|
+
queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1});
|
|
1436
|
+
|
|
1437
|
+
console.log(queue.runningTasks);
|
|
1438
|
+
// => [{
|
|
1439
|
+
// id: 'user-123',
|
|
1440
|
+
// priority: 0,
|
|
1441
|
+
// startTime: 1759253001716,
|
|
1442
|
+
// timeout: 10000,
|
|
1443
|
+
// timeoutRemaining: 10000
|
|
1444
|
+
// }, {
|
|
1445
|
+
// id: 'posts-456',
|
|
1446
|
+
// priority: 1,
|
|
1447
|
+
// startTime: 1759253001716,
|
|
1448
|
+
// timeout: 10000,
|
|
1449
|
+
// timeoutRemaining: 10000
|
|
1450
|
+
// }]
|
|
1451
|
+
```
|
|
1452
|
+
*/
|
|
1453
|
+
get runningTasks() {
|
|
1454
|
+
return Array.from(this.#runningTasks, (task) => ({
|
|
1455
|
+
...task,
|
|
1456
|
+
timeoutRemaining: task.timeout === void 0 ? void 0 : Math.max(0, task.startTime + task.timeout - Date.now())
|
|
1457
|
+
}));
|
|
1458
|
+
}
|
|
1459
|
+
};
|
|
1460
|
+
var TimeoutError = class extends DOMException {
|
|
1461
|
+
constructor(message) {
|
|
1462
|
+
super(message, "TimeoutError");
|
|
1463
|
+
}
|
|
1464
|
+
};
|
|
1465
|
+
|
|
1466
|
+
// src/orchestration/canonical/KrnlQ.ts
|
|
1467
|
+
var import_node_crypto = require("crypto");
|
|
1468
|
+
|
|
1469
|
+
// src/orchestration/canonical/model.ts
|
|
1470
|
+
function validateOrchestrationDAG(steps) {
|
|
1471
|
+
const errors = [];
|
|
1472
|
+
const stepMap = /* @__PURE__ */ new Map();
|
|
1473
|
+
for (const step of steps) {
|
|
1474
|
+
if (!step.id || typeof step.id !== "string" || step.id.trim() === "") {
|
|
1475
|
+
errors.push("Step must have a non-empty string ID.");
|
|
1476
|
+
continue;
|
|
1477
|
+
}
|
|
1478
|
+
if (stepMap.has(step.id)) {
|
|
1479
|
+
errors.push(`Duplicate step ID detected: "${step.id}"`);
|
|
1480
|
+
}
|
|
1481
|
+
stepMap.set(step.id, step);
|
|
1482
|
+
if (step.timeoutPolicy) {
|
|
1483
|
+
if (typeof step.timeoutPolicy.timeoutMs !== "number" || step.timeoutPolicy.timeoutMs <= 0) {
|
|
1484
|
+
errors.push(`Step "${step.id}" has invalid timeoutMs: must be a positive number.`);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
if (step.retryPolicy) {
|
|
1488
|
+
if (typeof step.retryPolicy.maxAttempts !== "number" || step.retryPolicy.maxAttempts < 1) {
|
|
1489
|
+
errors.push(`Step "${step.id}" has invalid maxAttempts: must be >= 1.`);
|
|
1490
|
+
}
|
|
1491
|
+
if (step.retryPolicy.backoffMs !== void 0 && step.retryPolicy.backoffMs < 0) {
|
|
1492
|
+
errors.push(`Step "${step.id}" has negative backoffMs.`);
|
|
1493
|
+
}
|
|
1494
|
+
if (step.retryPolicy.initialDelayMs !== void 0 && step.retryPolicy.initialDelayMs < 0) {
|
|
1495
|
+
errors.push(`Step "${step.id}" has negative initialDelayMs.`);
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
if (step.concurrency !== void 0 && (typeof step.concurrency !== "number" || step.concurrency < 1)) {
|
|
1499
|
+
errors.push(`Step "${step.id}" has invalid concurrency: must be >= 1.`);
|
|
1500
|
+
}
|
|
1501
|
+
if (step.type === "task" || step.type === "sequential") {
|
|
1502
|
+
if (!step.target && !step.handler) {
|
|
1503
|
+
errors.push(`Step "${step.id}" requires a non-empty target or handler.`);
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
for (const step of steps) {
|
|
1508
|
+
if (step.dependsOn) {
|
|
1509
|
+
for (const dep of step.dependsOn) {
|
|
1510
|
+
if (!stepMap.has(dep)) {
|
|
1511
|
+
errors.push(`Step "${step.id}" depends on unknown step "${dep}".`);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
if (errors.length > 0) {
|
|
1517
|
+
return { valid: false, order: [], errors };
|
|
1518
|
+
}
|
|
1519
|
+
const inDegree = /* @__PURE__ */ new Map();
|
|
1520
|
+
const graph = /* @__PURE__ */ new Map();
|
|
1521
|
+
for (const step of steps) {
|
|
1522
|
+
inDegree.set(step.id, 0);
|
|
1523
|
+
graph.set(step.id, []);
|
|
1524
|
+
}
|
|
1525
|
+
for (const step of steps) {
|
|
1526
|
+
if (step.dependsOn) {
|
|
1527
|
+
for (const dep of step.dependsOn) {
|
|
1528
|
+
inDegree.set(step.id, (inDegree.get(step.id) || 0) + 1);
|
|
1529
|
+
graph.get(dep)?.push(step.id);
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
const queue = [];
|
|
1534
|
+
for (const [id, deg] of inDegree.entries()) {
|
|
1535
|
+
if (deg === 0) queue.push(id);
|
|
1536
|
+
}
|
|
1537
|
+
const order = [];
|
|
1538
|
+
while (queue.length > 0) {
|
|
1539
|
+
const current = queue.shift();
|
|
1540
|
+
order.push(current);
|
|
1541
|
+
const neighbors = graph.get(current) || [];
|
|
1542
|
+
for (const neighbor of neighbors) {
|
|
1543
|
+
const newDeg = (inDegree.get(neighbor) || 0) - 1;
|
|
1544
|
+
inDegree.set(neighbor, newDeg);
|
|
1545
|
+
if (newDeg === 0) {
|
|
1546
|
+
queue.push(neighbor);
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
if (order.length !== steps.length) {
|
|
1551
|
+
errors.push("Circular dependency cycle detected in orchestration DAG.");
|
|
1552
|
+
return { valid: false, order: [], errors };
|
|
1553
|
+
}
|
|
1554
|
+
return { valid: true, order, errors: [] };
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
// src/orchestration/canonical/WorkerExecutionBoundary.ts
|
|
1558
|
+
var WorkerExecutionBoundary = class _WorkerExecutionBoundary {
|
|
1559
|
+
constructor(workerId, handler) {
|
|
1560
|
+
this.workerId = workerId;
|
|
1561
|
+
this.handler = handler;
|
|
1562
|
+
}
|
|
1563
|
+
workerId;
|
|
1564
|
+
handler;
|
|
1565
|
+
async processJob(command, metadata) {
|
|
1566
|
+
if (!this.handler) {
|
|
1567
|
+
return {
|
|
1568
|
+
correlationId: command.correlationId,
|
|
1569
|
+
status: "COMPLETED",
|
|
1570
|
+
data: command.payload,
|
|
1571
|
+
executionTimestamp: Date.now()
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
const context = {
|
|
1575
|
+
isWorkerContext: true,
|
|
1576
|
+
workerId: this.workerId,
|
|
1577
|
+
timestamp: Date.now(),
|
|
1578
|
+
correlationId: command.correlationId,
|
|
1579
|
+
metadata
|
|
1580
|
+
};
|
|
1581
|
+
_WorkerExecutionBoundary.assertWorkerContext(context);
|
|
1582
|
+
return await this.handler(command, context);
|
|
1583
|
+
}
|
|
1584
|
+
static assertWorkerContext(context) {
|
|
1585
|
+
if (!context || !context.isWorkerContext) {
|
|
1586
|
+
throw new Error(
|
|
1587
|
+
"[WorkerExecutionBoundary] Violation: DIRECT_CALL -> SERVICE_BOUNDARY is strictly forbidden. All operations must execute inside KrnlWorker context."
|
|
1588
|
+
);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
};
|
|
1592
|
+
|
|
1593
|
+
// src/orchestration/canonical/KrnlWorkerPool.ts
|
|
1594
|
+
var KrnlWorkerPool = class {
|
|
1595
|
+
constructor(queueName, workerId = `worker_${queueName}_${Math.random().toString(36).substring(2, 7)}`) {
|
|
1596
|
+
this.queueName = queueName;
|
|
1597
|
+
this.workerId = workerId;
|
|
1598
|
+
this.workerBoundary = new WorkerExecutionBoundary(this.workerId);
|
|
1599
|
+
}
|
|
1600
|
+
queueName;
|
|
1601
|
+
workerId;
|
|
1602
|
+
state = "created";
|
|
1603
|
+
activeJobsCount = 0;
|
|
1604
|
+
startedAt = Date.now();
|
|
1605
|
+
workerBoundary;
|
|
1606
|
+
getState() {
|
|
1607
|
+
return this.state;
|
|
1608
|
+
}
|
|
1609
|
+
getActiveJobs() {
|
|
1610
|
+
return this.activeJobsCount;
|
|
1611
|
+
}
|
|
1612
|
+
getWorkerBoundary() {
|
|
1613
|
+
return this.workerBoundary;
|
|
1614
|
+
}
|
|
1615
|
+
getInfo() {
|
|
1616
|
+
return {
|
|
1617
|
+
id: this.workerId,
|
|
1618
|
+
queueName: this.queueName,
|
|
1619
|
+
state: this.state,
|
|
1620
|
+
startedAt: this.startedAt,
|
|
1621
|
+
activeJobs: this.activeJobsCount
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
start() {
|
|
1625
|
+
if (this.state === "stopped") {
|
|
1626
|
+
throw new Error(`[KrnlWorkerPool:${this.workerId}] Cannot start stopped worker.`);
|
|
1627
|
+
}
|
|
1628
|
+
this.state = "started";
|
|
1629
|
+
}
|
|
1630
|
+
createContext(correlationId, metadata) {
|
|
1631
|
+
return {
|
|
1632
|
+
isWorkerContext: true,
|
|
1633
|
+
workerId: this.workerId,
|
|
1634
|
+
timestamp: Date.now(),
|
|
1635
|
+
correlationId: correlationId || `corr_${Math.random().toString(36).substring(2, 11)}`,
|
|
1636
|
+
metadata
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1639
|
+
async runWithContext(correlationId, metadata, fn) {
|
|
1640
|
+
if (this.state === "stopped" || this.state === "draining") {
|
|
1641
|
+
throw new Error(`[KrnlWorkerPool:${this.workerId}] Worker is not accepting new jobs (state: ${this.state}).`);
|
|
1642
|
+
}
|
|
1643
|
+
this.state = "running";
|
|
1644
|
+
this.activeJobsCount++;
|
|
1645
|
+
const ctx = this.createContext(correlationId, metadata);
|
|
1646
|
+
WorkerExecutionBoundary.assertWorkerContext(ctx);
|
|
1647
|
+
try {
|
|
1648
|
+
return await fn(ctx);
|
|
1649
|
+
} finally {
|
|
1650
|
+
this.activeJobsCount--;
|
|
1651
|
+
if (this.activeJobsCount === 0 && this.state === "running") {
|
|
1652
|
+
this.state = "started";
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
async drain() {
|
|
1657
|
+
this.state = "draining";
|
|
1658
|
+
while (this.activeJobsCount > 0) {
|
|
1659
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
async stop() {
|
|
1663
|
+
await this.drain();
|
|
1664
|
+
this.state = "stopped";
|
|
1665
|
+
}
|
|
1666
|
+
};
|
|
1667
|
+
|
|
1668
|
+
// src/orchestration/canonical/KrnlQ.ts
|
|
1669
|
+
function generateSecureId(prefix) {
|
|
1670
|
+
try {
|
|
1671
|
+
return `${prefix}_${(0, import_node_crypto.randomUUID)()}`;
|
|
1672
|
+
} catch {
|
|
1673
|
+
return `${prefix}_${Math.random().toString(36).substring(2, 11)}_${Date.now()}`;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
var KrnlQueue = class {
|
|
1677
|
+
queueName;
|
|
1678
|
+
queue;
|
|
1679
|
+
workerPool;
|
|
1680
|
+
jobs = /* @__PURE__ */ new Map();
|
|
1681
|
+
idempotencyStore = /* @__PURE__ */ new Map();
|
|
1682
|
+
activeOrchestrations = /* @__PURE__ */ new Map();
|
|
1683
|
+
maxRetainedJobs;
|
|
1684
|
+
constructor(options = {}) {
|
|
1685
|
+
this.queueName = options.queueName ?? "krnl_default_queue";
|
|
1686
|
+
this.maxRetainedJobs = options.maxRetainedJobs ?? 1e3;
|
|
1687
|
+
const concurrency = options.concurrency ?? 10;
|
|
1688
|
+
this.queue = new PQueue({
|
|
1689
|
+
concurrency,
|
|
1690
|
+
autoStart: options.autoStart ?? true
|
|
1691
|
+
});
|
|
1692
|
+
this.workerPool = new KrnlWorkerPool(this.queueName);
|
|
1693
|
+
this.workerPool.start();
|
|
1694
|
+
}
|
|
1695
|
+
get concurrency() {
|
|
1696
|
+
return this.queue.concurrency;
|
|
1697
|
+
}
|
|
1698
|
+
set concurrency(value) {
|
|
1699
|
+
this.queue.concurrency = value;
|
|
1700
|
+
}
|
|
1701
|
+
get size() {
|
|
1702
|
+
return this.queue.size;
|
|
1703
|
+
}
|
|
1704
|
+
get pending() {
|
|
1705
|
+
return this.queue.pending;
|
|
1706
|
+
}
|
|
1707
|
+
get isPaused() {
|
|
1708
|
+
return this.queue.isPaused;
|
|
1709
|
+
}
|
|
1710
|
+
getWorkerBoundary() {
|
|
1711
|
+
return this.workerPool.getWorkerBoundary();
|
|
1712
|
+
}
|
|
1713
|
+
getWorkerPool() {
|
|
1714
|
+
return this.workerPool;
|
|
1715
|
+
}
|
|
1716
|
+
pause() {
|
|
1717
|
+
this.queue.pause();
|
|
1718
|
+
}
|
|
1719
|
+
resume() {
|
|
1720
|
+
this.queue.start();
|
|
1721
|
+
}
|
|
1722
|
+
clear() {
|
|
1723
|
+
this.queue.clear();
|
|
1724
|
+
for (const job of this.jobs.values()) {
|
|
1725
|
+
if (job.status === "waiting") {
|
|
1726
|
+
job.status = "cancelled";
|
|
1727
|
+
job.completedAt = Date.now();
|
|
1728
|
+
job.abortController.abort();
|
|
1729
|
+
const cancelErr = new Error("The operation was aborted");
|
|
1730
|
+
cancelErr.name = "AbortError";
|
|
1731
|
+
job.rejectPromise(cancelErr);
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
pruneJobs() {
|
|
1736
|
+
if (this.jobs.size <= this.maxRetainedJobs) return;
|
|
1737
|
+
const excess = this.jobs.size - this.maxRetainedJobs;
|
|
1738
|
+
let pruned = 0;
|
|
1739
|
+
for (const [id, record] of this.jobs.entries()) {
|
|
1740
|
+
if (record.status === "completed" || record.status === "failed" || record.status === "cancelled") {
|
|
1741
|
+
this.jobs.delete(id);
|
|
1742
|
+
pruned++;
|
|
1743
|
+
if (pruned >= excess) break;
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
async drain() {
|
|
1748
|
+
await this.queue.onIdle();
|
|
1749
|
+
}
|
|
1750
|
+
async shutdown(options = { drain: true }) {
|
|
1751
|
+
if (options.drain) {
|
|
1752
|
+
await this.drain();
|
|
1753
|
+
} else {
|
|
1754
|
+
this.clear();
|
|
1755
|
+
}
|
|
1756
|
+
for (const active of this.activeOrchestrations.values()) {
|
|
1757
|
+
active.abortController.abort();
|
|
1758
|
+
active.context.isCancelled = true;
|
|
1759
|
+
}
|
|
1760
|
+
this.activeOrchestrations.clear();
|
|
1761
|
+
await this.workerPool.stop();
|
|
1762
|
+
}
|
|
1763
|
+
async close() {
|
|
1764
|
+
await this.shutdown({ drain: false });
|
|
1765
|
+
}
|
|
1766
|
+
async dispose() {
|
|
1767
|
+
await this.shutdown({ drain: false });
|
|
1768
|
+
}
|
|
1769
|
+
async start() {
|
|
1770
|
+
this.resume();
|
|
1771
|
+
}
|
|
1772
|
+
async stop() {
|
|
1773
|
+
this.pause();
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Enqueues a job returning a strong handle.
|
|
1777
|
+
*/
|
|
1778
|
+
enqueue(jobDef) {
|
|
1779
|
+
this.pruneJobs();
|
|
1780
|
+
const jobId = jobDef.id || generateSecureId("job");
|
|
1781
|
+
const abortController = new AbortController();
|
|
1782
|
+
if (jobDef.options?.abortSignal) {
|
|
1783
|
+
if (jobDef.options.abortSignal.aborted) {
|
|
1784
|
+
abortController.abort();
|
|
1785
|
+
} else {
|
|
1786
|
+
jobDef.options.abortSignal.addEventListener("abort", () => abortController.abort(), { once: true });
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
let resolvePromise;
|
|
1790
|
+
let rejectPromise;
|
|
1791
|
+
const promise = new Promise((res, rej) => {
|
|
1792
|
+
resolvePromise = res;
|
|
1793
|
+
rejectPromise = rej;
|
|
1794
|
+
});
|
|
1795
|
+
const record = {
|
|
1796
|
+
id: jobId,
|
|
1797
|
+
name: jobDef.name,
|
|
1798
|
+
status: "waiting",
|
|
1799
|
+
createdAt: Date.now(),
|
|
1800
|
+
abortController,
|
|
1801
|
+
resolvePromise,
|
|
1802
|
+
rejectPromise,
|
|
1803
|
+
promise
|
|
1804
|
+
};
|
|
1805
|
+
this.jobs.set(jobId, record);
|
|
1806
|
+
const priority = jobDef.options?.priority ?? 0;
|
|
1807
|
+
this.queue.add(
|
|
1808
|
+
async () => {
|
|
1809
|
+
if (record.status === "cancelled" || abortController.signal.aborted) {
|
|
1810
|
+
record.status = "cancelled";
|
|
1811
|
+
const cancelErr = new Error("The operation was aborted");
|
|
1812
|
+
cancelErr.name = "AbortError";
|
|
1813
|
+
rejectPromise(cancelErr);
|
|
1814
|
+
return;
|
|
1815
|
+
}
|
|
1816
|
+
record.status = "active";
|
|
1817
|
+
record.startedAt = Date.now();
|
|
1818
|
+
const idemKey = jobDef.options?.idempotencyKey;
|
|
1819
|
+
if (idemKey && this.idempotencyStore.has(idemKey)) {
|
|
1820
|
+
const cached = this.idempotencyStore.get(idemKey);
|
|
1821
|
+
record.status = cached.status === "COMPLETED" ? "completed" : "failed";
|
|
1822
|
+
record.completedAt = Date.now();
|
|
1823
|
+
if (cached.status === "COMPLETED") {
|
|
1824
|
+
record.result = cached.data;
|
|
1825
|
+
resolvePromise(cached.data);
|
|
1826
|
+
} else {
|
|
1827
|
+
record.error = cached.error;
|
|
1828
|
+
rejectPromise(new Error(cached.error));
|
|
1829
|
+
}
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
const retries = jobDef.options?.retries ?? 0;
|
|
1833
|
+
const maxAttempts = retries + 1;
|
|
1834
|
+
const timeoutMs = jobDef.options?.timeoutMs;
|
|
1835
|
+
const backoffMs = jobDef.options?.backoffMs ?? 100;
|
|
1836
|
+
const backoffPolicy = jobDef.options?.backoffPolicy ?? "exponential";
|
|
1837
|
+
let attempt = 0;
|
|
1838
|
+
let lastError;
|
|
1839
|
+
while (attempt < maxAttempts) {
|
|
1840
|
+
if (abortController.signal.aborted) {
|
|
1841
|
+
record.status = "cancelled";
|
|
1842
|
+
const cancelErr = new Error("The operation was aborted");
|
|
1843
|
+
cancelErr.name = "AbortError";
|
|
1844
|
+
rejectPromise(cancelErr);
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
attempt++;
|
|
1848
|
+
try {
|
|
1849
|
+
const result = await this.workerPool.runWithContext(
|
|
1850
|
+
jobDef.options?.correlationId,
|
|
1851
|
+
jobDef.options?.metadata,
|
|
1852
|
+
async (workerCtx) => {
|
|
1853
|
+
let timer;
|
|
1854
|
+
try {
|
|
1855
|
+
const workPromise = jobDef.handler(jobDef.payload, workerCtx);
|
|
1856
|
+
if (timeoutMs && timeoutMs > 0) {
|
|
1857
|
+
const timeoutPromise = new Promise((_, rej) => {
|
|
1858
|
+
timer = setTimeout(() => {
|
|
1859
|
+
const err = new Error(`Job "${jobDef.name}" timed out after ${timeoutMs}ms.`);
|
|
1860
|
+
err.name = "TimeoutError";
|
|
1861
|
+
rej(err);
|
|
1862
|
+
}, timeoutMs);
|
|
1863
|
+
});
|
|
1864
|
+
return await Promise.race([workPromise, timeoutPromise]);
|
|
1865
|
+
}
|
|
1866
|
+
return await workPromise;
|
|
1867
|
+
} finally {
|
|
1868
|
+
if (timer) clearTimeout(timer);
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
);
|
|
1872
|
+
record.status = "completed";
|
|
1873
|
+
record.completedAt = Date.now();
|
|
1874
|
+
record.result = result;
|
|
1875
|
+
if (idemKey) {
|
|
1876
|
+
this.idempotencyStore.set(idemKey, {
|
|
1877
|
+
correlationId: jobDef.options?.correlationId || jobId,
|
|
1878
|
+
status: "COMPLETED",
|
|
1879
|
+
data: result,
|
|
1880
|
+
executionTimestamp: Date.now()
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
1883
|
+
resolvePromise(result);
|
|
1884
|
+
return;
|
|
1885
|
+
} catch (err) {
|
|
1886
|
+
lastError = err;
|
|
1887
|
+
if (abortController.signal.aborted || err?.name === "AbortError") {
|
|
1888
|
+
record.status = "cancelled";
|
|
1889
|
+
record.completedAt = Date.now();
|
|
1890
|
+
rejectPromise(err);
|
|
1891
|
+
return;
|
|
1892
|
+
}
|
|
1893
|
+
if (attempt < maxAttempts) {
|
|
1894
|
+
const delay = backoffPolicy === "exponential" ? backoffMs * Math.pow(2, attempt - 1) : backoffMs * attempt;
|
|
1895
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
record.status = "failed";
|
|
1900
|
+
record.completedAt = Date.now();
|
|
1901
|
+
record.error = lastError?.message || String(lastError);
|
|
1902
|
+
if (idemKey) {
|
|
1903
|
+
this.idempotencyStore.set(idemKey, {
|
|
1904
|
+
correlationId: jobDef.options?.correlationId || jobId,
|
|
1905
|
+
status: "FAILED",
|
|
1906
|
+
error: record.error,
|
|
1907
|
+
executionTimestamp: Date.now()
|
|
1908
|
+
});
|
|
1909
|
+
}
|
|
1910
|
+
rejectPromise(lastError);
|
|
1911
|
+
},
|
|
1912
|
+
{ priority }
|
|
1913
|
+
);
|
|
1914
|
+
return {
|
|
1915
|
+
id: jobId,
|
|
1916
|
+
name: jobDef.name,
|
|
1917
|
+
getStatus: () => record.status,
|
|
1918
|
+
result: () => record.promise,
|
|
1919
|
+
cancel: () => this.cancel(jobId)
|
|
1920
|
+
};
|
|
1921
|
+
}
|
|
1922
|
+
cancel(jobId) {
|
|
1923
|
+
const job = this.jobs.get(jobId);
|
|
1924
|
+
if (!job) return false;
|
|
1925
|
+
if (job.status === "completed" || job.status === "failed" || job.status === "cancelled") {
|
|
1926
|
+
return false;
|
|
1927
|
+
}
|
|
1928
|
+
job.status = "cancelled";
|
|
1929
|
+
job.abortController.abort();
|
|
1930
|
+
return true;
|
|
1931
|
+
}
|
|
1932
|
+
getJob(jobId) {
|
|
1933
|
+
return this.jobs.get(jobId);
|
|
1934
|
+
}
|
|
1935
|
+
/**
|
|
1936
|
+
* Dispatches a single command through the KrnlQ worker boundary.
|
|
1937
|
+
*/
|
|
1938
|
+
async executeCommand(command, handler) {
|
|
1939
|
+
if (command.idempotencyKey && this.idempotencyStore.has(command.idempotencyKey)) {
|
|
1940
|
+
return this.idempotencyStore.get(command.idempotencyKey);
|
|
1941
|
+
}
|
|
1942
|
+
try {
|
|
1943
|
+
const handle = this.enqueue({
|
|
1944
|
+
id: command.id,
|
|
1945
|
+
name: command.type,
|
|
1946
|
+
payload: command.payload,
|
|
1947
|
+
handler,
|
|
1948
|
+
options: {
|
|
1949
|
+
idempotencyKey: command.idempotencyKey,
|
|
1950
|
+
correlationId: command.correlationId
|
|
1951
|
+
}
|
|
1952
|
+
});
|
|
1953
|
+
const data = await handle.result();
|
|
1954
|
+
const res = {
|
|
1955
|
+
correlationId: command.correlationId,
|
|
1956
|
+
status: "COMPLETED",
|
|
1957
|
+
data,
|
|
1958
|
+
executionTimestamp: Date.now()
|
|
1959
|
+
};
|
|
1960
|
+
return res;
|
|
1961
|
+
} catch (err) {
|
|
1962
|
+
const isAbort = err?.name === "AbortError" || err?.message === "The operation was aborted";
|
|
1963
|
+
const res = {
|
|
1964
|
+
correlationId: command.correlationId,
|
|
1965
|
+
status: isAbort ? "CANCELLED" : "FAILED",
|
|
1966
|
+
error: err?.message || String(err),
|
|
1967
|
+
executionTimestamp: Date.now()
|
|
1968
|
+
};
|
|
1969
|
+
return res;
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
/**
|
|
1973
|
+
* Executes a full Canonical Orchestration DAG through KrnlQ and worker boundary.
|
|
1974
|
+
* This is a first-class queued job scheduled via this.enqueue() to respect concurrency and worker limits.
|
|
1975
|
+
*/
|
|
1976
|
+
async executeOrchestration(descriptor, steps, input, options = {}) {
|
|
1977
|
+
const startedAt = Date.now();
|
|
1978
|
+
const correlationId = options.correlationId || generateSecureId("corr");
|
|
1979
|
+
const executionId = generateSecureId("exec");
|
|
1980
|
+
if (options.idempotencyKey && this.idempotencyStore.has(options.idempotencyKey)) {
|
|
1981
|
+
const cached = this.idempotencyStore.get(options.idempotencyKey);
|
|
1982
|
+
return cached.data;
|
|
1983
|
+
}
|
|
1984
|
+
const validation = validateOrchestrationDAG(steps);
|
|
1985
|
+
if (!validation.valid) {
|
|
1986
|
+
return {
|
|
1987
|
+
orchestrationId: descriptor.id,
|
|
1988
|
+
correlationId,
|
|
1989
|
+
status: "FAILED",
|
|
1990
|
+
stepResults: {},
|
|
1991
|
+
error: `Invalid DAG: ${validation.errors.join("; ")}`,
|
|
1992
|
+
startedAt,
|
|
1993
|
+
completedAt: Date.now(),
|
|
1994
|
+
executionMetadata: { validationErrors: validation.errors }
|
|
1995
|
+
};
|
|
1996
|
+
}
|
|
1997
|
+
const abortController = new AbortController();
|
|
1998
|
+
if (options.abortSignal) {
|
|
1999
|
+
if (options.abortSignal.aborted) {
|
|
2000
|
+
abortController.abort();
|
|
2001
|
+
} else {
|
|
2002
|
+
options.abortSignal.addEventListener("abort", () => abortController.abort(), { once: true });
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
const context = {
|
|
2006
|
+
correlationId,
|
|
2007
|
+
parentCorrelationId: options.parentCorrelationId,
|
|
2008
|
+
orchestrationId: descriptor.id,
|
|
2009
|
+
executionId,
|
|
2010
|
+
idempotencyKey: options.idempotencyKey,
|
|
2011
|
+
scope: descriptor.scope || "functionality",
|
|
2012
|
+
results: { input },
|
|
2013
|
+
metadata: { ...options.metadata },
|
|
2014
|
+
timestamp: startedAt,
|
|
2015
|
+
isCancelled: abortController.signal.aborted,
|
|
2016
|
+
abortSignal: abortController.signal
|
|
2017
|
+
};
|
|
2018
|
+
abortController.signal.addEventListener("abort", () => {
|
|
2019
|
+
context.isCancelled = true;
|
|
2020
|
+
});
|
|
2021
|
+
this.activeOrchestrations.set(executionId, { abortController, context });
|
|
2022
|
+
const handle = this.enqueue({
|
|
2023
|
+
id: executionId,
|
|
2024
|
+
name: descriptor.name || descriptor.id,
|
|
2025
|
+
payload: input,
|
|
2026
|
+
options: {
|
|
2027
|
+
idempotencyKey: options.idempotencyKey,
|
|
2028
|
+
correlationId,
|
|
2029
|
+
metadata: options.metadata,
|
|
2030
|
+
abortSignal: abortController.signal
|
|
2031
|
+
},
|
|
2032
|
+
handler: async () => {
|
|
2033
|
+
const timeoutMs = options.timeoutMs || descriptor.timeoutMs;
|
|
2034
|
+
let timeoutTimer;
|
|
2035
|
+
let isWorkflowTimeout = false;
|
|
2036
|
+
if (timeoutMs && timeoutMs > 0) {
|
|
2037
|
+
timeoutTimer = setTimeout(() => {
|
|
2038
|
+
isWorkflowTimeout = true;
|
|
2039
|
+
context.isCancelled = true;
|
|
2040
|
+
abortController.abort();
|
|
2041
|
+
}, timeoutMs);
|
|
2042
|
+
}
|
|
2043
|
+
const stepResults = {};
|
|
2044
|
+
const executedSteps = /* @__PURE__ */ new Set();
|
|
2045
|
+
const executedComps = [];
|
|
2046
|
+
let finalOutput = void 0;
|
|
2047
|
+
let orchestrationStatus = "COMPLETED";
|
|
2048
|
+
let errorMessage;
|
|
2049
|
+
try {
|
|
2050
|
+
while (executedSteps.size < steps.length) {
|
|
2051
|
+
if (context.isCancelled) {
|
|
2052
|
+
orchestrationStatus = "CANCELLED";
|
|
2053
|
+
errorMessage = "Orchestration execution cancelled.";
|
|
2054
|
+
break;
|
|
2055
|
+
}
|
|
2056
|
+
const readySteps = steps.filter((step) => {
|
|
2057
|
+
if (executedSteps.has(step.id)) return false;
|
|
2058
|
+
if (!step.dependsOn || step.dependsOn.length === 0) return true;
|
|
2059
|
+
return step.dependsOn.every((dep) => executedSteps.has(dep));
|
|
2060
|
+
});
|
|
2061
|
+
if (readySteps.length === 0) {
|
|
2062
|
+
break;
|
|
2063
|
+
}
|
|
2064
|
+
const batch = readySteps.slice(0, this.concurrency);
|
|
2065
|
+
const batchPromises = batch.map(async (step) => {
|
|
2066
|
+
const stepRes = await this.executeSingleStep(step, context, options.nestedRunner);
|
|
2067
|
+
stepResults[step.id] = stepRes;
|
|
2068
|
+
executedSteps.add(step.id);
|
|
2069
|
+
if (stepRes.status === "COMPLETED") {
|
|
2070
|
+
context.results[step.id] = stepRes.output;
|
|
2071
|
+
finalOutput = stepRes.output;
|
|
2072
|
+
if (step.compensation?.handler) {
|
|
2073
|
+
executedComps.push(() => step.compensation.handler(context));
|
|
2074
|
+
}
|
|
2075
|
+
} else if (stepRes.status === "SKIPPED") {
|
|
2076
|
+
} else if (stepRes.status === "CANCELLED") {
|
|
2077
|
+
const cancelErr = new Error("The operation was aborted");
|
|
2078
|
+
cancelErr.name = "AbortError";
|
|
2079
|
+
throw cancelErr;
|
|
2080
|
+
} else {
|
|
2081
|
+
throw new Error(stepRes.error || `Step "${step.id}" failed with status ${stepRes.status}`);
|
|
2082
|
+
}
|
|
2083
|
+
});
|
|
2084
|
+
await Promise.all(batchPromises);
|
|
2085
|
+
}
|
|
2086
|
+
} catch (err) {
|
|
2087
|
+
const isExplicitStepFailure = err && err.name !== "AbortError" && err.message !== "The operation was aborted";
|
|
2088
|
+
const wasCancelled = (context.isCancelled || abortController.signal.aborted || err?.name === "AbortError") && !isExplicitStepFailure;
|
|
2089
|
+
if (isWorkflowTimeout) {
|
|
2090
|
+
orchestrationStatus = "TIMED_OUT";
|
|
2091
|
+
errorMessage = `Orchestration timed out after ${timeoutMs}ms.`;
|
|
2092
|
+
} else if (isExplicitStepFailure) {
|
|
2093
|
+
orchestrationStatus = "FAILED";
|
|
2094
|
+
errorMessage = err?.message || String(err);
|
|
2095
|
+
} else if (wasCancelled) {
|
|
2096
|
+
orchestrationStatus = "CANCELLED";
|
|
2097
|
+
errorMessage = "The operation was aborted";
|
|
2098
|
+
} else {
|
|
2099
|
+
orchestrationStatus = "FAILED";
|
|
2100
|
+
errorMessage = err?.message || String(err);
|
|
2101
|
+
}
|
|
2102
|
+
if (executedComps.length > 0) {
|
|
2103
|
+
for (let i = executedComps.length - 1; i >= 0; i--) {
|
|
2104
|
+
try {
|
|
2105
|
+
await executedComps[i]();
|
|
2106
|
+
} catch (compErr) {
|
|
2107
|
+
console.error(`[KrnlQ] Compensation failed:`, compErr);
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
} finally {
|
|
2112
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
2113
|
+
this.activeOrchestrations.delete(executionId);
|
|
2114
|
+
}
|
|
2115
|
+
const result = {
|
|
2116
|
+
orchestrationId: descriptor.id,
|
|
2117
|
+
correlationId,
|
|
2118
|
+
status: orchestrationStatus,
|
|
2119
|
+
output: finalOutput,
|
|
2120
|
+
stepResults,
|
|
2121
|
+
error: errorMessage,
|
|
2122
|
+
startedAt,
|
|
2123
|
+
completedAt: Date.now(),
|
|
2124
|
+
executionMetadata: {
|
|
2125
|
+
executionId,
|
|
2126
|
+
scope: descriptor.scope,
|
|
2127
|
+
stepsCount: steps.length,
|
|
2128
|
+
executedCount: executedSteps.size
|
|
2129
|
+
}
|
|
2130
|
+
};
|
|
2131
|
+
if (options.idempotencyKey) {
|
|
2132
|
+
this.idempotencyStore.set(options.idempotencyKey, {
|
|
2133
|
+
correlationId,
|
|
2134
|
+
status: orchestrationStatus === "COMPLETED" ? "COMPLETED" : "FAILED",
|
|
2135
|
+
data: result,
|
|
2136
|
+
executionTimestamp: Date.now()
|
|
2137
|
+
});
|
|
2138
|
+
}
|
|
2139
|
+
return result;
|
|
2140
|
+
}
|
|
2141
|
+
});
|
|
2142
|
+
return await handle.result();
|
|
2143
|
+
}
|
|
2144
|
+
async executeSingleStep(step, context, nestedRunner) {
|
|
2145
|
+
const stepStart = Date.now();
|
|
2146
|
+
let attempts = 0;
|
|
2147
|
+
const maxAttempts = step.retryPolicy?.maxAttempts ?? 1;
|
|
2148
|
+
if (step.condition) {
|
|
2149
|
+
try {
|
|
2150
|
+
const conditionPass = await step.condition(context);
|
|
2151
|
+
if (!conditionPass) {
|
|
2152
|
+
return {
|
|
2153
|
+
stepId: step.id,
|
|
2154
|
+
status: "SKIPPED",
|
|
2155
|
+
attempts: 0,
|
|
2156
|
+
startedAt: stepStart,
|
|
2157
|
+
completedAt: Date.now()
|
|
2158
|
+
};
|
|
2159
|
+
}
|
|
2160
|
+
} catch (condErr) {
|
|
2161
|
+
return {
|
|
2162
|
+
stepId: step.id,
|
|
2163
|
+
status: "FAILED",
|
|
2164
|
+
attempts: 1,
|
|
2165
|
+
error: `Condition evaluation failed: ${condErr?.message || String(condErr)}`,
|
|
2166
|
+
startedAt: stepStart,
|
|
2167
|
+
completedAt: Date.now()
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
let lastError;
|
|
2172
|
+
let stepCancelled = false;
|
|
2173
|
+
const stepTimeoutMs = step.timeoutPolicy?.timeoutMs;
|
|
2174
|
+
while (attempts < maxAttempts) {
|
|
2175
|
+
if (context.isCancelled) {
|
|
2176
|
+
return {
|
|
2177
|
+
stepId: step.id,
|
|
2178
|
+
status: "CANCELLED",
|
|
2179
|
+
attempts,
|
|
2180
|
+
startedAt: stepStart,
|
|
2181
|
+
completedAt: Date.now()
|
|
2182
|
+
};
|
|
2183
|
+
}
|
|
2184
|
+
attempts++;
|
|
2185
|
+
const stepAbortController = new AbortController();
|
|
2186
|
+
if (context.abortSignal) {
|
|
2187
|
+
if (context.abortSignal.aborted) {
|
|
2188
|
+
stepAbortController.abort();
|
|
2189
|
+
} else {
|
|
2190
|
+
context.abortSignal.addEventListener("abort", () => stepAbortController.abort(), { once: true });
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
const stepContext = {
|
|
2194
|
+
...context,
|
|
2195
|
+
abortSignal: stepAbortController.signal
|
|
2196
|
+
};
|
|
2197
|
+
try {
|
|
2198
|
+
let stepOutput;
|
|
2199
|
+
let stepTimer;
|
|
2200
|
+
stepCancelled = false;
|
|
2201
|
+
const runPromise = (async () => {
|
|
2202
|
+
if (step.type === "nested" && step.nestedOrchestrationId && nestedRunner) {
|
|
2203
|
+
const childContext = {
|
|
2204
|
+
...stepContext,
|
|
2205
|
+
parentCorrelationId: context.correlationId,
|
|
2206
|
+
correlationId: `${context.correlationId}.${step.id}`
|
|
2207
|
+
};
|
|
2208
|
+
return await nestedRunner(step.nestedOrchestrationId, context.results, childContext);
|
|
2209
|
+
}
|
|
2210
|
+
if (step.type === "fanOut" && step.getItems) {
|
|
2211
|
+
const items = await step.getItems(stepContext);
|
|
2212
|
+
if (!Array.isArray(items)) throw new Error(`[fanOut] getItems must return an array.`);
|
|
2213
|
+
const concurrency = step.concurrency || 5;
|
|
2214
|
+
const results = [];
|
|
2215
|
+
for (let i = 0; i < items.length; i += concurrency) {
|
|
2216
|
+
const slice = items.slice(i, i + concurrency);
|
|
2217
|
+
const sliceRes = await Promise.all(
|
|
2218
|
+
slice.map((item) => step.handler ? step.handler(item, stepContext) : Promise.resolve(item))
|
|
2219
|
+
);
|
|
2220
|
+
results.push(...sliceRes);
|
|
2221
|
+
}
|
|
2222
|
+
return results;
|
|
2223
|
+
}
|
|
2224
|
+
if (step.handler) {
|
|
2225
|
+
return await step.handler(context.results, stepContext);
|
|
2226
|
+
}
|
|
2227
|
+
return context.results;
|
|
2228
|
+
})();
|
|
2229
|
+
const abortPromise = new Promise((_, reject) => {
|
|
2230
|
+
if (stepAbortController.signal.aborted || context.isCancelled) {
|
|
2231
|
+
const err = new Error("The operation was aborted");
|
|
2232
|
+
err.name = "AbortError";
|
|
2233
|
+
reject(err);
|
|
2234
|
+
}
|
|
2235
|
+
stepAbortController.signal.addEventListener("abort", () => {
|
|
2236
|
+
const err = new Error("The operation was aborted");
|
|
2237
|
+
err.name = "AbortError";
|
|
2238
|
+
reject(err);
|
|
2239
|
+
});
|
|
2240
|
+
});
|
|
2241
|
+
const promisesToRace = [runPromise, abortPromise];
|
|
2242
|
+
if (stepTimeoutMs && stepTimeoutMs > 0) {
|
|
2243
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
2244
|
+
stepTimer = setTimeout(() => {
|
|
2245
|
+
stepCancelled = true;
|
|
2246
|
+
const tErr = new Error(`Step "${step.id}" timed out after ${stepTimeoutMs}ms.`);
|
|
2247
|
+
tErr.name = "TimeoutError";
|
|
2248
|
+
reject(tErr);
|
|
2249
|
+
}, stepTimeoutMs);
|
|
2250
|
+
});
|
|
2251
|
+
promisesToRace.push(timeoutPromise);
|
|
2252
|
+
}
|
|
2253
|
+
stepOutput = await Promise.race(promisesToRace);
|
|
2254
|
+
if (stepTimer) clearTimeout(stepTimer);
|
|
2255
|
+
return {
|
|
2256
|
+
stepId: step.id,
|
|
2257
|
+
status: "COMPLETED",
|
|
2258
|
+
attempts,
|
|
2259
|
+
output: stepOutput,
|
|
2260
|
+
startedAt: stepStart,
|
|
2261
|
+
completedAt: Date.now()
|
|
2262
|
+
};
|
|
2263
|
+
} catch (err) {
|
|
2264
|
+
if (stepCancelled || err?.name === "TimeoutError") {
|
|
2265
|
+
return {
|
|
2266
|
+
stepId: step.id,
|
|
2267
|
+
status: "TIMED_OUT",
|
|
2268
|
+
attempts,
|
|
2269
|
+
error: err?.message || `Step "${step.id}" timed out after ${stepTimeoutMs}ms.`,
|
|
2270
|
+
startedAt: stepStart,
|
|
2271
|
+
completedAt: Date.now()
|
|
2272
|
+
};
|
|
2273
|
+
}
|
|
2274
|
+
if (context.isCancelled || context.abortSignal?.aborted || err?.name === "AbortError" || err?.message === "Operation cancelled" || err?.message === "The operation was aborted") {
|
|
2275
|
+
return {
|
|
2276
|
+
stepId: step.id,
|
|
2277
|
+
status: "CANCELLED",
|
|
2278
|
+
attempts,
|
|
2279
|
+
startedAt: stepStart,
|
|
2280
|
+
completedAt: Date.now()
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
lastError = err;
|
|
2284
|
+
if (step.catchHandler && attempts >= maxAttempts) {
|
|
2285
|
+
try {
|
|
2286
|
+
const recovered = await step.catchHandler(err, stepContext);
|
|
2287
|
+
return {
|
|
2288
|
+
stepId: step.id,
|
|
2289
|
+
status: "COMPLETED",
|
|
2290
|
+
attempts,
|
|
2291
|
+
output: recovered,
|
|
2292
|
+
startedAt: stepStart,
|
|
2293
|
+
completedAt: Date.now()
|
|
2294
|
+
};
|
|
2295
|
+
} catch (catchErr) {
|
|
2296
|
+
lastError = catchErr;
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
if (attempts < maxAttempts && step.retryPolicy) {
|
|
2300
|
+
const backoffDelay = this.computeBackoff(step.retryPolicy, attempts);
|
|
2301
|
+
await new Promise((r) => setTimeout(r, backoffDelay));
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
}
|
|
2305
|
+
return {
|
|
2306
|
+
stepId: step.id,
|
|
2307
|
+
status: "FAILED",
|
|
2308
|
+
attempts,
|
|
2309
|
+
error: lastError?.message || String(lastError),
|
|
2310
|
+
startedAt: stepStart,
|
|
2311
|
+
completedAt: Date.now()
|
|
2312
|
+
};
|
|
2313
|
+
}
|
|
2314
|
+
computeBackoff(policy, attempt) {
|
|
2315
|
+
const base = policy.backoffMs || 100;
|
|
2316
|
+
let delay;
|
|
2317
|
+
if (policy.backoff === "exponential") {
|
|
2318
|
+
delay = base * Math.pow(2, attempt - 1);
|
|
2319
|
+
} else {
|
|
2320
|
+
delay = base * attempt;
|
|
123
2321
|
}
|
|
2322
|
+
if (policy.maxBackoffMs && delay > policy.maxBackoffMs) {
|
|
2323
|
+
delay = policy.maxBackoffMs;
|
|
2324
|
+
}
|
|
2325
|
+
if (policy.jitter) {
|
|
2326
|
+
delay += Math.floor(Math.random() * (base * 0.5));
|
|
2327
|
+
}
|
|
2328
|
+
return delay;
|
|
2329
|
+
}
|
|
2330
|
+
cancelExecution(executionId) {
|
|
2331
|
+
const active = this.activeOrchestrations.get(executionId);
|
|
2332
|
+
if (active) {
|
|
2333
|
+
active.context.isCancelled = true;
|
|
2334
|
+
active.abortController.abort();
|
|
2335
|
+
return true;
|
|
2336
|
+
}
|
|
2337
|
+
return false;
|
|
124
2338
|
}
|
|
125
2339
|
};
|
|
126
2340
|
|
|
127
|
-
// src/services/
|
|
128
|
-
var
|
|
129
|
-
constructor(definition) {
|
|
130
|
-
this.definition = definition;
|
|
131
|
-
this.id = definition.id;
|
|
132
|
-
this.name = definition.name;
|
|
133
|
-
this.version = definition.version;
|
|
134
|
-
this.lifecycle = new LifecycleManager();
|
|
135
|
-
this.eventBus = new ServiceEventBus();
|
|
136
|
-
if (definition.state?.initial) {
|
|
137
|
-
this.stateStore = new ServiceStateStore(definition.state.initial);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
definition;
|
|
2341
|
+
// src/services/ServiceFacade.ts
|
|
2342
|
+
var ServiceFacade = class {
|
|
141
2343
|
id;
|
|
142
2344
|
name;
|
|
143
2345
|
version;
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
2346
|
+
description;
|
|
2347
|
+
functionalities;
|
|
2348
|
+
functionalityOrchestrations;
|
|
2349
|
+
libraries;
|
|
2350
|
+
dependencies;
|
|
2351
|
+
capabilities;
|
|
2352
|
+
defaultFrontend;
|
|
2353
|
+
instance;
|
|
2354
|
+
queue;
|
|
2355
|
+
constructor(config) {
|
|
2356
|
+
if (!config || !config.id || typeof config.id !== "string") {
|
|
2357
|
+
throw new Error("[ServiceFacade] ServiceFacade requires a valid id.");
|
|
154
2358
|
}
|
|
155
|
-
|
|
156
|
-
|
|
2359
|
+
this.id = config.id;
|
|
2360
|
+
this.name = config.name || config.id;
|
|
2361
|
+
this.version = config.version || "1.0.0";
|
|
2362
|
+
this.description = config.description || "";
|
|
2363
|
+
this.functionalities = config.functionalities ? { ...config.functionalities } : {};
|
|
2364
|
+
this.functionalityOrchestrations = config.functionalityOrchestrations ? { ...config.functionalityOrchestrations } : config.orchestrations ? { ...config.orchestrations } : {};
|
|
2365
|
+
this.libraries = config.libraries ? { ...config.libraries } : {};
|
|
2366
|
+
this.dependencies = Object.freeze(config.dependencies ? [...config.dependencies] : []);
|
|
2367
|
+
this.capabilities = Object.freeze(config.capabilities ? [...config.capabilities] : []);
|
|
2368
|
+
this.defaultFrontend = config.defaultFrontend ? Object.freeze({ ...config.defaultFrontend }) : void 0;
|
|
2369
|
+
if (config.instance) {
|
|
2370
|
+
this.instance = config.instance;
|
|
2371
|
+
} else if (config.definition) {
|
|
2372
|
+
this.instance = new ServiceInstance(config.definition);
|
|
2373
|
+
} else {
|
|
2374
|
+
this.instance = new ServiceInstance({
|
|
2375
|
+
id: this.id,
|
|
2376
|
+
name: this.name,
|
|
2377
|
+
version: this.version,
|
|
2378
|
+
operations: {}
|
|
2379
|
+
});
|
|
157
2380
|
}
|
|
158
|
-
this.
|
|
2381
|
+
this.queue = new KrnlQueue({
|
|
2382
|
+
queueName: `krnl_queue_${this.id}`,
|
|
2383
|
+
concurrency: config.concurrency ?? config.queueOptions?.concurrency ?? 10,
|
|
2384
|
+
autoStart: config.queueOptions?.autoStart ?? true
|
|
2385
|
+
});
|
|
2386
|
+
}
|
|
2387
|
+
get orchestrations() {
|
|
2388
|
+
return this.functionalityOrchestrations;
|
|
2389
|
+
}
|
|
2390
|
+
getInstance() {
|
|
2391
|
+
return this.instance;
|
|
2392
|
+
}
|
|
2393
|
+
getQueue() {
|
|
2394
|
+
return this.queue;
|
|
2395
|
+
}
|
|
2396
|
+
getExecutionEngine() {
|
|
2397
|
+
return this.queue;
|
|
2398
|
+
}
|
|
2399
|
+
getWorkerBoundary() {
|
|
2400
|
+
return this.queue.getWorkerBoundary();
|
|
2401
|
+
}
|
|
2402
|
+
getStatus() {
|
|
2403
|
+
return this.instance.getStatus();
|
|
2404
|
+
}
|
|
2405
|
+
async start() {
|
|
2406
|
+
await this.instance.start();
|
|
2407
|
+
await this.queue.start();
|
|
159
2408
|
}
|
|
160
2409
|
async stop() {
|
|
161
|
-
this.
|
|
162
|
-
|
|
163
|
-
|
|
2410
|
+
await this.queue.stop();
|
|
2411
|
+
await this.instance.stop();
|
|
2412
|
+
}
|
|
2413
|
+
async dispose() {
|
|
2414
|
+
await this.queue.dispose();
|
|
2415
|
+
await this.instance.dispose();
|
|
2416
|
+
}
|
|
2417
|
+
/**
|
|
2418
|
+
* External caller callable boundary for single functionality / operation execution.
|
|
2419
|
+
* Path: External Caller -> Service Facade -> KrnlQ Job -> Worker -> Functionality -> Result.
|
|
2420
|
+
* Strictly avoids synchronous unmediated execution outside the queue.
|
|
2421
|
+
*/
|
|
2422
|
+
async call(op, input, ctx) {
|
|
2423
|
+
const correlationId = ctx?.correlationId || `corr_${Math.random().toString(36).substring(2, 11)}`;
|
|
2424
|
+
const commandId = `cmd_${this.id}_${op}_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
|
|
2425
|
+
const command = {
|
|
2426
|
+
id: commandId,
|
|
2427
|
+
type: `${this.id}.${op}`,
|
|
2428
|
+
payload: input ?? {},
|
|
2429
|
+
correlationId,
|
|
2430
|
+
idempotencyKey: ctx?.idempotencyKey,
|
|
2431
|
+
createdAt: Date.now()
|
|
2432
|
+
};
|
|
2433
|
+
const result = await this.queue.executeCommand(command, async (payload, workerCtx) => {
|
|
2434
|
+
WorkerExecutionBoundary.assertWorkerContext(workerCtx);
|
|
2435
|
+
if (this.functionalities[op] && typeof this.functionalities[op].execute === "function") {
|
|
2436
|
+
return await this.functionalities[op].execute(payload, {
|
|
2437
|
+
correlationId: workerCtx.correlationId,
|
|
2438
|
+
state: this.instance.getState()
|
|
2439
|
+
});
|
|
2440
|
+
}
|
|
2441
|
+
return await this.instance.call(op, payload, {
|
|
2442
|
+
correlationId: workerCtx.correlationId,
|
|
2443
|
+
idempotencyKey: command.idempotencyKey
|
|
2444
|
+
});
|
|
2445
|
+
});
|
|
2446
|
+
if (result.status === "FAILED") {
|
|
2447
|
+
throw new Error(result.error || `[ServiceFacade:${this.id}] Operation '${op}' execution failed.`);
|
|
2448
|
+
}
|
|
2449
|
+
return result.data;
|
|
2450
|
+
}
|
|
2451
|
+
/**
|
|
2452
|
+
* External caller callable boundary for functionality orchestration execution.
|
|
2453
|
+
* Path: External Caller -> Service Facade -> KrnlQ Command -> Worker -> FunctionalityOrchestration -> Result.
|
|
2454
|
+
*/
|
|
2455
|
+
async orchestrate(orchestrationName, input, options = {}) {
|
|
2456
|
+
const orch = this.functionalityOrchestrations[orchestrationName];
|
|
2457
|
+
if (!orch) {
|
|
2458
|
+
throw new Error(
|
|
2459
|
+
`[ServiceFacade:${this.id}] FunctionalityOrchestration "${orchestrationName}" not found.`
|
|
2460
|
+
);
|
|
164
2461
|
}
|
|
165
|
-
|
|
166
|
-
|
|
2462
|
+
const correlationId = options.correlationId || `corr_${Math.random().toString(36).substring(2, 11)}`;
|
|
2463
|
+
const commandId = `cmd_orch_${this.id}_${orchestrationName}_${Date.now()}`;
|
|
2464
|
+
const command = {
|
|
2465
|
+
id: commandId,
|
|
2466
|
+
type: `${this.id}.orchestrations.${orchestrationName}`,
|
|
2467
|
+
payload: input ?? {},
|
|
2468
|
+
correlationId,
|
|
2469
|
+
idempotencyKey: options.idempotencyKey,
|
|
2470
|
+
createdAt: Date.now()
|
|
2471
|
+
};
|
|
2472
|
+
const cmdResult = await this.queue.executeCommand(
|
|
2473
|
+
command,
|
|
2474
|
+
async (payload, workerCtx) => {
|
|
2475
|
+
WorkerExecutionBoundary.assertWorkerContext(workerCtx);
|
|
2476
|
+
const resolveStepInput = (step, results) => {
|
|
2477
|
+
const deps = step.dependsOn;
|
|
2478
|
+
if (!deps || deps.length === 0) {
|
|
2479
|
+
return results["input"];
|
|
2480
|
+
}
|
|
2481
|
+
if (deps.length === 1) {
|
|
2482
|
+
const depRes = results[deps[0]];
|
|
2483
|
+
const initialInput = results["input"];
|
|
2484
|
+
if (typeof depRes === "object" && depRes !== null && typeof initialInput === "object" && initialInput !== null && !Array.isArray(depRes) && !Array.isArray(initialInput)) {
|
|
2485
|
+
return { ...initialInput, ...depRes };
|
|
2486
|
+
}
|
|
2487
|
+
return depRes !== void 0 ? depRes : results["input"];
|
|
2488
|
+
}
|
|
2489
|
+
const joined = {};
|
|
2490
|
+
for (const dep of deps) {
|
|
2491
|
+
joined[dep] = results[dep];
|
|
2492
|
+
}
|
|
2493
|
+
return joined;
|
|
2494
|
+
};
|
|
2495
|
+
const rawSteps = orch.getSteps();
|
|
2496
|
+
const boundSteps = rawSteps.map((s) => {
|
|
2497
|
+
let compensation = s.compensation;
|
|
2498
|
+
if (s.compensation?.target && !s.compensation.handler) {
|
|
2499
|
+
compensation = {
|
|
2500
|
+
...s.compensation,
|
|
2501
|
+
handler: async (compCtx) => {
|
|
2502
|
+
await this.call(s.compensation.target, compCtx.results[s.id], {
|
|
2503
|
+
correlationId: compCtx.correlationId
|
|
2504
|
+
});
|
|
2505
|
+
}
|
|
2506
|
+
};
|
|
2507
|
+
}
|
|
2508
|
+
if (s.type === "task" && s.target) {
|
|
2509
|
+
return {
|
|
2510
|
+
...s,
|
|
2511
|
+
compensation,
|
|
2512
|
+
handler: async (_stepInput, stepCtx) => {
|
|
2513
|
+
const resolvedInput = resolveStepInput(s, stepCtx.results);
|
|
2514
|
+
const stepPayload = typeof resolvedInput === "object" && resolvedInput !== null && !Array.isArray(resolvedInput) ? { ...stepCtx.results, ...resolvedInput } : { ...stepCtx.results };
|
|
2515
|
+
if (stepCtx.results.input) {
|
|
2516
|
+
stepPayload.input = stepCtx.results.input;
|
|
2517
|
+
}
|
|
2518
|
+
return await this.call(s.target, stepPayload, {
|
|
2519
|
+
correlationId: stepCtx.correlationId
|
|
2520
|
+
});
|
|
2521
|
+
}
|
|
2522
|
+
};
|
|
2523
|
+
}
|
|
2524
|
+
return {
|
|
2525
|
+
...s,
|
|
2526
|
+
compensation
|
|
2527
|
+
};
|
|
2528
|
+
});
|
|
2529
|
+
const nestedRunner = async (childOrchId, childInput, childCtx) => {
|
|
2530
|
+
const childOrch = this.functionalityOrchestrations[childOrchId];
|
|
2531
|
+
if (!childOrch) {
|
|
2532
|
+
throw new Error(
|
|
2533
|
+
`[ServiceFacade:${this.id}] Nested FunctionalityOrchestration "${childOrchId}" not found in service.`
|
|
2534
|
+
);
|
|
2535
|
+
}
|
|
2536
|
+
const nestedResult = await this.orchestrate(childOrchId, childInput, {
|
|
2537
|
+
correlationId: childCtx.correlationId,
|
|
2538
|
+
timeoutMs: childOrch.timeoutMs,
|
|
2539
|
+
abortSignal: options.abortSignal
|
|
2540
|
+
});
|
|
2541
|
+
if (nestedResult.status !== "COMPLETED") {
|
|
2542
|
+
throw new Error(nestedResult.error || `Nested orchestration "${childOrchId}" failed.`);
|
|
2543
|
+
}
|
|
2544
|
+
return nestedResult.output;
|
|
2545
|
+
};
|
|
2546
|
+
return await this.queue.executeOrchestration(
|
|
2547
|
+
{ id: orch.id, name: orch.name, version: orch.version, timeoutMs: orch.timeoutMs, scope: "functionality" },
|
|
2548
|
+
boundSteps,
|
|
2549
|
+
payload,
|
|
2550
|
+
{
|
|
2551
|
+
correlationId: workerCtx.correlationId,
|
|
2552
|
+
idempotencyKey: command.idempotencyKey,
|
|
2553
|
+
timeoutMs: options.timeoutMs || orch.timeoutMs,
|
|
2554
|
+
metadata: options.metadata,
|
|
2555
|
+
nestedRunner,
|
|
2556
|
+
abortSignal: options.abortSignal
|
|
2557
|
+
}
|
|
2558
|
+
);
|
|
2559
|
+
}
|
|
2560
|
+
);
|
|
2561
|
+
if (cmdResult.status === "FAILED") {
|
|
2562
|
+
throw new Error(cmdResult.error || `[ServiceFacade:${this.id}] Orchestration failed.`);
|
|
167
2563
|
}
|
|
168
|
-
|
|
2564
|
+
return cmdResult.data;
|
|
169
2565
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
2566
|
+
/**
|
|
2567
|
+
* Executes a callable operation or orchestration through KrnlQ and worker boundary.
|
|
2568
|
+
* Path: External Caller -> Service Facade -> KrnlQ Command -> Worker -> Functionality / Orchestration -> Result.
|
|
2569
|
+
* Strictly queue-mediated; zero unmediated bypasses.
|
|
2570
|
+
*/
|
|
2571
|
+
async execute(target, input, options) {
|
|
2572
|
+
if (this.functionalityOrchestrations[target]) {
|
|
2573
|
+
const res = await this.orchestrate(target, input, options);
|
|
2574
|
+
if (res.status === "FAILED") {
|
|
2575
|
+
throw new Error(res.error || `[ServiceFacade:${this.id}] Orchestration "${target}" failed.`);
|
|
2576
|
+
}
|
|
2577
|
+
return res;
|
|
175
2578
|
}
|
|
176
|
-
return
|
|
2579
|
+
return this.call(target, input, {
|
|
2580
|
+
correlationId: options?.correlationId,
|
|
2581
|
+
idempotencyKey: options?.idempotencyKey
|
|
2582
|
+
});
|
|
177
2583
|
}
|
|
178
2584
|
getState() {
|
|
179
|
-
|
|
180
|
-
return Object.freeze({});
|
|
181
|
-
}
|
|
182
|
-
return this.stateStore.getState();
|
|
2585
|
+
return this.instance.getState();
|
|
183
2586
|
}
|
|
184
2587
|
setState(mutation) {
|
|
185
|
-
|
|
186
|
-
this.stateStore = new ServiceStateStore(mutation);
|
|
187
|
-
return;
|
|
188
|
-
}
|
|
189
|
-
this.stateStore.setState(mutation);
|
|
2588
|
+
this.instance.setState(mutation);
|
|
190
2589
|
}
|
|
191
2590
|
on(event, handler) {
|
|
192
|
-
return this.
|
|
2591
|
+
return this.instance.on(event, handler);
|
|
193
2592
|
}
|
|
194
2593
|
emit(event, payload) {
|
|
195
|
-
this.
|
|
196
|
-
}
|
|
197
|
-
};
|
|
198
|
-
|
|
199
|
-
// src/services/ServiceProxy.ts
|
|
200
|
-
var ServiceProxy = class {
|
|
201
|
-
constructor(definition, adapter, endpoint) {
|
|
202
|
-
this.definition = definition;
|
|
203
|
-
this.adapter = adapter;
|
|
204
|
-
this.endpoint = endpoint;
|
|
205
|
-
this.id = definition.id;
|
|
206
|
-
this.name = definition.name;
|
|
207
|
-
this.version = definition.version;
|
|
208
|
-
this.stateCache = definition.state?.initial || {};
|
|
2594
|
+
this.instance.emit(event, payload);
|
|
209
2595
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
stateCache;
|
|
217
|
-
eventHandlers = /* @__PURE__ */ new Map();
|
|
218
|
-
getDefinition() {
|
|
219
|
-
return this.definition;
|
|
2596
|
+
registerFunctionality(name, functionality) {
|
|
2597
|
+
if (!name || typeof name !== "string") {
|
|
2598
|
+
throw new Error("[ServiceFacade] Functionality name must be a non-empty string.");
|
|
2599
|
+
}
|
|
2600
|
+
this.functionalities[name] = functionality;
|
|
2601
|
+
return this;
|
|
220
2602
|
}
|
|
221
|
-
|
|
2603
|
+
registerFunctionalityOrchestration(name, orchestration) {
|
|
2604
|
+
if (!name || typeof name !== "string") {
|
|
2605
|
+
throw new Error("[ServiceFacade] FunctionalityOrchestration name must be a non-empty string.");
|
|
2606
|
+
}
|
|
2607
|
+
if (!orchestration) {
|
|
2608
|
+
throw new Error("[ServiceFacade] FunctionalityOrchestration instance is required.");
|
|
2609
|
+
}
|
|
2610
|
+
this.functionalityOrchestrations[name] = orchestration;
|
|
2611
|
+
return this;
|
|
222
2612
|
}
|
|
223
|
-
|
|
2613
|
+
/** @deprecated Use registerFunctionalityOrchestration */
|
|
2614
|
+
registerOrchestration(name, orchestration) {
|
|
2615
|
+
return this.registerFunctionalityOrchestration(name, orchestration);
|
|
224
2616
|
}
|
|
225
|
-
|
|
226
|
-
if (!
|
|
227
|
-
throw new Error(
|
|
2617
|
+
registerLibrary(name, library) {
|
|
2618
|
+
if (!name || typeof name !== "string") {
|
|
2619
|
+
throw new Error("[ServiceFacade] Library name must be a non-empty string.");
|
|
228
2620
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
type: "request",
|
|
232
|
-
operation: op,
|
|
233
|
-
payload: input,
|
|
234
|
-
timestamp: Date.now()
|
|
235
|
-
};
|
|
236
|
-
const response = await this.adapter.send(this.endpoint, envelope);
|
|
237
|
-
if (response.error) {
|
|
238
|
-
throw new Error(`[ServiceProxy:${this.name}] Remote error: ${response.error}`);
|
|
2621
|
+
if (library === void 0 || library === null) {
|
|
2622
|
+
throw new Error(`[ServiceFacade] Library "${name}" must not be null or undefined.`);
|
|
239
2623
|
}
|
|
240
|
-
|
|
2624
|
+
this.libraries[name] = library;
|
|
2625
|
+
return this;
|
|
241
2626
|
}
|
|
242
|
-
|
|
243
|
-
|
|
2627
|
+
getLibrary(name) {
|
|
2628
|
+
const lib = this.libraries[name];
|
|
2629
|
+
if (lib === void 0 || lib === null) {
|
|
2630
|
+
throw new Error(`[ServiceFacade:${this.id}] Library "${name}" not found on service facade.`);
|
|
2631
|
+
}
|
|
2632
|
+
return lib;
|
|
244
2633
|
}
|
|
245
|
-
|
|
246
|
-
|
|
2634
|
+
get namespace() {
|
|
2635
|
+
return this.getNamespace();
|
|
247
2636
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
this.
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
2637
|
+
getNamespace() {
|
|
2638
|
+
return {
|
|
2639
|
+
serviceId: this.id,
|
|
2640
|
+
serviceName: this.name,
|
|
2641
|
+
version: this.version,
|
|
2642
|
+
description: this.description,
|
|
2643
|
+
libraries: { ...this.libraries },
|
|
2644
|
+
functionalities: { ...this.functionalities },
|
|
2645
|
+
functionalityOrchestrations: { ...this.functionalityOrchestrations },
|
|
2646
|
+
capabilities: this.capabilities,
|
|
2647
|
+
dependencies: this.dependencies
|
|
256
2648
|
};
|
|
257
2649
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
if (handlers) {
|
|
261
|
-
for (const handler of Array.from(handlers)) {
|
|
262
|
-
handler(payload);
|
|
263
|
-
}
|
|
264
|
-
}
|
|
2650
|
+
getServiceFacadeMetadata() {
|
|
2651
|
+
return this.getNamespace();
|
|
265
2652
|
}
|
|
266
2653
|
};
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
function createServiceDefinition(definition) {
|
|
270
|
-
return definition;
|
|
271
|
-
}
|
|
272
|
-
function createService(definition) {
|
|
273
|
-
return new ServiceInstance(definition);
|
|
274
|
-
}
|
|
275
|
-
function createServiceProxy(definition, adapter, endpoint) {
|
|
276
|
-
return new ServiceProxy(definition, adapter, endpoint);
|
|
2654
|
+
function createServiceFacade(config) {
|
|
2655
|
+
return new ServiceFacade(config);
|
|
277
2656
|
}
|
|
278
2657
|
|
|
279
2658
|
// src/protocols/HttpProtocolAdapter.ts
|
|
@@ -451,10 +2830,14 @@ var WebSocketProtocolAdapter = class {
|
|
|
451
2830
|
};
|
|
452
2831
|
}
|
|
453
2832
|
async send(endpoint, envelope) {
|
|
454
|
-
let WS
|
|
455
|
-
|
|
2833
|
+
let WS;
|
|
2834
|
+
const isNode = Boolean(globalThis.process?.versions?.node);
|
|
2835
|
+
if (isNode) {
|
|
456
2836
|
const wsMod = await import("ws").catch(() => null);
|
|
457
|
-
WS = wsMod?.WebSocket || wsMod?.default?.WebSocket || wsMod;
|
|
2837
|
+
WS = wsMod?.WebSocket || wsMod?.default?.WebSocket || wsMod?.default || wsMod;
|
|
2838
|
+
}
|
|
2839
|
+
if (!WS) {
|
|
2840
|
+
WS = globalThis.WebSocket;
|
|
458
2841
|
}
|
|
459
2842
|
if (!WS) {
|
|
460
2843
|
throw new Error("No WebSocket client implementation available in this environment.");
|
|
@@ -660,23 +3043,74 @@ var MemoryTransport = class {
|
|
|
660
3043
|
};
|
|
661
3044
|
|
|
662
3045
|
// src/registry/ServiceRegistry.ts
|
|
3046
|
+
var PROTOCOLS = ["http", "https", "ws", "wss", "udp", "p2p", "signaling", "memory"];
|
|
3047
|
+
function validateEndpoint(endpoint) {
|
|
3048
|
+
if (!endpoint || typeof endpoint !== "object") throw new Error("[ServiceRegistry] Invalid endpoint.");
|
|
3049
|
+
if (!PROTOCOLS.includes(endpoint.protocol)) throw new Error("[ServiceRegistry] Unsupported endpoint protocol.");
|
|
3050
|
+
if (typeof endpoint.address !== "string" || endpoint.address.trim() === "") throw new Error("[ServiceRegistry] Endpoint address must be non-empty.");
|
|
3051
|
+
if (endpoint.port !== void 0 && (!Number.isInteger(endpoint.port) || endpoint.port < 0 || endpoint.port > 65535)) throw new Error("[ServiceRegistry] Endpoint port is invalid.");
|
|
3052
|
+
if (!Array.isArray(endpoint.capabilities)) throw new Error("[ServiceRegistry] Endpoint capabilities must be an array.");
|
|
3053
|
+
}
|
|
663
3054
|
var ServiceRegistry = class {
|
|
664
3055
|
services = /* @__PURE__ */ new Map();
|
|
3056
|
+
/**
|
|
3057
|
+
* Registers a service definition and its endpoints into the registry.
|
|
3058
|
+
*
|
|
3059
|
+
* @param definition Validated service definition.
|
|
3060
|
+
* @param endpoints Optional list of active endpoint descriptors.
|
|
3061
|
+
* @throws Error if definition or endpoints fail validation.
|
|
3062
|
+
* @throws Error if service is already registered under the same ID.
|
|
3063
|
+
*/
|
|
665
3064
|
register(definition, endpoints = []) {
|
|
3065
|
+
validateServiceDefinition(definition);
|
|
3066
|
+
for (const endpoint of endpoints) validateEndpoint(endpoint);
|
|
3067
|
+
const existing = this.services.get(definition.id);
|
|
3068
|
+
if (existing) {
|
|
3069
|
+
throw new Error(
|
|
3070
|
+
"[ServiceRegistry] Service '" + definition.id + "' is already registered at version '" + existing.definition.version + "'. Use replace() to explicitly replace an existing service."
|
|
3071
|
+
);
|
|
3072
|
+
}
|
|
666
3073
|
this.services.set(definition.id, {
|
|
667
3074
|
definition,
|
|
668
|
-
endpoints,
|
|
3075
|
+
endpoints: endpoints.map((endpoint) => ({ ...endpoint, capabilities: [...endpoint.capabilities] })),
|
|
669
3076
|
registeredAt: Date.now()
|
|
670
3077
|
});
|
|
671
3078
|
}
|
|
3079
|
+
/**
|
|
3080
|
+
* Explicitly replaces or updates a service definition and its endpoints in the registry.
|
|
3081
|
+
* Preserves original registeredAt timestamp if the service was previously registered.
|
|
3082
|
+
*
|
|
3083
|
+
* @param definition Validated service definition.
|
|
3084
|
+
* @param endpoints Optional list of active endpoint descriptors.
|
|
3085
|
+
*/
|
|
3086
|
+
replace(definition, endpoints = []) {
|
|
3087
|
+
validateServiceDefinition(definition);
|
|
3088
|
+
for (const endpoint of endpoints) validateEndpoint(endpoint);
|
|
3089
|
+
const existing = this.services.get(definition.id);
|
|
3090
|
+
this.services.set(definition.id, {
|
|
3091
|
+
definition,
|
|
3092
|
+
endpoints: endpoints.map((endpoint) => ({ ...endpoint, capabilities: [...endpoint.capabilities] })),
|
|
3093
|
+
registeredAt: existing?.registeredAt ?? Date.now()
|
|
3094
|
+
});
|
|
3095
|
+
}
|
|
672
3096
|
unregister(serviceId) {
|
|
673
|
-
this.services.delete(serviceId);
|
|
3097
|
+
return this.services.delete(serviceId);
|
|
674
3098
|
}
|
|
675
3099
|
get(serviceId) {
|
|
676
|
-
|
|
3100
|
+
const record = this.services.get(serviceId);
|
|
3101
|
+
if (!record) return void 0;
|
|
3102
|
+
return {
|
|
3103
|
+
definition: record.definition,
|
|
3104
|
+
endpoints: record.endpoints.map((endpoint) => ({ ...endpoint, capabilities: [...endpoint.capabilities] })),
|
|
3105
|
+
registeredAt: record.registeredAt
|
|
3106
|
+
};
|
|
677
3107
|
}
|
|
678
3108
|
list() {
|
|
679
|
-
return Array.from(this.services.values())
|
|
3109
|
+
return Array.from(this.services.values()).map((record) => ({
|
|
3110
|
+
definition: record.definition,
|
|
3111
|
+
endpoints: record.endpoints.map((endpoint) => ({ ...endpoint, capabilities: [...endpoint.capabilities] })),
|
|
3112
|
+
registeredAt: record.registeredAt
|
|
3113
|
+
}));
|
|
680
3114
|
}
|
|
681
3115
|
findByCapability(capabilityName) {
|
|
682
3116
|
return this.list().filter(
|
|
@@ -690,32 +3124,75 @@ var ServiceRuntime = class {
|
|
|
690
3124
|
instances = /* @__PURE__ */ new Map();
|
|
691
3125
|
registry;
|
|
692
3126
|
constructor(registry) {
|
|
693
|
-
this.registry = registry
|
|
3127
|
+
this.registry = registry ?? new ServiceRegistry();
|
|
694
3128
|
}
|
|
695
3129
|
register(service) {
|
|
696
|
-
this.instances.
|
|
3130
|
+
const existing = this.instances.get(service.id);
|
|
3131
|
+
if (existing && existing !== service) {
|
|
3132
|
+
throw new Error("[ServiceRuntime] Service '" + service.id + "' is already registered.");
|
|
3133
|
+
}
|
|
697
3134
|
this.registry.register(service.getDefinition());
|
|
3135
|
+
this.instances.set(service.id, service);
|
|
698
3136
|
return this;
|
|
699
3137
|
}
|
|
3138
|
+
unregister(serviceId) {
|
|
3139
|
+
const removed = this.instances.delete(serviceId);
|
|
3140
|
+
this.registry.unregister(serviceId);
|
|
3141
|
+
return removed;
|
|
3142
|
+
}
|
|
700
3143
|
get(serviceId) {
|
|
701
3144
|
return this.instances.get(serviceId);
|
|
702
3145
|
}
|
|
3146
|
+
list() {
|
|
3147
|
+
return Array.from(this.instances.values());
|
|
3148
|
+
}
|
|
703
3149
|
async execute(target, operation, input, ctx) {
|
|
704
3150
|
const service = this.instances.get(target);
|
|
705
3151
|
if (!service) {
|
|
706
|
-
throw new Error(
|
|
3152
|
+
throw new Error("[ServiceRuntime] Target service '" + target + "' not found.");
|
|
707
3153
|
}
|
|
708
|
-
return
|
|
3154
|
+
return service.call(operation, input, ctx);
|
|
709
3155
|
}
|
|
710
3156
|
async startAll() {
|
|
711
|
-
|
|
712
|
-
|
|
3157
|
+
const started = [];
|
|
3158
|
+
try {
|
|
3159
|
+
for (const service of this.instances.values()) {
|
|
3160
|
+
await service.start();
|
|
3161
|
+
started.push(service);
|
|
3162
|
+
}
|
|
3163
|
+
} catch (error) {
|
|
3164
|
+
for (const service of started.reverse()) {
|
|
3165
|
+
try {
|
|
3166
|
+
await service.stop();
|
|
3167
|
+
} catch {
|
|
3168
|
+
}
|
|
3169
|
+
}
|
|
3170
|
+
throw error;
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
async disposeAll() {
|
|
3174
|
+
let firstError;
|
|
3175
|
+
const services = Array.from(this.instances.values()).reverse();
|
|
3176
|
+
for (const service of services) {
|
|
3177
|
+
try {
|
|
3178
|
+
await service.dispose();
|
|
3179
|
+
} catch (error) {
|
|
3180
|
+
firstError ??= error;
|
|
3181
|
+
}
|
|
713
3182
|
}
|
|
3183
|
+
if (firstError) throw firstError;
|
|
714
3184
|
}
|
|
715
3185
|
async stopAll() {
|
|
716
|
-
|
|
717
|
-
|
|
3186
|
+
let firstError;
|
|
3187
|
+
const services = Array.from(this.instances.values()).reverse();
|
|
3188
|
+
for (const service of services) {
|
|
3189
|
+
try {
|
|
3190
|
+
await service.stop();
|
|
3191
|
+
} catch (error) {
|
|
3192
|
+
firstError ??= error;
|
|
3193
|
+
}
|
|
718
3194
|
}
|
|
3195
|
+
if (firstError) throw firstError;
|
|
719
3196
|
}
|
|
720
3197
|
};
|
|
721
3198
|
|
|
@@ -741,6 +3218,7 @@ var ServiceDiscovery = class {
|
|
|
741
3218
|
// src/discovery/KrnlPackageReconciler.ts
|
|
742
3219
|
var fs = __toESM(require("fs"), 1);
|
|
743
3220
|
var path = __toESM(require("path"), 1);
|
|
3221
|
+
var import_gutts = require("@dinilmusick/gutts");
|
|
744
3222
|
var KrnlPackageReconciler = class {
|
|
745
3223
|
/**
|
|
746
3224
|
* Scans all manifest.json files across backend and frontend and reconciles root package.json.
|
|
@@ -752,7 +3230,7 @@ var KrnlPackageReconciler = class {
|
|
|
752
3230
|
for (const mPath of manifests) {
|
|
753
3231
|
try {
|
|
754
3232
|
const raw = fs.readFileSync(mPath, "utf8");
|
|
755
|
-
const json =
|
|
3233
|
+
const json = (0, import_gutts.tryParseJson)(raw) ?? {};
|
|
756
3234
|
if (json.dependencies && typeof json.dependencies === "object") {
|
|
757
3235
|
for (const [pkg, ver] of Object.entries(json.dependencies)) {
|
|
758
3236
|
if (!aggregatedDeps[pkg]) aggregatedDeps[pkg] = [];
|
|
@@ -826,10 +3304,13 @@ var KrnlPackageReconciler = class {
|
|
|
826
3304
|
*/
|
|
827
3305
|
static findManifests(projectRoot) {
|
|
828
3306
|
const searchDirs = [
|
|
3307
|
+
path.join(projectRoot, "krnl", "backend", "services"),
|
|
829
3308
|
path.join(projectRoot, "krnl", "backend", "libraries"),
|
|
830
3309
|
path.join(projectRoot, "krnl", "backend", "functionalities"),
|
|
831
3310
|
path.join(projectRoot, "krnl", "frontend", "libraries"),
|
|
832
3311
|
path.join(projectRoot, "krnl", "frontend", "functionalities"),
|
|
3312
|
+
path.join(projectRoot, "src", "backend", "services"),
|
|
3313
|
+
path.join(projectRoot, "src", "services"),
|
|
833
3314
|
path.join(projectRoot, "src", "functionalities"),
|
|
834
3315
|
path.join(projectRoot, "src", "libraries")
|
|
835
3316
|
];
|
|
@@ -869,16 +3350,302 @@ var ProtocolResolver = class {
|
|
|
869
3350
|
return definition.protocols || ["http"];
|
|
870
3351
|
}
|
|
871
3352
|
};
|
|
3353
|
+
|
|
3354
|
+
// src/orchestration/FunctionalityOrchestration.ts
|
|
3355
|
+
var FunctionalityOrchestration = class {
|
|
3356
|
+
id;
|
|
3357
|
+
name;
|
|
3358
|
+
version;
|
|
3359
|
+
description;
|
|
3360
|
+
timeoutMs;
|
|
3361
|
+
scope = "functionality";
|
|
3362
|
+
steps = [];
|
|
3363
|
+
flows = /* @__PURE__ */ new Map();
|
|
3364
|
+
constructor(descriptor) {
|
|
3365
|
+
if (!descriptor || typeof descriptor !== "object" || !descriptor.id) {
|
|
3366
|
+
throw new Error("[FunctionalityOrchestration] Valid descriptor with non-empty id is required.");
|
|
3367
|
+
}
|
|
3368
|
+
this.id = descriptor.id;
|
|
3369
|
+
this.name = descriptor.name || descriptor.id;
|
|
3370
|
+
this.version = descriptor.version || "1.0.0";
|
|
3371
|
+
this.description = descriptor.description || "";
|
|
3372
|
+
this.timeoutMs = descriptor.timeoutMs;
|
|
3373
|
+
}
|
|
3374
|
+
/**
|
|
3375
|
+
* Adds a sequential functionality step to the DAG.
|
|
3376
|
+
*/
|
|
3377
|
+
thenFunctionality(funcName, options = {}) {
|
|
3378
|
+
if (!funcName) {
|
|
3379
|
+
throw new Error("[FunctionalityOrchestration] Functionality name must be a non-empty string.");
|
|
3380
|
+
}
|
|
3381
|
+
if (typeof funcName !== "string") {
|
|
3382
|
+
if (typeof funcName === "object" && ("call" in funcName || "getStatus" in funcName || "definition" in funcName || "instance" in funcName || "id" in funcName)) {
|
|
3383
|
+
throw new Error(
|
|
3384
|
+
"[FunctionalityOrchestration] Invariant Violation: FunctionalityOrchestration only composes functionalities within the service, not independent services."
|
|
3385
|
+
);
|
|
3386
|
+
}
|
|
3387
|
+
throw new Error("[FunctionalityOrchestration] Functionality name must be a non-empty string.");
|
|
3388
|
+
}
|
|
3389
|
+
this.assertServiceBoundary(funcName);
|
|
3390
|
+
const stepId = options.id || `step_${funcName}_${this.steps.length + 1}`;
|
|
3391
|
+
const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
|
|
3392
|
+
const dependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
|
|
3393
|
+
const step = {
|
|
3394
|
+
id: stepId,
|
|
3395
|
+
name: funcName,
|
|
3396
|
+
type: "task",
|
|
3397
|
+
target: funcName,
|
|
3398
|
+
dependsOn,
|
|
3399
|
+
retryPolicy: options.retry,
|
|
3400
|
+
timeoutPolicy: options.timeoutMs ? { timeoutMs: options.timeoutMs } : void 0,
|
|
3401
|
+
compensation: options.compensation ? { name: options.compensation, target: options.compensation } : void 0,
|
|
3402
|
+
catchHandler: options.catchHandler
|
|
3403
|
+
};
|
|
3404
|
+
this.steps.push(step);
|
|
3405
|
+
return this;
|
|
3406
|
+
}
|
|
3407
|
+
/**
|
|
3408
|
+
* Adds parallel functionality steps to the DAG.
|
|
3409
|
+
*/
|
|
3410
|
+
parallel(name, functionalityNames, options = {}) {
|
|
3411
|
+
if (!name || typeof name !== "string") {
|
|
3412
|
+
throw new Error("[FunctionalityOrchestration] Parallel group name must be a non-empty string.");
|
|
3413
|
+
}
|
|
3414
|
+
if (!functionalityNames || functionalityNames.length === 0) {
|
|
3415
|
+
throw new Error("[FunctionalityOrchestration] Parallel step requires at least one functionality.");
|
|
3416
|
+
}
|
|
3417
|
+
const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
|
|
3418
|
+
const baseDependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
|
|
3419
|
+
const parallelStepIds = [];
|
|
3420
|
+
for (const funcName of functionalityNames) {
|
|
3421
|
+
this.assertServiceBoundary(funcName);
|
|
3422
|
+
const stepId = `${name}_${funcName}`;
|
|
3423
|
+
parallelStepIds.push(stepId);
|
|
3424
|
+
this.steps.push({
|
|
3425
|
+
id: stepId,
|
|
3426
|
+
name: funcName,
|
|
3427
|
+
type: "task",
|
|
3428
|
+
target: funcName,
|
|
3429
|
+
dependsOn: baseDependsOn
|
|
3430
|
+
});
|
|
3431
|
+
}
|
|
3432
|
+
const joinId = `${name}_join`;
|
|
3433
|
+
this.steps.push({
|
|
3434
|
+
id: joinId,
|
|
3435
|
+
name: `${name} Join`,
|
|
3436
|
+
type: "fanIn",
|
|
3437
|
+
dependsOn: parallelStepIds
|
|
3438
|
+
});
|
|
3439
|
+
return this;
|
|
3440
|
+
}
|
|
3441
|
+
/**
|
|
3442
|
+
* Adds conditional branching to the DAG.
|
|
3443
|
+
*/
|
|
3444
|
+
branch(name, condition, thenFunc, elseFunc, options = {}) {
|
|
3445
|
+
this.assertServiceBoundary(thenFunc);
|
|
3446
|
+
if (elseFunc) this.assertServiceBoundary(elseFunc);
|
|
3447
|
+
const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
|
|
3448
|
+
const baseDependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
|
|
3449
|
+
const thenStepId = `${name}_then_${thenFunc}`;
|
|
3450
|
+
this.steps.push({
|
|
3451
|
+
id: thenStepId,
|
|
3452
|
+
name: thenFunc,
|
|
3453
|
+
type: "task",
|
|
3454
|
+
target: thenFunc,
|
|
3455
|
+
condition,
|
|
3456
|
+
dependsOn: baseDependsOn
|
|
3457
|
+
});
|
|
3458
|
+
let joinDeps = [thenStepId];
|
|
3459
|
+
if (elseFunc) {
|
|
3460
|
+
const elseStepId = `${name}_else_${elseFunc}`;
|
|
3461
|
+
this.steps.push({
|
|
3462
|
+
id: elseStepId,
|
|
3463
|
+
name: elseFunc,
|
|
3464
|
+
type: "task",
|
|
3465
|
+
target: elseFunc,
|
|
3466
|
+
condition: async (ctx) => !await condition(ctx),
|
|
3467
|
+
dependsOn: baseDependsOn
|
|
3468
|
+
});
|
|
3469
|
+
joinDeps.push(elseStepId);
|
|
3470
|
+
}
|
|
3471
|
+
const joinId = `${name}_join`;
|
|
3472
|
+
this.steps.push({
|
|
3473
|
+
id: joinId,
|
|
3474
|
+
name: `${name} Join`,
|
|
3475
|
+
type: "fanIn",
|
|
3476
|
+
dependsOn: joinDeps
|
|
3477
|
+
});
|
|
3478
|
+
return this;
|
|
3479
|
+
}
|
|
3480
|
+
/**
|
|
3481
|
+
* Adds fan-out step processing items through a functionality.
|
|
3482
|
+
*/
|
|
3483
|
+
fanOut(name, funcName, getItems, options = {}) {
|
|
3484
|
+
this.assertServiceBoundary(funcName);
|
|
3485
|
+
const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
|
|
3486
|
+
const dependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
|
|
3487
|
+
this.steps.push({
|
|
3488
|
+
id: name,
|
|
3489
|
+
name,
|
|
3490
|
+
type: "fanOut",
|
|
3491
|
+
target: funcName,
|
|
3492
|
+
getItems,
|
|
3493
|
+
concurrency: options.concurrency ?? 5,
|
|
3494
|
+
dependsOn
|
|
3495
|
+
});
|
|
3496
|
+
return this;
|
|
3497
|
+
}
|
|
3498
|
+
/**
|
|
3499
|
+
* Nested orchestration: Invokes a child FunctionalityOrchestration within the same service boundary.
|
|
3500
|
+
*/
|
|
3501
|
+
thenFunctionalityOrchestration(childOrchId, options = {}) {
|
|
3502
|
+
if (!childOrchId || typeof childOrchId !== "string") {
|
|
3503
|
+
throw new Error("[FunctionalityOrchestration] Child orchestration id must be a non-empty string.");
|
|
3504
|
+
}
|
|
3505
|
+
const stepId = options.id || `nested_${childOrchId}_${this.steps.length + 1}`;
|
|
3506
|
+
const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
|
|
3507
|
+
const dependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
|
|
3508
|
+
this.steps.push({
|
|
3509
|
+
id: stepId,
|
|
3510
|
+
name: childOrchId,
|
|
3511
|
+
type: "nested",
|
|
3512
|
+
nestedOrchestrationId: childOrchId,
|
|
3513
|
+
dependsOn,
|
|
3514
|
+
retryPolicy: options.retry,
|
|
3515
|
+
timeoutPolicy: options.timeoutMs ? { timeoutMs: options.timeoutMs } : void 0
|
|
3516
|
+
});
|
|
3517
|
+
return this;
|
|
3518
|
+
}
|
|
3519
|
+
getSteps() {
|
|
3520
|
+
return Object.freeze([...this.steps]);
|
|
3521
|
+
}
|
|
3522
|
+
/**
|
|
3523
|
+
* Converts this FunctionalityOrchestration to a pure serializable OrchestrationDefinition.
|
|
3524
|
+
*/
|
|
3525
|
+
toDefinition() {
|
|
3526
|
+
return {
|
|
3527
|
+
id: this.id,
|
|
3528
|
+
name: this.name,
|
|
3529
|
+
version: this.version,
|
|
3530
|
+
description: this.description,
|
|
3531
|
+
timeoutMs: this.timeoutMs,
|
|
3532
|
+
scope: "functionality",
|
|
3533
|
+
dependencies: [],
|
|
3534
|
+
steps: this.steps.map((s) => ({
|
|
3535
|
+
id: s.id,
|
|
3536
|
+
name: s.name,
|
|
3537
|
+
type: s.type,
|
|
3538
|
+
target: s.target,
|
|
3539
|
+
dependsOn: s.dependsOn ? [...s.dependsOn] : void 0,
|
|
3540
|
+
retryPolicy: s.retryPolicy ? { ...s.retryPolicy } : void 0,
|
|
3541
|
+
timeoutPolicy: s.timeoutPolicy ? { ...s.timeoutPolicy } : void 0,
|
|
3542
|
+
compensationTarget: s.compensation?.target ?? s.compensation?.name,
|
|
3543
|
+
compensationOperation: s.compensation?.operation ?? s.compensation?.name,
|
|
3544
|
+
nestedOrchestrationId: s.nestedOrchestrationId,
|
|
3545
|
+
concurrency: s.concurrency
|
|
3546
|
+
}))
|
|
3547
|
+
};
|
|
3548
|
+
}
|
|
3549
|
+
/**
|
|
3550
|
+
* Named flow builder interface.
|
|
3551
|
+
*/
|
|
3552
|
+
flow(name) {
|
|
3553
|
+
if (!name || typeof name !== "string" || name.trim() === "") {
|
|
3554
|
+
throw new Error("[FunctionalityOrchestration] Flow name must be a non-empty string.");
|
|
3555
|
+
}
|
|
3556
|
+
const steps = [];
|
|
3557
|
+
const self = this;
|
|
3558
|
+
const flowInstance = {
|
|
3559
|
+
name,
|
|
3560
|
+
steps,
|
|
3561
|
+
visibility: "internal",
|
|
3562
|
+
thenFunctionality(funcName, options) {
|
|
3563
|
+
if (!funcName) {
|
|
3564
|
+
throw new Error("[FunctionalityFlow] Functionality name must be a non-empty string.");
|
|
3565
|
+
}
|
|
3566
|
+
if (typeof funcName !== "string") {
|
|
3567
|
+
if (typeof funcName === "object" && ("call" in funcName || "getStatus" in funcName || "definition" in funcName || "instance" in funcName || "id" in funcName)) {
|
|
3568
|
+
throw new Error(
|
|
3569
|
+
"[FunctionalityOrchestration] Invariant Violation: FunctionalityOrchestration only composes functionalities within the service, not independent services."
|
|
3570
|
+
);
|
|
3571
|
+
}
|
|
3572
|
+
throw new Error("[FunctionalityFlow] Functionality name must be a non-empty string.");
|
|
3573
|
+
}
|
|
3574
|
+
self.assertServiceBoundary(funcName);
|
|
3575
|
+
const stepId = `${name}_${funcName}_${steps.length + 1}`;
|
|
3576
|
+
steps.push({
|
|
3577
|
+
id: stepId,
|
|
3578
|
+
type: "functionality",
|
|
3579
|
+
target: funcName,
|
|
3580
|
+
dependsOn: options?.dependsOn,
|
|
3581
|
+
retryPolicy: options?.retry,
|
|
3582
|
+
timeoutPolicy: options?.timeoutMs ? { timeoutMs: options?.timeoutMs } : void 0
|
|
3583
|
+
});
|
|
3584
|
+
self.thenFunctionality(funcName, {
|
|
3585
|
+
id: stepId,
|
|
3586
|
+
retry: options?.retry,
|
|
3587
|
+
timeoutMs: options?.timeoutMs,
|
|
3588
|
+
dependsOn: options?.dependsOn
|
|
3589
|
+
});
|
|
3590
|
+
return flowInstance;
|
|
3591
|
+
},
|
|
3592
|
+
thenFunctionalityOrchestration(childName, flowName) {
|
|
3593
|
+
if (!childName || typeof childName !== "string") {
|
|
3594
|
+
throw new Error("[FunctionalityFlow] Orchestration name must be a non-empty string.");
|
|
3595
|
+
}
|
|
3596
|
+
const stepId = `${name}_orch_${childName}_${steps.length + 1}`;
|
|
3597
|
+
steps.push({
|
|
3598
|
+
id: stepId,
|
|
3599
|
+
type: "functionalityOrchestration",
|
|
3600
|
+
target: childName,
|
|
3601
|
+
flow: flowName
|
|
3602
|
+
});
|
|
3603
|
+
self.thenFunctionalityOrchestration(childName, { id: stepId });
|
|
3604
|
+
return flowInstance;
|
|
3605
|
+
},
|
|
3606
|
+
register(options) {
|
|
3607
|
+
if (options?.visibility) flowInstance.visibility = options.visibility;
|
|
3608
|
+
return flowInstance;
|
|
3609
|
+
}
|
|
3610
|
+
};
|
|
3611
|
+
this.flows.set(name, flowInstance);
|
|
3612
|
+
return flowInstance;
|
|
3613
|
+
}
|
|
3614
|
+
getFlow(name) {
|
|
3615
|
+
return this.flows.get(name);
|
|
3616
|
+
}
|
|
3617
|
+
listFlows() {
|
|
3618
|
+
return Array.from(this.flows.values());
|
|
3619
|
+
}
|
|
3620
|
+
clearFlows() {
|
|
3621
|
+
this.flows.clear();
|
|
3622
|
+
this.steps.length = 0;
|
|
3623
|
+
}
|
|
3624
|
+
assertServiceBoundary(target) {
|
|
3625
|
+
if (target.endsWith("ServiceFacade") || target.startsWith("service.") || target.includes("Service.") || target.endsWith("Service") && !target.includes("Functionality") && !target.includes("Atom") || target.startsWith("Service") && !target.includes("Functionality") && !target.includes("Atom")) {
|
|
3626
|
+
throw new Error(
|
|
3627
|
+
`[FunctionalityOrchestration] Plane Isolation Invariant Violation: Invariant Violation: FunctionalityOrchestration only composes functionalities within the service, not independent services. External Service composition is forbidden. Target "${target}" is not an internal functionality.`
|
|
3628
|
+
);
|
|
3629
|
+
}
|
|
3630
|
+
}
|
|
3631
|
+
};
|
|
3632
|
+
|
|
3633
|
+
// src/index.ts
|
|
3634
|
+
var gutts = __toESM(require("@dinilmusick/gutts"), 1);
|
|
872
3635
|
// Annotate the CommonJS export names for ESM import in node:
|
|
873
3636
|
0 && (module.exports = {
|
|
3637
|
+
FunctionalityOrchestration,
|
|
874
3638
|
HttpProtocolAdapter,
|
|
875
3639
|
KrnlPackageReconciler,
|
|
3640
|
+
KrnlQueue,
|
|
3641
|
+
KrnlWorkerPool,
|
|
876
3642
|
LifecycleManager,
|
|
877
3643
|
MemoryTransport,
|
|
878
3644
|
P2PProtocolAdapter,
|
|
879
3645
|
ProtocolResolver,
|
|
880
3646
|
ServiceDiscovery,
|
|
881
3647
|
ServiceEventBus,
|
|
3648
|
+
ServiceFacade,
|
|
882
3649
|
ServiceInstance,
|
|
883
3650
|
ServiceProxy,
|
|
884
3651
|
ServiceRegistry,
|
|
@@ -886,7 +3653,12 @@ var ProtocolResolver = class {
|
|
|
886
3653
|
ServiceStateStore,
|
|
887
3654
|
UdpProtocolAdapter,
|
|
888
3655
|
WebSocketProtocolAdapter,
|
|
3656
|
+
WorkerExecutionBoundary,
|
|
889
3657
|
createService,
|
|
890
3658
|
createServiceDefinition,
|
|
891
|
-
|
|
3659
|
+
createServiceFacade,
|
|
3660
|
+
createServiceProxy,
|
|
3661
|
+
gutts,
|
|
3662
|
+
validateOrchestrationDAG,
|
|
3663
|
+
validateServiceDefinition
|
|
892
3664
|
});
|