akanjs 0.0.1 → 2.0.0-beta.0
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/CODE_OF_CONDUCT.md +54 -0
- package/CONTRIBUTING.md +83 -0
- package/LICENSE +21 -0
- package/README.ko.md +244 -0
- package/README.md +237 -6
- package/base/base.ts +194 -0
- package/base/baseEnv.ts +162 -0
- package/base/index.ts +6 -0
- package/base/primitiveRegistry.ts +342 -0
- package/base/symbols.ts +11 -0
- package/base/types.ts +137 -0
- package/base/utils.ts +30 -0
- package/cli/application/application.command.ts +213 -0
- package/cli/application/application.interface.tsx +225 -0
- package/cli/application/application.runner.ts +359 -0
- package/cli/application/application.script.ts +244 -0
- package/cli/build.ts +25 -0
- package/cli/cloud/cloud.command.ts +48 -0
- package/cli/cloud/cloud.runner.ts +158 -0
- package/cli/cloud/cloud.script.ts +40 -0
- package/cli/guideline/guideline.command.ts +31 -0
- package/cli/guideline/guideline.prompt.ts +212 -0
- package/cli/guideline/guideline.runner.ts +53 -0
- package/cli/guideline/guideline.script.ts +33 -0
- package/cli/guidelines/___library/sharedUiStructureDescription.en.md +767 -0
- package/cli/guidelines/___library/utilUiStructureDescription.en.md +395 -0
- package/cli/guidelines/___lint/lintRuleDescription.en.md +64 -0
- package/cli/guidelines/___module/moduleStructureDescription.en.md +80 -0
- package/cli/guidelines/componentRule/componentRule.generate.json +131 -0
- package/cli/guidelines/componentRule/componentRule.instruction.md +637 -0
- package/cli/guidelines/cssRule/cssRule.generate.json +93 -0
- package/cli/guidelines/cssRule/cssRule.instruction.md +435 -0
- package/cli/guidelines/databaseModule/databaseModule.generate.json +51 -0
- package/cli/guidelines/databaseModule/databaseModule.instruction.md +612 -0
- package/cli/guidelines/docPageRule/docPageRule.generate.json +72 -0
- package/cli/guidelines/docPageRule/docPageRule.instruction.md +389 -0
- package/cli/guidelines/enumConstant/enumConstant.generate.json +24 -0
- package/cli/guidelines/enumConstant/enumConstant.instruction.md +232 -0
- package/cli/guidelines/framework/framework.generate.json +119 -0
- package/cli/guidelines/framework/framework.instruction.md +1110 -0
- package/cli/guidelines/howToUseStore/howToUseStore.generate.json +0 -0
- package/cli/guidelines/modelConstant/modelConstant.generate.json +128 -0
- package/cli/guidelines/modelConstant/modelConstant.instruction.md +506 -0
- package/cli/guidelines/modelDictionary/modelDictionary.generate.json +108 -0
- package/cli/guidelines/modelDictionary/modelDictionary.instruction.md +547 -0
- package/cli/guidelines/modelDocument/modelDocument.generate.json +129 -0
- package/cli/guidelines/modelDocument/modelDocument.instruction.md +536 -0
- package/cli/guidelines/modelService/modelService.generate.json +135 -0
- package/cli/guidelines/modelService/modelService.instruction.md +708 -0
- package/cli/guidelines/modelSignal/modelSignal.generate.json +201 -0
- package/cli/guidelines/modelSignal/modelSignal.instruction.md +552 -0
- package/cli/guidelines/modelStore/modelStore.generate.json +130 -0
- package/cli/guidelines/modelStore/modelStore.instruction.md +585 -0
- package/cli/guidelines/modelTemplate/modelTemplate.generate.json +104 -0
- package/cli/guidelines/modelTemplate/modelTemplate.instruction.md +604 -0
- package/cli/guidelines/modelUnit/modelUnit.generate.json +92 -0
- package/cli/guidelines/modelUnit/modelUnit.instruction.md +541 -0
- package/cli/guidelines/modelUtil/modelUtil.generate.json +93 -0
- package/cli/guidelines/modelUtil/modelUtil.instruction.md +752 -0
- package/cli/guidelines/modelView/modelView.generate.json +80 -0
- package/cli/guidelines/modelView/modelView.instruction.md +1005 -0
- package/cli/guidelines/modelZone/modelZone.generate.json +126 -0
- package/cli/guidelines/modelZone/modelZone.instruction.md +528 -0
- package/cli/guidelines/scalarConstant/scalarConstant.generate.json +106 -0
- package/cli/guidelines/scalarConstant/scalarConstant.instruction.md +442 -0
- package/cli/guidelines/scalarDictionary/scalarDictionary.generate.json +83 -0
- package/cli/guidelines/scalarDictionary/scalarDictionary.instruction.md +273 -0
- package/cli/guidelines/scalarModule/scalarModule.generate.json +35 -0
- package/cli/guidelines/scalarModule/scalarModule.instruction.md +81 -0
- package/cli/guidelines/sharedUiUsage/sharedUiUsage.generate.json +108 -0
- package/cli/guidelines/sharedUiUsage/sharedUiUsage.instruction.md +310 -0
- package/cli/guidelines/utilUiUsage/utilUiUsage.generate.json +140 -0
- package/cli/guidelines/utilUiUsage/utilUiUsage.instruction.md +339 -0
- package/cli/index.js +11401 -0
- package/cli/index.ts +24 -0
- package/cli/library/library.command.ts +28 -0
- package/cli/library/library.runner.ts +69 -0
- package/cli/library/library.script.ts +39 -0
- package/cli/module/module.command.ts +35 -0
- package/cli/module/module.prompt.ts +18 -0
- package/cli/module/module.request.ts +319 -0
- package/cli/module/module.runner.ts +76 -0
- package/cli/module/module.script.ts +161 -0
- package/cli/package/package.command.ts +32 -0
- package/cli/package/package.runner.ts +64 -0
- package/cli/package/package.script.ts +35 -0
- package/cli/page/page.command.ts +14 -0
- package/cli/page/page.runner.ts +14 -0
- package/cli/page/page.script.ts +12 -0
- package/cli/scalar/scalar.command.ts +21 -0
- package/cli/scalar/scalar.prompt.ts +131 -0
- package/cli/scalar/scalar.runner.ts +38 -0
- package/cli/scalar/scalar.script.ts +16 -0
- package/cli/templates/__scalar/__model__/__model__.constant.ts +15 -0
- package/cli/templates/__scalar/__model__/__model__.dictionary.ts +19 -0
- package/cli/templates/__scalar/__model__/__model__.document.ts +15 -0
- package/cli/templates/app/akan.config.ts +14 -0
- package/cli/templates/app/capacitor.config.ts.template +8 -0
- package/cli/templates/app/common/commonLogic.ts +12 -0
- package/cli/templates/app/common/index.ts +10 -0
- package/cli/templates/app/env/env.client.debug.ts.template +7 -0
- package/cli/templates/app/env/env.client.develop.ts.template +7 -0
- package/cli/templates/app/env/env.client.local.ts.template +7 -0
- package/cli/templates/app/env/env.client.main.ts.template +7 -0
- package/cli/templates/app/env/env.client.testing.ts.template +7 -0
- package/cli/templates/app/env/env.client.ts +21 -0
- package/cli/templates/app/env/env.client.type.ts +16 -0
- package/cli/templates/app/env/env.server.debug.ts.template +7 -0
- package/cli/templates/app/env/env.server.develop.ts.template +9 -0
- package/cli/templates/app/env/env.server.local.ts.template +14 -0
- package/cli/templates/app/env/env.server.main.ts.template +9 -0
- package/cli/templates/app/env/env.server.testing.ts.template +6 -0
- package/cli/templates/app/env/env.server.ts +20 -0
- package/cli/templates/app/lib/___appName__/__appName__.dictionary.ts +17 -0
- package/cli/templates/app/lib/___appName__/__appName__.service.ts +13 -0
- package/cli/templates/app/lib/___appName__/__appName__.signal.ts +17 -0
- package/cli/templates/app/lib/___appName__/__appName__.store.ts +15 -0
- package/cli/templates/app/lib/option.ts +17 -0
- package/cli/templates/app/main.ts +16 -0
- package/cli/templates/app/package.json.template +5 -0
- package/cli/templates/app/page/_index.tsx +172 -0
- package/cli/templates/app/page/_layout.tsx +32 -0
- package/cli/templates/app/page/styles.css.template +53 -0
- package/cli/templates/app/public/favicon.ico +0 -0
- package/cli/templates/app/public/logo.png +0 -0
- package/cli/templates/app/srvkit/backendLogic.ts +12 -0
- package/cli/templates/app/srvkit/index.ts +10 -0
- package/cli/templates/app/tsconfig.json.template +21 -0
- package/cli/templates/app/ui/UiComponent.ts +16 -0
- package/cli/templates/app/ui/index.ts +10 -0
- package/cli/templates/app/webkit/frontendLogic.ts +12 -0
- package/cli/templates/app/webkit/index.ts +10 -0
- package/cli/templates/client.ts +46 -0
- package/cli/templates/crudPages/[__model__Id]/edit/page.tsx +47 -0
- package/cli/templates/crudPages/[__model__Id]/page.tsx +52 -0
- package/cli/templates/crudPages/new/page.tsx +42 -0
- package/cli/templates/crudPages/page.tsx +43 -0
- package/cli/templates/crudSinglePage/page.tsx +37 -0
- package/cli/templates/env/_env.server.type.ts +16 -0
- package/cli/templates/facetIndex/index.ts +32 -0
- package/cli/templates/index.ts +10 -0
- package/cli/templates/lib/__lib/lib.constant.ts +38 -0
- package/cli/templates/lib/__lib/lib.dictionary.ts +33 -0
- package/cli/templates/lib/__lib/lib.document.ts +35 -0
- package/cli/templates/lib/__lib/lib.service.ts +33 -0
- package/cli/templates/lib/__lib/lib.signal.ts +34 -0
- package/cli/templates/lib/__lib/lib.store.ts +33 -0
- package/cli/templates/lib/cnst.ts +29 -0
- package/cli/templates/lib/db.ts +32 -0
- package/cli/templates/lib/dict.ts +49 -0
- package/cli/templates/lib/sig.ts +60 -0
- package/cli/templates/lib/srv.ts +34 -0
- package/cli/templates/lib/st.ts +31 -0
- package/cli/templates/lib/useClient.ts +19 -0
- package/cli/templates/lib/useServer.ts +7 -0
- package/cli/templates/libRoot/.gitignore.template +16 -0
- package/cli/templates/libRoot/akan.config.ts +12 -0
- package/cli/templates/libRoot/base/baseLogic.ts +10 -0
- package/cli/templates/libRoot/base/index.ts +8 -0
- package/cli/templates/libRoot/common/commonLogic.ts +10 -0
- package/cli/templates/libRoot/common/index.ts +8 -0
- package/cli/templates/libRoot/env/env.server.example.ts.template +6 -0
- package/cli/templates/libRoot/env/env.server.testing.ts.template +6 -0
- package/cli/templates/libRoot/lib/___libName__/__libName__.dictionary.ts +15 -0
- package/cli/templates/libRoot/lib/___libName__/__libName__.service.ts +11 -0
- package/cli/templates/libRoot/lib/___libName__/__libName__.store.ts +13 -0
- package/cli/templates/libRoot/lib/option.ts +17 -0
- package/cli/templates/libRoot/package.json.template +5 -0
- package/cli/templates/libRoot/srvkit/backendLogic.ts +10 -0
- package/cli/templates/libRoot/srvkit/index.ts +8 -0
- package/cli/templates/libRoot/tsconfig.json.template +11 -0
- package/cli/templates/libRoot/ui/index.ts +7 -0
- package/cli/templates/libRoot/webkit/frontendLogic.ts +10 -0
- package/cli/templates/libRoot/webkit/index.ts +8 -0
- package/cli/templates/localDev/docker-compose.yaml.template +37 -0
- package/cli/templates/module/__Model__.Template.tsx +36 -0
- package/cli/templates/module/__Model__.Unit.tsx +26 -0
- package/cli/templates/module/__Model__.Util.tsx +30 -0
- package/cli/templates/module/__Model__.View.tsx +29 -0
- package/cli/templates/module/__Model__.Zone.tsx +43 -0
- package/cli/templates/module/__model__.constant.ts +24 -0
- package/cli/templates/module/__model__.dictionary.ts +30 -0
- package/cli/templates/module/__model__.document.ts +23 -0
- package/cli/templates/module/__model__.service.ts +16 -0
- package/cli/templates/module/__model__.signal.ts +27 -0
- package/cli/templates/module/__model__.store.ts +19 -0
- package/cli/templates/module/index.tsx +44 -0
- package/cli/templates/moduleRoot/index.tsx +31 -0
- package/cli/templates/pkgRoot/tsconfig.json.template +10 -0
- package/cli/templates/server.ts +45 -0
- package/cli/templates/workspaceRoot/.env.template +14 -0
- package/cli/templates/workspaceRoot/.gitignore.template +130 -0
- package/cli/templates/workspaceRoot/.vscode/settings.json.template +23 -0
- package/cli/templates/workspaceRoot/biome.json.template +175 -0
- package/cli/templates/workspaceRoot/bunfig.toml +4 -0
- package/cli/templates/workspaceRoot/infra/app/Chart.yaml.template +6 -0
- package/cli/templates/workspaceRoot/infra/app/templates/frontend.yaml.template +182 -0
- package/cli/templates/workspaceRoot/infra/app/values/_common-values.yaml.template +183 -0
- package/cli/templates/workspaceRoot/package.json.template +7 -0
- package/cli/templates/workspaceRoot/tsconfig.json.template +26 -0
- package/cli/testHelpers.ts +171 -0
- package/cli/workspace/workspace.command.ts +60 -0
- package/cli/workspace/workspace.runner.ts +57 -0
- package/cli/workspace/workspace.script.ts +68 -0
- package/client/capacitor.ts +68 -0
- package/client/clientRuntime.ts +141 -0
- package/client/cookie.ts +121 -0
- package/client/createFont.ts +8 -0
- package/client/csrTypes.ts +259 -0
- package/client/decorators.ts +25 -0
- package/client/device.ts +147 -0
- package/client/fetch.ts +1 -0
- package/client/index.ts +15 -0
- package/client/locale.ts +4 -0
- package/client/makePageProto.tsx +178 -0
- package/client/router.ts +286 -0
- package/client/rscNavigation.ts +19 -0
- package/client/storage.ts +33 -0
- package/client/translator.ts +43 -0
- package/client/types.ts +228 -0
- package/client/useClient.ts +1 -0
- package/common/Logger.ts +177 -0
- package/common/applyMixins.ts +14 -0
- package/common/capitalize.ts +4 -0
- package/common/deepObjectify.ts +27 -0
- package/common/formatNumber.ts +14 -0
- package/common/formatPhone.ts +7 -0
- package/common/getAllPropertyDescriptors.ts +13 -0
- package/common/hmrPhase.ts +17 -0
- package/common/httpClient.ts +101 -0
- package/common/index.ts +50 -0
- package/common/isDayjs.ts +3 -0
- package/common/isEmail.ts +2 -0
- package/common/isPhoneNumber.ts +8 -0
- package/common/isQueryEqual.ts +23 -0
- package/common/isValidDate.ts +14 -0
- package/common/localeConfig.ts +41 -0
- package/common/lowerlize.ts +4 -0
- package/common/mergeVersion.ts +10 -0
- package/common/objectify.ts +7 -0
- package/common/pathGet.ts +13 -0
- package/common/pathSet.ts +16 -0
- package/common/randomPick.ts +1 -0
- package/common/randomPicks.ts +12 -0
- package/common/routeConvention.ts +203 -0
- package/common/sleep.ts +8 -0
- package/common/splitVersion.ts +11 -0
- package/common/subRoute.ts +34 -0
- package/common/types.ts +15 -0
- package/constant/constantRegistry.ts +334 -0
- package/constant/crystalize.ts +45 -0
- package/constant/deserialize.ts +70 -0
- package/constant/fieldInfo.ts +415 -0
- package/constant/getDefault.ts +18 -0
- package/constant/immerify.ts +16 -0
- package/constant/index.ts +10 -0
- package/constant/purify.ts +118 -0
- package/constant/serialize.ts +87 -0
- package/constant/types.ts +105 -0
- package/constant/via.ts +360 -0
- package/devkit/aiEditor.ts +299 -0
- package/devkit/akanApp/akanApp.host.ts +356 -0
- package/devkit/akanApp/index.ts +1 -0
- package/devkit/akanConfig/akanConfig.ts +332 -0
- package/devkit/akanConfig/index.ts +2 -0
- package/devkit/akanConfig/types.ts +187 -0
- package/devkit/applicationBuildReporter.ts +69 -0
- package/devkit/applicationBuildRunner.ts +302 -0
- package/devkit/applicationReleasePackager.ts +205 -0
- package/devkit/artifact/implicitRootLayout.ts +155 -0
- package/devkit/artifact/index.ts +1 -0
- package/devkit/artifact/routeSeedIndex.ts +128 -0
- package/devkit/auth.ts +41 -0
- package/devkit/builder.ts +164 -0
- package/devkit/capacitor.base.config.ts +74 -0
- package/devkit/capacitorApp.ts +385 -0
- package/devkit/commandDecorators/argMeta.ts +88 -0
- package/devkit/commandDecorators/command.ts +314 -0
- package/devkit/commandDecorators/commandBuilder.ts +188 -0
- package/devkit/commandDecorators/commandMeta.ts +6 -0
- package/devkit/commandDecorators/dependencyBuilder.ts +100 -0
- package/devkit/commandDecorators/helpFormatter.ts +217 -0
- package/devkit/commandDecorators/index.ts +8 -0
- package/devkit/commandDecorators/targetMeta.ts +31 -0
- package/devkit/commandDecorators/types.ts +10 -0
- package/devkit/constants.ts +25 -0
- package/devkit/createTunnel.ts +36 -0
- package/devkit/dependencyScanner.ts +339 -0
- package/devkit/executors.ts +1326 -0
- package/devkit/extractDeps.ts +85 -0
- package/devkit/fileEditor.ts +106 -0
- package/devkit/fileSys.ts +39 -0
- package/devkit/frontendBuild/allRoutesBuilder.ts +103 -0
- package/devkit/frontendBuild/clientBuildTypes.ts +114 -0
- package/devkit/frontendBuild/clientEntriesBundler.ts +300 -0
- package/devkit/frontendBuild/clientEntryDiscovery.ts +196 -0
- package/devkit/frontendBuild/csrArtifactBuilder.ts +237 -0
- package/devkit/frontendBuild/cssCompiler.ts +279 -0
- package/devkit/frontendBuild/cssImportResolver.ts +116 -0
- package/devkit/frontendBuild/fontOptimizer.ts +427 -0
- package/devkit/frontendBuild/hmrChangeClassifier.ts +28 -0
- package/devkit/frontendBuild/hmrWatcher.ts +101 -0
- package/devkit/frontendBuild/index.ts +18 -0
- package/devkit/frontendBuild/pagesBundleBuilder.ts +137 -0
- package/devkit/frontendBuild/pagesEntrySourceGenerator.ts +37 -0
- package/devkit/frontendBuild/precompressArtifacts.ts +59 -0
- package/devkit/frontendBuild/routeClientBuilder.ts +290 -0
- package/devkit/frontendBuild/routesManifestArtifactSerializer.ts +62 -0
- package/devkit/frontendBuild/ssrBaseArtifactBuilder.ts +139 -0
- package/devkit/frontendBuild/vendorSpecifiers.ts +16 -0
- package/devkit/frontendBuild/watchRootResolver.ts +28 -0
- package/devkit/getCredentials.ts +19 -0
- package/devkit/getDirname.ts +3 -0
- package/devkit/getModelFileData.ts +59 -0
- package/devkit/getRelatedCnsts.ts +300 -0
- package/devkit/guideline.ts +19 -0
- package/devkit/incrementalBuilder/incrementalBuilder.host.ts +78 -0
- package/devkit/incrementalBuilder/incrementalBuilder.proc.ts +330 -0
- package/devkit/incrementalBuilder/index.ts +1 -0
- package/devkit/index.ts +36 -0
- package/devkit/lint/no-import-client-functions.grit +32 -0
- package/devkit/lint/no-import-external-library.grit +21 -0
- package/devkit/lint/no-js-private-class-method.grit +42 -0
- package/devkit/lint/no-use-client-in-server.grit +7 -0
- package/devkit/lint/non-scalar-props-restricted.grit +13 -0
- package/devkit/linter.ts +248 -0
- package/devkit/mobile/index.ts +1 -0
- package/devkit/mobile/mobileTarget.ts +47 -0
- package/devkit/prompter.ts +71 -0
- package/devkit/scanInfo.ts +605 -0
- package/devkit/selectModel.ts +11 -0
- package/devkit/spinner.ts +54 -0
- package/devkit/sshTunnel.ts +151 -0
- package/devkit/streamAi.ts +45 -0
- package/devkit/transforms/barrelAnalyzer.ts +249 -0
- package/devkit/transforms/barrelImportsPlugin.ts +451 -0
- package/devkit/transforms/externalizeFrameworkPlugin.ts +159 -0
- package/devkit/transforms/index.ts +5 -0
- package/devkit/transforms/rscUseClientTransform.ts +52 -0
- package/devkit/transforms/useClientBundlePlugin.ts +47 -0
- package/devkit/typeChecker.ts +260 -0
- package/devkit/types.ts +42 -0
- package/devkit/ui/MultiScrollList.tsx +228 -0
- package/devkit/ui/ScrollList.tsx +106 -0
- package/devkit/ui/index.ts +2 -0
- package/devkit/uploadRelease.ts +95 -0
- package/devkit/useStdoutDimensions.ts +20 -0
- package/dictionary/base.dictionary.ts +91 -0
- package/dictionary/dictInfo.ts +1079 -0
- package/dictionary/dictionary.ts +10 -0
- package/dictionary/index.ts +12 -0
- package/dictionary/locale.ts +230 -0
- package/dictionary/trans.ts +196 -0
- package/document/by.ts +39 -0
- package/document/dataLoader.ts +91 -0
- package/document/database.ts +168 -0
- package/document/databaseRegistry.ts +113 -0
- package/document/documentQuery.ts +143 -0
- package/document/documentSchema.ts +91 -0
- package/document/filterMeta.ts +210 -0
- package/document/index.ts +11 -0
- package/document/into.ts +169 -0
- package/document/loaderInfo.ts +50 -0
- package/document/schema.ts +24 -0
- package/document/types.ts +41 -0
- package/fetch/client/fetchClient.ts +600 -0
- package/fetch/client/httpClient.ts +157 -0
- package/fetch/client/index.ts +3 -0
- package/fetch/client/wsClient.ts +246 -0
- package/fetch/fetchType/appliedReturn.type.ts +108 -0
- package/fetch/fetchType/buildFetch.type.ts +24 -0
- package/fetch/fetchType/clientSignal.type.ts +22 -0
- package/fetch/fetchType/endpointFetch.type.ts +56 -0
- package/fetch/fetchType/index.ts +5 -0
- package/fetch/fetchType/sliceFetch.type.ts +173 -0
- package/fetch/index.ts +4 -0
- package/fetch/requestStorage.ts +127 -0
- package/fetch/serializer/fetch.serializer.ts +131 -0
- package/fetch/serializer/index.ts +1 -0
- package/fetch/types.ts +28 -0
- package/package.json +202 -5
- package/server/SSR_MEMORY_DIAGNOSIS.md +107 -0
- package/server/akanApp.ts +855 -0
- package/server/akanLib.ts +43 -0
- package/server/akanOption.ts +42 -0
- package/server/akanServer.ts +369 -0
- package/server/artifact/builderRpc.ts +124 -0
- package/server/artifact/index.ts +6 -0
- package/server/artifact/ipcTypes.ts +46 -0
- package/server/artifact/manifestTypes.ts +19 -0
- package/server/artifact/routeClientCache.ts +224 -0
- package/server/artifact/routeSeedIndexStore.ts +89 -0
- package/server/artifact/routesManifestStore.ts +120 -0
- package/server/decorators.ts +95 -0
- package/server/di/diLifecycle.ts +520 -0
- package/server/di/index.ts +4 -0
- package/server/di/predefinedAdaptor.ts +77 -0
- package/server/di/resolveAdaptorHierarchy.ts +82 -0
- package/server/di/resolveHierarchy.ts +89 -0
- package/server/di/resolveServiceHierarchy.ts +47 -0
- package/server/di/utils.ts +40 -0
- package/server/hmr/changeBatch.ts +14 -0
- package/server/hmr/clientScript.ts +310 -0
- package/server/hmr/devHmrController.ts +395 -0
- package/server/hmr/index.ts +4 -0
- package/server/hmr/wsHub.ts +56 -0
- package/server/imageOptimizer.ts +427 -0
- package/server/imageOptimizerError.ts +8 -0
- package/server/index.ts +14 -0
- package/server/lifecycle/shutdownManager.ts +52 -0
- package/server/logging/rotatingLogWriter.ts +190 -0
- package/server/processMetricsCollector.ts +78 -0
- package/server/proxy/akanResponse.ts +16 -0
- package/server/proxy/bunRequestFields.ts +12 -0
- package/server/proxy/hostBasePathWebProxy.ts +112 -0
- package/server/proxy/index.ts +15 -0
- package/server/proxy/localeWebProxy.ts +71 -0
- package/server/proxy/types.ts +41 -0
- package/server/proxy/webProxyRunner.ts +90 -0
- package/server/resolver/database.resolver.ts +340 -0
- package/server/resolver/index.ts +3 -0
- package/server/resolver/resolver.contract.fixture.ts +222 -0
- package/server/resolver/service.resolver.ts +176 -0
- package/server/resolver/signal.resolver.ts +386 -0
- package/server/robots.ts +32 -0
- package/server/routeElementComposer.tsx +91 -0
- package/server/routeTreeBuilder.ts +279 -0
- package/server/routing/apiRouter.ts +226 -0
- package/server/rscClient.tsx +140 -0
- package/server/rscWorker.tsx +625 -0
- package/server/rscWorkerHost.ts +616 -0
- package/server/sitemap.ts +90 -0
- package/server/ssrFromRscRenderer.tsx +285 -0
- package/server/ssrTypes.ts +48 -0
- package/server/types/react-server-dom-webpack.d.ts +91 -0
- package/server/types.tsx +109 -0
- package/server/vendor/akanjs-base.ts +1 -0
- package/server/vendor/akanjs-common.ts +1 -0
- package/server/vendor/akanjs-constant.ts +1 -0
- package/server/vendor/akanjs-store.ts +1 -0
- package/server/vendor/react-dom-client.ts +5 -0
- package/server/vendor/react-dom.ts +21 -0
- package/server/vendor/react-jsx-dev-runtime.ts +5 -0
- package/server/vendor/react-jsx-runtime.ts +5 -0
- package/server/vendor/react-refresh-runtime.ts +6 -0
- package/server/vendor/react-server-dom-webpack-client-browser.ts +12 -0
- package/server/vendor/react.ts +51 -0
- package/server/vendor/scheduler.ts +23 -0
- package/server/webRouter.ts +712 -0
- package/service/adapt.ts +47 -0
- package/service/base.service.ts +18 -0
- package/service/index.ts +10 -0
- package/service/injectInfo.ts +393 -0
- package/service/ipcTypes.ts +127 -0
- package/service/predefinedAdaptor/cache.adaptor.ts +105 -0
- package/service/predefinedAdaptor/compress.adaptor.ts +357 -0
- package/service/predefinedAdaptor/database.adaptor.ts +1310 -0
- package/service/predefinedAdaptor/index.ts +13 -0
- package/service/predefinedAdaptor/logging.adaptor.ts +36 -0
- package/service/predefinedAdaptor/queue.adaptor.ts +42 -0
- package/service/predefinedAdaptor/role.adaptor.ts +18 -0
- package/service/predefinedAdaptor/schedule.adaptor.ts +188 -0
- package/service/predefinedAdaptor/solidCache.adaptor.ts +143 -0
- package/service/predefinedAdaptor/solidPubsub.adaptor.ts +98 -0
- package/service/predefinedAdaptor/solidQueue.adaptor.ts +203 -0
- package/service/predefinedAdaptor/solidSqlite.ts +85 -0
- package/service/predefinedAdaptor/sqlitePath.ts +20 -0
- package/service/predefinedAdaptor/storage.adaptor.ts +121 -0
- package/service/predefinedAdaptor/websocket.adaptor.ts +313 -0
- package/service/serve.ts +223 -0
- package/service/serviceModule.ts +221 -0
- package/service/serviceRegistry.ts +26 -0
- package/service/types.ts +113 -0
- package/signal/base.signal.ts +46 -0
- package/signal/endpoint.ts +122 -0
- package/signal/endpointInfo.ts +374 -0
- package/signal/exception.ts +50 -0
- package/signal/guard.ts +18 -0
- package/signal/guards.ts +16 -0
- package/signal/index.ts +18 -0
- package/signal/intercept.ts +39 -0
- package/signal/internal.ts +56 -0
- package/signal/internalArg.ts +38 -0
- package/signal/internalInfo.ts +208 -0
- package/signal/middleware.ts +108 -0
- package/signal/serializer/fetch.serializer.ts +128 -0
- package/signal/serializer/index.ts +1 -0
- package/signal/serverSignal.ts +114 -0
- package/signal/signalContext.ts +446 -0
- package/signal/signalRegistry.ts +82 -0
- package/signal/slice.ts +158 -0
- package/signal/sliceInfo.ts +254 -0
- package/signal/types.ts +131 -0
- package/store/action.ts +1067 -0
- package/store/baseSt.ts +81 -0
- package/store/hooks.ts +2 -0
- package/store/index.ts +8 -0
- package/store/rootStore.ts +26 -0
- package/store/state.ts +226 -0
- package/store/stateBuilder.ts +429 -0
- package/store/stateInfo.ts +66 -0
- package/store/store.ts +194 -0
- package/store/storeInstance.ts +382 -0
- package/store/storeRegistry.ts +84 -0
- package/store/types.ts +69 -0
- package/store/withSelector.ts +62 -0
- package/test/index.ts +16 -0
- package/test/playwright.config.base.ts +48 -0
- package/test/playwright.pageAgent.ts +41 -0
- package/test/sample.ts +19 -0
- package/test/sampleOf.ts +70 -0
- package/test/signalTest.preload.ts +10 -0
- package/test/signalTestRuntime.ts +126 -0
- package/test/testServer.ts +187 -0
- package/ui/BottomSheet.tsx +103 -0
- package/ui/Button.tsx +70 -0
- package/ui/ClientSide.tsx +11 -0
- package/ui/Clipboard.tsx +49 -0
- package/ui/Constant/Doc.tsx +696 -0
- package/ui/Constant/Mermaid.tsx +149 -0
- package/ui/Constant/index.ts +6 -0
- package/ui/Constant/schemaDoc.ts +324 -0
- package/ui/Copy.tsx +27 -0
- package/ui/CsrImage.tsx +38 -0
- package/ui/Data/CardList.tsx +141 -0
- package/ui/Data/Dashboard.tsx +72 -0
- package/ui/Data/Insight.tsx +35 -0
- package/ui/Data/Item.tsx +285 -0
- package/ui/Data/ListContainer.tsx +320 -0
- package/ui/Data/Pagination.tsx +54 -0
- package/ui/Data/QueryMaker.tsx +21 -0
- package/ui/Data/TableList.tsx +161 -0
- package/ui/Data/index.ts +11 -0
- package/ui/Data/index_.tsx +11 -0
- package/ui/DatePicker.tsx +184 -0
- package/ui/Dialog/Action.tsx +15 -0
- package/ui/Dialog/Close.tsx +22 -0
- package/ui/Dialog/Content.tsx +11 -0
- package/ui/Dialog/Modal.tsx +137 -0
- package/ui/Dialog/Provider.tsx +33 -0
- package/ui/Dialog/Title.tsx +15 -0
- package/ui/Dialog/Trigger.tsx +22 -0
- package/ui/Dialog/context.ts +20 -0
- package/ui/Dialog/index.tsx +15 -0
- package/ui/DragAction.tsx +129 -0
- package/ui/DraggableList.tsx +230 -0
- package/ui/Dropdown.tsx +51 -0
- package/ui/Empty.tsx +32 -0
- package/ui/Field.tsx +1556 -0
- package/ui/FontFace.tsx +26 -0
- package/ui/Image.tsx +185 -0
- package/ui/InfiniteScroll.tsx +67 -0
- package/ui/Input.tsx +636 -0
- package/ui/KeyboardAvoiding.tsx +62 -0
- package/ui/Layout/BottomAction.tsx +15 -0
- package/ui/Layout/BottomInset.tsx +42 -0
- package/ui/Layout/BottomTab.tsx +71 -0
- package/ui/Layout/Header.tsx +38 -0
- package/ui/Layout/LeftSider.tsx +34 -0
- package/ui/Layout/Navbar.tsx +46 -0
- package/ui/Layout/RightSider.tsx +41 -0
- package/ui/Layout/Sider.tsx +69 -0
- package/ui/Layout/Template.tsx +11 -0
- package/ui/Layout/TopLeftAction.tsx +28 -0
- package/ui/Layout/Unit.tsx +19 -0
- package/ui/Layout/View.tsx +12 -0
- package/ui/Layout/Zone.tsx +10 -0
- package/ui/Layout/index.ts +27 -0
- package/ui/Link/Back.tsx +15 -0
- package/ui/Link/Close.tsx +20 -0
- package/ui/Link/CsrLink.tsx +41 -0
- package/ui/Link/Lang.tsx +16 -0
- package/ui/Link/SsrLink.tsx +68 -0
- package/ui/Link/index.tsx +32 -0
- package/ui/Link/types.ts +47 -0
- package/ui/Load/Edit.tsx +19 -0
- package/ui/Load/Edit_Client.tsx +120 -0
- package/ui/Load/Page.tsx +40 -0
- package/ui/Load/PageCSR.tsx +39 -0
- package/ui/Load/Pagination.tsx +89 -0
- package/ui/Load/Units.tsx +330 -0
- package/ui/Load/View.tsx +115 -0
- package/ui/Load/index.ts +11 -0
- package/ui/Load/index_.tsx +6 -0
- package/ui/Loading/Area.tsx +10 -0
- package/ui/Loading/Button.tsx +17 -0
- package/ui/Loading/Input.tsx +17 -0
- package/ui/Loading/ProgressBar.tsx +14 -0
- package/ui/Loading/Skeleton.tsx +22 -0
- package/ui/Loading/Spin.tsx +22 -0
- package/ui/Loading/index.tsx +8 -0
- package/ui/Menu.tsx +273 -0
- package/ui/Modal.tsx +87 -0
- package/ui/Model/AdminPanel.tsx +51 -0
- package/ui/Model/Edit.tsx +46 -0
- package/ui/Model/EditModal.tsx +301 -0
- package/ui/Model/EditWrapper.tsx +48 -0
- package/ui/Model/LoadInit.tsx +11 -0
- package/ui/Model/New.tsx +46 -0
- package/ui/Model/NewWrapper.tsx +20 -0
- package/ui/Model/NewWrapper_Client.tsx +57 -0
- package/ui/Model/Remove.tsx +75 -0
- package/ui/Model/RemoveWrapper.tsx +38 -0
- package/ui/Model/SureToRemove.tsx +108 -0
- package/ui/Model/View.tsx +65 -0
- package/ui/Model/ViewEditModal.tsx +125 -0
- package/ui/Model/ViewModal.tsx +71 -0
- package/ui/Model/ViewWrapper.tsx +38 -0
- package/ui/Model/index.ts +33 -0
- package/ui/Model/index_.tsx +16 -0
- package/ui/More.tsx +56 -0
- package/ui/ObjectId.tsx +29 -0
- package/ui/Pagination.tsx +120 -0
- package/ui/Popconfirm.tsx +135 -0
- package/ui/Portal.tsx +10 -0
- package/ui/Radio.tsx +53 -0
- package/ui/RecentTime.tsx +123 -0
- package/ui/Refresh.tsx +24 -0
- package/ui/ScreenNavigator.tsx +129 -0
- package/ui/Select.tsx +322 -0
- package/ui/Signal/Arg.tsx +352 -0
- package/ui/Signal/Doc.tsx +231 -0
- package/ui/Signal/Listener.tsx +74 -0
- package/ui/Signal/Message.tsx +267 -0
- package/ui/Signal/Object.tsx +131 -0
- package/ui/Signal/PubSub.tsx +247 -0
- package/ui/Signal/Request.tsx +30 -0
- package/ui/Signal/Response.tsx +76 -0
- package/ui/Signal/RestApi.tsx +390 -0
- package/ui/Signal/WebSocket.tsx +47 -0
- package/ui/Signal/index.ts +10 -0
- package/ui/Signal/makeExample.ts +75 -0
- package/ui/System/CSR.tsx +420 -0
- package/ui/System/Client.tsx +296 -0
- package/ui/System/Common.tsx +83 -0
- package/ui/System/DevModeToggle.tsx +21 -0
- package/ui/System/Gtag.tsx +69 -0
- package/ui/System/Messages.tsx +175 -0
- package/ui/System/Reconnect.tsx +156 -0
- package/ui/System/Root.tsx +10 -0
- package/ui/System/SSR.tsx +163 -0
- package/ui/System/SelectLanguage.tsx +47 -0
- package/ui/System/ThemeToggle.tsx +98 -0
- package/ui/System/index.tsx +23 -0
- package/ui/Tab/Menu.tsx +56 -0
- package/ui/Tab/Menus.tsx +10 -0
- package/ui/Tab/Panel.tsx +25 -0
- package/ui/Tab/Provider.tsx +25 -0
- package/ui/Tab/context.ts +16 -0
- package/ui/Tab/index.tsx +11 -0
- package/ui/Table.tsx +131 -0
- package/ui/ToggleSelect.tsx +144 -0
- package/ui/Unauthorized.tsx +29 -0
- package/ui/animated.tsx +8 -0
- package/ui/fontCss.ts +86 -0
- package/ui/index.ts +44 -0
- package/ui/styles.css +617 -0
- package/webkit/bootCsr.tsx +275 -0
- package/webkit/createRobotPage.ts +15 -0
- package/webkit/createSitemapPage.ts +4 -0
- package/webkit/index.ts +19 -0
- package/webkit/lazy.tsx +37 -0
- package/webkit/types.ts +7 -0
- package/webkit/useCamera.tsx +99 -0
- package/webkit/useCodepush.tsx +99 -0
- package/webkit/useContact.tsx +48 -0
- package/webkit/useCsrValues.ts +661 -0
- package/webkit/useDebounce.ts +24 -0
- package/webkit/useFetch.ts +48 -0
- package/webkit/useGeoLocation.tsx +24 -0
- package/webkit/useHistory.ts +76 -0
- package/webkit/useInterval.ts +21 -0
- package/webkit/useLocation.ts +69 -0
- package/webkit/usePurchase.tsx +156 -0
- package/webkit/usePushNoti.tsx +48 -0
- package/webkit/useThrottle.ts +22 -0
- package/src/index.js +0 -2
- package/src/index.js.map +0 -1
- package/src/lib/akan2.js +0 -4
- package/src/lib/akan2.js.map +0 -1
- package/src/run.js +0 -4
- package/src/run.js.map +0 -1
|
@@ -0,0 +1,855 @@
|
|
|
1
|
+
import { mkdir, rm } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { Logger } from "akanjs/common";
|
|
4
|
+
import type { AkanChildRole, AkanChildStatus, AkanIpcMessage, AkanMetricsReport, AkanUpstream } from "akanjs/service";
|
|
5
|
+
import type { BuilderMessage, BuilderReq, BuilderRes } from "./artifact";
|
|
6
|
+
import { RotatingLogWriter } from "./logging/rotatingLogWriter";
|
|
7
|
+
import { ProcessMetricsCollector } from "./processMetricsCollector";
|
|
8
|
+
|
|
9
|
+
interface ChildState {
|
|
10
|
+
idx: number;
|
|
11
|
+
role: AkanChildRole;
|
|
12
|
+
proc: Bun.Subprocess<"ignore", "pipe", "pipe">;
|
|
13
|
+
ready: boolean;
|
|
14
|
+
status: AkanChildStatus;
|
|
15
|
+
pid?: number;
|
|
16
|
+
upstream?: AkanUpstream;
|
|
17
|
+
healthPath?: string;
|
|
18
|
+
metrics: AkanMetricsReport;
|
|
19
|
+
lastPongAt?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface GatewayWsData {
|
|
23
|
+
childIdx: number;
|
|
24
|
+
socketId: string;
|
|
25
|
+
upstream: WebSocket;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type GatewayUpstream = {
|
|
29
|
+
http: Extract<AkanUpstream, { type: "unix" }>;
|
|
30
|
+
ws?: Extract<AkanUpstream, { type: "tcp" }>;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** Options for the Akan gateway that launches child server replicas and listens for traffic. */
|
|
34
|
+
export interface AkanAppOptions {
|
|
35
|
+
replica?: number | string;
|
|
36
|
+
serverPath?: string;
|
|
37
|
+
runtimeDir?: string;
|
|
38
|
+
port?: number;
|
|
39
|
+
wsBasePort?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface AkanReplicaConfig {
|
|
43
|
+
federation: number;
|
|
44
|
+
batch: number;
|
|
45
|
+
all: number;
|
|
46
|
+
total: number;
|
|
47
|
+
value: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Gateway/orchestrator that starts Akan child servers and proxies HTTP/WebSocket traffic. */
|
|
51
|
+
export class AkanApp {
|
|
52
|
+
static readonly #hopByHopHeaders = new Set([
|
|
53
|
+
"connection",
|
|
54
|
+
"keep-alive",
|
|
55
|
+
"proxy-authenticate",
|
|
56
|
+
"proxy-authorization",
|
|
57
|
+
"te",
|
|
58
|
+
"trailer",
|
|
59
|
+
"transfer-encoding",
|
|
60
|
+
"upgrade",
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
readonly logger = new Logger("AkanApp");
|
|
64
|
+
readonly #serverPath: string;
|
|
65
|
+
readonly #artifactDir: string;
|
|
66
|
+
readonly #replica: AkanReplicaConfig;
|
|
67
|
+
readonly #runtimeDir: string;
|
|
68
|
+
readonly #port: number;
|
|
69
|
+
readonly #wsBasePort: number;
|
|
70
|
+
readonly #children = new Map<number, ChildState>();
|
|
71
|
+
readonly #roomChildren = new Map<string, Set<number>>();
|
|
72
|
+
readonly #childRooms = new Map<number, Set<string>>();
|
|
73
|
+
readonly #socketRooms = new Map<string, { childIdx: number; rooms: Set<string> }>();
|
|
74
|
+
#nextBuilderReqId = 1;
|
|
75
|
+
readonly #builderReqMap = new Map<number, { childIdx: number; childLocalId: number }>();
|
|
76
|
+
#server: Bun.Server<GatewayWsData> | null = null;
|
|
77
|
+
#rrIdx = 0;
|
|
78
|
+
#snapshotTimer: Timer | null = null;
|
|
79
|
+
#healthTimer: Timer | null = null;
|
|
80
|
+
#metricsTimer: Timer | null = null;
|
|
81
|
+
#logWriter: RotatingLogWriter | null = null;
|
|
82
|
+
#removeLogSink: (() => void) | null = null;
|
|
83
|
+
readonly #childOutputBuffers = new Map<string, string>();
|
|
84
|
+
static readonly #ansiPattern = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
|
|
85
|
+
#gatewayMetrics: AkanMetricsReport = {};
|
|
86
|
+
#resolveStopped: (() => void) | null = null;
|
|
87
|
+
#exitAfterStop = false;
|
|
88
|
+
#stopping = false;
|
|
89
|
+
|
|
90
|
+
constructor(serverPath = "./server", options: AkanAppOptions = {}) {
|
|
91
|
+
this.#serverPath = AkanApp.#resolveServerPath(options.serverPath ?? serverPath);
|
|
92
|
+
this.#artifactDir = path.resolve(path.dirname(this.#serverPath), ".akan", "artifact");
|
|
93
|
+
this.#replica = AkanApp.#parseReplicaConfig(options.replica);
|
|
94
|
+
this.#runtimeDir =
|
|
95
|
+
(options.runtimeDir ?? process.env.AKAN_RUNTIME_DIR ?? process.env.NODE_ENV === "production")
|
|
96
|
+
? path.resolve(process.cwd(), "runtime")
|
|
97
|
+
: path.resolve(process.cwd(), "local", "apps", process.env.AKAN_PUBLIC_APP_NAME ?? "unknown", "runtime");
|
|
98
|
+
this.#port = Number(options.port ?? process.env.PORT ?? 8282);
|
|
99
|
+
this.#wsBasePort = Number(options.wsBasePort ?? process.env.AKAN_WS_BASE_PORT ?? this.#port + 10_000);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
static #resolveServerPath(serverPath: string) {
|
|
103
|
+
const baseDir = path.dirname(Bun.main);
|
|
104
|
+
const resolved = path.isAbsolute(serverPath) ? serverPath : path.resolve(baseDir, serverPath);
|
|
105
|
+
if (path.extname(resolved)) return resolved;
|
|
106
|
+
return Bun.main.endsWith(".js") ? `${resolved}.js` : `${resolved}.ts`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
static #parseReplicaConfig(value?: number | string): AkanReplicaConfig {
|
|
110
|
+
const configured = value ?? process.env.AKAN_REPLICA;
|
|
111
|
+
const raw = String(configured ?? "0,0,1").trim();
|
|
112
|
+
const [federationRaw, batchRaw, allRaw] = raw.split(",");
|
|
113
|
+
const federation = AkanApp.#parseReplicaCount(federationRaw, configured == null ? 0 : 0, 0);
|
|
114
|
+
const batch = AkanApp.#parseReplicaCount(batchRaw, configured == null ? 0 : 0, 0);
|
|
115
|
+
const all = AkanApp.#parseReplicaCount(allRaw, configured == null ? 1 : 0, 0);
|
|
116
|
+
const normalizedAll = federation + batch + all > 0 ? all : 1;
|
|
117
|
+
return {
|
|
118
|
+
federation,
|
|
119
|
+
batch,
|
|
120
|
+
all: normalizedAll,
|
|
121
|
+
total: federation + batch + normalizedAll,
|
|
122
|
+
value: `${federation},${batch},${normalizedAll}`,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
static #parseReplicaCount(value: string | undefined, fallback: number, min: number) {
|
|
127
|
+
const parsed = Number.parseInt(value ?? "", 10);
|
|
128
|
+
if (!Number.isFinite(parsed)) return fallback;
|
|
129
|
+
return Math.max(min, parsed);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
static #defaultChildNodeEnv() {
|
|
133
|
+
if (process.env.NODE_ENV) return process.env.NODE_ENV;
|
|
134
|
+
if (process.env.AKAN_COMMAND_TYPE === "start") return "development";
|
|
135
|
+
if (process.env.AKAN_COMMAND_TYPE === "build") return "production";
|
|
136
|
+
return Bun.main.endsWith(".js") ? "production" : "development";
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async start() {
|
|
140
|
+
await this.#prepareRuntimeDir();
|
|
141
|
+
this.#startFileLogging();
|
|
142
|
+
for (let idx = 0; idx < this.#replica.total; idx++) this.#spawn(idx);
|
|
143
|
+
this.#listen();
|
|
144
|
+
this.#snapshotTimer = setInterval(() => this.#requestRoomSnapshots(), 30_000);
|
|
145
|
+
this.#healthTimer = setInterval(() => this.#checkHealth(), 2_000);
|
|
146
|
+
this.#startMetricsReporting();
|
|
147
|
+
process.on("message", (message) => this.#handleHostMessage(message as BuilderMessage));
|
|
148
|
+
process.on("SIGINT", () => this.#handleShutdownSignal("SIGINT"));
|
|
149
|
+
process.on("SIGTERM", () => this.#handleShutdownSignal("SIGTERM"));
|
|
150
|
+
await new Promise<void>((resolve) => {
|
|
151
|
+
|
|
152
|
+
this.#resolveStopped = resolve;
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async stop(signal = "SIGTERM") {
|
|
157
|
+
if (this.#stopping) return;
|
|
158
|
+
this.#stopping = true;
|
|
159
|
+
if (this.#snapshotTimer) {
|
|
160
|
+
clearInterval(this.#snapshotTimer);
|
|
161
|
+
this.#snapshotTimer = null;
|
|
162
|
+
}
|
|
163
|
+
if (this.#healthTimer) {
|
|
164
|
+
clearInterval(this.#healthTimer);
|
|
165
|
+
this.#healthTimer = null;
|
|
166
|
+
}
|
|
167
|
+
if (this.#metricsTimer) {
|
|
168
|
+
clearInterval(this.#metricsTimer);
|
|
169
|
+
this.#metricsTimer = null;
|
|
170
|
+
}
|
|
171
|
+
this.#server?.stop(true);
|
|
172
|
+
this.#server = null;
|
|
173
|
+
for (const child of this.#children.values()) {
|
|
174
|
+
if (!child.proc.killed) child.proc.send({ type: "shutdown", signal } satisfies AkanIpcMessage);
|
|
175
|
+
}
|
|
176
|
+
await Promise.race([
|
|
177
|
+
Promise.all([...this.#children.values()].map((child) => child.proc.exited.catch(() => undefined))),
|
|
178
|
+
new Promise((resolve) => setTimeout(resolve, 30_000)),
|
|
179
|
+
]);
|
|
180
|
+
for (const child of this.#children.values()) {
|
|
181
|
+
if (!child.proc.killed) child.proc.kill();
|
|
182
|
+
}
|
|
183
|
+
this.#children.clear();
|
|
184
|
+
await this.#stopFileLogging();
|
|
185
|
+
this.#resolveStopped?.();
|
|
186
|
+
this.#resolveStopped = null;
|
|
187
|
+
if (this.#exitAfterStop) process.exit(0);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
#handleShutdownSignal(signal: NodeJS.Signals) {
|
|
191
|
+
if (this.#stopping) process.exit(1);
|
|
192
|
+
this.#exitAfterStop = true;
|
|
193
|
+
void this.stop(signal).catch((error) => {
|
|
194
|
+
this.logger.error(`Failed to shutdown gateway: ${error instanceof Error ? error.message : String(error)}`);
|
|
195
|
+
process.exit(1);
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#spawn(idx: number) {
|
|
200
|
+
const role = this.#getRole(idx);
|
|
201
|
+
const upstream = this.#getChildUpstream(idx, role);
|
|
202
|
+
const childCode = `import(${JSON.stringify(path.resolve(this.#serverPath))}).then((mod)=>{ const server = mod.server ?? mod.app; if (!server?.start) throw new Error("server.ts must export server or app with start()"); return server.start({ listen: process.env.SERVER_MODE !== "batch" }); }).catch((error)=>{ process.send?.({ type: "error", message: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined, pid: process.pid }); process.exit(1); });`;
|
|
203
|
+
const proc = Bun.spawn(["bun", "-e", childCode], {
|
|
204
|
+
cwd: process.cwd(),
|
|
205
|
+
env: {
|
|
206
|
+
...process.env,
|
|
207
|
+
NODE_ENV: AkanApp.#defaultChildNodeEnv(),
|
|
208
|
+
AKAN_REPLICA: this.#replica.value,
|
|
209
|
+
AKAN_REPLICA_IDX: String(idx),
|
|
210
|
+
AKAN_APP_DIR: path.dirname(this.#serverPath),
|
|
211
|
+
SERVER_MODE: role,
|
|
212
|
+
AKAN_CHILD_SOCKET: upstream.http.socketPath,
|
|
213
|
+
AKAN_CHILD_WS_PORT: upstream.ws ? String(upstream.ws.port) : "",
|
|
214
|
+
},
|
|
215
|
+
ipc: (message) => this.#handleMessage(idx, message as AkanIpcMessage),
|
|
216
|
+
stdout: "pipe",
|
|
217
|
+
stderr: "pipe",
|
|
218
|
+
stdin: "ignore",
|
|
219
|
+
});
|
|
220
|
+
this.#children.set(idx, { idx, role, proc, ready: false, status: "starting", metrics: {} });
|
|
221
|
+
this.#pipeOutput(idx, role, proc.stdout, "stdout");
|
|
222
|
+
this.#pipeOutput(idx, role, proc.stderr, "stderr");
|
|
223
|
+
proc.exited.then((code) => {
|
|
224
|
+
const child = this.#children.get(idx);
|
|
225
|
+
if (child) child.status = "exited";
|
|
226
|
+
this.#removeChildRooms(idx);
|
|
227
|
+
if (this.#stopping) return;
|
|
228
|
+
this.logger.error(`Child ${idx}/${role} exited with code ${code}; shutting down all children`);
|
|
229
|
+
void this.stop("child-exit");
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async #prepareRuntimeDir() {
|
|
234
|
+
await mkdir(this.#runtimeDir, { recursive: true });
|
|
235
|
+
for (let idx = 0; idx < this.#replica.total; idx++) {
|
|
236
|
+
const socketPath = this.#getChildUpstream(idx, this.#getRole(idx)).http.socketPath;
|
|
237
|
+
try {
|
|
238
|
+
await rm(socketPath, { force: true });
|
|
239
|
+
} catch {
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
#startFileLogging() {
|
|
245
|
+
this.#logWriter = RotatingLogWriter.fromRuntimeDir(this.#runtimeDir);
|
|
246
|
+
if (!this.#logWriter) return;
|
|
247
|
+
this.#removeLogSink = Logger.addSink((entry) => {
|
|
248
|
+
this.#logWriter?.write("gateway", entry.plainMessage);
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async #stopFileLogging() {
|
|
253
|
+
this.#removeLogSink?.();
|
|
254
|
+
this.#removeLogSink = null;
|
|
255
|
+
const writer = this.#logWriter;
|
|
256
|
+
this.#logWriter = null;
|
|
257
|
+
await writer?.close();
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
#listen() {
|
|
261
|
+
this.#server = Bun.serve({
|
|
262
|
+
idleTimeout: 0,
|
|
263
|
+
port: this.#port,
|
|
264
|
+
fetch: (req, server) => this.#handleFetch(req, server),
|
|
265
|
+
websocket: {
|
|
266
|
+
idleTimeout: 0,
|
|
267
|
+
maxPayloadLength: 16 * 1024 * 1024,
|
|
268
|
+
backpressureLimit: 1024 * 1024,
|
|
269
|
+
closeOnBackpressureLimit: true,
|
|
270
|
+
open: (ws) => this.#handleWsOpen(ws),
|
|
271
|
+
message: (ws, message) => this.#handleWsMessage(ws, message),
|
|
272
|
+
close: (ws, code, reason) => this.#handleWsClose(ws, code, reason),
|
|
273
|
+
data: {} as GatewayWsData,
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
this.logger.info(`AkanApp gateway is running on port ${this.#port}`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async #handleFetch(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response | undefined> {
|
|
280
|
+
const url = new URL(req.url);
|
|
281
|
+
if (url.pathname === "/_akan/app/health") return Response.json(this.#getHealthStatus());
|
|
282
|
+
if (url.pathname === "/_akan/app/metrics") return Response.json(this.#getMetricsStatus());
|
|
283
|
+
if (this.#isWebSocketPath(url.pathname)) return this.#upgradeWebSocket(req, server);
|
|
284
|
+
const assetResponse = await this.#serveImmutableArtifact(req, url);
|
|
285
|
+
if (assetResponse) return assetResponse;
|
|
286
|
+
return await this.#proxyHttp(req);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
#isWebSocketPath(pathname: string) {
|
|
290
|
+
return pathname === "/api/ws" || pathname === "/_akan/hmr";
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async #serveImmutableArtifact(req: Request, url: URL): Promise<Response | null> {
|
|
294
|
+
const clientPrefix = "/_akan/client/";
|
|
295
|
+
if (url.pathname.startsWith(clientPrefix)) {
|
|
296
|
+
const filePath = this.#safeResolve(
|
|
297
|
+
path.join(this.#artifactDir, "client"),
|
|
298
|
+
url.pathname.slice(clientPrefix.length),
|
|
299
|
+
);
|
|
300
|
+
if (!filePath) return new Response("Not Found", { status: 404 });
|
|
301
|
+
const file = Bun.file(filePath);
|
|
302
|
+
if (!(await file.exists())) return new Response("Not Found", { status: 404 });
|
|
303
|
+
return this.#fileResponse(req, filePath, {
|
|
304
|
+
contentType: file.type || "application/javascript",
|
|
305
|
+
cacheControl: "public, max-age=31536000, immutable",
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
for (const prefix of ["/_akan/styles/", "/_akan/fonts/"]) {
|
|
310
|
+
if (!url.pathname.startsWith(prefix)) continue;
|
|
311
|
+
const filePath = this.#safeResolve(this.#artifactDir, url.pathname.slice("/_akan/".length));
|
|
312
|
+
if (!filePath) return new Response("Not Found", { status: 404 });
|
|
313
|
+
const file = Bun.file(filePath);
|
|
314
|
+
if (!(await file.exists())) return new Response("Not Found", { status: 404 });
|
|
315
|
+
return this.#fileResponse(req, filePath, {
|
|
316
|
+
contentType: file.type || (prefix === "/_akan/styles/" ? "text/css; charset=utf-8" : "font/woff2"),
|
|
317
|
+
cacheControl: "public, max-age=31536000, immutable",
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
#upgradeWebSocket(req: Request, server: Bun.Server<GatewayWsData>): Response | undefined {
|
|
325
|
+
const child = this.#pickFederationChild();
|
|
326
|
+
if (!child?.upstream || !child.upstream || !this.#getChildUpstream(child.idx, child.role).ws) {
|
|
327
|
+
return new Response("No websocket upstream is ready", { status: 503 });
|
|
328
|
+
}
|
|
329
|
+
const upstream = this.#getChildUpstream(child.idx, child.role).ws;
|
|
330
|
+
if (!upstream) return new Response("No websocket upstream is ready", { status: 503 });
|
|
331
|
+
const url = new URL(req.url);
|
|
332
|
+
const upstreamWs = new WebSocket(`ws://${upstream.host}:${upstream.port}${url.pathname}${url.search}`, {
|
|
333
|
+
headers: this.#makeProxyHeaders(req, child.idx),
|
|
334
|
+
} as unknown as string[]);
|
|
335
|
+
const socketId = crypto.randomUUID();
|
|
336
|
+
const upgraded = server.upgrade(req, { data: { childIdx: child.idx, socketId, upstream: upstreamWs } });
|
|
337
|
+
if (!upgraded) {
|
|
338
|
+
upstreamWs.close();
|
|
339
|
+
return new Response("WebSocket upgrade failed", { status: 500 });
|
|
340
|
+
}
|
|
341
|
+
child.metrics.activeWebSockets = (child.metrics.activeWebSockets ?? 0) + 1;
|
|
342
|
+
return undefined;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
#handleWsOpen(ws: Bun.ServerWebSocket<GatewayWsData>) {
|
|
346
|
+
const upstream = ws.data.upstream;
|
|
347
|
+
const pending: (string | ArrayBuffer)[] = [];
|
|
348
|
+
upstream.addEventListener("open", () => {
|
|
349
|
+
for (const message of pending.splice(0)) upstream.send(message);
|
|
350
|
+
});
|
|
351
|
+
upstream.addEventListener("message", (event) => {
|
|
352
|
+
const result = ws.send(event.data as string | ArrayBuffer);
|
|
353
|
+
if (result === 0) upstream.close();
|
|
354
|
+
});
|
|
355
|
+
upstream.addEventListener("close", (event) => ws.close(event.code, event.reason));
|
|
356
|
+
upstream.addEventListener("error", () => ws.close(1011, "upstream websocket error"));
|
|
357
|
+
Object.assign(ws.data, { pending });
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
#handleWsMessage(
|
|
361
|
+
ws: Bun.ServerWebSocket<GatewayWsData & { pending?: (string | ArrayBuffer)[] }>,
|
|
362
|
+
message: string | ArrayBuffer | Uint8Array,
|
|
363
|
+
) {
|
|
364
|
+
const upstream = ws.data.upstream;
|
|
365
|
+
const payload =
|
|
366
|
+
typeof message === "string"
|
|
367
|
+
? message
|
|
368
|
+
: message instanceof ArrayBuffer
|
|
369
|
+
? message
|
|
370
|
+
: new Uint8Array(message).slice().buffer;
|
|
371
|
+
if (upstream.readyState === WebSocket.OPEN) upstream.send(payload);
|
|
372
|
+
else ws.data.pending?.push(payload as string | ArrayBuffer);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
#handleWsClose(ws: Bun.ServerWebSocket<GatewayWsData>, code: number, reason: string) {
|
|
376
|
+
ws.data.upstream.close(code, reason);
|
|
377
|
+
const child = this.#children.get(ws.data.childIdx);
|
|
378
|
+
if (child) child.metrics.activeWebSockets = Math.max(0, (child.metrics.activeWebSockets ?? 1) - 1);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
#getHealthStatus() {
|
|
382
|
+
return {
|
|
383
|
+
status: this.#stopping ? "stopping" : "running",
|
|
384
|
+
children: [...this.#children.values()].map((child) => ({
|
|
385
|
+
idx: child.idx,
|
|
386
|
+
role: child.role,
|
|
387
|
+
status: child.status,
|
|
388
|
+
ready: child.ready,
|
|
389
|
+
pid: child.pid,
|
|
390
|
+
upstream: child.upstream,
|
|
391
|
+
})),
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
#getMetricsStatus() {
|
|
396
|
+
return {
|
|
397
|
+
rooms: this.#roomChildren.size,
|
|
398
|
+
sockets: this.#socketRooms.size,
|
|
399
|
+
gateway: this.#gatewayMetrics,
|
|
400
|
+
children: [...this.#children.values()].map((child) => ({
|
|
401
|
+
idx: child.idx,
|
|
402
|
+
role: child.role,
|
|
403
|
+
metrics: child.metrics,
|
|
404
|
+
rooms: this.#childRooms.get(child.idx)?.size ?? 0,
|
|
405
|
+
})),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async #proxyHttp(req: Request): Promise<Response> {
|
|
410
|
+
const child = this.#pickFederationChild();
|
|
411
|
+
if (!child?.upstream || child.upstream.type !== "unix") {
|
|
412
|
+
return new Response("No healthy federation child is ready", { status: 503 });
|
|
413
|
+
}
|
|
414
|
+
const url = new URL(req.url);
|
|
415
|
+
const upstreamUrl = `http://akan-child${url.pathname}${url.search}`;
|
|
416
|
+
const headers = this.#makeProxyHeaders(req, child.idx);
|
|
417
|
+
child.metrics.activeRequests = (child.metrics.activeRequests ?? 0) + 1;
|
|
418
|
+
child.metrics.totalRequests = (child.metrics.totalRequests ?? 0) + 1;
|
|
419
|
+
try {
|
|
420
|
+
const upstreamRes = await fetch(upstreamUrl, {
|
|
421
|
+
unix: child.upstream.socketPath,
|
|
422
|
+
method: req.method,
|
|
423
|
+
headers,
|
|
424
|
+
body: req.method === "GET" || req.method === "HEAD" ? undefined : req.body,
|
|
425
|
+
signal: req.signal,
|
|
426
|
+
redirect: "manual",
|
|
427
|
+
});
|
|
428
|
+
return this.#proxyResponse(upstreamRes);
|
|
429
|
+
} finally {
|
|
430
|
+
child.metrics.activeRequests = Math.max(0, (child.metrics.activeRequests ?? 1) - 1);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
#proxyResponse(upstreamRes: Response): Response {
|
|
435
|
+
const headers = new Headers(upstreamRes.headers);
|
|
436
|
+
|
|
437
|
+
headers.delete("content-encoding");
|
|
438
|
+
headers.delete("content-length");
|
|
439
|
+
this.#rewriteInternalLocation(headers);
|
|
440
|
+
return new Response(upstreamRes.body, {
|
|
441
|
+
status: upstreamRes.status,
|
|
442
|
+
statusText: upstreamRes.statusText,
|
|
443
|
+
headers,
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
#rewriteInternalLocation(headers: Headers) {
|
|
448
|
+
const location = headers.get("location");
|
|
449
|
+
if (!location) return;
|
|
450
|
+
try {
|
|
451
|
+
const parsed = new URL(location);
|
|
452
|
+
if (parsed.hostname === "akan-child") headers.set("location", `${parsed.pathname}${parsed.search}${parsed.hash}`);
|
|
453
|
+
} catch {
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async #fileResponse(
|
|
458
|
+
req: Request,
|
|
459
|
+
filePath: string,
|
|
460
|
+
options: { contentType: string; cacheControl?: string },
|
|
461
|
+
): Promise<Response> {
|
|
462
|
+
const headers = new Headers({ "Content-Type": options.contentType });
|
|
463
|
+
if (options.cacheControl) headers.set("Cache-Control", options.cacheControl);
|
|
464
|
+
|
|
465
|
+
const gzipPath = `${filePath}.gz`;
|
|
466
|
+
if (this.#acceptsGzip(req) && this.#isCompressible(options.contentType)) {
|
|
467
|
+
const gzipFile = Bun.file(gzipPath);
|
|
468
|
+
if (await gzipFile.exists()) {
|
|
469
|
+
const gzipBytes = await gzipFile.bytes();
|
|
470
|
+
headers.set("Content-Encoding", "gzip");
|
|
471
|
+
headers.set("Content-Length", String(gzipBytes.byteLength));
|
|
472
|
+
headers.set("Vary", "Accept-Encoding");
|
|
473
|
+
return new Response(this.#toArrayBuffer(gzipBytes), { headers });
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
return new Response(Bun.file(filePath).stream(), { headers });
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
#acceptsGzip(req: Request): boolean {
|
|
481
|
+
const acceptEncoding = req.headers.get("accept-encoding") ?? "";
|
|
482
|
+
return /\bgzip\b/.test(acceptEncoding);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
#isCompressible(contentType: string): boolean {
|
|
486
|
+
const type = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
487
|
+
return (
|
|
488
|
+
type.startsWith("text/") ||
|
|
489
|
+
type === "application/javascript" ||
|
|
490
|
+
type === "application/json" ||
|
|
491
|
+
type === "application/manifest+json" ||
|
|
492
|
+
type === "image/svg+xml"
|
|
493
|
+
);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
#toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
|
|
497
|
+
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
#safeResolve(baseDir: string, urlPath: string): string | null {
|
|
501
|
+
let decoded: string;
|
|
502
|
+
try {
|
|
503
|
+
decoded = decodeURIComponent(urlPath);
|
|
504
|
+
} catch {
|
|
505
|
+
return null;
|
|
506
|
+
}
|
|
507
|
+
if (decoded.includes("\0")) return null;
|
|
508
|
+
const normalizedBase = path.resolve(baseDir);
|
|
509
|
+
const rel = decoded.replace(/^[/\\]+/, "");
|
|
510
|
+
const resolved = path.resolve(normalizedBase, rel);
|
|
511
|
+
if (resolved === normalizedBase) return resolved;
|
|
512
|
+
const baseWithSep = normalizedBase.endsWith(path.sep) ? normalizedBase : `${normalizedBase}${path.sep}`;
|
|
513
|
+
if (!resolved.startsWith(baseWithSep)) return null;
|
|
514
|
+
return resolved;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
#makeProxyHeaders(req: Request, childIdx: number) {
|
|
518
|
+
const headers = new Headers(req.headers);
|
|
519
|
+
for (const key of AkanApp.#hopByHopHeaders) headers.delete(key);
|
|
520
|
+
const url = new URL(req.url);
|
|
521
|
+
const forwardedFor = headers.get("x-forwarded-for");
|
|
522
|
+
const clientAddress = headers.get("x-real-ip") ?? "127.0.0.1";
|
|
523
|
+
headers.set("x-forwarded-for", forwardedFor ? `${forwardedFor}, ${clientAddress}` : clientAddress);
|
|
524
|
+
headers.set("x-forwarded-host", headers.get("host") ?? url.host);
|
|
525
|
+
headers.set("x-forwarded-proto", url.protocol.replace(":", ""));
|
|
526
|
+
headers.set("x-akan-child-idx", String(childIdx));
|
|
527
|
+
headers.set("x-request-id", headers.get("x-request-id") ?? crypto.randomUUID());
|
|
528
|
+
headers.set("host", "akan-child");
|
|
529
|
+
return headers;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
#pickFederationChild() {
|
|
533
|
+
const candidates = [...this.#children.values()].filter(
|
|
534
|
+
(child) =>
|
|
535
|
+
(child.role === "federation" || child.role === "all") &&
|
|
536
|
+
child.ready &&
|
|
537
|
+
child.status !== "unhealthy" &&
|
|
538
|
+
child.status !== "exited" &&
|
|
539
|
+
!child.proc.killed,
|
|
540
|
+
);
|
|
541
|
+
if (candidates.length === 0) return null;
|
|
542
|
+
const child = candidates[this.#rrIdx % candidates.length];
|
|
543
|
+
this.#rrIdx++;
|
|
544
|
+
return child;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
#getRole(idx: number): AkanChildRole {
|
|
548
|
+
if (idx < this.#replica.federation) return "federation";
|
|
549
|
+
if (idx < this.#replica.federation + this.#replica.batch) return "batch";
|
|
550
|
+
return "all";
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
#getChildUpstream(idx: number, role: AkanChildRole): GatewayUpstream {
|
|
554
|
+
return {
|
|
555
|
+
http: { type: "unix", socketPath: path.join(this.#runtimeDir, `akan-child-${idx}.sock`) },
|
|
556
|
+
ws: role === "batch" ? undefined : { type: "tcp", host: "127.0.0.1", port: this.#wsBasePort + idx },
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
#handleMessage(idx: number, message: AkanIpcMessage | BuilderMessage) {
|
|
561
|
+
if (!message || typeof message !== "object") return;
|
|
562
|
+
switch (message.type) {
|
|
563
|
+
case "ready":
|
|
564
|
+
this.#markReady(idx, message);
|
|
565
|
+
return;
|
|
566
|
+
case "pubsub.publish":
|
|
567
|
+
this.#deliverPubsub(idx, message);
|
|
568
|
+
return;
|
|
569
|
+
case "pubsub.subscribe":
|
|
570
|
+
this.#addRoomMembership(idx, message.roomId, message.socketId);
|
|
571
|
+
return;
|
|
572
|
+
case "pubsub.unsubscribe":
|
|
573
|
+
this.#removeRoomMembership(idx, message.roomId, message.socketId);
|
|
574
|
+
return;
|
|
575
|
+
case "pubsub.snapshot":
|
|
576
|
+
this.#replaceRoomSnapshot(idx, message.rooms);
|
|
577
|
+
return;
|
|
578
|
+
case "metrics.report":
|
|
579
|
+
this.#updateMetrics(idx, message.metrics);
|
|
580
|
+
return;
|
|
581
|
+
case "health.pong":
|
|
582
|
+
this.#markHealthy(idx);
|
|
583
|
+
return;
|
|
584
|
+
case "queue.enqueued":
|
|
585
|
+
this.#fanoutToBatch({ type: "queue.wake", queue: message.queue, name: message.name });
|
|
586
|
+
return;
|
|
587
|
+
case "error":
|
|
588
|
+
this.logger.error(message.message);
|
|
589
|
+
void this.stop("child-error");
|
|
590
|
+
return;
|
|
591
|
+
case "build-route":
|
|
592
|
+
this.#forwardBuildRoute(idx, message);
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
#handleHostMessage(message: BuilderMessage) {
|
|
598
|
+
if (!message || typeof message !== "object") return;
|
|
599
|
+
switch (message.type) {
|
|
600
|
+
case "builder-ready":
|
|
601
|
+
case "invalidate":
|
|
602
|
+
case "css-updated":
|
|
603
|
+
case "pages-updated":
|
|
604
|
+
this.#fanoutToFederation(message);
|
|
605
|
+
return;
|
|
606
|
+
case "build-route-res":
|
|
607
|
+
this.#forwardBuildRouteResponse(message);
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
#markReady(idx: number, message: Extract<AkanIpcMessage, { type: "ready" }>) {
|
|
613
|
+
const child = this.#children.get(idx);
|
|
614
|
+
if (!child) return;
|
|
615
|
+
child.ready = true;
|
|
616
|
+
child.status = "ready";
|
|
617
|
+
child.pid = message.pid;
|
|
618
|
+
child.upstream = message.upstream;
|
|
619
|
+
child.healthPath = message.healthPath;
|
|
620
|
+
child.lastPongAt = Date.now();
|
|
621
|
+
if ([...this.#children.values()].every((item) => item.ready)) {
|
|
622
|
+
process.send?.({ type: "backend-ready", pid: process.pid } satisfies AkanIpcMessage);
|
|
623
|
+
this.logger.verbose(`All ${this.#children.size} child process(es) are ready`);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
#markHealthy(idx: number) {
|
|
628
|
+
const child = this.#children.get(idx);
|
|
629
|
+
if (!child) return;
|
|
630
|
+
child.status = "healthy";
|
|
631
|
+
child.lastPongAt = Date.now();
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
#deliverPubsub(originIdx: number, message: Extract<AkanIpcMessage, { type: "pubsub.publish" }>) {
|
|
635
|
+
const targets = this.#roomChildren.get(message.roomId);
|
|
636
|
+
if (!targets?.size) {
|
|
637
|
+
const child = this.#children.get(originIdx);
|
|
638
|
+
if (child) child.metrics.pubsubDropCount = (child.metrics.pubsubDropCount ?? 0) + 1;
|
|
639
|
+
this.logger.verbose(`Dropping pubsub ${message.roomId}; no subscribers`);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
for (const childIdx of targets) {
|
|
643
|
+
if (childIdx === originIdx) continue;
|
|
644
|
+
const child = this.#children.get(childIdx);
|
|
645
|
+
if (!child || child.proc.killed || child.status === "exited") continue;
|
|
646
|
+
child.proc.send({
|
|
647
|
+
type: "pubsub.deliver",
|
|
648
|
+
roomId: message.roomId,
|
|
649
|
+
data: message.data,
|
|
650
|
+
origin: message.origin,
|
|
651
|
+
} satisfies AkanIpcMessage);
|
|
652
|
+
child.metrics.pubsubDeliverCount = (child.metrics.pubsubDeliverCount ?? 0) + 1;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
#addRoomMembership(childIdx: number, roomId: string, socketId?: string) {
|
|
657
|
+
const roomChildren = this.#roomChildren.get(roomId) ?? new Set<number>();
|
|
658
|
+
roomChildren.add(childIdx);
|
|
659
|
+
this.#roomChildren.set(roomId, roomChildren);
|
|
660
|
+
|
|
661
|
+
const childRooms = this.#childRooms.get(childIdx) ?? new Set<string>();
|
|
662
|
+
childRooms.add(roomId);
|
|
663
|
+
this.#childRooms.set(childIdx, childRooms);
|
|
664
|
+
|
|
665
|
+
if (socketId) {
|
|
666
|
+
const socketRooms = this.#socketRooms.get(socketId) ?? { childIdx, rooms: new Set<string>() };
|
|
667
|
+
socketRooms.rooms.add(roomId);
|
|
668
|
+
this.#socketRooms.set(socketId, socketRooms);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
#removeRoomMembership(childIdx: number, roomId: string, socketId?: string) {
|
|
673
|
+
const roomChildren = this.#roomChildren.get(roomId);
|
|
674
|
+
roomChildren?.delete(childIdx);
|
|
675
|
+
if (roomChildren?.size === 0) this.#roomChildren.delete(roomId);
|
|
676
|
+
|
|
677
|
+
const childRooms = this.#childRooms.get(childIdx);
|
|
678
|
+
childRooms?.delete(roomId);
|
|
679
|
+
if (childRooms?.size === 0) this.#childRooms.delete(childIdx);
|
|
680
|
+
|
|
681
|
+
if (socketId) {
|
|
682
|
+
const socketRooms = this.#socketRooms.get(socketId);
|
|
683
|
+
socketRooms?.rooms.delete(roomId);
|
|
684
|
+
if (!socketRooms || socketRooms.rooms.size === 0) this.#socketRooms.delete(socketId);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
#replaceRoomSnapshot(childIdx: number, rooms: string[]) {
|
|
689
|
+
for (const roomId of this.#childRooms.get(childIdx) ?? []) {
|
|
690
|
+
const roomChildren = this.#roomChildren.get(roomId);
|
|
691
|
+
roomChildren?.delete(childIdx);
|
|
692
|
+
if (roomChildren?.size === 0) this.#roomChildren.delete(roomId);
|
|
693
|
+
}
|
|
694
|
+
this.#childRooms.set(childIdx, new Set());
|
|
695
|
+
for (const roomId of rooms) this.#addRoomMembership(childIdx, roomId);
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
#removeChildRooms(childIdx: number) {
|
|
699
|
+
for (const roomId of this.#childRooms.get(childIdx) ?? []) {
|
|
700
|
+
const roomChildren = this.#roomChildren.get(roomId);
|
|
701
|
+
roomChildren?.delete(childIdx);
|
|
702
|
+
if (roomChildren?.size === 0) this.#roomChildren.delete(roomId);
|
|
703
|
+
}
|
|
704
|
+
this.#childRooms.delete(childIdx);
|
|
705
|
+
for (const [socketId, socket] of this.#socketRooms.entries()) {
|
|
706
|
+
if (socket.childIdx === childIdx) this.#socketRooms.delete(socketId);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
#updateMetrics(childIdx: number, metrics: AkanMetricsReport) {
|
|
711
|
+
const child = this.#children.get(childIdx);
|
|
712
|
+
if (!child) return;
|
|
713
|
+
child.metrics = { ...child.metrics, pid: metrics.pid ?? child.pid, ...metrics };
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
#startMetricsReporting() {
|
|
717
|
+
if (this.#metricsTimer) return;
|
|
718
|
+
const report = () => {
|
|
719
|
+
void this.#reportMetrics();
|
|
720
|
+
};
|
|
721
|
+
report();
|
|
722
|
+
this.#metricsTimer = setInterval(report, ProcessMetricsCollector.parseMemoryLogIntervalMs());
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
async #reportMetrics() {
|
|
726
|
+
this.#gatewayMetrics = await ProcessMetricsCollector.collect({ role: "gateway" });
|
|
727
|
+
if (process.env.AKAN_MEMORY_LOG !== "1") return;
|
|
728
|
+
this.logger.verbose(
|
|
729
|
+
`memory role=gateway ${ProcessMetricsCollector.format(this.#gatewayMetrics)} children=${this.#children.size}`,
|
|
730
|
+
);
|
|
731
|
+
for (const child of this.#children.values()) {
|
|
732
|
+
if (!child.metrics.rssBytes) continue;
|
|
733
|
+
const rooms = this.#childRooms.get(child.idx)?.size ?? 0;
|
|
734
|
+
this.logger.verbose(
|
|
735
|
+
`memory role=${child.role} idx=${child.idx} ${ProcessMetricsCollector.format({
|
|
736
|
+
...child.metrics,
|
|
737
|
+
pid: child.metrics.pid ?? child.pid,
|
|
738
|
+
})} activeRequests=${child.metrics.activeRequests ?? 0} activeWebSockets=${
|
|
739
|
+
child.metrics.activeWebSockets ?? 0
|
|
740
|
+
} rooms=${rooms} rscPending=${child.metrics.rscPendingRenderCount ?? 0} rscModules=${
|
|
741
|
+
child.metrics.rscLoadedRouteModuleCount ?? 0
|
|
742
|
+
}`,
|
|
743
|
+
);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
#requestRoomSnapshots() {
|
|
748
|
+
for (const child of this.#children.values()) {
|
|
749
|
+
if (child.proc.killed || child.status === "exited") continue;
|
|
750
|
+
child.proc.send({ type: "pubsub.snapshot.request" } satisfies AkanIpcMessage);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
#checkHealth() {
|
|
755
|
+
const now = Date.now();
|
|
756
|
+
for (const child of this.#children.values()) {
|
|
757
|
+
if (child.proc.killed || child.status === "exited") continue;
|
|
758
|
+
if (child.lastPongAt && now - child.lastPongAt > 5_000) {
|
|
759
|
+
child.status = "unhealthy";
|
|
760
|
+
this.logger.error(`Child ${child.idx}/${child.role} health check timed out; shutting down all children`);
|
|
761
|
+
void this.stop("health-timeout");
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
child.proc.send({ type: "health.ping", nonce: crypto.randomUUID(), sentAt: now } satisfies AkanIpcMessage);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
#forwardBuildRoute(childIdx: number, message: BuilderReq) {
|
|
769
|
+
const gatewayReqId = this.#nextBuilderReqId++;
|
|
770
|
+
this.#builderReqMap.set(gatewayReqId, { childIdx, childLocalId: message.id });
|
|
771
|
+
process.send?.({ ...message, id: gatewayReqId } satisfies BuilderReq);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
#forwardBuildRouteResponse(message: BuilderRes) {
|
|
775
|
+
const request = this.#builderReqMap.get(message.id);
|
|
776
|
+
if (!request) {
|
|
777
|
+
this.logger.warn(`No child found for build-route response id=${message.id}`);
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
this.#builderReqMap.delete(message.id);
|
|
781
|
+
const child = this.#children.get(request.childIdx);
|
|
782
|
+
if (!child || child.proc.killed) return;
|
|
783
|
+
child.proc.send({ ...message, id: request.childLocalId } satisfies BuilderRes);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
#fanoutToFederation(message: AkanIpcMessage | BuilderMessage, exceptIdx?: number) {
|
|
787
|
+
for (const child of this.#children.values()) {
|
|
788
|
+
if (child.idx === exceptIdx) continue;
|
|
789
|
+
if (child.role === "federation" || child.role === "all") child.proc.send(message);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
#fanoutToBatch(message: AkanIpcMessage) {
|
|
794
|
+
for (const child of this.#children.values()) {
|
|
795
|
+
if (child.role === "batch" || child.role === "all") {
|
|
796
|
+
child.proc.send(message);
|
|
797
|
+
if (message.type === "queue.wake") child.metrics.queueWakeCount = (child.metrics.queueWakeCount ?? 0) + 1;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
async #pipeOutput(
|
|
803
|
+
idx: number,
|
|
804
|
+
role: AkanChildRole,
|
|
805
|
+
stream: ReadableStream<Uint8Array> | null,
|
|
806
|
+
type: "stdout" | "stderr",
|
|
807
|
+
) {
|
|
808
|
+
if (!stream) return;
|
|
809
|
+
const bufferKey = `${idx}:${type}`;
|
|
810
|
+
const reader = stream.getReader();
|
|
811
|
+
const decoder = new TextDecoder();
|
|
812
|
+
try {
|
|
813
|
+
while (true) {
|
|
814
|
+
const { done, value } = await reader.read();
|
|
815
|
+
if (done) break;
|
|
816
|
+
const text = decoder.decode(value, { stream: true });
|
|
817
|
+
this.#writeChildOutput(idx, role, type, bufferKey, text);
|
|
818
|
+
}
|
|
819
|
+
const remaining = decoder.decode();
|
|
820
|
+
if (remaining) this.#writeChildOutput(idx, role, type, bufferKey, remaining);
|
|
821
|
+
} finally {
|
|
822
|
+
this.#flushChildOutput(idx, role, type, bufferKey);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
#writeChildOutput(idx: number, role: AkanChildRole, type: "stdout" | "stderr", bufferKey: string, text: string) {
|
|
827
|
+
let buffered = `${this.#childOutputBuffers.get(bufferKey) ?? ""}${text}`;
|
|
828
|
+
while (true) {
|
|
829
|
+
const newlineIdx = buffered.indexOf("\n");
|
|
830
|
+
if (newlineIdx === -1) break;
|
|
831
|
+
const line = buffered.slice(0, newlineIdx + 1);
|
|
832
|
+
buffered = buffered.slice(newlineIdx + 1);
|
|
833
|
+
this.#writeChildOutputLine(idx, role, type, line);
|
|
834
|
+
}
|
|
835
|
+
if (buffered) this.#childOutputBuffers.set(bufferKey, buffered);
|
|
836
|
+
else this.#childOutputBuffers.delete(bufferKey);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
#flushChildOutput(idx: number, role: AkanChildRole, type: "stdout" | "stderr", bufferKey: string) {
|
|
840
|
+
const buffered = this.#childOutputBuffers.get(bufferKey);
|
|
841
|
+
if (!buffered) return;
|
|
842
|
+
this.#childOutputBuffers.delete(bufferKey);
|
|
843
|
+
this.#writeChildOutputLine(idx, role, type, `${buffered}\n`);
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
#writeChildOutputLine(idx: number, role: AkanChildRole, type: "stdout" | "stderr", line: string) {
|
|
847
|
+
const prefixedLine = `[child:${idx} ${role}] [${type}] ${line}`;
|
|
848
|
+
process[type].write(prefixedLine);
|
|
849
|
+
this.#logWriter?.write(`${idx}-${role}`, AkanApp.#stripAnsi(prefixedLine));
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
static #stripAnsi(msg: string) {
|
|
853
|
+
return msg.replace(AkanApp.#ansiPattern, "");
|
|
854
|
+
}
|
|
855
|
+
}
|