@ohos-ports/core 1.0.113-beta.0 → 1.16.33-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/LICENSE +13 -0
- package/README.md +3 -0
- package/lib/api/node.js +176 -0
- package/lib/api/team.js +1889 -0
- package/lib/blocklet/downloader/blocklet-downloader.js +246 -0
- package/lib/blocklet/downloader/bundle-downloader.js +316 -0
- package/lib/blocklet/downloader/constants.js +3 -0
- package/lib/blocklet/downloader/resolve-download.js +187 -0
- package/lib/blocklet/extras.js +177 -0
- package/lib/blocklet/hooks.js +89 -0
- package/lib/blocklet/manager/base.js +49 -0
- package/lib/blocklet/manager/config-synchronizer.js +128 -0
- package/lib/blocklet/manager/disk.js +5170 -0
- package/lib/blocklet/manager/engine.js +124 -0
- package/lib/blocklet/manager/helper/install-application-from-backup.js +285 -0
- package/lib/blocklet/manager/helper/install-application-from-dev.js +72 -0
- package/lib/blocklet/manager/helper/install-application-from-general.js +209 -0
- package/lib/blocklet/manager/helper/install-component-from-dev.js +128 -0
- package/lib/blocklet/manager/helper/install-component-from-upload.js +197 -0
- package/lib/blocklet/manager/helper/install-component-from-url.js +214 -0
- package/lib/blocklet/manager/helper/migrate-application-to-struct-v2.js +557 -0
- package/lib/blocklet/manager/helper/rollback-cache.js +41 -0
- package/lib/blocklet/manager/helper/upgrade-components.js +179 -0
- package/lib/blocklet/manager/pm2-events.js +50 -0
- package/lib/blocklet/migration-dist/migration.cjs +38605 -0
- package/lib/blocklet/migration-dist/run-script.cjs +29 -0
- package/lib/blocklet/migration.js +145 -0
- package/lib/blocklet/project/connect-by-studio.js +91 -0
- package/lib/blocklet/project/connect-to-store.js +64 -0
- package/lib/blocklet/project/create-pack-release.js +293 -0
- package/lib/blocklet/project/disconnect-from-store.js +13 -0
- package/lib/blocklet/project/get-is-multiple-tenant.js +8 -0
- package/lib/blocklet/project/index.js +545 -0
- package/lib/blocklet/project/logo.png +0 -0
- package/lib/blocklet/project/publish-to-store.js +108 -0
- package/lib/blocklet/project/util.js +194 -0
- package/lib/blocklet/security/access-policy.js +131 -0
- package/lib/blocklet/security/index.js +309 -0
- package/lib/blocklet/security/response-header-policy.js +178 -0
- package/lib/blocklet/security/security-rule.js +127 -0
- package/lib/blocklet/security/utils.js +35 -0
- package/lib/blocklet/security/validator.js +40 -0
- package/lib/blocklet/storage/backup/base.js +149 -0
- package/lib/blocklet/storage/backup/blocklet-extras.js +110 -0
- package/lib/blocklet/storage/backup/blocklet.js +159 -0
- package/lib/blocklet/storage/backup/blocklets.js +109 -0
- package/lib/blocklet/storage/backup/data.js +35 -0
- package/lib/blocklet/storage/backup/disk.js +131 -0
- package/lib/blocklet/storage/backup/logs.js +24 -0
- package/lib/blocklet/storage/backup/routing-rule.js +47 -0
- package/lib/blocklet/storage/backup/spaces.js +345 -0
- package/lib/blocklet/storage/restore/base.js +74 -0
- package/lib/blocklet/storage/restore/blocklet-extras.js +89 -0
- package/lib/blocklet/storage/restore/blocklet.js +56 -0
- package/lib/blocklet/storage/restore/blocklets.js +43 -0
- package/lib/blocklet/storage/restore/disk.js +104 -0
- package/lib/blocklet/storage/restore/logs.js +21 -0
- package/lib/blocklet/storage/restore/spaces.js +174 -0
- package/lib/blocklet/storage/utils/disk.js +178 -0
- package/lib/blocklet/storage/utils/hash.js +53 -0
- package/lib/blocklet/storage/utils/zip.js +43 -0
- package/lib/cert.js +221 -0
- package/lib/crons/check-new-version.js +68 -0
- package/lib/crons/monitor-disk-usage.js +46 -0
- package/lib/crons/rotate-pm2-logs/index.js +41 -0
- package/lib/crons/rotate-pm2-logs/script.js +56 -0
- package/lib/event/auto-backup-handler.js +48 -0
- package/lib/event/index.js +520 -0
- package/lib/index.js +768 -364
- package/lib/locales/ar.js +18 -0
- package/lib/locales/de.js +21 -0
- package/lib/locales/en.js +19 -0
- package/lib/locales/es.js +21 -0
- package/lib/locales/fr.js +21 -0
- package/lib/locales/hi.js +18 -0
- package/lib/locales/i18n.db +0 -0
- package/lib/locales/id.js +20 -0
- package/lib/locales/index.js +54 -0
- package/lib/locales/ja.js +19 -0
- package/lib/locales/ko.js +18 -0
- package/lib/locales/pt.js +20 -0
- package/lib/locales/ru.js +21 -0
- package/lib/locales/th.js +18 -0
- package/lib/locales/vi.js +18 -0
- package/lib/locales/zh-tw.js +17 -0
- package/lib/locales/zh.js +17 -0
- package/lib/migrations/1.0.21-update-config.js +34 -0
- package/lib/migrations/1.0.22-max-memory.js +40 -0
- package/lib/migrations/1.0.25.js +36 -0
- package/lib/migrations/1.0.32-update-config.js +30 -0
- package/lib/migrations/1.0.33-blocklets.js +33 -0
- package/lib/migrations/1.0.36-snapshot.js +10 -0
- package/lib/migrations/1.1.10-team.js +26 -0
- package/lib/migrations/1.1.9-snapshot.js +7 -0
- package/lib/migrations/1.16.11-component-status.js +22 -0
- package/lib/migrations/1.16.33-blocklet-security-rule.js +17 -0
- package/lib/migrations/1.16.6-chain-info.js +78 -0
- package/lib/migrations/1.16.8-component-title.js +66 -0
- package/lib/migrations/1.2.11-blocklet-registry.js +10 -0
- package/lib/migrations/1.2.2-blocklet-registry.js +10 -0
- package/lib/migrations/1.3.1-disk-alert-threshold.js +10 -0
- package/lib/migrations/1.4.5-access-key.js +18 -0
- package/lib/migrations/1.5.0-site.js +34 -0
- package/lib/migrations/1.5.15-site.js +184 -0
- package/lib/migrations/1.5.20-registry.js +15 -0
- package/lib/migrations/1.6.17-blocklet-children.js +48 -0
- package/lib/migrations/1.6.21-rename-ip-echo-domain.js +35 -0
- package/lib/migrations/1.6.4-security.js +59 -0
- package/lib/migrations/1.6.5-security.js +60 -0
- package/lib/migrations/1.6.9-update-node-info-and-certificate.js +39 -0
- package/lib/migrations/1.7.1-blocklet-setup.js +18 -0
- package/lib/migrations/1.7.12-blocklet-meta.js +51 -0
- package/lib/migrations/1.7.15-blocklet-bundle-source.js +42 -0
- package/lib/migrations/1.7.20-blocklet-component.js +41 -0
- package/lib/migrations/1.8.33-blocklet-mem-limit.js +20 -0
- package/lib/migrations/README.md +71 -0
- package/lib/migrations/index.js +215 -0
- package/lib/monitor/blocklet-runtime-monitor.js +204 -0
- package/lib/monitor/get-history-list.js +37 -0
- package/lib/monitor/node-monit-sender.js +99 -0
- package/lib/monitor/node-runtime-monitor.js +205 -0
- package/lib/processes/updater.js +186 -0
- package/lib/router/helper.js +1653 -0
- package/lib/router/index.js +341 -0
- package/lib/router/manager.js +806 -0
- package/lib/states/README.md +38 -0
- package/lib/states/access-key.js +124 -0
- package/lib/states/access-policy.js +29 -0
- package/lib/states/audit-log.js +734 -0
- package/lib/states/backup.js +165 -0
- package/lib/states/base.js +25 -0
- package/lib/states/blocklet-extras.js +257 -0
- package/lib/states/blocklet.js +755 -0
- package/lib/states/cache.js +23 -0
- package/lib/states/connect-account.js +8 -0
- package/lib/states/index.js +76 -0
- package/lib/states/job.js +8 -0
- package/lib/states/migration.js +34 -0
- package/lib/states/node.js +324 -0
- package/lib/states/notification.js +81 -0
- package/lib/states/passport.js +8 -0
- package/lib/states/project.js +119 -0
- package/lib/states/release.js +50 -0
- package/lib/states/response-header-policy.js +30 -0
- package/lib/states/routing-snapshot.js +146 -0
- package/lib/states/runtime-insight.js +25 -0
- package/lib/states/security-rule.js +30 -0
- package/lib/states/session.js +53 -0
- package/lib/states/site.js +102 -0
- package/lib/states/tag.js +8 -0
- package/lib/states/traffic-insight.js +25 -0
- package/lib/states/user-session.js +8 -0
- package/lib/states/user.js +717 -0
- package/lib/states/verify-code.js +152 -0
- package/lib/states/webhook.js +66 -0
- package/lib/team/manager.js +508 -0
- package/lib/util/blocklet.js +2182 -0
- package/lib/util/cache.js +63 -0
- package/lib/util/chain.js +29 -0
- package/lib/util/default-node-config.js +46 -0
- package/lib/util/docker/blocklet-custom-dockerfile.js +92 -0
- package/lib/util/docker/check-docker-has-image.js +23 -0
- package/lib/util/docker/check-docker-installed.js +32 -0
- package/lib/util/docker/check-docker-run-history.js +18 -0
- package/lib/util/docker/check-need-run-docker.js +32 -0
- package/lib/util/docker/create-docker-image.js +65 -0
- package/lib/util/docker/debian-dockerfile.js +50 -0
- package/lib/util/docker/docker-container-prune.js +75 -0
- package/lib/util/docker/docker-exec-chown.js +39 -0
- package/lib/util/docker/docker-exec.js +68 -0
- package/lib/util/docker/docker-remove-by-name.js +20 -0
- package/lib/util/docker/get-docker-runtime-info.js +39 -0
- package/lib/util/docker/parse-docker-name.js +10 -0
- package/lib/util/docker/parse-docker-options-from-pm2.js +295 -0
- package/lib/util/docker/shard-network.js +10 -0
- package/lib/util/domain-status.js +118 -0
- package/lib/util/get-accessible-external-node-ip.js +92 -0
- package/lib/util/get-dynamic-components.js +47 -0
- package/lib/util/get-meta-from-url.js +30 -0
- package/lib/util/get-migration-scripts.js +36 -0
- package/lib/util/get-safe-env.js +12 -0
- package/lib/util/index.js +522 -0
- package/lib/util/install-external-dependencies.js +67 -0
- package/lib/util/ip.js +53 -0
- package/lib/util/launcher.js +475 -0
- package/lib/util/log.js +431 -0
- package/lib/util/maintain.js +178 -0
- package/lib/util/promise-debounce.js +29 -0
- package/lib/util/promise-once.js +14 -0
- package/lib/util/promise-spawn.js +93 -0
- package/lib/util/queue.js +44 -0
- package/lib/util/ready.js +89 -0
- package/lib/util/request.js +10 -0
- package/lib/util/requirement.js +61 -0
- package/lib/util/reset-node.js +166 -0
- package/lib/util/rotator.js +194 -0
- package/lib/util/router.js +122 -0
- package/lib/util/rpc.js +78 -0
- package/lib/util/spaces.js +102 -0
- package/lib/util/store.js +184 -0
- package/lib/util/sysinfo.js +46 -0
- package/lib/util/ua.js +54 -0
- package/lib/validators/backup.js +34 -0
- package/lib/validators/blocklet-extra.js +18 -0
- package/lib/validators/node.js +73 -0
- package/lib/validators/permission.js +38 -0
- package/lib/validators/project.js +39 -0
- package/lib/validators/role.js +64 -0
- package/lib/validators/router.js +192 -0
- package/lib/validators/space-gateway.js +33 -0
- package/lib/validators/trusted-factory.js +28 -0
- package/lib/validators/trusted-passport.js +32 -0
- package/lib/validators/user.js +62 -0
- package/lib/validators/util.js +92 -0
- package/lib/validators/webhook.js +42 -0
- package/lib/webhook/index.js +216 -0
- package/lib/webhook/reduce-queue.js +12 -0
- package/lib/webhook/sender/api/index.js +67 -0
- package/lib/webhook/sender/base.js +11 -0
- package/lib/webhook/sender/index.js +44 -0
- package/lib/webhook/sender/slack/index.js +167 -0
- package/lib/webhook/sender/wallet/index.js +62 -0
- package/package.json +107 -34
- package/examples/BatchClient.js +0 -61
- package/examples/compressor/example.js +0 -7
- package/examples/jsonrpcserver/rpcmethod.js +0 -21
- package/examples/jsonrpcserver/rpcrequest.js +0 -20
- package/examples/jsonrpcserver/rpctest.js +0 -6
- package/examples/loader-pipes/test-mc.js +0 -52
- package/examples/loader-pipes/test.js +0 -51
- package/examples/mc-test.js +0 -44
- package/examples/redisdebug.js +0 -80
- package/lib/cache/CFMemcache.js +0 -57
- package/lib/cache/CacheLoader.js +0 -217
- package/lib/cache/Memcache.js +0 -406
- package/lib/class/Class.js +0 -54
- package/lib/client/MemcacheAdapter.js +0 -139
- package/lib/client/Memcached.js +0 -142
- package/lib/client/MemcachedSocket.js +0 -570
- package/lib/client/MySQLPool.js +0 -153
- package/lib/client/PGPool.js +0 -296
- package/lib/client/Redis.js +0 -787
- package/lib/client/S3.js +0 -103
- package/lib/client/S3Client.js +0 -392
- package/lib/client/pg/CursorQueryWorker.js +0 -160
- package/lib/client/rabbitmq/RbmqChannel.js +0 -61
- package/lib/client/rabbitmq/RbmqConfig.js +0 -144
- package/lib/client/rabbitmq/RbmqConnection.js +0 -259
- package/lib/client/rabbitmq/RbmqExchange.js +0 -112
- package/lib/client/rabbitmq/RbmqIncomingMessage.js +0 -53
- package/lib/client/rabbitmq/RbmqMessage.js +0 -120
- package/lib/client/rabbitmq/RbmqOutcomingMessage.js +0 -47
- package/lib/client/rabbitmq/RbmqQueue.js +0 -87
- package/lib/client/rabbitmq/index.js +0 -8
- package/lib/common/Assertions.js +0 -184
- package/lib/common/Merge.js +0 -32
- package/lib/common/Net.js +0 -56
- package/lib/common/Process.js +0 -20
- package/lib/common/Random.js +0 -53
- package/lib/common/Sort.js +0 -19
- package/lib/common/Types.js +0 -163
- package/lib/credentials/CredentialsProvider.js +0 -45
- package/lib/credentials/Manager.js +0 -101
- package/lib/crypto/Crypto.js +0 -66
- package/lib/data/BinaryData.js +0 -363
- package/lib/data/Compressor.js +0 -83
- package/lib/data/FormData.js +0 -144
- package/lib/data/Mime.js +0 -45
- package/lib/event/ErrorEvent.js +0 -71
- package/lib/event/Event.js +0 -20
- package/lib/event/EventDispatcher.js +0 -157
- package/lib/http/ConnectionPool.js +0 -82
- package/lib/http/ExpressServer.js +0 -19
- package/lib/http/Headers.js +0 -165
- package/lib/http/Loader.js +0 -584
- package/lib/http/Message.js +0 -189
- package/lib/http/Request.js +0 -848
- package/lib/http/RequestProcessor.js +0 -150
- package/lib/http/Response.js +0 -850
- package/lib/http/Server.js +0 -267
- package/lib/http/Socket.js +0 -157
- package/lib/http/Url.js +0 -2
- package/lib/jsonrpc/JsonRpcAbstract.js +0 -109
- package/lib/jsonrpc/JsonRpcBatchRequest.js +0 -54
- package/lib/jsonrpc/JsonRpcBatchResponse.js +0 -73
- package/lib/jsonrpc/JsonRpcError.js +0 -191
- package/lib/jsonrpc/JsonRpcMethod.js +0 -67
- package/lib/jsonrpc/JsonRpcRequest.js +0 -224
- package/lib/jsonrpc/JsonRpcRequestProcessor.js +0 -366
- package/lib/jsonrpc/JsonRpcResponse.js +0 -175
- package/lib/jsonrpc/JsonRpcServer.js +0 -81
- package/lib/logger/EmptyLogger.js +0 -15
- package/lib/logger/LoggerFactory.js +0 -20
- package/lib/logger/WildFireLogger.js +0 -267
- package/lib/pattern/Pool.js +0 -187
- package/lib/pattern/decorator/AbstractDecorator.js +0 -49
- package/lib/pattern/decorator/DecoratorChain.js +0 -285
- package/lib/util/DeviceDetector.js +0 -153
- package/lib/yaml/YAML.js +0 -46
- package/patterns.conf +0 -6
- package/tests/cache/CacheLoaderSpec.js +0 -7
- package/tests/class/ClassSpec.js +0 -106
- package/tests/client/MemcachedSocketSpec.js +0 -1228
- package/tests/client/MemcachedSpec.js +0 -77
- package/tests/client/MySQLPoolSpec.js +0 -231
- package/tests/client/PGPoolSpec.js +0 -479
- package/tests/client/RedisSpec.js +0 -471
- package/tests/client/S3ClientSpec.js +0 -26
- package/tests/client/S3Spec.js +0 -129
- package/tests/client/rabbitmq/RbmqConnectionSpec.js +0 -71
- package/tests/common/AssertionsSpec.js +0 -278
- package/tests/common/NetSpec.js +0 -6
- package/tests/common/RandomSpec.js +0 -35
- package/tests/common/TypesSpec.js +0 -7
- package/tests/credentials/CredentialsProviderSpec.js +0 -46
- package/tests/crypto/CryptoSpec.js +0 -33
- package/tests/data/BinaryDataSpec.js +0 -50
- package/tests/data/CompressorSpec.js +0 -7
- package/tests/data/FormDataSpec.js +0 -7
- package/tests/data/MimeSpec.js +0 -7
- package/tests/event/ErrorEventSpec.js +0 -20
- package/tests/event/EventDispatcherSpec.js +0 -319
- package/tests/event/EventSpec.js +0 -17
- package/tests/http/ConnectionPoolSpec.js +0 -7
- package/tests/http/HeadersSpec.js +0 -79
- package/tests/http/LoaderSpec.js +0 -43
- package/tests/http/MessageSpec.js +0 -251
- package/tests/http/RequestProcessorSpec.js +0 -124
- package/tests/http/RequestSpec.js +0 -651
- package/tests/http/ResponseSpec.js +0 -491
- package/tests/http/ServerSpec.js +0 -7
- package/tests/http/SocketSpec.js +0 -7
- package/tests/http/UrlSpec.js +0 -14
- package/tests/jsonrpc/JsonRpcAbstractSpec.js +0 -20
- package/tests/jsonrpc/JsonRpcBatchRequestSpec.js +0 -31
- package/tests/jsonrpc/JsonRpcBatchResponseSpec.js +0 -38
- package/tests/jsonrpc/JsonRpcErrorSpec.js +0 -58
- package/tests/jsonrpc/JsonRpcMethodSpec.js +0 -7
- package/tests/jsonrpc/JsonRpcRequestProcessorSpec.js +0 -271
- package/tests/jsonrpc/JsonRpcRequestSpec.js +0 -70
- package/tests/jsonrpc/JsonRpcResponseSpec.js +0 -63
- package/tests/jsonrpc/JsonRpcServerSpec.js +0 -42
- package/tests/pattern/PoolSpec.js +0 -180
- package/tests/pattern/decorator/AbstractDecoratorSpec.js +0 -7
- package/tests/pattern/decorator/DecoratorChainSpec.js +0 -7
- package/tests/yaml/YAMLSpec.js +0 -132
|
@@ -0,0 +1,2182 @@
|
|
|
1
|
+
/* eslint-disable camelcase */
|
|
2
|
+
/* eslint-disable no-await-in-loop */
|
|
3
|
+
|
|
4
|
+
const fs = require('fs-extra');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const shelljs = require('shelljs');
|
|
7
|
+
const os = require('os');
|
|
8
|
+
const tar = require('tar');
|
|
9
|
+
const get = require('lodash/get');
|
|
10
|
+
const uniq = require('lodash/uniq');
|
|
11
|
+
const toLower = require('lodash/toLower');
|
|
12
|
+
const isEmpty = require('lodash/isEmpty');
|
|
13
|
+
const streamToPromise = require('stream-to-promise');
|
|
14
|
+
const { Throttle } = require('stream-throttle');
|
|
15
|
+
const { slugify } = require('transliteration');
|
|
16
|
+
const ssri = require('ssri');
|
|
17
|
+
const diff = require('deep-diff');
|
|
18
|
+
const createArchive = require('archiver');
|
|
19
|
+
const isUrl = require('is-url');
|
|
20
|
+
const semver = require('semver');
|
|
21
|
+
const { chainInfo: chainInfoSchema } = require('@arcblock/did-auth/lib/schema');
|
|
22
|
+
|
|
23
|
+
const urlPathFriendly = require('@blocklet/meta/lib/url-path-friendly').default;
|
|
24
|
+
const { fromSecretKey, fromPublicKey } = require('@ocap/wallet');
|
|
25
|
+
const { toHex, isHex, toDid, toAddress, toBuffer } = require('@ocap/util');
|
|
26
|
+
const { isValid: isValidDid, isEthereumDid } = require('@arcblock/did');
|
|
27
|
+
const logger = require('@abtnode/logger')('@abtnode/core:util:blocklet');
|
|
28
|
+
const pm2 = require('@abtnode/util/lib/async-pm2');
|
|
29
|
+
const sleep = require('@abtnode/util/lib/sleep');
|
|
30
|
+
const getPm2ProcessInfo = require('@abtnode/util/lib/get-pm2-process-info');
|
|
31
|
+
const { formatEnv, getSecurityNodeOptions } = require('@abtnode/util/lib/security');
|
|
32
|
+
const ensureEndpointHealthy = require('@abtnode/util/lib/ensure-endpoint-healthy');
|
|
33
|
+
const getFolderSize = require('@abtnode/util/lib/get-folder-size');
|
|
34
|
+
const normalizePathPrefix = require('@abtnode/util/lib/normalize-path-prefix');
|
|
35
|
+
const hashFiles = require('@abtnode/util/lib/hash-files');
|
|
36
|
+
const didDocument = require('@abtnode/util/lib/did-document');
|
|
37
|
+
const { BLOCKLET_MAX_MEM_LIMIT_IN_MB, BLOCKLET_INSTALL_TYPE, APP_STRUCT_VERSION } = require('@abtnode/constant');
|
|
38
|
+
const {
|
|
39
|
+
parseComponents,
|
|
40
|
+
ensureMeta,
|
|
41
|
+
filterDuplicateComponents,
|
|
42
|
+
validateBlockletMeta,
|
|
43
|
+
getComponentConfig,
|
|
44
|
+
parseOptionalComponents,
|
|
45
|
+
filterRequiredComponents,
|
|
46
|
+
} = require('@blocklet/resolver');
|
|
47
|
+
const formatBackSlash = require('@abtnode/util/lib/format-back-slash');
|
|
48
|
+
const { isPortsOccupiedByOtherProcess, killProcessOccupiedPorts } = require('@abtnode/util/lib/port');
|
|
49
|
+
const { getComponentApiKey } = require('@abtnode/util/lib/blocklet');
|
|
50
|
+
const { toSvg: createDidLogo } =
|
|
51
|
+
process.env.NODE_ENV !== 'test' ? require('@arcblock/did-motif') : require('@arcblock/did-motif/dist/did-motif.cjs');
|
|
52
|
+
const { createBlockiesSvg } = require('@blocklet/meta/lib/blockies');
|
|
53
|
+
|
|
54
|
+
const SCRIPT_ENGINES_WHITE_LIST = ['npm', 'npx', 'pnpm', 'yarn'];
|
|
55
|
+
|
|
56
|
+
const {
|
|
57
|
+
BlockletStatus,
|
|
58
|
+
BlockletSource,
|
|
59
|
+
BlockletGroup,
|
|
60
|
+
BLOCKLET_MODES,
|
|
61
|
+
BLOCKLET_BUNDLE_FILE,
|
|
62
|
+
BLOCKLET_ENTRY_FILE,
|
|
63
|
+
BLOCKLET_DEFAULT_PORT_NAME,
|
|
64
|
+
BLOCKLET_INTERFACE_TYPE_WEB,
|
|
65
|
+
BLOCKLET_CONFIGURABLE_KEY,
|
|
66
|
+
fromBlockletStatus,
|
|
67
|
+
BLOCKLET_PREFERENCE_FILE,
|
|
68
|
+
BLOCKLET_PREFERENCE_PREFIX,
|
|
69
|
+
BLOCKLET_RESOURCE_DIR,
|
|
70
|
+
BLOCKLET_TENANT_MODES,
|
|
71
|
+
PROJECT,
|
|
72
|
+
BLOCKLET_INTERFACE_TYPE_DOCKER,
|
|
73
|
+
} = require('@blocklet/constant');
|
|
74
|
+
const validateBlockletEntry = require('@blocklet/meta/lib/entry');
|
|
75
|
+
const { getBlockletEngine } = require('@blocklet/meta/lib/engine');
|
|
76
|
+
const getBlockletInfo = require('@blocklet/meta/lib/info');
|
|
77
|
+
const getBlockletWallet = require('@blocklet/meta/lib/wallet');
|
|
78
|
+
const {
|
|
79
|
+
forEachBlocklet,
|
|
80
|
+
getDisplayName,
|
|
81
|
+
findWebInterface,
|
|
82
|
+
forEachBlockletSync,
|
|
83
|
+
forEachChildSync,
|
|
84
|
+
forEachComponentV2,
|
|
85
|
+
forEachComponentV2Sync,
|
|
86
|
+
getSharedConfigObj,
|
|
87
|
+
getComponentName,
|
|
88
|
+
getBlockletAppIdList,
|
|
89
|
+
getChainInfo,
|
|
90
|
+
isInProgress,
|
|
91
|
+
isRunning,
|
|
92
|
+
hasStartEngine,
|
|
93
|
+
isEnvShareable,
|
|
94
|
+
} = require('@blocklet/meta/lib/util');
|
|
95
|
+
const { getComponentsInternalInfo } = require('@blocklet/meta/lib/blocklet');
|
|
96
|
+
const { titleSchema, descriptionSchema, logoSchema } = require('@blocklet/meta/lib/schema');
|
|
97
|
+
const { getBlockletMetaFromUrl } = require('@blocklet/meta/lib/util-meta');
|
|
98
|
+
const getComponentProcessId = require('@blocklet/meta/lib/get-component-process-id');
|
|
99
|
+
const { isInServerlessMode } = require('@abtnode/util/lib/serverless');
|
|
100
|
+
const { getDidDomainForBlocklet } = require('@abtnode/util/lib/get-domain-for-blocklet');
|
|
101
|
+
const md5 = require('@abtnode/util/lib/md5');
|
|
102
|
+
|
|
103
|
+
const ensureDockerEndpointHealthy = require('@abtnode/util/lib/ensure-docker-endpoint-healthy');
|
|
104
|
+
const { validate: validateEngine, get: getEngine } = require('../blocklet/manager/engine');
|
|
105
|
+
|
|
106
|
+
const isRequirementsSatisfied = require('./requirement');
|
|
107
|
+
const { expandBundle, findInterfacePortByName, prettyURL, templateReplace, getServerDidDomain } = require('./index');
|
|
108
|
+
const { installExternalDependencies } = require('./install-external-dependencies');
|
|
109
|
+
const parseDockerOptionsFromPm2 = require('./docker/parse-docker-options-from-pm2');
|
|
110
|
+
const dockerRemoveByName = require('./docker/docker-remove-by-name');
|
|
111
|
+
const checkNeedRunDocker = require('./docker/check-need-run-docker');
|
|
112
|
+
const getDockerRuntimeInfo = require('./docker/get-docker-runtime-info');
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* get blocklet engine info, default is node
|
|
116
|
+
* @param {object} meta blocklet meta
|
|
117
|
+
* @return {string} engine name
|
|
118
|
+
*/
|
|
119
|
+
const getBlockletEngineNameByPlatform = (meta) => getBlockletEngine(meta).interpreter;
|
|
120
|
+
|
|
121
|
+
const noop = () => {
|
|
122
|
+
//
|
|
123
|
+
};
|
|
124
|
+
const noopAsync = async () => {
|
|
125
|
+
//
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const statusMap = {
|
|
129
|
+
online: BlockletStatus.running,
|
|
130
|
+
launching: BlockletStatus.starting,
|
|
131
|
+
errored: BlockletStatus.error,
|
|
132
|
+
stopping: BlockletStatus.stopping,
|
|
133
|
+
stopped: BlockletStatus.stopped,
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const PRIVATE_NODE_ENVS = [
|
|
137
|
+
'ABT_NODE_UPDATER_PORT',
|
|
138
|
+
'ABT_NODE_SESSION_TTL',
|
|
139
|
+
'ABT_NODE_ROUTER_PROVIDER',
|
|
140
|
+
'ABT_NODE_DATA_DIR',
|
|
141
|
+
'ABT_NODE_TOKEN_SECRET',
|
|
142
|
+
'ABT_NODE_SK',
|
|
143
|
+
'ABT_NODE_SESSION_SECRET',
|
|
144
|
+
'ABT_NODE_BASE_URL',
|
|
145
|
+
'ABT_NODE_LOG_LEVEL',
|
|
146
|
+
'ABT_NODE_LOG_DIR',
|
|
147
|
+
// in /core/cli/bin/blocklet.js
|
|
148
|
+
'CLI_MODE',
|
|
149
|
+
'ABT_NODE_HOME',
|
|
150
|
+
'PM2_HOME',
|
|
151
|
+
'ABT_NODE_CONFIG_FILE',
|
|
152
|
+
];
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* @returns { dataDir, logsDir, cacheDir, appDir }
|
|
156
|
+
* dataDir: dataDirs.data/name (root component) or dataDirs.data/name/childName (child component)
|
|
157
|
+
* logsDir: dataDirs.log/name
|
|
158
|
+
* cacheDir: dataDirs.cache/name (root component) or dataDirs.cache/name/childName (child component)
|
|
159
|
+
* appDir: component bundle dir
|
|
160
|
+
*/
|
|
161
|
+
const getComponentDirs = (component, { dataDirs, ensure = false, ancestors = [] } = {}) => {
|
|
162
|
+
const componentName = getComponentName(component, ancestors);
|
|
163
|
+
|
|
164
|
+
const logsDir = path.join(dataDirs.logs, componentName);
|
|
165
|
+
const dataDir = path.join(dataDirs.data, componentName);
|
|
166
|
+
const cacheDir = path.join(dataDirs.cache, componentName);
|
|
167
|
+
|
|
168
|
+
let appDir = null;
|
|
169
|
+
if (component.source === BlockletSource.local) {
|
|
170
|
+
appDir = component.deployedFrom;
|
|
171
|
+
} else {
|
|
172
|
+
// eslint-disable-next-line no-use-before-define
|
|
173
|
+
appDir = getBundleDir(dataDirs.blocklets, component.meta);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (!appDir) {
|
|
177
|
+
throw new Error('Can not determine blocklet directory, maybe invalid deployment from local blocklets');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (ensure) {
|
|
181
|
+
try {
|
|
182
|
+
fs.mkdirSync(dataDir, { recursive: true });
|
|
183
|
+
fs.mkdirSync(path.join(dataDir, PROJECT.DIR), { recursive: true });
|
|
184
|
+
fs.mkdirSync(logsDir, { recursive: true });
|
|
185
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
186
|
+
fs.mkdirSync(appDir, { recursive: true }); // prevent getDiskInfo failed from custom blocklet
|
|
187
|
+
} catch (err) {
|
|
188
|
+
logger.error('make blocklet dir failed', { error: err });
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return { dataDir, logsDir, cacheDir, appDir };
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* @param component {import('@abtnode/client').ComponentState & { environmentObj: {[key: string]: string } } }
|
|
197
|
+
* @returns {{cwd, script, args, environmentObj, interpreter, interpreterArgs}: { args: []}}
|
|
198
|
+
* @return {*}
|
|
199
|
+
*/
|
|
200
|
+
const getComponentStartEngine = (component, { e2eMode = false } = {}) => {
|
|
201
|
+
if (!hasStartEngine(component.meta)) {
|
|
202
|
+
return {};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const { appDir } = component.env;
|
|
206
|
+
|
|
207
|
+
const cwd = appDir;
|
|
208
|
+
|
|
209
|
+
// get app dirs
|
|
210
|
+
const { main, group } = component.meta;
|
|
211
|
+
|
|
212
|
+
let startFromDevEntry = '';
|
|
213
|
+
if (component.mode === BLOCKLET_MODES.DEVELOPMENT && component.meta.scripts) {
|
|
214
|
+
startFromDevEntry = component.meta.scripts.dev;
|
|
215
|
+
if (e2eMode && component.meta.scripts.e2eDev) {
|
|
216
|
+
startFromDevEntry = component.meta.scripts.e2eDev;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const blockletEngineInfo = getBlockletEngine(component.meta);
|
|
221
|
+
if (blockletEngineInfo.interpreter === 'blocklet') {
|
|
222
|
+
return {};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
let script = null;
|
|
226
|
+
let interpreter;
|
|
227
|
+
let interpreterArgs = [];
|
|
228
|
+
const environmentObj = {};
|
|
229
|
+
let args = [];
|
|
230
|
+
|
|
231
|
+
if (startFromDevEntry) {
|
|
232
|
+
script = startFromDevEntry;
|
|
233
|
+
} else if (group === 'dapp') {
|
|
234
|
+
script = blockletEngineInfo.source || BLOCKLET_ENTRY_FILE;
|
|
235
|
+
args = blockletEngineInfo.args || [];
|
|
236
|
+
} else if (group === 'static') {
|
|
237
|
+
// FIXME: @wangshijun deprecate this
|
|
238
|
+
script = require.resolve('@abtnode/static-server');
|
|
239
|
+
environmentObj.BLOCKLET_MAIN_DIR = path.join(appDir, main);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (component.mode !== BLOCKLET_MODES.DEVELOPMENT) {
|
|
243
|
+
const engine = getEngine(blockletEngineInfo.interpreter);
|
|
244
|
+
interpreter = engine.interpreter === 'node' ? undefined : engine.interpreter;
|
|
245
|
+
interpreterArgs = interpreterArgs.concat(engine.args ? [engine.args] : []);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return {
|
|
249
|
+
cwd,
|
|
250
|
+
script,
|
|
251
|
+
args,
|
|
252
|
+
environmentObj,
|
|
253
|
+
interpreter,
|
|
254
|
+
interpreterArgs: interpreterArgs.join(' ').trim(),
|
|
255
|
+
};
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
const getBlockletConfigObj = (blocklet, { excludeSecure } = {}) => {
|
|
259
|
+
const obj = (blocklet?.configs || [])
|
|
260
|
+
.filter((x) => {
|
|
261
|
+
if (excludeSecure) {
|
|
262
|
+
return !x.secure;
|
|
263
|
+
}
|
|
264
|
+
return true;
|
|
265
|
+
})
|
|
266
|
+
.reduce((acc, x) => {
|
|
267
|
+
acc[x.key] = templateReplace(x.value, blocklet);
|
|
268
|
+
return acc;
|
|
269
|
+
}, {});
|
|
270
|
+
|
|
271
|
+
return obj;
|
|
272
|
+
};
|
|
273
|
+
/**
|
|
274
|
+
* set 'configs', configObj', 'environmentObj' to blocklet TODO
|
|
275
|
+
* @param {*} blocklet
|
|
276
|
+
* @param {*} configs
|
|
277
|
+
*/
|
|
278
|
+
const fillBlockletConfigs = (blocklet, configs) => {
|
|
279
|
+
blocklet.configs = configs || [];
|
|
280
|
+
blocklet.configObj = getBlockletConfigObj(blocklet);
|
|
281
|
+
blocklet.environments = blocklet.environments || [];
|
|
282
|
+
blocklet.environmentObj = blocklet.environments.reduce((acc, x) => {
|
|
283
|
+
acc[x.key] = templateReplace(x.value, blocklet);
|
|
284
|
+
return acc;
|
|
285
|
+
}, {});
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
const ensureBlockletExpanded = async (meta, appDir) => {
|
|
289
|
+
const bundlePath = path.join(appDir, BLOCKLET_BUNDLE_FILE);
|
|
290
|
+
if (fs.existsSync(bundlePath)) {
|
|
291
|
+
try {
|
|
292
|
+
const nodeModulesPath = path.join(appDir, 'node_modules');
|
|
293
|
+
if (fs.existsSync(nodeModulesPath)) {
|
|
294
|
+
fs.removeSync(nodeModulesPath);
|
|
295
|
+
}
|
|
296
|
+
await expandBundle(bundlePath, appDir);
|
|
297
|
+
fs.removeSync(bundlePath);
|
|
298
|
+
} catch (err) {
|
|
299
|
+
throw new Error(`Failed to expand blocklet bundle: ${err.message}`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
const getAppSystemEnvironments = (blocklet, nodeInfo, dataDirs) => {
|
|
305
|
+
const { did, name, title, description } = blocklet.meta;
|
|
306
|
+
const keys = Object.keys(BLOCKLET_CONFIGURABLE_KEY);
|
|
307
|
+
const result = getBlockletInfo(
|
|
308
|
+
{
|
|
309
|
+
meta: blocklet.meta,
|
|
310
|
+
environments: keys.map((key) => ({ key, value: blocklet.configObj[key] })).filter((x) => x.value),
|
|
311
|
+
},
|
|
312
|
+
nodeInfo.sk
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
const { wallet } = result;
|
|
316
|
+
const appSk = toHex(wallet.secretKey);
|
|
317
|
+
const appPk = toHex(wallet.publicKey);
|
|
318
|
+
const appId = wallet.address;
|
|
319
|
+
const appName = title || name || result.name;
|
|
320
|
+
const appDescription = description || result.description;
|
|
321
|
+
|
|
322
|
+
const isMigrated = Array.isArray(blocklet.migratedFrom) && blocklet.migratedFrom.length > 0;
|
|
323
|
+
const appPid = blocklet.appPid || appId;
|
|
324
|
+
const appPsk = isMigrated ? blocklet.migratedFrom[0].appSk : appSk;
|
|
325
|
+
|
|
326
|
+
/* 获取 did domain 方式:
|
|
327
|
+
* 1. 先从 site 里读
|
|
328
|
+
* 2. 如果没有,再拼接
|
|
329
|
+
*/
|
|
330
|
+
|
|
331
|
+
const pidDomain = getDidDomainForBlocklet({ did: appPid, didDomain: nodeInfo.didDomain });
|
|
332
|
+
const domainAliases = get(blocklet, 'site.domainAliases') || [];
|
|
333
|
+
|
|
334
|
+
let didDomain = domainAliases.find((item) => toLower(item.value) === toLower(pidDomain));
|
|
335
|
+
|
|
336
|
+
if (!didDomain) {
|
|
337
|
+
didDomain = domainAliases.find(
|
|
338
|
+
(item) => item.value.endsWith(nodeInfo.didDomain) || item.value.endsWith('did.staging.arcblock.io') // did.staging.arcblock.io 是旧 did domain, 但主要存在于比较旧的节点中, 需要做兼容
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const appUrl = didDomain ? prettyURL(didDomain.value, true) : `https://${pidDomain}`;
|
|
343
|
+
|
|
344
|
+
return {
|
|
345
|
+
BLOCKLET_DID: did, // BLOCKLET_DID is always same as BLOCKLET_APP_PID in structV2 application
|
|
346
|
+
BLOCKLET_APP_PK: appPk,
|
|
347
|
+
BLOCKLET_APP_SK: appSk,
|
|
348
|
+
BLOCKLET_APP_ID: appId,
|
|
349
|
+
BLOCKLET_APP_PSK: appPsk, // permanent sk even the blocklet has been migrated
|
|
350
|
+
BLOCKLET_APP_PID: appPid, // permanent did even the blocklet has been migrated
|
|
351
|
+
BLOCKLET_APP_NAME: appName,
|
|
352
|
+
BLOCKLET_APP_NAME_SLUG: urlPathFriendly(slugify(appName)),
|
|
353
|
+
BLOCKLET_APP_DESCRIPTION: appDescription,
|
|
354
|
+
BLOCKLET_APP_URL: appUrl,
|
|
355
|
+
BLOCKLET_APP_DATA_DIR: path.join(dataDirs.data, blocklet.meta.name),
|
|
356
|
+
BLOCKLET_APP_TENANT_MODE: result.tenantMode || BLOCKLET_TENANT_MODES.SINGLE,
|
|
357
|
+
};
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
const getAppOverwrittenEnvironments = (blocklet, nodeInfo) => {
|
|
361
|
+
const result = {};
|
|
362
|
+
if (!blocklet || !blocklet.configObj) {
|
|
363
|
+
return result;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
Object.keys(BLOCKLET_CONFIGURABLE_KEY).forEach((x) => {
|
|
367
|
+
if (!blocklet.configObj[x]) {
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
result[x] = blocklet.configObj[x];
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
const keys = ['BLOCKLET_APP_SK', 'BLOCKLET_APP_CHAIN_TYPE', 'BLOCKLET_WALLET_TYPE'];
|
|
375
|
+
const isAppDidRewritten = keys.some((key) => blocklet.configObj[key]);
|
|
376
|
+
if (!isAppDidRewritten) {
|
|
377
|
+
return result;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// We use user configuration here without any validation since the validation is done during update phase
|
|
381
|
+
const { wallet } = getBlockletInfo(
|
|
382
|
+
{
|
|
383
|
+
meta: blocklet.meta,
|
|
384
|
+
environments: keys.map((key) => ({ key, value: blocklet.configObj[key] })).filter((x) => x.value),
|
|
385
|
+
},
|
|
386
|
+
nodeInfo.sk
|
|
387
|
+
);
|
|
388
|
+
result.BLOCKLET_APP_ID = wallet.address;
|
|
389
|
+
|
|
390
|
+
return result;
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
const getComponentSystemEnvironments = (blocklet) => {
|
|
394
|
+
const { port, ports } = blocklet;
|
|
395
|
+
const portEnvironments = {};
|
|
396
|
+
if (port) {
|
|
397
|
+
portEnvironments[BLOCKLET_DEFAULT_PORT_NAME] = port;
|
|
398
|
+
}
|
|
399
|
+
if (ports) {
|
|
400
|
+
Object.assign(portEnvironments, ports);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
return {
|
|
404
|
+
BLOCKLET_REAL_DID: blocklet.env.id, // <appDid>/componentDid> e.g. xxxxx/xxxxx
|
|
405
|
+
BLOCKLET_REAL_NAME: blocklet.env.name,
|
|
406
|
+
BLOCKLET_COMPONENT_DID: blocklet.meta.did, // component meta did e.g. xxxxxx
|
|
407
|
+
BLOCKLET_DATA_DIR: blocklet.env.dataDir,
|
|
408
|
+
BLOCKLET_LOG_DIR: blocklet.env.logsDir,
|
|
409
|
+
BLOCKLET_CACHE_DIR: blocklet.env.cacheDir,
|
|
410
|
+
BLOCKLET_APP_DIR: blocklet.env.appDir,
|
|
411
|
+
...portEnvironments,
|
|
412
|
+
};
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
const getRuntimeEnvironments = (blocklet, nodeEnvironments, ancestors) => {
|
|
416
|
+
const root = (ancestors || [])[0] || blocklet;
|
|
417
|
+
|
|
418
|
+
const initialized = root?.settings?.initialized;
|
|
419
|
+
|
|
420
|
+
// pm2 will force inject env variables of daemon process to blocklet process
|
|
421
|
+
// we can only rewrite these private env variables to empty
|
|
422
|
+
const safeNodeEnvironments = PRIVATE_NODE_ENVS.reduce((o, x) => {
|
|
423
|
+
o[x] = '';
|
|
424
|
+
return o;
|
|
425
|
+
}, {});
|
|
426
|
+
|
|
427
|
+
// get devEnvironments, when blocklet is in dev mode
|
|
428
|
+
const devEnvironments =
|
|
429
|
+
blocklet.mode === BLOCKLET_MODES.DEVELOPMENT
|
|
430
|
+
? {
|
|
431
|
+
BLOCKLET_DEV_MOUNT_POINT: blocklet?.mountPoint || '',
|
|
432
|
+
}
|
|
433
|
+
: {};
|
|
434
|
+
|
|
435
|
+
// BLOCKLET_DEV_PORT should NOT in components of production mode
|
|
436
|
+
if (process.env.BLOCKLET_DEV_PORT) {
|
|
437
|
+
devEnvironments.BLOCKLET_DEV_PORT =
|
|
438
|
+
blocklet.mode === BLOCKLET_MODES.DEVELOPMENT ? process.env.BLOCKLET_DEV_PORT : '';
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const ports = {};
|
|
442
|
+
forEachBlockletSync(root, (x) => {
|
|
443
|
+
const webInterface = findWebInterface(x);
|
|
444
|
+
if (webInterface && x.environmentObj[webInterface.port]) {
|
|
445
|
+
ports[x.environmentObj.BLOCKLET_REAL_NAME] = x.environmentObj[webInterface.port];
|
|
446
|
+
}
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
const componentsInternalInfo = getComponentsInternalInfo(root);
|
|
450
|
+
|
|
451
|
+
// use index 1 as the path to derive deterministic encryption key for blocklet
|
|
452
|
+
const tmp = get(nodeEnvironments, 'ABT_NODE_SK')
|
|
453
|
+
? getBlockletWallet(blocklet.meta.did, nodeEnvironments.ABT_NODE_SK, undefined, 1)
|
|
454
|
+
: null;
|
|
455
|
+
|
|
456
|
+
const BLOCKLET_APP_IDS = getBlockletAppIdList(root).join(',');
|
|
457
|
+
|
|
458
|
+
const componentApiKey = getComponentApiKey({
|
|
459
|
+
serverSk: nodeEnvironments.ABT_NODE_SK,
|
|
460
|
+
app: root,
|
|
461
|
+
component: blocklet,
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
const env = {
|
|
465
|
+
...blocklet.configObj,
|
|
466
|
+
...getSharedConfigObj((ancestors || [])[0], blocklet, true),
|
|
467
|
+
...blocklet.environmentObj,
|
|
468
|
+
...devEnvironments,
|
|
469
|
+
BLOCKLET_MOUNT_POINTS: JSON.stringify(componentsInternalInfo),
|
|
470
|
+
BLOCKLET_MODE: blocklet.mode || BLOCKLET_MODES.PRODUCTION,
|
|
471
|
+
BLOCKLET_APP_EK: tmp?.secretKey,
|
|
472
|
+
BLOCKLET_APP_VERSION: root.meta.version,
|
|
473
|
+
BLOCKLET_APP_IDS,
|
|
474
|
+
BLOCKLET_COMPONENT_API_KEY: componentApiKey,
|
|
475
|
+
...nodeEnvironments,
|
|
476
|
+
...safeNodeEnvironments,
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
if (root?.environmentObj?.BLOCKLET_APP_DATA_DIR) {
|
|
480
|
+
env.BLOCKLET_APP_SHARE_DIR = path.join(root.environmentObj.BLOCKLET_APP_DATA_DIR, '.share');
|
|
481
|
+
env.BLOCKLET_SHARE_DIR = path.join(root.environmentObj.BLOCKLET_APP_DATA_DIR, '.share', blocklet.meta.did);
|
|
482
|
+
if (!fs.existsSync(env.BLOCKLET_APP_SHARE_DIR) && process.env.ABT_NODE_DATA_DIR) {
|
|
483
|
+
fs.mkdirSync(env.BLOCKLET_APP_SHARE_DIR, { recursive: true });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
if (initialized) {
|
|
488
|
+
env.initialized = initialized;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// ensure all envs are literals and do not contain line breaks
|
|
492
|
+
Object.keys(env).forEach((key) => {
|
|
493
|
+
env[key] = formatEnv(env[key]);
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
return env;
|
|
497
|
+
};
|
|
498
|
+
|
|
499
|
+
const isUsefulError = (err) =>
|
|
500
|
+
err &&
|
|
501
|
+
err.message !== 'process or namespace not found' &&
|
|
502
|
+
!/id unknown/.test(err.message) &&
|
|
503
|
+
!/^Process \d+ not found$/.test(err.message);
|
|
504
|
+
|
|
505
|
+
const getHealthyCheckTimeout = (blocklet, { checkHealthImmediately } = {}) => {
|
|
506
|
+
let minConsecutiveTime = 2000;
|
|
507
|
+
if (process.env.NODE_ENV === 'test' && process.env.ABT_NODE_TEST_MIN_CONSECUTIVE_TIME !== undefined) {
|
|
508
|
+
minConsecutiveTime = process.env.ABT_NODE_TEST_MIN_CONSECUTIVE_TIME;
|
|
509
|
+
} else if (checkHealthImmediately) {
|
|
510
|
+
minConsecutiveTime = 1000;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
if (process.env.BLOCKLET_START_TIMEOUT) {
|
|
514
|
+
return {
|
|
515
|
+
startTimeout: process.env.BLOCKLET_START_TIMEOUT * 1000,
|
|
516
|
+
minConsecutiveTime,
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
if (blocklet.mode === BLOCKLET_MODES.DEVELOPMENT) {
|
|
520
|
+
return {
|
|
521
|
+
startTimeout: 3600 * 1000,
|
|
522
|
+
minConsecutiveTime: 1000,
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// Let's wait for at least 1 minute for the blocklet to go live
|
|
527
|
+
let startTimeout = process.env.NODE_ENV === 'test' ? 10 : 60;
|
|
528
|
+
startTimeout = Math.max(get(blocklet, 'meta.timeout.start', startTimeout), startTimeout) * 1000;
|
|
529
|
+
|
|
530
|
+
return {
|
|
531
|
+
startTimeout,
|
|
532
|
+
minConsecutiveTime,
|
|
533
|
+
};
|
|
534
|
+
};
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Start all precesses of a blocklet
|
|
538
|
+
* @param {*} blocklet should contain env props
|
|
539
|
+
*/
|
|
540
|
+
const startBlockletProcess = async (
|
|
541
|
+
blocklet,
|
|
542
|
+
{
|
|
543
|
+
preFlight = noop,
|
|
544
|
+
preStart = noop,
|
|
545
|
+
postStart = noopAsync,
|
|
546
|
+
nodeEnvironments,
|
|
547
|
+
nodeInfo,
|
|
548
|
+
e2eMode,
|
|
549
|
+
skippedProcessIds = [],
|
|
550
|
+
componentDids,
|
|
551
|
+
configSynchronizer,
|
|
552
|
+
onlyStart = false,
|
|
553
|
+
} = {}
|
|
554
|
+
) => {
|
|
555
|
+
if (!blocklet) {
|
|
556
|
+
throw new Error('blocklet should not be empty');
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// 需要在在这里传入字符串类型,否则进程中如法转化成 Date 对象
|
|
560
|
+
const now = `${new Date()}`;
|
|
561
|
+
await forEachBlocklet(
|
|
562
|
+
blocklet,
|
|
563
|
+
/**
|
|
564
|
+
*
|
|
565
|
+
* @param {import('@abtnode/client').BlockletState} b
|
|
566
|
+
* @param {*} param1
|
|
567
|
+
* @returns
|
|
568
|
+
*/
|
|
569
|
+
async (b, { ancestors }) => {
|
|
570
|
+
if (b.meta.group === BlockletGroup.gateway) {
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
if (!hasStartEngine(b.meta)) {
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
const { processId, logsDir, appDir } = b.env;
|
|
579
|
+
|
|
580
|
+
if (skippedProcessIds.includes(processId)) {
|
|
581
|
+
logger.info('skip start skipped process', { processId });
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// eslint-disable-next-line no-use-before-define
|
|
586
|
+
if (shouldSkipComponent(b.meta.did, componentDids)) {
|
|
587
|
+
logger.info('skip start process not selected', { processId });
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (b.mode !== BLOCKLET_MODES.DEVELOPMENT) {
|
|
592
|
+
validateBlockletEntry(appDir, b.meta);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const { cwd, script, args, environmentObj, interpreter, interpreterArgs } = getComponentStartEngine(b, {
|
|
596
|
+
e2eMode,
|
|
597
|
+
});
|
|
598
|
+
if (!script) {
|
|
599
|
+
logger.info('skip start process without script', { processId });
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// get env
|
|
604
|
+
const env = getRuntimeEnvironments(b, nodeEnvironments, ancestors);
|
|
605
|
+
const startedAt = Date.now();
|
|
606
|
+
const needRunDocker = await checkNeedRunDocker(b.meta, env, nodeInfo);
|
|
607
|
+
|
|
608
|
+
if (!needRunDocker) {
|
|
609
|
+
await installExternalDependencies({ appDir: env?.BLOCKLET_APP_DIR });
|
|
610
|
+
// run hook
|
|
611
|
+
await preFlight(b, { env: { ...env } });
|
|
612
|
+
await preStart(b, { env: { ...env } });
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// kill process if port is occupied
|
|
616
|
+
try {
|
|
617
|
+
const { ports } = b;
|
|
618
|
+
await killProcessOccupiedPorts({ ports, pm2ProcessId: processId, printError: logger.error.bind(logger) });
|
|
619
|
+
} catch (error) {
|
|
620
|
+
logger.error('Failed to killProcessOccupiedPorts', { error });
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// start process
|
|
624
|
+
const maxMemoryRestart = get(nodeInfo, 'runtimeConfig.blockletMaxMemoryLimit', BLOCKLET_MAX_MEM_LIMIT_IN_MB);
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* @type {pm2.StartOptions}
|
|
628
|
+
*/
|
|
629
|
+
const options = {
|
|
630
|
+
namespace: 'blocklets',
|
|
631
|
+
name: processId,
|
|
632
|
+
cwd,
|
|
633
|
+
// FIXME @linchen [] does not work, so use () here
|
|
634
|
+
log_date_format: '(YYYY-MM-DD HH:mm:ss)',
|
|
635
|
+
output: path.join(logsDir, 'output.log'),
|
|
636
|
+
error: path.join(logsDir, 'error.log'),
|
|
637
|
+
wait_ready: process.env.NODE_ENV !== 'test',
|
|
638
|
+
listen_timeout: 3000,
|
|
639
|
+
max_memory_restart: `${maxMemoryRestart}M`,
|
|
640
|
+
max_restarts: b.mode === BLOCKLET_MODES.DEVELOPMENT ? 0 : 3,
|
|
641
|
+
exp_backoff_restart_delay: 300,
|
|
642
|
+
env: {
|
|
643
|
+
...environmentObj,
|
|
644
|
+
...env,
|
|
645
|
+
NODE_ENV: 'production',
|
|
646
|
+
BLOCKLET_START_AT: now,
|
|
647
|
+
NODE_OPTIONS: getSecurityNodeOptions(b, nodeInfo.enableFileSystemIsolation),
|
|
648
|
+
},
|
|
649
|
+
script,
|
|
650
|
+
args,
|
|
651
|
+
interpreter,
|
|
652
|
+
interpreterArgs,
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
const clusterMode = get(b.meta, 'capabilities.clusterMode', false);
|
|
656
|
+
if (clusterMode && b.mode !== BLOCKLET_MODES.DEVELOPMENT) {
|
|
657
|
+
const clusterSize = Number(blocklet.configObj.BLOCKLET_CLUSTER_SIZE) || +process.env.ABT_NODE_MAX_CLUSTER_SIZE;
|
|
658
|
+
options.execMode = 'cluster';
|
|
659
|
+
options.mergeLogs = true;
|
|
660
|
+
options.instances = Math.max(Math.min(os.cpus().length, clusterSize), 1);
|
|
661
|
+
options.env.BLOCKLET_CLUSTER_SIZE = options.instances;
|
|
662
|
+
if (options.instances !== clusterSize) {
|
|
663
|
+
logger.warn(`Fallback cluster size to ${options.instances} for ${processId}, ignore custom ${clusterSize}`);
|
|
664
|
+
}
|
|
665
|
+
} else {
|
|
666
|
+
delete options.env.BLOCKLET_CLUSTER_SIZE;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
if (b.mode === BLOCKLET_MODES.DEVELOPMENT) {
|
|
670
|
+
options.env.NODE_ENV = e2eMode ? 'e2e' : 'development';
|
|
671
|
+
options.env.BROWSER = 'none';
|
|
672
|
+
options.env.PORT = options.env[BLOCKLET_DEFAULT_PORT_NAME];
|
|
673
|
+
|
|
674
|
+
if (process.platform === 'win32') {
|
|
675
|
+
const [cmd, ...argList] = options.script.split(' ').filter(Boolean);
|
|
676
|
+
|
|
677
|
+
if (!SCRIPT_ENGINES_WHITE_LIST.includes(cmd)) {
|
|
678
|
+
throw new Error(`${cmd} script is not supported, ${SCRIPT_ENGINES_WHITE_LIST.join(', ')} are supported`);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const { stdout: nodejsBinPath } = shelljs.which('node');
|
|
682
|
+
|
|
683
|
+
const cmdPath = path.join(path.dirname(nodejsBinPath), 'node_modules', cmd);
|
|
684
|
+
|
|
685
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(cmdPath, 'package.json'), 'utf8'));
|
|
686
|
+
const cmdBinPath = pkg.bin[cmd];
|
|
687
|
+
|
|
688
|
+
options.script = path.resolve(cmdPath, cmdBinPath);
|
|
689
|
+
options.args = [...argList].join(' ');
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
await configSynchronizer.syncComponentConfig(b.meta.did, blocklet.meta.did, {
|
|
694
|
+
serverSk: nodeEnvironments.ABT_NODE_SK,
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
const nextOptions =
|
|
698
|
+
b.mode === BLOCKLET_MODES.DEVELOPMENT
|
|
699
|
+
? options
|
|
700
|
+
: await parseDockerOptionsFromPm2({ options, nodeInfo, meta: b.meta, ports: b.ports, onlyStart });
|
|
701
|
+
|
|
702
|
+
await pm2.startAsync(nextOptions);
|
|
703
|
+
|
|
704
|
+
// eslint-disable-next-line no-use-before-define
|
|
705
|
+
const status = await getProcessState(processId);
|
|
706
|
+
if (status === BlockletStatus.error) {
|
|
707
|
+
throw new Error(`${processId} is not running within 3 seconds`);
|
|
708
|
+
}
|
|
709
|
+
logger.info('done start blocklet', { processId, status, time: Date.now() - startedAt });
|
|
710
|
+
|
|
711
|
+
// run hook
|
|
712
|
+
postStart(b, { env }).catch((err) => {
|
|
713
|
+
logger.error('blocklet post start failed', { processId, error: err });
|
|
714
|
+
});
|
|
715
|
+
},
|
|
716
|
+
{ parallel: true, concurrencyLimit: 4 }
|
|
717
|
+
);
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Stop all precesses of a blocklet
|
|
722
|
+
* @param {*} blocklet should contain env props
|
|
723
|
+
*/
|
|
724
|
+
const stopBlockletProcess = (blocklet, { preStop = noop, skippedProcessIds = [], componentDids } = {}) => {
|
|
725
|
+
// eslint-disable-next-line no-use-before-define
|
|
726
|
+
return deleteBlockletProcess(blocklet, { preDelete: preStop, skippedProcessIds, componentDids });
|
|
727
|
+
};
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* Delete all precesses of a blocklet
|
|
731
|
+
* @param {*} blocklet should contain env props
|
|
732
|
+
*/
|
|
733
|
+
const deleteBlockletProcess = async (blocklet, { preDelete = noop, skippedProcessIds = [], componentDids } = {}) => {
|
|
734
|
+
await forEachBlocklet(
|
|
735
|
+
blocklet,
|
|
736
|
+
async (b, { ancestors }) => {
|
|
737
|
+
// NOTICE: 如果不判断 group, 在 github action 中测试 disk.spec.js 时会报错, 但是在 mac 中跑测试不会报错
|
|
738
|
+
if (b.meta?.group === BlockletGroup.gateway) {
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
if (skippedProcessIds.includes(b.env.processId)) {
|
|
743
|
+
logger.info(`skip delete skipped process ${b.env.processId}`);
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// eslint-disable-next-line no-use-before-define
|
|
748
|
+
if (shouldSkipComponent(b.meta?.did, componentDids)) {
|
|
749
|
+
logger.info(`skip delete process not selected: ${b.meta.did}`, { processId: b.env.processId });
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
if (!hasStartEngine(b.meta)) {
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
await preDelete(b, { ancestors });
|
|
757
|
+
// eslint-disable-next-line no-use-before-define
|
|
758
|
+
await deleteProcess(b.env.processId);
|
|
759
|
+
},
|
|
760
|
+
{ parallel: true }
|
|
761
|
+
);
|
|
762
|
+
};
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Reload all precesses of a blocklet
|
|
766
|
+
* @param {*} blocklet should contain env props
|
|
767
|
+
*/
|
|
768
|
+
const reloadBlockletProcess = (blocklet, { componentDids } = {}) =>
|
|
769
|
+
forEachBlocklet(
|
|
770
|
+
blocklet,
|
|
771
|
+
async (b) => {
|
|
772
|
+
if (b.meta.group === BlockletGroup.gateway) {
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// eslint-disable-next-line no-use-before-define
|
|
777
|
+
if (shouldSkipComponent(b.meta.did, componentDids)) {
|
|
778
|
+
logger.info('skip reload process', { processId: b.env.processId });
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// eslint-disable-next-line no-use-before-define
|
|
783
|
+
await reloadProcess(b.env.processId);
|
|
784
|
+
logger.info('done reload process', { processId: b.env.processId });
|
|
785
|
+
},
|
|
786
|
+
{ parallel: false }
|
|
787
|
+
);
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* @param {*} processId
|
|
791
|
+
* @returns {BlockletStatus}
|
|
792
|
+
*/
|
|
793
|
+
const getProcessState = async (processId) => {
|
|
794
|
+
// eslint-disable-next-line no-use-before-define
|
|
795
|
+
const info = await getProcessInfo(processId);
|
|
796
|
+
if (!statusMap[info.pm2_env.status]) {
|
|
797
|
+
logger.error('Cannot find the blocklet status for pm2 status mapping', {
|
|
798
|
+
pm2Status: info.pm2_env.status,
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
return BlockletStatus.error;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
return statusMap[info.pm2_env.status];
|
|
805
|
+
};
|
|
806
|
+
|
|
807
|
+
const getProcessInfo = (processId, { throwOnNotExist = true } = {}) =>
|
|
808
|
+
getPm2ProcessInfo(processId, { printError: logger.error.bind(logger), throwOnNotExist });
|
|
809
|
+
|
|
810
|
+
const deleteProcess = (processId) => {
|
|
811
|
+
return new Promise((resolve, reject) => {
|
|
812
|
+
pm2.delete(processId, async (err) => {
|
|
813
|
+
if (isUsefulError(err)) {
|
|
814
|
+
logger.error('blocklet process delete failed', { processId, error: err });
|
|
815
|
+
return reject(err);
|
|
816
|
+
}
|
|
817
|
+
await dockerRemoveByName(processId);
|
|
818
|
+
return resolve(processId);
|
|
819
|
+
});
|
|
820
|
+
});
|
|
821
|
+
};
|
|
822
|
+
|
|
823
|
+
const reloadProcess = (processId) =>
|
|
824
|
+
new Promise((resolve, reject) => {
|
|
825
|
+
pm2.reload(processId, (err) => {
|
|
826
|
+
if (err) {
|
|
827
|
+
if (isUsefulError(err)) {
|
|
828
|
+
logger.error('blocklet reload failed', { processId, error: err });
|
|
829
|
+
}
|
|
830
|
+
return reject(err);
|
|
831
|
+
}
|
|
832
|
+
return resolve(processId);
|
|
833
|
+
});
|
|
834
|
+
});
|
|
835
|
+
|
|
836
|
+
const validateBlocklet = (blocklet) =>
|
|
837
|
+
forEachComponentV2(blocklet, (b) => {
|
|
838
|
+
isRequirementsSatisfied(b.meta.requirements);
|
|
839
|
+
validateEngine(getBlockletEngineNameByPlatform(b.meta));
|
|
840
|
+
});
|
|
841
|
+
|
|
842
|
+
const validateBlockletChainInfo = (blocklet) => {
|
|
843
|
+
const chainInfo = getChainInfo({
|
|
844
|
+
CHAIN_TYPE: blocklet.configObj[BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_CHAIN_TYPE],
|
|
845
|
+
CHAIN_ID: blocklet.configObj[BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_CHAIN_ID],
|
|
846
|
+
CHAIN_HOST: blocklet.configObj[BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_CHAIN_HOST],
|
|
847
|
+
});
|
|
848
|
+
|
|
849
|
+
const { error } = chainInfoSchema.validate(chainInfo);
|
|
850
|
+
if (error) {
|
|
851
|
+
throw error;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
return chainInfo;
|
|
855
|
+
};
|
|
856
|
+
|
|
857
|
+
const checkBlockletProcessHealthy = async (blocklet, { minConsecutiveTime, timeout, componentDids } = {}) => {
|
|
858
|
+
await forEachBlocklet(
|
|
859
|
+
blocklet,
|
|
860
|
+
async (b) => {
|
|
861
|
+
if (b.meta.group === BlockletGroup.gateway) {
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// components that relies on another engine component should not be checked
|
|
866
|
+
const engine = getBlockletEngine(b.meta);
|
|
867
|
+
if (engine.interpreter === 'blocklet') {
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
if (!hasStartEngine(b.meta)) {
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
// eslint-disable-next-line no-use-before-define
|
|
876
|
+
if (shouldSkipComponent(b.meta.did, componentDids)) {
|
|
877
|
+
logger.info('skip check component healthy', { processId: b.env.processId });
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
const logToTerminal = [blocklet.mode, b.mode].includes(BLOCKLET_MODES.DEVELOPMENT);
|
|
882
|
+
|
|
883
|
+
const startedAt = Date.now();
|
|
884
|
+
// eslint-disable-next-line no-use-before-define
|
|
885
|
+
await _checkProcessHealthy(b, { minConsecutiveTime, timeout, logToTerminal });
|
|
886
|
+
logger.info('done check component healthy', { processId: b.env.processId, time: Date.now() - startedAt });
|
|
887
|
+
},
|
|
888
|
+
{ parallel: true }
|
|
889
|
+
);
|
|
890
|
+
};
|
|
891
|
+
|
|
892
|
+
const _checkProcessHealthy = async (blocklet, { minConsecutiveTime, timeout, logToTerminal }) => {
|
|
893
|
+
const { meta, ports, env } = blocklet;
|
|
894
|
+
const { name } = meta;
|
|
895
|
+
const { processId } = env;
|
|
896
|
+
|
|
897
|
+
const webInterface = (meta.interfaces || []).find((x) => x.type === BLOCKLET_INTERFACE_TYPE_WEB);
|
|
898
|
+
const dockerInterface = (meta.interfaces || []).find((x) => x.type === BLOCKLET_INTERFACE_TYPE_DOCKER);
|
|
899
|
+
|
|
900
|
+
if (!webInterface && !dockerInterface) {
|
|
901
|
+
// TODO: how do we check healthy for service interfaces
|
|
902
|
+
throw new Error(`Blocklet ${name} does not have any web interface`);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
try {
|
|
906
|
+
// ensure pm2 status is 'online'
|
|
907
|
+
const getStatus = async () => {
|
|
908
|
+
try {
|
|
909
|
+
const info = await getProcessInfo(processId);
|
|
910
|
+
return info.pm2_env.status;
|
|
911
|
+
} catch (err) {
|
|
912
|
+
logger.error('blocklet checkStart error', { error: err, processId, name });
|
|
913
|
+
return '';
|
|
914
|
+
}
|
|
915
|
+
};
|
|
916
|
+
|
|
917
|
+
let status = await getStatus();
|
|
918
|
+
for (let i = 0; i < 20 && status !== 'online'; i++) {
|
|
919
|
+
const t = process.env.NODE_ENV !== 'test' ? 500 : 30;
|
|
920
|
+
await sleep(t);
|
|
921
|
+
status = await getStatus();
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
if (status !== 'online') {
|
|
925
|
+
throw new Error('process not start within 10s');
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
const port = findInterfacePortByName({ meta, ports }, (webInterface || dockerInterface).name);
|
|
929
|
+
if (logToTerminal) {
|
|
930
|
+
// eslint-disable-next-line no-console
|
|
931
|
+
console.log(
|
|
932
|
+
`Checking endpoint healthy for ${meta.title}, port: ${port}, minConsecutiveTime: ${
|
|
933
|
+
minConsecutiveTime / 1000
|
|
934
|
+
}s, timeout: ${timeout / 1000}s`
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
try {
|
|
938
|
+
if (webInterface) {
|
|
939
|
+
await ensureEndpointHealthy({ port, minConsecutiveTime, timeout });
|
|
940
|
+
} else {
|
|
941
|
+
await ensureDockerEndpointHealthy({ hostIP: dockerInterface.hostIP, port, minConsecutiveTime, timeout });
|
|
942
|
+
}
|
|
943
|
+
} catch (error) {
|
|
944
|
+
logger.error('ensure endpoint healthy failed', { port, minConsecutiveTime, timeout });
|
|
945
|
+
throw error;
|
|
946
|
+
}
|
|
947
|
+
} catch (error) {
|
|
948
|
+
logger.error('start blocklet failed', { processId, name });
|
|
949
|
+
throw error;
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
|
|
953
|
+
const expandTarball = async ({ source, dest, strip = 1 }) => {
|
|
954
|
+
logger.info('expand blocklet', { source, dest });
|
|
955
|
+
|
|
956
|
+
if (!fs.existsSync(source)) {
|
|
957
|
+
throw new Error(`Blocklet tarball ${source} does not exist`);
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
961
|
+
|
|
962
|
+
await streamToPromise(
|
|
963
|
+
fs
|
|
964
|
+
.createReadStream(source)
|
|
965
|
+
.pipe(new Throttle({ rate: 1024 * 1024 * 20 })) // 20MB
|
|
966
|
+
.pipe(tar.x({ C: dest, strip }))
|
|
967
|
+
);
|
|
968
|
+
|
|
969
|
+
return dest;
|
|
970
|
+
};
|
|
971
|
+
|
|
972
|
+
const verifyIntegrity = async ({ file, integrity: expected }) => {
|
|
973
|
+
const result = await ssri.checkStream(fs.createReadStream(file), ssri.parse(expected));
|
|
974
|
+
logger.debug('verify integrity result', { result });
|
|
975
|
+
return true;
|
|
976
|
+
};
|
|
977
|
+
|
|
978
|
+
/**
|
|
979
|
+
* @param {string} installDir
|
|
980
|
+
* @returns {Promise<Array<{ key: string, dir: string }>>} key is <[scope/]name/version>, dir is appDir
|
|
981
|
+
*/
|
|
982
|
+
const getAppDirs = async (installDir) => {
|
|
983
|
+
const appDirs = [];
|
|
984
|
+
|
|
985
|
+
const getNextLevel = (level, name) => {
|
|
986
|
+
if (level === 'root') {
|
|
987
|
+
if (name.startsWith('@')) {
|
|
988
|
+
return 'scope';
|
|
989
|
+
}
|
|
990
|
+
return 'name';
|
|
991
|
+
}
|
|
992
|
+
if (level === 'scope') {
|
|
993
|
+
return 'name';
|
|
994
|
+
}
|
|
995
|
+
if (level === 'name') {
|
|
996
|
+
return 'version';
|
|
997
|
+
}
|
|
998
|
+
throw new Error(`Invalid level ${level}`);
|
|
999
|
+
};
|
|
1000
|
+
|
|
1001
|
+
const fillAppDirs = async (dir, level = 'root') => {
|
|
1002
|
+
if (level === 'version') {
|
|
1003
|
+
appDirs.push({
|
|
1004
|
+
key: formatBackSlash(path.relative(installDir, dir)),
|
|
1005
|
+
dir,
|
|
1006
|
+
});
|
|
1007
|
+
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
const nextDirs = [];
|
|
1012
|
+
for (const x of await fs.promises.readdir(dir)) {
|
|
1013
|
+
if (!fs.lstatSync(path.join(dir, x)).isDirectory()) {
|
|
1014
|
+
logger.error('pruneBlockletBundle: invalid file in bundle storage', { dir, file: x });
|
|
1015
|
+
// eslint-disable-next-line no-continue
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
nextDirs.push(x);
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
for (const x of nextDirs) {
|
|
1022
|
+
await fillAppDirs(path.join(dir, x), getNextLevel(level, x));
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
|
|
1026
|
+
await fillAppDirs(installDir, 'root');
|
|
1027
|
+
|
|
1028
|
+
return appDirs;
|
|
1029
|
+
};
|
|
1030
|
+
|
|
1031
|
+
const pruneBlockletBundle = async ({ blocklets, installDir, blockletSettings }) => {
|
|
1032
|
+
for (const blocklet of blocklets) {
|
|
1033
|
+
if (
|
|
1034
|
+
[
|
|
1035
|
+
BlockletStatus.waiting,
|
|
1036
|
+
BlockletStatus.installing,
|
|
1037
|
+
BlockletStatus.upgrading,
|
|
1038
|
+
BlockletStatus.downloading,
|
|
1039
|
+
].includes(blocklet.status)
|
|
1040
|
+
) {
|
|
1041
|
+
logger.info('There are blocklet activities in progress, abort pruning', {
|
|
1042
|
+
bundleName: blocklet.meta.bundleName,
|
|
1043
|
+
status: fromBlockletStatus(blocklet.status),
|
|
1044
|
+
});
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
// blockletMap: { <[scope/]name/version>: true }
|
|
1050
|
+
const blockletMap = {};
|
|
1051
|
+
for (const blocklet of blocklets) {
|
|
1052
|
+
forEachBlockletSync(blocklet, (component) => {
|
|
1053
|
+
blockletMap[`${component.meta.bundleName}/${component.meta.version}`] = true;
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
for (const setting of blockletSettings) {
|
|
1057
|
+
for (const child of setting.children || []) {
|
|
1058
|
+
if (child.status !== BlockletStatus.deleted) {
|
|
1059
|
+
forEachBlockletSync(child, (component) => {
|
|
1060
|
+
blockletMap[`${component.meta.bundleName}/${component.meta.version}`] = true;
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// fill appDirs
|
|
1067
|
+
let appDirs = [];
|
|
1068
|
+
try {
|
|
1069
|
+
appDirs = await getAppDirs(installDir);
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
logger.error('fill app dirs failed', { error });
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
const ensureBundleDirRemoved = async (dir) => {
|
|
1075
|
+
const relativeDir = path.relative(installDir, dir);
|
|
1076
|
+
const arr = relativeDir.split(path.sep).filter(Boolean);
|
|
1077
|
+
const { length } = arr;
|
|
1078
|
+
const bundleName = arr[length - 2];
|
|
1079
|
+
const scopeName = length > 2 ? arr[length - 3] : '';
|
|
1080
|
+
const bundleDir = path.join(installDir, scopeName, bundleName);
|
|
1081
|
+
const isDirEmpty = (await fs.promises.readdir(bundleDir)).length === 0;
|
|
1082
|
+
if (isDirEmpty) {
|
|
1083
|
+
logger.info('Remove bundle folder', { bundleDir });
|
|
1084
|
+
await fs.remove(bundleDir);
|
|
1085
|
+
}
|
|
1086
|
+
if (scopeName) {
|
|
1087
|
+
const scopeDir = path.join(installDir, scopeName);
|
|
1088
|
+
const isScopeEmpty = (await fs.promises.readdir(scopeDir)).length === 0;
|
|
1089
|
+
if (isScopeEmpty) {
|
|
1090
|
+
logger.info('Remove scope folder', { scopeDir });
|
|
1091
|
+
await fs.remove(scopeDir);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
};
|
|
1095
|
+
|
|
1096
|
+
// remove trash
|
|
1097
|
+
for (const app of appDirs) {
|
|
1098
|
+
if (!blockletMap[app.key]) {
|
|
1099
|
+
logger.info('Remove app folder', { dir: app.dir });
|
|
1100
|
+
await fs.remove(app.dir);
|
|
1101
|
+
await ensureBundleDirRemoved(app.dir);
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
logger.info('Blocklet source folder has been pruned');
|
|
1106
|
+
};
|
|
1107
|
+
|
|
1108
|
+
const _diskInfoTasks = {};
|
|
1109
|
+
const _getDiskInfo = async (blocklet) => {
|
|
1110
|
+
try {
|
|
1111
|
+
const { env } = blocklet;
|
|
1112
|
+
const [app, cache, log, data] = await Promise.all([
|
|
1113
|
+
getFolderSize(env.appDir),
|
|
1114
|
+
getFolderSize(env.cacheDir),
|
|
1115
|
+
getFolderSize(env.logsDir),
|
|
1116
|
+
getFolderSize(env.dataDir),
|
|
1117
|
+
]);
|
|
1118
|
+
return { app, cache, log, data };
|
|
1119
|
+
} catch (error) {
|
|
1120
|
+
logger.error('Get disk info failed', { name: getDisplayName(blocklet), error });
|
|
1121
|
+
return { app: 0, cache: 0, log: 0, data: 0 };
|
|
1122
|
+
}
|
|
1123
|
+
};
|
|
1124
|
+
|
|
1125
|
+
const getDiskInfo = (blocklet, { useFakeDiskInfo } = {}) => {
|
|
1126
|
+
if (useFakeDiskInfo) {
|
|
1127
|
+
return { app: 0, cache: 0, log: 0, data: 0 };
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
const { appDid } = blocklet;
|
|
1131
|
+
|
|
1132
|
+
// Cache disk info results for 1 minute
|
|
1133
|
+
_diskInfoTasks[appDid] ??= _getDiskInfo(blocklet).finally(() => {
|
|
1134
|
+
setTimeout(() => {
|
|
1135
|
+
delete _diskInfoTasks[appDid];
|
|
1136
|
+
}, 120 * 1000);
|
|
1137
|
+
});
|
|
1138
|
+
|
|
1139
|
+
return new Promise((resolve) => {
|
|
1140
|
+
_diskInfoTasks[appDid].then(resolve).catch(() => {
|
|
1141
|
+
resolve({ app: 0, cache: 0, log: 0, data: 0 });
|
|
1142
|
+
});
|
|
1143
|
+
});
|
|
1144
|
+
};
|
|
1145
|
+
|
|
1146
|
+
const getRuntimeInfo = async (processId) => {
|
|
1147
|
+
const proc = await getProcessInfo(processId);
|
|
1148
|
+
const dockerName = proc.pm2_env?.env?.dockerName;
|
|
1149
|
+
if (dockerName) {
|
|
1150
|
+
const dockerInfo = await getDockerRuntimeInfo(dockerName);
|
|
1151
|
+
return {
|
|
1152
|
+
...dockerInfo,
|
|
1153
|
+
pid: proc.pid,
|
|
1154
|
+
uptime: proc.pm2_env ? +new Date() - Number(proc.pm2_env.pm_uptime) : 0,
|
|
1155
|
+
port: proc.pm2_env ? proc.pm2_env.BLOCKLET_PORT : null,
|
|
1156
|
+
status: proc.pm2_env ? proc.pm2_env.status : null,
|
|
1157
|
+
runningDocker: !!dockerName,
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
return {
|
|
1161
|
+
pid: proc.pid,
|
|
1162
|
+
uptime: proc.pm2_env ? +new Date() - Number(proc.pm2_env.pm_uptime) : 0,
|
|
1163
|
+
memoryUsage: proc.monit.memory,
|
|
1164
|
+
cpuUsage: proc.monit.cpu,
|
|
1165
|
+
status: proc.pm2_env ? proc.pm2_env.status : null,
|
|
1166
|
+
port: proc.pm2_env ? proc.pm2_env.BLOCKLET_PORT : null,
|
|
1167
|
+
runningDocker: false,
|
|
1168
|
+
};
|
|
1169
|
+
};
|
|
1170
|
+
|
|
1171
|
+
/**
|
|
1172
|
+
* merge services
|
|
1173
|
+
* from meta.children[].mountPoints[].services, meta.children[].services
|
|
1174
|
+
* to childrenMeta[].interfaces[].services
|
|
1175
|
+
*
|
|
1176
|
+
* @param {array<child>|object{children:array}} source e.g. [<config>] or { children: [<config>] }
|
|
1177
|
+
* @param {array<meta|{meta}>} childrenMeta e.g. [<meta>] or [{ meta: <meta> }]
|
|
1178
|
+
*/
|
|
1179
|
+
|
|
1180
|
+
const mergeMeta = (source, childrenMeta = []) => {
|
|
1181
|
+
// configMap
|
|
1182
|
+
const configMap = {};
|
|
1183
|
+
(Array.isArray(source) ? source : getComponentConfig(source) || []).forEach((x) => {
|
|
1184
|
+
configMap[x.name] = x;
|
|
1185
|
+
});
|
|
1186
|
+
|
|
1187
|
+
// merge service from config to child meta
|
|
1188
|
+
childrenMeta.forEach((child) => {
|
|
1189
|
+
const childMeta = child.meta || child;
|
|
1190
|
+
const config = configMap[childMeta.name];
|
|
1191
|
+
if (!config) {
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
(config.mountPoints || []).forEach((mountPoint) => {
|
|
1196
|
+
if (!mountPoint.services) {
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
const childInterface = childMeta.interfaces.find((y) => y.name === mountPoint.child.interfaceName);
|
|
1201
|
+
if (childInterface) {
|
|
1202
|
+
// merge
|
|
1203
|
+
const services = childInterface.services || [];
|
|
1204
|
+
mountPoint.services.forEach((x) => {
|
|
1205
|
+
const index = services.findIndex((y) => y.name === x.name);
|
|
1206
|
+
if (index >= 0) {
|
|
1207
|
+
services.splice(index, 1, x);
|
|
1208
|
+
} else {
|
|
1209
|
+
services.push(x);
|
|
1210
|
+
}
|
|
1211
|
+
});
|
|
1212
|
+
childInterface.services = services;
|
|
1213
|
+
}
|
|
1214
|
+
});
|
|
1215
|
+
|
|
1216
|
+
if (config.services) {
|
|
1217
|
+
const childInterface = findWebInterface(childMeta);
|
|
1218
|
+
if (childInterface) {
|
|
1219
|
+
// merge
|
|
1220
|
+
const services = childInterface.services || [];
|
|
1221
|
+
config.services.forEach((x) => {
|
|
1222
|
+
const index = services.findIndex((y) => y.name === x.name);
|
|
1223
|
+
if (index >= 0) {
|
|
1224
|
+
services.splice(index, 1, x);
|
|
1225
|
+
} else {
|
|
1226
|
+
services.push(x);
|
|
1227
|
+
}
|
|
1228
|
+
});
|
|
1229
|
+
childInterface.services = services;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
};
|
|
1234
|
+
|
|
1235
|
+
const getUpdateMetaList = (oldBlocklet = {}, newBlocklet = {}) => {
|
|
1236
|
+
const oldMap = {};
|
|
1237
|
+
forEachChildSync(oldBlocklet, (b, { id }) => {
|
|
1238
|
+
if (b.bundleSource) {
|
|
1239
|
+
oldMap[id] = b.meta.version;
|
|
1240
|
+
}
|
|
1241
|
+
});
|
|
1242
|
+
|
|
1243
|
+
const res = [];
|
|
1244
|
+
|
|
1245
|
+
forEachChildSync(newBlocklet, (b, { id }) => {
|
|
1246
|
+
if (b.bundleSource && semver.gt(b.meta.version, oldMap[id])) {
|
|
1247
|
+
res.push({ id, meta: b.meta });
|
|
1248
|
+
}
|
|
1249
|
+
});
|
|
1250
|
+
|
|
1251
|
+
return res;
|
|
1252
|
+
};
|
|
1253
|
+
|
|
1254
|
+
/**
|
|
1255
|
+
* @returns BLOCKLET_INSTALL_TYPE
|
|
1256
|
+
*/
|
|
1257
|
+
const getTypeFromInstallParams = (params) => {
|
|
1258
|
+
if (params.type) {
|
|
1259
|
+
if (!Object.values(BLOCKLET_INSTALL_TYPE).includes(params.type)) {
|
|
1260
|
+
throw new Error(`Can only install blocklet from ${Object.values(BLOCKLET_INSTALL_TYPE).join('/')}`);
|
|
1261
|
+
}
|
|
1262
|
+
return params.type;
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
if (params.url) {
|
|
1266
|
+
return BLOCKLET_INSTALL_TYPE.URL;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
if (params.file) {
|
|
1270
|
+
throw new Error('install from upload is not supported');
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
if (params.did) {
|
|
1274
|
+
return BLOCKLET_INSTALL_TYPE.STORE;
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
if (params.title && params.description) {
|
|
1278
|
+
return BLOCKLET_INSTALL_TYPE.CREATE;
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
throw new Error(`Can only install blocklet from ${Object.values(BLOCKLET_INSTALL_TYPE).join('/')}`);
|
|
1282
|
+
};
|
|
1283
|
+
|
|
1284
|
+
const checkDuplicateComponents = (components = []) => {
|
|
1285
|
+
const duplicates = components.filter(
|
|
1286
|
+
(item, index) => components.findIndex((x) => x.meta.did === item.meta.did) !== index
|
|
1287
|
+
);
|
|
1288
|
+
if (duplicates.length) {
|
|
1289
|
+
throw new Error(
|
|
1290
|
+
`Cannot add duplicate component${duplicates.length > 1 ? 's' : ''}: ${duplicates
|
|
1291
|
+
.map((x) => getDisplayName(x, true))
|
|
1292
|
+
.join(', ')}`
|
|
1293
|
+
);
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
|
|
1297
|
+
const getDiffFiles = async (inputFiles, sourceDir) => {
|
|
1298
|
+
if (!fs.existsSync(sourceDir)) {
|
|
1299
|
+
throw new Error(`${sourceDir} does not exist`);
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
const files = inputFiles.reduce((obj, item) => {
|
|
1303
|
+
obj[item.file] = item.hash;
|
|
1304
|
+
return obj;
|
|
1305
|
+
}, {});
|
|
1306
|
+
|
|
1307
|
+
const { files: sourceFiles } = await hashFiles(sourceDir, {
|
|
1308
|
+
filter: (x) => x.indexOf('node_modules') === -1,
|
|
1309
|
+
concurrentHash: 1,
|
|
1310
|
+
});
|
|
1311
|
+
|
|
1312
|
+
const addSet = [];
|
|
1313
|
+
const changeSet = [];
|
|
1314
|
+
const deleteSet = [];
|
|
1315
|
+
|
|
1316
|
+
const diffFiles = diff(sourceFiles, files);
|
|
1317
|
+
if (diffFiles) {
|
|
1318
|
+
diffFiles.forEach((item) => {
|
|
1319
|
+
if (item.kind === 'D') {
|
|
1320
|
+
deleteSet.push(item.path[0]);
|
|
1321
|
+
}
|
|
1322
|
+
if (item.kind === 'E') {
|
|
1323
|
+
changeSet.push(item.path[0]);
|
|
1324
|
+
}
|
|
1325
|
+
if (item.kind === 'N') {
|
|
1326
|
+
addSet.push(item.path[0]);
|
|
1327
|
+
}
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
return {
|
|
1332
|
+
addSet,
|
|
1333
|
+
changeSet,
|
|
1334
|
+
deleteSet,
|
|
1335
|
+
};
|
|
1336
|
+
};
|
|
1337
|
+
|
|
1338
|
+
const getBundleDir = (installDir, meta) => path.join(installDir, meta.bundleName || meta.name, meta.version);
|
|
1339
|
+
|
|
1340
|
+
const needBlockletDownload = (blocklet, oldBlocklet) => {
|
|
1341
|
+
if ([BlockletSource.upload, BlockletSource.local, BlockletSource.custom].includes(blocklet.source)) {
|
|
1342
|
+
return false;
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
if (!get(oldBlocklet, 'meta.dist.integrity')) {
|
|
1346
|
+
return true;
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
return get(oldBlocklet, 'meta.dist.integrity') !== get(blocklet, 'meta.dist.integrity');
|
|
1350
|
+
};
|
|
1351
|
+
|
|
1352
|
+
const getBlocklet = async ({
|
|
1353
|
+
did,
|
|
1354
|
+
dataDirs,
|
|
1355
|
+
states,
|
|
1356
|
+
e2eMode = false,
|
|
1357
|
+
throwOnNotExist = true,
|
|
1358
|
+
ensureIntegrity = false,
|
|
1359
|
+
getOptionalComponents = false,
|
|
1360
|
+
} = {}) => {
|
|
1361
|
+
if (!did) {
|
|
1362
|
+
throw new Error('Blocklet did does not exist');
|
|
1363
|
+
}
|
|
1364
|
+
if (!isValidDid(did)) {
|
|
1365
|
+
throw new Error(`Blocklet did is invalid: ${did}`);
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
if (!dataDirs) {
|
|
1369
|
+
throw new Error('dataDirs does not exist');
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
if (!states) {
|
|
1373
|
+
throw new Error('states does not exist');
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
const blocklet = await states.blocklet.getBlocklet(did);
|
|
1377
|
+
if (!blocklet) {
|
|
1378
|
+
if (throwOnNotExist || ensureIntegrity) {
|
|
1379
|
+
throw new Error(`can not find blocklet in database by did ${did}`);
|
|
1380
|
+
}
|
|
1381
|
+
return null;
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
// app settings
|
|
1385
|
+
// FIXME: @zhanghan 在 server 开发模式下,使用 `node /workspace/arcblock/blocklet-server/core/cli/tools/dev.js` 运行的 blocklet,blocklet.meta.did 和 blocklet.appPid 是不一致的
|
|
1386
|
+
const settings = await states.blockletExtras.getSettings(blocklet.meta.did);
|
|
1387
|
+
blocklet.trustedPassports = get(settings, 'trustedPassports') || [];
|
|
1388
|
+
blocklet.trustedFactories = (get(settings, 'trustedFactories') || []).map((x) => {
|
|
1389
|
+
if (!x.passport.ttlPolicy) {
|
|
1390
|
+
x.passport.ttlPolicy = 'never';
|
|
1391
|
+
x.passport.ttl = 0;
|
|
1392
|
+
}
|
|
1393
|
+
if (x.factoryAddress) {
|
|
1394
|
+
x.factoryAddress = toAddress(x.factoryAddress);
|
|
1395
|
+
}
|
|
1396
|
+
return x;
|
|
1397
|
+
});
|
|
1398
|
+
blocklet.enablePassportIssuance = get(settings, 'enablePassportIssuance', true);
|
|
1399
|
+
blocklet.settings = settings || {};
|
|
1400
|
+
|
|
1401
|
+
const extrasMeta = await states.blockletExtras.getMeta(blocklet.meta.did);
|
|
1402
|
+
if (extrasMeta) {
|
|
1403
|
+
blocklet.controller = extrasMeta.controller;
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
blocklet.settings.storeList = blocklet.settings.storeList || [];
|
|
1407
|
+
|
|
1408
|
+
const nodeInfo = await states.node.read();
|
|
1409
|
+
|
|
1410
|
+
(nodeInfo?.blockletRegistryList || []).forEach((store) => {
|
|
1411
|
+
if (!blocklet.settings.storeList.find((x) => x.url === store.url)) {
|
|
1412
|
+
blocklet.settings.storeList.push({
|
|
1413
|
+
...store,
|
|
1414
|
+
protected: true,
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
});
|
|
1418
|
+
|
|
1419
|
+
blocklet.site = await states.site.findOneByBlocklet(blocklet.meta.did);
|
|
1420
|
+
|
|
1421
|
+
await forEachBlocklet(blocklet, async (component, { id, level, ancestors }) => {
|
|
1422
|
+
// component env
|
|
1423
|
+
component.env = {
|
|
1424
|
+
id,
|
|
1425
|
+
name: getComponentName(component, ancestors),
|
|
1426
|
+
processId: getComponentProcessId(component, ancestors),
|
|
1427
|
+
...getComponentDirs(component, {
|
|
1428
|
+
dataDirs,
|
|
1429
|
+
ensure: ensureIntegrity,
|
|
1430
|
+
ancestors,
|
|
1431
|
+
e2eMode: level === 0 ? e2eMode : false,
|
|
1432
|
+
}),
|
|
1433
|
+
};
|
|
1434
|
+
|
|
1435
|
+
// component config
|
|
1436
|
+
const configs = await states.blockletExtras.getConfigs([...ancestors.map((x) => x.meta.did), component.meta.did]);
|
|
1437
|
+
fillBlockletConfigs(component, configs);
|
|
1438
|
+
});
|
|
1439
|
+
|
|
1440
|
+
if (getOptionalComponents) {
|
|
1441
|
+
const optionalComponents = await parseOptionalComponents(blocklet);
|
|
1442
|
+
blocklet.optionalComponents = optionalComponents;
|
|
1443
|
+
} else {
|
|
1444
|
+
blocklet.optionalComponents = [];
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
return blocklet;
|
|
1448
|
+
};
|
|
1449
|
+
|
|
1450
|
+
const fromProperty2Config = (properties = {}, result) => {
|
|
1451
|
+
Object.keys(properties).forEach((key) => {
|
|
1452
|
+
const prop = properties[key];
|
|
1453
|
+
if (prop.properties && ['ArrayTable', 'ArrayCards'].includes(prop['x-component']) === false) {
|
|
1454
|
+
fromProperty2Config(prop.properties, result);
|
|
1455
|
+
} else if (prop['x-decorator'] === 'FormItem') {
|
|
1456
|
+
const secure = prop['x-component'] === 'Password';
|
|
1457
|
+
result.push({
|
|
1458
|
+
default: prop.default || '',
|
|
1459
|
+
description: prop.title || key,
|
|
1460
|
+
name: `${BLOCKLET_PREFERENCE_PREFIX}${key}`,
|
|
1461
|
+
required: prop.required || false,
|
|
1462
|
+
secure,
|
|
1463
|
+
shared: secure ? false : prop.shared,
|
|
1464
|
+
});
|
|
1465
|
+
}
|
|
1466
|
+
});
|
|
1467
|
+
};
|
|
1468
|
+
const getConfigFromPreferences = (blocklet) => {
|
|
1469
|
+
const result = [];
|
|
1470
|
+
const schemaFile = path.join(blocklet.env.appDir, BLOCKLET_PREFERENCE_FILE);
|
|
1471
|
+
if (fs.existsSync(schemaFile)) {
|
|
1472
|
+
try {
|
|
1473
|
+
const schema = JSON.parse(fs.readFileSync(schemaFile, 'utf8'));
|
|
1474
|
+
fromProperty2Config(schema.schema?.properties, result);
|
|
1475
|
+
} catch {
|
|
1476
|
+
// do nothing
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
return result;
|
|
1481
|
+
};
|
|
1482
|
+
|
|
1483
|
+
const getBlockletURLForLauncher = ({ blocklet, nodeInfo }) => {
|
|
1484
|
+
const didDomain = getDidDomainForBlocklet({
|
|
1485
|
+
// eslint-disable-next-line no-use-before-define
|
|
1486
|
+
did: getSlpDid(nodeInfo.did, blocklet.appPid),
|
|
1487
|
+
didDomain: nodeInfo.slpDomain,
|
|
1488
|
+
});
|
|
1489
|
+
|
|
1490
|
+
return `https://${didDomain}`;
|
|
1491
|
+
};
|
|
1492
|
+
const createDataArchive = (dataDir, fileName) => {
|
|
1493
|
+
const zipPath = path.join(os.tmpdir(), fileName);
|
|
1494
|
+
if (fs.existsSync(zipPath)) {
|
|
1495
|
+
fs.removeSync(zipPath);
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
const archive = createArchive('zip', { zlib: { level: 9 } });
|
|
1499
|
+
const stream = fs.createWriteStream(zipPath);
|
|
1500
|
+
|
|
1501
|
+
return new Promise((resolve, reject) => {
|
|
1502
|
+
archive
|
|
1503
|
+
.directory(dataDir, false)
|
|
1504
|
+
.on('error', (err) => reject(err))
|
|
1505
|
+
.pipe(stream);
|
|
1506
|
+
|
|
1507
|
+
stream.on('close', () => resolve(zipPath));
|
|
1508
|
+
archive.finalize();
|
|
1509
|
+
});
|
|
1510
|
+
};
|
|
1511
|
+
|
|
1512
|
+
const isBlockletAppSkUsed = ({ environments, migratedFrom = [] }, appSk) => {
|
|
1513
|
+
const isUsedInEnv = environments.find((e) => e.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_SK)?.value === appSk;
|
|
1514
|
+
const isUsedInHistory = migratedFrom.some((x) => x.appSk === appSk);
|
|
1515
|
+
return isUsedInEnv || isUsedInHistory;
|
|
1516
|
+
};
|
|
1517
|
+
|
|
1518
|
+
const isRotatingAppSk = (newConfigs, oldConfigs, externalSk) => {
|
|
1519
|
+
const newSk = newConfigs.find((x) => BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_SK === x.key);
|
|
1520
|
+
if (!newSk) {
|
|
1521
|
+
// If no newSk found, we are not rotating the appSk
|
|
1522
|
+
return false;
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
const oldSk = oldConfigs.find((x) => BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_SK === x.key);
|
|
1526
|
+
if (!oldSk) {
|
|
1527
|
+
// If we have no oldSk, we are setting the initial appSk for external managed apps
|
|
1528
|
+
// If we have no oldSk, but we are not external managed apps, we are rotating the appSk
|
|
1529
|
+
return !externalSk;
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
// Otherwise, we must be rotating the appSk
|
|
1533
|
+
// eslint-disable-next-line sonarjs/prefer-single-boolean-return
|
|
1534
|
+
if (oldSk.value !== newSk.value) {
|
|
1535
|
+
return true;
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
return false;
|
|
1539
|
+
};
|
|
1540
|
+
|
|
1541
|
+
/**
|
|
1542
|
+
* this function has side effect on config.value
|
|
1543
|
+
* @param {{ key: string, value?: string }} config
|
|
1544
|
+
*/
|
|
1545
|
+
const validateAppConfig = async (config, states) => {
|
|
1546
|
+
const x = config;
|
|
1547
|
+
|
|
1548
|
+
// sk should be force secured while other app prop should not be secured
|
|
1549
|
+
config.secure = x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_SK;
|
|
1550
|
+
|
|
1551
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_SK) {
|
|
1552
|
+
if (x.value) {
|
|
1553
|
+
try {
|
|
1554
|
+
fromSecretKey(x.value);
|
|
1555
|
+
} catch {
|
|
1556
|
+
try {
|
|
1557
|
+
fromSecretKey(x.value, 'eth');
|
|
1558
|
+
} catch {
|
|
1559
|
+
throw new Error('Invalid custom blocklet secret key');
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
// Ensure sk is not used by existing blocklets, otherwise we may encounter appDid collision
|
|
1564
|
+
const blocklets = await states.blocklet.getBlocklets({});
|
|
1565
|
+
if (blocklets.some((b) => isBlockletAppSkUsed(b, x.value))) {
|
|
1566
|
+
throw new Error('Invalid custom blocklet secret key: already used by existing blocklet');
|
|
1567
|
+
}
|
|
1568
|
+
} else {
|
|
1569
|
+
delete x.value;
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_URL) {
|
|
1574
|
+
if (isEmpty(x.value)) {
|
|
1575
|
+
throw new Error(`${x.key} can not be empty`);
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
if (!isUrl(x.value)) {
|
|
1579
|
+
throw new Error(`${x.key}(${x.value}) is not a valid URL`);
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_NAME) {
|
|
1584
|
+
x.value = await titleSchema.validateAsync(x.value);
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_DESCRIPTION) {
|
|
1588
|
+
x.value = await descriptionSchema.validateAsync(x.value);
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
if (
|
|
1592
|
+
[
|
|
1593
|
+
BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_LOGO,
|
|
1594
|
+
BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_LOGO_RECT,
|
|
1595
|
+
BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_LOGO_SQUARE,
|
|
1596
|
+
BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_LOGO_FAVICON,
|
|
1597
|
+
].includes(x.key)
|
|
1598
|
+
) {
|
|
1599
|
+
x.value = await logoSchema.validateAsync(x.value);
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_CHAIN_TYPE) {
|
|
1603
|
+
if (['arcblock', 'ethereum'].includes(x.value) === false) {
|
|
1604
|
+
throw new Error('Invalid blocklet wallet type, only "default" and "eth" are supported');
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_DELETABLE) {
|
|
1609
|
+
if (['yes', 'no'].includes(x.value) === false) {
|
|
1610
|
+
throw new Error('BLOCKLET_DELETABLE must be either "yes" or "no"');
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_PASSPORT_COLOR) {
|
|
1615
|
+
if (x.value && x.value !== 'auto') {
|
|
1616
|
+
if (x.value.length !== 7 || !isHex(x.value.slice(-6))) {
|
|
1617
|
+
throw new Error('BLOCKLET_PASSPORT_COLOR must be a hex encoded color, eg. #ffeeaa');
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_SPACE_ENDPOINT) {
|
|
1623
|
+
// @note: value 置空以表删除
|
|
1624
|
+
if (x.value && !isUrl(x.value)) {
|
|
1625
|
+
throw new Error(`${x.key}(${x.value}) is not a valid URL`);
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_SPACES_URL) {
|
|
1630
|
+
if (isEmpty(x.value)) {
|
|
1631
|
+
throw new Error(`${x.key} can not be empty`);
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
if (!isUrl(x.value)) {
|
|
1635
|
+
throw new Error(`${x.key}(${x.value}) is not a valid URL`);
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_BACKUP_ENDPOINT) {
|
|
1640
|
+
// @note: value 置空以表删除
|
|
1641
|
+
if (isEmpty(x.value)) {
|
|
1642
|
+
x.value = '';
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
if (!isEmpty(x.value) && !isUrl(x.value)) {
|
|
1646
|
+
throw new Error(`${x.key}(${x.value}) is not a valid URL`);
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
if (x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_CLUSTER_SIZE) {
|
|
1651
|
+
if (isEmpty(x.value)) {
|
|
1652
|
+
x.value = '';
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
const v = Number(x.value);
|
|
1656
|
+
if (Number.isNaN(v)) {
|
|
1657
|
+
throw new Error(`${x.key} must be number`);
|
|
1658
|
+
}
|
|
1659
|
+
if (!Number.isInteger(v)) {
|
|
1660
|
+
throw new Error(`${x.key} must be integer`);
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
};
|
|
1664
|
+
|
|
1665
|
+
const checkDuplicateAppSk = async ({ sk, did, states }) => {
|
|
1666
|
+
if (!sk && !did) {
|
|
1667
|
+
throw new Error('sk and did is empty');
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
let appSk = sk;
|
|
1671
|
+
if (!sk) {
|
|
1672
|
+
const nodeInfo = await states.node.read();
|
|
1673
|
+
const blocklet = await states.blocklet.getBlocklet(did);
|
|
1674
|
+
const configs = await states.blockletExtras.getConfigs([did]);
|
|
1675
|
+
const { wallet } = getBlockletInfo(
|
|
1676
|
+
{
|
|
1677
|
+
meta: blocklet.meta,
|
|
1678
|
+
environments: (configs || []).filter((x) => x.value),
|
|
1679
|
+
},
|
|
1680
|
+
nodeInfo.sk
|
|
1681
|
+
);
|
|
1682
|
+
appSk = wallet.secretKey;
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
const blocklets = await states.blocklet.getBlocklets({});
|
|
1686
|
+
const others = did ? blocklets.filter((b) => b.meta.did !== did) : blocklets;
|
|
1687
|
+
|
|
1688
|
+
const exist = others.find((b) => {
|
|
1689
|
+
const item = (b.environments || []).find((e) => e.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_SK);
|
|
1690
|
+
return item?.value === toHex(appSk);
|
|
1691
|
+
});
|
|
1692
|
+
|
|
1693
|
+
if (exist) {
|
|
1694
|
+
throw new Error(`blocklet secret key already used by ${exist.meta.title || exist.meta.name}`);
|
|
1695
|
+
}
|
|
1696
|
+
};
|
|
1697
|
+
|
|
1698
|
+
const checkDuplicateMountPoint = (app, mountPoint) => {
|
|
1699
|
+
const err = new Error(`cannot add duplicate mount point, ${mountPoint || '/'} already exist`);
|
|
1700
|
+
|
|
1701
|
+
for (const component of app.children || []) {
|
|
1702
|
+
if (
|
|
1703
|
+
hasStartEngine(component.meta) &&
|
|
1704
|
+
normalizePathPrefix(component.mountPoint) === normalizePathPrefix(mountPoint)
|
|
1705
|
+
) {
|
|
1706
|
+
throw err;
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
};
|
|
1710
|
+
|
|
1711
|
+
const validateStore = (nodeInfo, storeUrl) => {
|
|
1712
|
+
if (nodeInfo.mode !== 'serverless') {
|
|
1713
|
+
return;
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
const inStoreList = nodeInfo.blockletRegistryList.find((item) => {
|
|
1717
|
+
const itemURLObj = new URL(item.url);
|
|
1718
|
+
const storeUrlObj = new URL(storeUrl);
|
|
1719
|
+
|
|
1720
|
+
return itemURLObj.host === storeUrlObj.host;
|
|
1721
|
+
});
|
|
1722
|
+
|
|
1723
|
+
if (!inStoreList) {
|
|
1724
|
+
throw new Error('Must be installed from the compliant blocklet store list');
|
|
1725
|
+
}
|
|
1726
|
+
};
|
|
1727
|
+
|
|
1728
|
+
const validateInServerless = ({ blockletMeta }) => {
|
|
1729
|
+
const { interfaces } = blockletMeta;
|
|
1730
|
+
const externalPortInterfaces = (interfaces || []).filter((item) => !!item.port?.external);
|
|
1731
|
+
|
|
1732
|
+
if (externalPortInterfaces.length > 0) {
|
|
1733
|
+
throw new Error('Blocklets with exposed ports cannot be installed');
|
|
1734
|
+
}
|
|
1735
|
+
};
|
|
1736
|
+
|
|
1737
|
+
const checkStructVersion = (blocklet) => {
|
|
1738
|
+
if (blocklet.structVersion !== APP_STRUCT_VERSION) {
|
|
1739
|
+
throw new Error('You should migrate the application first');
|
|
1740
|
+
}
|
|
1741
|
+
};
|
|
1742
|
+
|
|
1743
|
+
const isVersionCompatible = (actualVersion, expectedRange) =>
|
|
1744
|
+
!expectedRange || expectedRange === 'latest' || semver.satisfies(actualVersion, expectedRange);
|
|
1745
|
+
|
|
1746
|
+
const checkVersionCompatibility = (components) => {
|
|
1747
|
+
for (const component of components) {
|
|
1748
|
+
// eslint-disable-next-line no-loop-func
|
|
1749
|
+
forEachBlockletSync(component, (x) => {
|
|
1750
|
+
const dependencies = x.dependencies || [];
|
|
1751
|
+
dependencies.forEach((dep) => {
|
|
1752
|
+
const { did, version: expectedRange } = dep;
|
|
1753
|
+
const exist = components.find((y) => y.meta.did === did);
|
|
1754
|
+
if (exist && !isVersionCompatible(exist.meta.version, expectedRange)) {
|
|
1755
|
+
throw new Error(
|
|
1756
|
+
`Check version compatible failed: ${component.meta.title || component.meta.did} expects ${
|
|
1757
|
+
exist.meta.title || exist.meta.did
|
|
1758
|
+
}'s version to be ${expectedRange}, but actual is ${exist.meta.version}`
|
|
1759
|
+
);
|
|
1760
|
+
}
|
|
1761
|
+
});
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
};
|
|
1765
|
+
|
|
1766
|
+
const getBlockletKnownAs = (blocklet) => {
|
|
1767
|
+
const alsoKnownAs = [blocklet.appDid];
|
|
1768
|
+
if (Array.isArray(blocklet.migratedFrom)) {
|
|
1769
|
+
blocklet.migratedFrom.filter((x) => x.appDid !== blocklet.appPid).forEach((x) => alsoKnownAs.push(x.appDid));
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
return alsoKnownAs.filter(Boolean).map(toDid);
|
|
1773
|
+
};
|
|
1774
|
+
|
|
1775
|
+
const getFixedBundleSource = (component) => {
|
|
1776
|
+
if (!component) {
|
|
1777
|
+
return null;
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
if (component.bundleSource) {
|
|
1781
|
+
return component.bundleSource;
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
const { source, deployedFrom, meta: { bundleName } = {} } = component;
|
|
1785
|
+
|
|
1786
|
+
if (!deployedFrom) {
|
|
1787
|
+
return null;
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
if (source === BlockletSource.registry && bundleName) {
|
|
1791
|
+
return {
|
|
1792
|
+
store: deployedFrom,
|
|
1793
|
+
name: bundleName,
|
|
1794
|
+
version: 'latest',
|
|
1795
|
+
};
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
if (source === BlockletSource.url) {
|
|
1799
|
+
return {
|
|
1800
|
+
url: deployedFrom,
|
|
1801
|
+
};
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
return null;
|
|
1805
|
+
};
|
|
1806
|
+
|
|
1807
|
+
const updateBlockletFallbackLogo = async (blocklet) => {
|
|
1808
|
+
if (isEthereumDid(blocklet.meta.did)) {
|
|
1809
|
+
await fs.writeFile(path.join(blocklet.env.dataDir, 'logo.svg'), createBlockiesSvg(blocklet.meta.did));
|
|
1810
|
+
} else {
|
|
1811
|
+
await fs.writeFile(path.join(blocklet.env.dataDir, 'logo.svg'), createDidLogo(blocklet.meta.did));
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
|
|
1815
|
+
const ensureAppLogo = async (blocklet, blockletsDir) => {
|
|
1816
|
+
if (!blocklet) {
|
|
1817
|
+
return;
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
if (
|
|
1821
|
+
blocklet.source === BlockletSource.custom &&
|
|
1822
|
+
(blocklet.children || [])[0]?.meta?.logo &&
|
|
1823
|
+
blocklet.children[0].env.appDir
|
|
1824
|
+
) {
|
|
1825
|
+
const fileName = blocklet.children[0].meta.logo;
|
|
1826
|
+
const src = path.join(blocklet.children[0].env.appDir, fileName);
|
|
1827
|
+
const dist = path.join(getBundleDir(blockletsDir, blocklet.meta), fileName);
|
|
1828
|
+
|
|
1829
|
+
if (fs.existsSync(src)) {
|
|
1830
|
+
await fs.copy(src, dist);
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
};
|
|
1834
|
+
|
|
1835
|
+
const getBlockletDidDomainList = (blocklet, nodeInfo) => {
|
|
1836
|
+
const domainAliases = [];
|
|
1837
|
+
const alsoKnownAs = getBlockletKnownAs(blocklet);
|
|
1838
|
+
|
|
1839
|
+
const dids = [blocklet.appPid, blocklet.appDid, ...alsoKnownAs].filter(Boolean).map((did) => toAddress(did));
|
|
1840
|
+
|
|
1841
|
+
uniq(dids).forEach((did) => {
|
|
1842
|
+
const domain = getDidDomainForBlocklet({ did, didDomain: nodeInfo.didDomain });
|
|
1843
|
+
|
|
1844
|
+
domainAliases.push({ value: domain, isProtected: true });
|
|
1845
|
+
});
|
|
1846
|
+
|
|
1847
|
+
// eslint-disable-next-line no-use-before-define
|
|
1848
|
+
const enableSlpDomain = shouldEnableSlpDomain({
|
|
1849
|
+
mode: nodeInfo.mode,
|
|
1850
|
+
launcher: nodeInfo.launcher,
|
|
1851
|
+
});
|
|
1852
|
+
if (enableSlpDomain) {
|
|
1853
|
+
// eslint-disable-next-line no-use-before-define
|
|
1854
|
+
const slpDid = getSlpDid(nodeInfo.did, blocklet.appPid);
|
|
1855
|
+
const domain = getDidDomainForBlocklet({ did: slpDid, didDomain: nodeInfo.slpDomain });
|
|
1856
|
+
|
|
1857
|
+
domainAliases.push({ value: domain, isProtected: true });
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
return domainAliases;
|
|
1861
|
+
};
|
|
1862
|
+
|
|
1863
|
+
const getBlockletStatus = (blocklet) => {
|
|
1864
|
+
const fallbackStatus = BlockletStatus.stopped;
|
|
1865
|
+
|
|
1866
|
+
if (!blocklet) {
|
|
1867
|
+
return fallbackStatus;
|
|
1868
|
+
}
|
|
1869
|
+
|
|
1870
|
+
if (!blocklet.children?.length) {
|
|
1871
|
+
if (blocklet.meta?.group === BlockletGroup.gateway) {
|
|
1872
|
+
return blocklet.status;
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
if (blocklet.status === BlockletStatus.added) {
|
|
1876
|
+
return BlockletStatus.added;
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
// for backward compatibility
|
|
1880
|
+
if (!blocklet.structVersion) {
|
|
1881
|
+
return blocklet.status;
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
return fallbackStatus;
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
let inProgressStatus;
|
|
1888
|
+
let runningStatus;
|
|
1889
|
+
let status;
|
|
1890
|
+
|
|
1891
|
+
forEachComponentV2Sync(blocklet, (component) => {
|
|
1892
|
+
if (component.meta?.group === BlockletGroup.gateway) {
|
|
1893
|
+
return;
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
if (isInProgress(component.status)) {
|
|
1897
|
+
if (!inProgressStatus) {
|
|
1898
|
+
inProgressStatus = component.status;
|
|
1899
|
+
}
|
|
1900
|
+
return;
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
if (isRunning(component.status)) {
|
|
1904
|
+
runningStatus = component.status;
|
|
1905
|
+
return;
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
if (status === BlockletStatus.stopped) {
|
|
1909
|
+
return;
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
status = component.status;
|
|
1913
|
+
});
|
|
1914
|
+
|
|
1915
|
+
return inProgressStatus || runningStatus || status;
|
|
1916
|
+
};
|
|
1917
|
+
|
|
1918
|
+
const shouldSkipComponent = (componentDid, whiteList) => {
|
|
1919
|
+
if (!whiteList || !Array.isArray(whiteList)) {
|
|
1920
|
+
return false;
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
const arr = whiteList.filter(Boolean);
|
|
1924
|
+
|
|
1925
|
+
if (!arr.length) {
|
|
1926
|
+
return false;
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
return !arr.includes(componentDid);
|
|
1930
|
+
};
|
|
1931
|
+
|
|
1932
|
+
const ensureAppPortsNotOccupied = async ({
|
|
1933
|
+
blocklet,
|
|
1934
|
+
componentDids: inputDids,
|
|
1935
|
+
states,
|
|
1936
|
+
manager,
|
|
1937
|
+
checkPortsFn = isPortsOccupiedByOtherProcess,
|
|
1938
|
+
}) => {
|
|
1939
|
+
const { did } = blocklet.meta;
|
|
1940
|
+
const componentDids = [];
|
|
1941
|
+
await forEachComponentV2(blocklet, async (b) => {
|
|
1942
|
+
try {
|
|
1943
|
+
if (shouldSkipComponent(b.meta.did, inputDids)) {
|
|
1944
|
+
return;
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
const { processId } = b.env;
|
|
1948
|
+
const { ports } = b;
|
|
1949
|
+
if (
|
|
1950
|
+
await checkPortsFn({
|
|
1951
|
+
ports,
|
|
1952
|
+
pm2ProcessId: processId,
|
|
1953
|
+
printError: logger.error.bind(logger),
|
|
1954
|
+
})
|
|
1955
|
+
) {
|
|
1956
|
+
componentDids.push(b.meta.did);
|
|
1957
|
+
}
|
|
1958
|
+
} catch (error) {
|
|
1959
|
+
logger.error('Failed to check ports occupied', { error });
|
|
1960
|
+
}
|
|
1961
|
+
});
|
|
1962
|
+
|
|
1963
|
+
let newBlocklet = blocklet;
|
|
1964
|
+
if (componentDids.length) {
|
|
1965
|
+
await states.blocklet.refreshBlockletPorts(did, componentDids);
|
|
1966
|
+
logger.info('refresh component ports', { did, componentDids });
|
|
1967
|
+
await manager._updateBlockletEnvironment(did);
|
|
1968
|
+
newBlocklet = await manager.ensureBlocklet(did);
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
return newBlocklet;
|
|
1972
|
+
};
|
|
1973
|
+
|
|
1974
|
+
const getComponentNamesWithVersion = (app = {}, componentDids = []) => {
|
|
1975
|
+
const str = uniq(componentDids)
|
|
1976
|
+
.map((x) => {
|
|
1977
|
+
const component = (app.children || []).find((y) => y.meta.did === x);
|
|
1978
|
+
return `${component.meta.title}@${component.meta.version}`;
|
|
1979
|
+
})
|
|
1980
|
+
.join(', ');
|
|
1981
|
+
return str;
|
|
1982
|
+
};
|
|
1983
|
+
|
|
1984
|
+
const shouldEnableSlpDomain = ({ mode, launcher }) => {
|
|
1985
|
+
if (process.env.ABT_NODE_ENABLE_SLP_DOMAIN === 'true') {
|
|
1986
|
+
return true;
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
return isInServerlessMode({ mode }) && !!launcher;
|
|
1990
|
+
};
|
|
1991
|
+
|
|
1992
|
+
const getSlpDid = (serverDid, appPid) => {
|
|
1993
|
+
if (!serverDid || !appPid) {
|
|
1994
|
+
throw new Error('serverDid and appPid is required');
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
const buffer = Buffer.concat([toBuffer(serverDid), toBuffer(appPid)]);
|
|
1998
|
+
const md5Str = md5(buffer);
|
|
1999
|
+
|
|
2000
|
+
const wallet = fromPublicKey(md5Str);
|
|
2001
|
+
return wallet.address;
|
|
2002
|
+
};
|
|
2003
|
+
|
|
2004
|
+
// eslint-disable-next-line require-await
|
|
2005
|
+
const updateDidDocument = async ({ blocklet, nodeInfo }) => {
|
|
2006
|
+
const alsoKnownAs = getBlockletKnownAs(blocklet);
|
|
2007
|
+
const { wallet } = getBlockletInfo(blocklet, nodeInfo.sk);
|
|
2008
|
+
const { mode, launcher, did: serverDid } = nodeInfo;
|
|
2009
|
+
|
|
2010
|
+
let slpDid = null;
|
|
2011
|
+
const enableSlpDomain = shouldEnableSlpDomain({ mode, launcher });
|
|
2012
|
+
if (enableSlpDomain) {
|
|
2013
|
+
slpDid = getSlpDid(serverDid, blocklet.appPid);
|
|
2014
|
+
|
|
2015
|
+
if (alsoKnownAs.indexOf(slpDid) === -1) {
|
|
2016
|
+
alsoKnownAs.push(toDid(slpDid));
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
return didDocument.updateBlockletDocument({
|
|
2021
|
+
blocklet,
|
|
2022
|
+
wallet,
|
|
2023
|
+
alsoKnownAs,
|
|
2024
|
+
slpDid,
|
|
2025
|
+
daemonDidDomain: getServerDidDomain(nodeInfo),
|
|
2026
|
+
didRegistryUrl: nodeInfo.didRegistry,
|
|
2027
|
+
domain: nodeInfo.didDomain,
|
|
2028
|
+
slpDomain: nodeInfo.slpDomain,
|
|
2029
|
+
serverDid,
|
|
2030
|
+
blockletServerVersion: nodeInfo.version,
|
|
2031
|
+
});
|
|
2032
|
+
};
|
|
2033
|
+
|
|
2034
|
+
const getAppConfigsFromComponent = (meta, configsInApp = [], configsInComponent = []) => {
|
|
2035
|
+
const configs = [];
|
|
2036
|
+
for (const configInMeta of meta?.environments || []) {
|
|
2037
|
+
if (isEnvShareable(configInMeta)) {
|
|
2038
|
+
const configInApp = (configsInApp || []).find((x) => x.key === configInMeta.name);
|
|
2039
|
+
if (!configInApp) {
|
|
2040
|
+
const configInComponent = configsInComponent.find((y) => y.key === configInMeta.name);
|
|
2041
|
+
if (configInComponent && isEnvShareable(configInComponent)) {
|
|
2042
|
+
configs.push(configInComponent);
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
return configs;
|
|
2048
|
+
};
|
|
2049
|
+
|
|
2050
|
+
const getConfigsFromInput = (configs = [], oldConfigs = []) => {
|
|
2051
|
+
const sharedConfigs = [];
|
|
2052
|
+
const selfConfigs = [];
|
|
2053
|
+
|
|
2054
|
+
configs.forEach((config) => {
|
|
2055
|
+
const oldConfig = oldConfigs.find((y) => y.key === config.key);
|
|
2056
|
+
if (isEnvShareable(config) || isEnvShareable(oldConfig)) {
|
|
2057
|
+
sharedConfigs.push(config);
|
|
2058
|
+
} else {
|
|
2059
|
+
selfConfigs.push(config);
|
|
2060
|
+
}
|
|
2061
|
+
});
|
|
2062
|
+
|
|
2063
|
+
return { sharedConfigs, selfConfigs };
|
|
2064
|
+
};
|
|
2065
|
+
|
|
2066
|
+
// remove app configs if no component use it
|
|
2067
|
+
const removeAppConfigsFromComponent = async (componentConfigs, app, blockletExtraState) => {
|
|
2068
|
+
const appConfigs = app.configs || [];
|
|
2069
|
+
const remainedConfigs = [].concat(...(app.children || []).map((x) => x.configs || []));
|
|
2070
|
+
const removedAppConfigs = [];
|
|
2071
|
+
|
|
2072
|
+
componentConfigs.forEach((config) => {
|
|
2073
|
+
const appConfig = appConfigs.find((x) => x.key === config.key);
|
|
2074
|
+
if (
|
|
2075
|
+
appConfig &&
|
|
2076
|
+
!appConfig.custom &&
|
|
2077
|
+
!(app.meta.environments || []).find((x) => x.name === config.key) &&
|
|
2078
|
+
!remainedConfigs.find((x) => x.key === config.key && isEnvShareable(x))
|
|
2079
|
+
) {
|
|
2080
|
+
removedAppConfigs.push({ key: appConfig.key, value: undefined });
|
|
2081
|
+
}
|
|
2082
|
+
});
|
|
2083
|
+
|
|
2084
|
+
if (removedAppConfigs.length) {
|
|
2085
|
+
await blockletExtraState.setConfigs(app.meta.did, removedAppConfigs);
|
|
2086
|
+
}
|
|
2087
|
+
};
|
|
2088
|
+
|
|
2089
|
+
const getPackConfig = (app) => {
|
|
2090
|
+
const packComponent = (app?.children || []).find((x) => x.meta.group === BlockletGroup.pack);
|
|
2091
|
+
if (!packComponent) {
|
|
2092
|
+
return null;
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
const resource = (packComponent.meta.resource?.bundles || []).find(
|
|
2096
|
+
(x) => x.did === packComponent.meta.did && x.type === 'config'
|
|
2097
|
+
);
|
|
2098
|
+
|
|
2099
|
+
if (!resource) {
|
|
2100
|
+
return null;
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
const { appDir } = packComponent.env;
|
|
2104
|
+
const configFile = path.join(appDir, BLOCKLET_RESOURCE_DIR, resource.did, resource.type, 'config.json');
|
|
2105
|
+
|
|
2106
|
+
if (!fs.existsSync(configFile)) {
|
|
2107
|
+
return null;
|
|
2108
|
+
}
|
|
2109
|
+
|
|
2110
|
+
return fs.readJSON(configFile);
|
|
2111
|
+
};
|
|
2112
|
+
|
|
2113
|
+
module.exports = {
|
|
2114
|
+
updateBlockletFallbackLogo,
|
|
2115
|
+
forEachBlocklet,
|
|
2116
|
+
getBlockletMetaFromUrl: (url) => getBlockletMetaFromUrl(url, { logger }),
|
|
2117
|
+
parseComponents,
|
|
2118
|
+
filterRequiredComponents,
|
|
2119
|
+
getComponentDirs,
|
|
2120
|
+
getAppSystemEnvironments,
|
|
2121
|
+
getAppOverwrittenEnvironments,
|
|
2122
|
+
getComponentSystemEnvironments,
|
|
2123
|
+
getRuntimeEnvironments,
|
|
2124
|
+
validateBlocklet,
|
|
2125
|
+
validateBlockletChainInfo,
|
|
2126
|
+
fillBlockletConfigs,
|
|
2127
|
+
ensureBlockletExpanded,
|
|
2128
|
+
startBlockletProcess,
|
|
2129
|
+
stopBlockletProcess,
|
|
2130
|
+
deleteBlockletProcess,
|
|
2131
|
+
reloadBlockletProcess,
|
|
2132
|
+
checkBlockletProcessHealthy,
|
|
2133
|
+
getHealthyCheckTimeout,
|
|
2134
|
+
getProcessInfo,
|
|
2135
|
+
expandTarball,
|
|
2136
|
+
verifyIntegrity,
|
|
2137
|
+
getAppDirs,
|
|
2138
|
+
pruneBlockletBundle,
|
|
2139
|
+
getDiskInfo,
|
|
2140
|
+
getRuntimeInfo,
|
|
2141
|
+
mergeMeta,
|
|
2142
|
+
getUpdateMetaList,
|
|
2143
|
+
getTypeFromInstallParams,
|
|
2144
|
+
findWebInterface,
|
|
2145
|
+
checkDuplicateComponents,
|
|
2146
|
+
filterDuplicateComponents,
|
|
2147
|
+
getDiffFiles,
|
|
2148
|
+
getBundleDir,
|
|
2149
|
+
needBlockletDownload,
|
|
2150
|
+
ensureMeta,
|
|
2151
|
+
getBlocklet,
|
|
2152
|
+
getConfigFromPreferences,
|
|
2153
|
+
createDataArchive,
|
|
2154
|
+
validateAppConfig,
|
|
2155
|
+
isBlockletAppSkUsed,
|
|
2156
|
+
isRotatingAppSk,
|
|
2157
|
+
checkDuplicateAppSk,
|
|
2158
|
+
checkDuplicateMountPoint,
|
|
2159
|
+
validateStore,
|
|
2160
|
+
validateInServerless,
|
|
2161
|
+
checkStructVersion,
|
|
2162
|
+
checkVersionCompatibility,
|
|
2163
|
+
validateBlockletMeta,
|
|
2164
|
+
getBlockletKnownAs,
|
|
2165
|
+
getFixedBundleSource,
|
|
2166
|
+
ensureAppLogo,
|
|
2167
|
+
getBlockletDidDomainList,
|
|
2168
|
+
getProcessState,
|
|
2169
|
+
getBlockletStatus,
|
|
2170
|
+
shouldSkipComponent,
|
|
2171
|
+
getBlockletURLForLauncher,
|
|
2172
|
+
ensureAppPortsNotOccupied,
|
|
2173
|
+
getComponentNamesWithVersion,
|
|
2174
|
+
updateDidDocument,
|
|
2175
|
+
getSlpDid,
|
|
2176
|
+
shouldEnableSlpDomain,
|
|
2177
|
+
getAppConfigsFromComponent,
|
|
2178
|
+
removeAppConfigsFromComponent,
|
|
2179
|
+
getConfigsFromInput,
|
|
2180
|
+
getPackConfig,
|
|
2181
|
+
getBlockletConfigObj,
|
|
2182
|
+
};
|