@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.
Files changed (346) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +3 -0
  3. package/lib/api/node.js +176 -0
  4. package/lib/api/team.js +1889 -0
  5. package/lib/blocklet/downloader/blocklet-downloader.js +246 -0
  6. package/lib/blocklet/downloader/bundle-downloader.js +316 -0
  7. package/lib/blocklet/downloader/constants.js +3 -0
  8. package/lib/blocklet/downloader/resolve-download.js +187 -0
  9. package/lib/blocklet/extras.js +177 -0
  10. package/lib/blocklet/hooks.js +89 -0
  11. package/lib/blocklet/manager/base.js +49 -0
  12. package/lib/blocklet/manager/config-synchronizer.js +128 -0
  13. package/lib/blocklet/manager/disk.js +5170 -0
  14. package/lib/blocklet/manager/engine.js +124 -0
  15. package/lib/blocklet/manager/helper/install-application-from-backup.js +285 -0
  16. package/lib/blocklet/manager/helper/install-application-from-dev.js +72 -0
  17. package/lib/blocklet/manager/helper/install-application-from-general.js +209 -0
  18. package/lib/blocklet/manager/helper/install-component-from-dev.js +128 -0
  19. package/lib/blocklet/manager/helper/install-component-from-upload.js +197 -0
  20. package/lib/blocklet/manager/helper/install-component-from-url.js +214 -0
  21. package/lib/blocklet/manager/helper/migrate-application-to-struct-v2.js +557 -0
  22. package/lib/blocklet/manager/helper/rollback-cache.js +41 -0
  23. package/lib/blocklet/manager/helper/upgrade-components.js +179 -0
  24. package/lib/blocklet/manager/pm2-events.js +50 -0
  25. package/lib/blocklet/migration-dist/migration.cjs +38605 -0
  26. package/lib/blocklet/migration-dist/run-script.cjs +29 -0
  27. package/lib/blocklet/migration.js +145 -0
  28. package/lib/blocklet/project/connect-by-studio.js +91 -0
  29. package/lib/blocklet/project/connect-to-store.js +64 -0
  30. package/lib/blocklet/project/create-pack-release.js +293 -0
  31. package/lib/blocklet/project/disconnect-from-store.js +13 -0
  32. package/lib/blocklet/project/get-is-multiple-tenant.js +8 -0
  33. package/lib/blocklet/project/index.js +545 -0
  34. package/lib/blocklet/project/logo.png +0 -0
  35. package/lib/blocklet/project/publish-to-store.js +108 -0
  36. package/lib/blocklet/project/util.js +194 -0
  37. package/lib/blocklet/security/access-policy.js +131 -0
  38. package/lib/blocklet/security/index.js +309 -0
  39. package/lib/blocklet/security/response-header-policy.js +178 -0
  40. package/lib/blocklet/security/security-rule.js +127 -0
  41. package/lib/blocklet/security/utils.js +35 -0
  42. package/lib/blocklet/security/validator.js +40 -0
  43. package/lib/blocklet/storage/backup/base.js +149 -0
  44. package/lib/blocklet/storage/backup/blocklet-extras.js +110 -0
  45. package/lib/blocklet/storage/backup/blocklet.js +159 -0
  46. package/lib/blocklet/storage/backup/blocklets.js +109 -0
  47. package/lib/blocklet/storage/backup/data.js +35 -0
  48. package/lib/blocklet/storage/backup/disk.js +131 -0
  49. package/lib/blocklet/storage/backup/logs.js +24 -0
  50. package/lib/blocklet/storage/backup/routing-rule.js +47 -0
  51. package/lib/blocklet/storage/backup/spaces.js +345 -0
  52. package/lib/blocklet/storage/restore/base.js +74 -0
  53. package/lib/blocklet/storage/restore/blocklet-extras.js +89 -0
  54. package/lib/blocklet/storage/restore/blocklet.js +56 -0
  55. package/lib/blocklet/storage/restore/blocklets.js +43 -0
  56. package/lib/blocklet/storage/restore/disk.js +104 -0
  57. package/lib/blocklet/storage/restore/logs.js +21 -0
  58. package/lib/blocklet/storage/restore/spaces.js +174 -0
  59. package/lib/blocklet/storage/utils/disk.js +178 -0
  60. package/lib/blocklet/storage/utils/hash.js +53 -0
  61. package/lib/blocklet/storage/utils/zip.js +43 -0
  62. package/lib/cert.js +221 -0
  63. package/lib/crons/check-new-version.js +68 -0
  64. package/lib/crons/monitor-disk-usage.js +46 -0
  65. package/lib/crons/rotate-pm2-logs/index.js +41 -0
  66. package/lib/crons/rotate-pm2-logs/script.js +56 -0
  67. package/lib/event/auto-backup-handler.js +48 -0
  68. package/lib/event/index.js +520 -0
  69. package/lib/index.js +768 -364
  70. package/lib/locales/ar.js +18 -0
  71. package/lib/locales/de.js +21 -0
  72. package/lib/locales/en.js +19 -0
  73. package/lib/locales/es.js +21 -0
  74. package/lib/locales/fr.js +21 -0
  75. package/lib/locales/hi.js +18 -0
  76. package/lib/locales/i18n.db +0 -0
  77. package/lib/locales/id.js +20 -0
  78. package/lib/locales/index.js +54 -0
  79. package/lib/locales/ja.js +19 -0
  80. package/lib/locales/ko.js +18 -0
  81. package/lib/locales/pt.js +20 -0
  82. package/lib/locales/ru.js +21 -0
  83. package/lib/locales/th.js +18 -0
  84. package/lib/locales/vi.js +18 -0
  85. package/lib/locales/zh-tw.js +17 -0
  86. package/lib/locales/zh.js +17 -0
  87. package/lib/migrations/1.0.21-update-config.js +34 -0
  88. package/lib/migrations/1.0.22-max-memory.js +40 -0
  89. package/lib/migrations/1.0.25.js +36 -0
  90. package/lib/migrations/1.0.32-update-config.js +30 -0
  91. package/lib/migrations/1.0.33-blocklets.js +33 -0
  92. package/lib/migrations/1.0.36-snapshot.js +10 -0
  93. package/lib/migrations/1.1.10-team.js +26 -0
  94. package/lib/migrations/1.1.9-snapshot.js +7 -0
  95. package/lib/migrations/1.16.11-component-status.js +22 -0
  96. package/lib/migrations/1.16.33-blocklet-security-rule.js +17 -0
  97. package/lib/migrations/1.16.6-chain-info.js +78 -0
  98. package/lib/migrations/1.16.8-component-title.js +66 -0
  99. package/lib/migrations/1.2.11-blocklet-registry.js +10 -0
  100. package/lib/migrations/1.2.2-blocklet-registry.js +10 -0
  101. package/lib/migrations/1.3.1-disk-alert-threshold.js +10 -0
  102. package/lib/migrations/1.4.5-access-key.js +18 -0
  103. package/lib/migrations/1.5.0-site.js +34 -0
  104. package/lib/migrations/1.5.15-site.js +184 -0
  105. package/lib/migrations/1.5.20-registry.js +15 -0
  106. package/lib/migrations/1.6.17-blocklet-children.js +48 -0
  107. package/lib/migrations/1.6.21-rename-ip-echo-domain.js +35 -0
  108. package/lib/migrations/1.6.4-security.js +59 -0
  109. package/lib/migrations/1.6.5-security.js +60 -0
  110. package/lib/migrations/1.6.9-update-node-info-and-certificate.js +39 -0
  111. package/lib/migrations/1.7.1-blocklet-setup.js +18 -0
  112. package/lib/migrations/1.7.12-blocklet-meta.js +51 -0
  113. package/lib/migrations/1.7.15-blocklet-bundle-source.js +42 -0
  114. package/lib/migrations/1.7.20-blocklet-component.js +41 -0
  115. package/lib/migrations/1.8.33-blocklet-mem-limit.js +20 -0
  116. package/lib/migrations/README.md +71 -0
  117. package/lib/migrations/index.js +215 -0
  118. package/lib/monitor/blocklet-runtime-monitor.js +204 -0
  119. package/lib/monitor/get-history-list.js +37 -0
  120. package/lib/monitor/node-monit-sender.js +99 -0
  121. package/lib/monitor/node-runtime-monitor.js +205 -0
  122. package/lib/processes/updater.js +186 -0
  123. package/lib/router/helper.js +1653 -0
  124. package/lib/router/index.js +341 -0
  125. package/lib/router/manager.js +806 -0
  126. package/lib/states/README.md +38 -0
  127. package/lib/states/access-key.js +124 -0
  128. package/lib/states/access-policy.js +29 -0
  129. package/lib/states/audit-log.js +734 -0
  130. package/lib/states/backup.js +165 -0
  131. package/lib/states/base.js +25 -0
  132. package/lib/states/blocklet-extras.js +257 -0
  133. package/lib/states/blocklet.js +755 -0
  134. package/lib/states/cache.js +23 -0
  135. package/lib/states/connect-account.js +8 -0
  136. package/lib/states/index.js +76 -0
  137. package/lib/states/job.js +8 -0
  138. package/lib/states/migration.js +34 -0
  139. package/lib/states/node.js +324 -0
  140. package/lib/states/notification.js +81 -0
  141. package/lib/states/passport.js +8 -0
  142. package/lib/states/project.js +119 -0
  143. package/lib/states/release.js +50 -0
  144. package/lib/states/response-header-policy.js +30 -0
  145. package/lib/states/routing-snapshot.js +146 -0
  146. package/lib/states/runtime-insight.js +25 -0
  147. package/lib/states/security-rule.js +30 -0
  148. package/lib/states/session.js +53 -0
  149. package/lib/states/site.js +102 -0
  150. package/lib/states/tag.js +8 -0
  151. package/lib/states/traffic-insight.js +25 -0
  152. package/lib/states/user-session.js +8 -0
  153. package/lib/states/user.js +717 -0
  154. package/lib/states/verify-code.js +152 -0
  155. package/lib/states/webhook.js +66 -0
  156. package/lib/team/manager.js +508 -0
  157. package/lib/util/blocklet.js +2182 -0
  158. package/lib/util/cache.js +63 -0
  159. package/lib/util/chain.js +29 -0
  160. package/lib/util/default-node-config.js +46 -0
  161. package/lib/util/docker/blocklet-custom-dockerfile.js +92 -0
  162. package/lib/util/docker/check-docker-has-image.js +23 -0
  163. package/lib/util/docker/check-docker-installed.js +32 -0
  164. package/lib/util/docker/check-docker-run-history.js +18 -0
  165. package/lib/util/docker/check-need-run-docker.js +32 -0
  166. package/lib/util/docker/create-docker-image.js +65 -0
  167. package/lib/util/docker/debian-dockerfile.js +50 -0
  168. package/lib/util/docker/docker-container-prune.js +75 -0
  169. package/lib/util/docker/docker-exec-chown.js +39 -0
  170. package/lib/util/docker/docker-exec.js +68 -0
  171. package/lib/util/docker/docker-remove-by-name.js +20 -0
  172. package/lib/util/docker/get-docker-runtime-info.js +39 -0
  173. package/lib/util/docker/parse-docker-name.js +10 -0
  174. package/lib/util/docker/parse-docker-options-from-pm2.js +295 -0
  175. package/lib/util/docker/shard-network.js +10 -0
  176. package/lib/util/domain-status.js +118 -0
  177. package/lib/util/get-accessible-external-node-ip.js +92 -0
  178. package/lib/util/get-dynamic-components.js +47 -0
  179. package/lib/util/get-meta-from-url.js +30 -0
  180. package/lib/util/get-migration-scripts.js +36 -0
  181. package/lib/util/get-safe-env.js +12 -0
  182. package/lib/util/index.js +522 -0
  183. package/lib/util/install-external-dependencies.js +67 -0
  184. package/lib/util/ip.js +53 -0
  185. package/lib/util/launcher.js +475 -0
  186. package/lib/util/log.js +431 -0
  187. package/lib/util/maintain.js +178 -0
  188. package/lib/util/promise-debounce.js +29 -0
  189. package/lib/util/promise-once.js +14 -0
  190. package/lib/util/promise-spawn.js +93 -0
  191. package/lib/util/queue.js +44 -0
  192. package/lib/util/ready.js +89 -0
  193. package/lib/util/request.js +10 -0
  194. package/lib/util/requirement.js +61 -0
  195. package/lib/util/reset-node.js +166 -0
  196. package/lib/util/rotator.js +194 -0
  197. package/lib/util/router.js +122 -0
  198. package/lib/util/rpc.js +78 -0
  199. package/lib/util/spaces.js +102 -0
  200. package/lib/util/store.js +184 -0
  201. package/lib/util/sysinfo.js +46 -0
  202. package/lib/util/ua.js +54 -0
  203. package/lib/validators/backup.js +34 -0
  204. package/lib/validators/blocklet-extra.js +18 -0
  205. package/lib/validators/node.js +73 -0
  206. package/lib/validators/permission.js +38 -0
  207. package/lib/validators/project.js +39 -0
  208. package/lib/validators/role.js +64 -0
  209. package/lib/validators/router.js +192 -0
  210. package/lib/validators/space-gateway.js +33 -0
  211. package/lib/validators/trusted-factory.js +28 -0
  212. package/lib/validators/trusted-passport.js +32 -0
  213. package/lib/validators/user.js +62 -0
  214. package/lib/validators/util.js +92 -0
  215. package/lib/validators/webhook.js +42 -0
  216. package/lib/webhook/index.js +216 -0
  217. package/lib/webhook/reduce-queue.js +12 -0
  218. package/lib/webhook/sender/api/index.js +67 -0
  219. package/lib/webhook/sender/base.js +11 -0
  220. package/lib/webhook/sender/index.js +44 -0
  221. package/lib/webhook/sender/slack/index.js +167 -0
  222. package/lib/webhook/sender/wallet/index.js +62 -0
  223. package/package.json +107 -34
  224. package/examples/BatchClient.js +0 -61
  225. package/examples/compressor/example.js +0 -7
  226. package/examples/jsonrpcserver/rpcmethod.js +0 -21
  227. package/examples/jsonrpcserver/rpcrequest.js +0 -20
  228. package/examples/jsonrpcserver/rpctest.js +0 -6
  229. package/examples/loader-pipes/test-mc.js +0 -52
  230. package/examples/loader-pipes/test.js +0 -51
  231. package/examples/mc-test.js +0 -44
  232. package/examples/redisdebug.js +0 -80
  233. package/lib/cache/CFMemcache.js +0 -57
  234. package/lib/cache/CacheLoader.js +0 -217
  235. package/lib/cache/Memcache.js +0 -406
  236. package/lib/class/Class.js +0 -54
  237. package/lib/client/MemcacheAdapter.js +0 -139
  238. package/lib/client/Memcached.js +0 -142
  239. package/lib/client/MemcachedSocket.js +0 -570
  240. package/lib/client/MySQLPool.js +0 -153
  241. package/lib/client/PGPool.js +0 -296
  242. package/lib/client/Redis.js +0 -787
  243. package/lib/client/S3.js +0 -103
  244. package/lib/client/S3Client.js +0 -392
  245. package/lib/client/pg/CursorQueryWorker.js +0 -160
  246. package/lib/client/rabbitmq/RbmqChannel.js +0 -61
  247. package/lib/client/rabbitmq/RbmqConfig.js +0 -144
  248. package/lib/client/rabbitmq/RbmqConnection.js +0 -259
  249. package/lib/client/rabbitmq/RbmqExchange.js +0 -112
  250. package/lib/client/rabbitmq/RbmqIncomingMessage.js +0 -53
  251. package/lib/client/rabbitmq/RbmqMessage.js +0 -120
  252. package/lib/client/rabbitmq/RbmqOutcomingMessage.js +0 -47
  253. package/lib/client/rabbitmq/RbmqQueue.js +0 -87
  254. package/lib/client/rabbitmq/index.js +0 -8
  255. package/lib/common/Assertions.js +0 -184
  256. package/lib/common/Merge.js +0 -32
  257. package/lib/common/Net.js +0 -56
  258. package/lib/common/Process.js +0 -20
  259. package/lib/common/Random.js +0 -53
  260. package/lib/common/Sort.js +0 -19
  261. package/lib/common/Types.js +0 -163
  262. package/lib/credentials/CredentialsProvider.js +0 -45
  263. package/lib/credentials/Manager.js +0 -101
  264. package/lib/crypto/Crypto.js +0 -66
  265. package/lib/data/BinaryData.js +0 -363
  266. package/lib/data/Compressor.js +0 -83
  267. package/lib/data/FormData.js +0 -144
  268. package/lib/data/Mime.js +0 -45
  269. package/lib/event/ErrorEvent.js +0 -71
  270. package/lib/event/Event.js +0 -20
  271. package/lib/event/EventDispatcher.js +0 -157
  272. package/lib/http/ConnectionPool.js +0 -82
  273. package/lib/http/ExpressServer.js +0 -19
  274. package/lib/http/Headers.js +0 -165
  275. package/lib/http/Loader.js +0 -584
  276. package/lib/http/Message.js +0 -189
  277. package/lib/http/Request.js +0 -848
  278. package/lib/http/RequestProcessor.js +0 -150
  279. package/lib/http/Response.js +0 -850
  280. package/lib/http/Server.js +0 -267
  281. package/lib/http/Socket.js +0 -157
  282. package/lib/http/Url.js +0 -2
  283. package/lib/jsonrpc/JsonRpcAbstract.js +0 -109
  284. package/lib/jsonrpc/JsonRpcBatchRequest.js +0 -54
  285. package/lib/jsonrpc/JsonRpcBatchResponse.js +0 -73
  286. package/lib/jsonrpc/JsonRpcError.js +0 -191
  287. package/lib/jsonrpc/JsonRpcMethod.js +0 -67
  288. package/lib/jsonrpc/JsonRpcRequest.js +0 -224
  289. package/lib/jsonrpc/JsonRpcRequestProcessor.js +0 -366
  290. package/lib/jsonrpc/JsonRpcResponse.js +0 -175
  291. package/lib/jsonrpc/JsonRpcServer.js +0 -81
  292. package/lib/logger/EmptyLogger.js +0 -15
  293. package/lib/logger/LoggerFactory.js +0 -20
  294. package/lib/logger/WildFireLogger.js +0 -267
  295. package/lib/pattern/Pool.js +0 -187
  296. package/lib/pattern/decorator/AbstractDecorator.js +0 -49
  297. package/lib/pattern/decorator/DecoratorChain.js +0 -285
  298. package/lib/util/DeviceDetector.js +0 -153
  299. package/lib/yaml/YAML.js +0 -46
  300. package/patterns.conf +0 -6
  301. package/tests/cache/CacheLoaderSpec.js +0 -7
  302. package/tests/class/ClassSpec.js +0 -106
  303. package/tests/client/MemcachedSocketSpec.js +0 -1228
  304. package/tests/client/MemcachedSpec.js +0 -77
  305. package/tests/client/MySQLPoolSpec.js +0 -231
  306. package/tests/client/PGPoolSpec.js +0 -479
  307. package/tests/client/RedisSpec.js +0 -471
  308. package/tests/client/S3ClientSpec.js +0 -26
  309. package/tests/client/S3Spec.js +0 -129
  310. package/tests/client/rabbitmq/RbmqConnectionSpec.js +0 -71
  311. package/tests/common/AssertionsSpec.js +0 -278
  312. package/tests/common/NetSpec.js +0 -6
  313. package/tests/common/RandomSpec.js +0 -35
  314. package/tests/common/TypesSpec.js +0 -7
  315. package/tests/credentials/CredentialsProviderSpec.js +0 -46
  316. package/tests/crypto/CryptoSpec.js +0 -33
  317. package/tests/data/BinaryDataSpec.js +0 -50
  318. package/tests/data/CompressorSpec.js +0 -7
  319. package/tests/data/FormDataSpec.js +0 -7
  320. package/tests/data/MimeSpec.js +0 -7
  321. package/tests/event/ErrorEventSpec.js +0 -20
  322. package/tests/event/EventDispatcherSpec.js +0 -319
  323. package/tests/event/EventSpec.js +0 -17
  324. package/tests/http/ConnectionPoolSpec.js +0 -7
  325. package/tests/http/HeadersSpec.js +0 -79
  326. package/tests/http/LoaderSpec.js +0 -43
  327. package/tests/http/MessageSpec.js +0 -251
  328. package/tests/http/RequestProcessorSpec.js +0 -124
  329. package/tests/http/RequestSpec.js +0 -651
  330. package/tests/http/ResponseSpec.js +0 -491
  331. package/tests/http/ServerSpec.js +0 -7
  332. package/tests/http/SocketSpec.js +0 -7
  333. package/tests/http/UrlSpec.js +0 -14
  334. package/tests/jsonrpc/JsonRpcAbstractSpec.js +0 -20
  335. package/tests/jsonrpc/JsonRpcBatchRequestSpec.js +0 -31
  336. package/tests/jsonrpc/JsonRpcBatchResponseSpec.js +0 -38
  337. package/tests/jsonrpc/JsonRpcErrorSpec.js +0 -58
  338. package/tests/jsonrpc/JsonRpcMethodSpec.js +0 -7
  339. package/tests/jsonrpc/JsonRpcRequestProcessorSpec.js +0 -271
  340. package/tests/jsonrpc/JsonRpcRequestSpec.js +0 -70
  341. package/tests/jsonrpc/JsonRpcResponseSpec.js +0 -63
  342. package/tests/jsonrpc/JsonRpcServerSpec.js +0 -42
  343. package/tests/pattern/PoolSpec.js +0 -180
  344. package/tests/pattern/decorator/AbstractDecoratorSpec.js +0 -7
  345. package/tests/pattern/decorator/DecoratorChainSpec.js +0 -7
  346. package/tests/yaml/YAMLSpec.js +0 -132
@@ -0,0 +1,23 @@
1
+ const BaseState = require('./base');
2
+
3
+ /**
4
+ * This db is used to save arbitrary cached data.
5
+ * @extends BaseState<import('@ohos-ports/models').CacheState>
6
+ */
7
+ class CacheState extends BaseState {
8
+ async set(key, value) {
9
+ const doc = await this.upsert({ key }, { value });
10
+ return doc.value;
11
+ }
12
+
13
+ async get(key) {
14
+ const doc = await this.findOne({ key });
15
+ return doc && doc.value;
16
+ }
17
+
18
+ delete(key) {
19
+ return this.remove({ key });
20
+ }
21
+ }
22
+
23
+ module.exports = CacheState;
@@ -0,0 +1,8 @@
1
+ const BaseState = require('./base');
2
+
3
+ /**
4
+ * @extends BaseState<import('@ohos-ports/models').ConnectedAccountState>
5
+ */
6
+ class ConnectedAccount extends BaseState {}
7
+
8
+ module.exports = ConnectedAccount;
@@ -0,0 +1,76 @@
1
+ const path = require('path');
2
+ const { createSequelize, createStateFactory, getServerModels, setupModels } = require('@ohos-ports/models');
3
+ const logger = require('@abtnode/logger')('@abtnode/core:states');
4
+
5
+ const NodeState = require('./node');
6
+ const BlockletState = require('./blocklet');
7
+ const NotificationState = require('./notification');
8
+ const SiteState = require('./site');
9
+ const AccessKeyState = require('./access-key');
10
+ const WebhookState = require('./webhook');
11
+ const MigrationState = require('./migration');
12
+ const SessionState = require('./session');
13
+ const ExtrasState = require('./blocklet-extras');
14
+ const CacheState = require('./cache');
15
+ const AuditLogState = require('./audit-log');
16
+ const JobState = require('./job');
17
+ const BackupState = require('./backup');
18
+ const TrafficInsightState = require('./traffic-insight');
19
+ const RuntimeInsightState = require('./runtime-insight');
20
+
21
+ const { getDbFilePath } = require('../util');
22
+
23
+ const models = getServerModels();
24
+
25
+ const init = (dataDirs, config = {}) => {
26
+ const dbPath = getDbFilePath(path.join(dataDirs.core, 'server.db'));
27
+ const sequelize = createSequelize(dbPath);
28
+ setupModels(models, sequelize);
29
+ logger.info(`Init server states in ${dbPath}`);
30
+
31
+ const notificationState = new NotificationState(models.Notification, config);
32
+ const nodeState = new NodeState(models.Server, config, dataDirs, notificationState);
33
+ const blockletState = new BlockletState(models.Blocklet, config);
34
+ const siteState = new SiteState(models.Site, config);
35
+ const accessKeyState = new AccessKeyState(models.AccessKey, config);
36
+ const webhookState = new WebhookState(models.WebHook, config);
37
+ const migrationState = new MigrationState(models.Migration, config);
38
+ const sessionState = new SessionState(models.Session, config);
39
+ const extrasState = new ExtrasState(models.BlockletExtra, config);
40
+ const cacheState = new CacheState(models.Cache, config);
41
+ const auditLogState = new AuditLogState(models.AuditLog, config);
42
+ const jobState = new JobState(models.Job, config);
43
+ const backupState = new BackupState(models.Backup, config);
44
+ const trafficInsight = new TrafficInsightState(models.TrafficInsight, config);
45
+ const runtimeInsight = new RuntimeInsightState(models.RuntimeInsight, { ...config, maxPageSize: 8640 });
46
+
47
+ return {
48
+ node: nodeState,
49
+ blocklet: blockletState,
50
+ notification: notificationState,
51
+ site: siteState,
52
+ accessKey: accessKeyState,
53
+ webhook: webhookState,
54
+ migration: migrationState,
55
+ session: sessionState,
56
+ blockletExtras: extrasState,
57
+ cache: cacheState,
58
+ auditLog: auditLogState,
59
+ job: jobState,
60
+ backup: backupState,
61
+ trafficInsight,
62
+ runtimeInsight,
63
+ };
64
+ };
65
+ /**
66
+ * @type {{
67
+ * backup: import('./backup'),
68
+ * blocklet: import('./blocklet'),
69
+ * blockletExtras: import('./blocklet-extras'),
70
+ * notification: import('./notification'),
71
+ * job: import('./job'),
72
+ * node: import('./node'),
73
+ * [key: string]: any
74
+ * }}
75
+ */
76
+ module.exports = createStateFactory(init, models);
@@ -0,0 +1,8 @@
1
+ const BaseState = require('./base');
2
+
3
+ /**
4
+ * @extends BaseState<import('@ohos-ports/models').JobState>
5
+ */
6
+ class Job extends BaseState {}
7
+
8
+ module.exports = Job;
@@ -0,0 +1,34 @@
1
+ // eslint-disable-next-line global-require
2
+ const logger = require('@abtnode/logger')('@abtnode/core:states:migration');
3
+
4
+ const BaseState = require('./base');
5
+
6
+ /**
7
+ * @extends BaseState<import('@ohos-ports/models').MigrationState>
8
+ */
9
+ class MigrationState extends BaseState {
10
+ // eslint-disable-next-line no-unused-vars
11
+ async isExecuted({ script, version }, context) {
12
+ try {
13
+ const item = await this.findOne({ script, version });
14
+ return !!item;
15
+ } catch (err) {
16
+ logger.error('failed to find migration', { script, version });
17
+ return false;
18
+ }
19
+ }
20
+
21
+ // eslint-disable-next-line no-unused-vars
22
+ async markExecuted({ script, version }, context) {
23
+ try {
24
+ const result = await this.insert({ script, version, executedAt: new Date() });
25
+ logger.info('mark executed', result);
26
+ return result;
27
+ } catch (error) {
28
+ logger.error('mark executed failed', { error, script, version });
29
+ return false;
30
+ }
31
+ }
32
+ }
33
+
34
+ module.exports = MigrationState;
@@ -0,0 +1,324 @@
1
+ /* eslint-disable no-underscore-dangle */
2
+ const semver = require('semver');
3
+ const omit = require('lodash/omit');
4
+ const isEmpty = require('lodash/isEmpty');
5
+ const security = require('@abtnode/util/lib/security');
6
+ const { isFromPublicKey } = require('@arcblock/did');
7
+ const {
8
+ NODE_MODES,
9
+ DISK_ALERT_THRESHOLD_PERCENT,
10
+ EVENTS,
11
+ SERVER_STATUS,
12
+ PROXY_MAX_MEM_LIMIT_IN_MB,
13
+ DEFAULT_NFT_DOMAIN_URL,
14
+ } = require('@abtnode/constant');
15
+ // const logger = require('@abtnode/logger')('@abtnode/core:states:node');
16
+
17
+ const BaseState = require('./base');
18
+ const { validateOwner } = require('../util');
19
+ const { get: getDefaultConfigs } = require('../util/default-node-config');
20
+ const { checkDockerInstalled } = require('../util/docker/check-docker-installed');
21
+
22
+ /**
23
+ * @extends BaseState<import('@ohos-ports/models').ServerState>
24
+ */
25
+ class NodeState extends BaseState {
26
+ /**
27
+ * Creates an instance of NodeState.
28
+ * @param {object} model
29
+ * @param {object} config
30
+ * @memberof NodeState
31
+ */
32
+ constructor(model, config = {}, dataDirs = {}, notification) {
33
+ super(model, config);
34
+
35
+ // Initialize the store
36
+ if (!config.nodeSk) {
37
+ throw new Error('Can not initialize node store without valid nodeSk');
38
+ }
39
+ if (!config.nodePk) {
40
+ throw new Error('Can not initialize node store without valid nodePk');
41
+ }
42
+ if (!config.nodeDid) {
43
+ throw new Error('Can not initialize node store without valid nodeDid');
44
+ }
45
+ if (!isFromPublicKey(config.nodeDid, config.nodePk)) {
46
+ throw new Error('Node pk and did does not match');
47
+ }
48
+
49
+ this.dataDirs = dataDirs;
50
+ this.notification = notification;
51
+ }
52
+
53
+ isInitialized(doc) {
54
+ const isOwnerConnected = !!doc.nodeOwner;
55
+ const isControlledBy3rdParty =
56
+ !doc.enablePassportIssuance && Array.isArray(doc.trustedPassports) && doc.trustedPassports.length > 0;
57
+ return isOwnerConnected || isControlledBy3rdParty;
58
+ }
59
+
60
+ /**
61
+ * Ensure we have an node record in the database
62
+ *
63
+ * @returns {Promise<import('@abtnode/client').NodeState>} Node document json
64
+ * @memberof NodeState
65
+ */
66
+ async read() {
67
+ const { nodeDid, dek } = this.config;
68
+
69
+ let doc = await this.findOne({ did: nodeDid });
70
+ if (doc) {
71
+ if (dek) {
72
+ doc.sk = security.decrypt(doc.sk, doc.did, dek);
73
+ }
74
+ doc.isDockerInstalled = await checkDockerInstalled();
75
+ return doc;
76
+ }
77
+
78
+ const {
79
+ name,
80
+ description,
81
+ nodeSk,
82
+ nodePk,
83
+ nodeOwner,
84
+ port,
85
+ version,
86
+ routing = { provider: 'default' },
87
+ docker,
88
+ mode,
89
+ runtimeConfig,
90
+ ownerNft,
91
+ launcher,
92
+ didRegistry,
93
+ didDomain,
94
+ slpDomain,
95
+ enablePassportIssuance = true,
96
+ trustedPassports = [],
97
+ webWalletUrl,
98
+ } = this.config;
99
+
100
+ if (nodeOwner && !validateOwner(nodeOwner)) {
101
+ throw new Error('Node owner is invalid');
102
+ }
103
+
104
+ const initialized = this.isInitialized({ nodeOwner, enablePassportIssuance, trustedPassports });
105
+ const defaultConfigs = await getDefaultConfigs();
106
+
107
+ doc = await this.insert({
108
+ ...(defaultConfigs || {}),
109
+ name,
110
+ description,
111
+ pk: nodePk,
112
+ sk: dek ? security.encrypt(nodeSk, nodeDid, dek) : nodeSk,
113
+ did: nodeDid,
114
+ initialized,
115
+ version,
116
+ nodeOwner: nodeOwner || null,
117
+ port,
118
+ initializedAt: initialized ? new Date() : null,
119
+ startedAt: null,
120
+ routing,
121
+ docker,
122
+ mode,
123
+ enableWelcomePage: mode !== NODE_MODES.SERVERLESS,
124
+ enableBetaRelease: false,
125
+ runtimeConfig,
126
+ ownerNft,
127
+ diskAlertThreshold: DISK_ALERT_THRESHOLD_PERCENT,
128
+ launcher: launcher || null,
129
+ didRegistry,
130
+ didDomain,
131
+ slpDomain,
132
+ enablePassportIssuance,
133
+ trustedPassports,
134
+ customBlockletNumber: 0,
135
+ webWalletUrl,
136
+ nftDomainUrl: DEFAULT_NFT_DOMAIN_URL,
137
+ });
138
+
139
+ if (dek) {
140
+ doc.sk = security.decrypt(doc.sk, doc.did, dek);
141
+ }
142
+ doc.isDockerInstalled = await checkDockerInstalled();
143
+
144
+ if (doc.runtimeConfig && !doc.runtimeConfig.proxyMaxMemoryLimit) {
145
+ doc.runtimeConfig.proxyMaxMemoryLimit = PROXY_MAX_MEM_LIMIT_IN_MB;
146
+ }
147
+
148
+ return doc;
149
+ }
150
+
151
+ // FIXME: 这个接口比较危险,可能会修改一些本不应该修改的字段,后续需要考虑改进
152
+ async updateNodeInfo(entity = {}) {
153
+ const old = await this.read();
154
+ const doc = await this.update({ $set: omit(entity, ['ownerNft', 'sk']) });
155
+ this.emit(EVENTS.NODE_UPDATED, doc, old);
156
+ return doc;
157
+ }
158
+
159
+ async updateNodeRouting(entity = {}) {
160
+ if (isEmpty(entity)) {
161
+ throw new Error('empty entity');
162
+ }
163
+
164
+ const nodeInfo = await this.updateNodeInfo({ routing: entity });
165
+ this.emit(EVENTS.ROUTING_UPDATED, nodeInfo);
166
+
167
+ return nodeInfo;
168
+ }
169
+
170
+ cleanupDirtyMaintainState() {
171
+ return this.read().then((doc) => {
172
+ if (doc.nextVersion && semver.lte(doc.nextVersion, doc.version)) {
173
+ const updates = { nextVersion: '', upgradeSessionId: '' };
174
+
175
+ // FIXME: this may cause the node exit some mode unexpectedly if it is not being upgraded
176
+ if (doc.previousMode) {
177
+ updates.mode = doc.previousMode;
178
+ updates.previousMode = '';
179
+ }
180
+
181
+ return this.update({ $set: updates });
182
+ }
183
+
184
+ return doc;
185
+ });
186
+ }
187
+
188
+ async addOwner(owner) {
189
+ const initialized = this.isInitialized({ nodeOwner: owner });
190
+ if (this.notification && typeof this.notification.setDefaultReceiver === 'function') {
191
+ this.notification.setDefaultReceiver(owner.did);
192
+ }
193
+
194
+ const updated = await this.update({
195
+ $set: { nodeOwner: owner, initialized, initializedAt: initialized ? new Date() : null },
196
+ });
197
+
198
+ this.emit(EVENTS.NODE_ADDED_OWNER, updated);
199
+
200
+ return updated;
201
+ }
202
+
203
+ async updateNodeOwner({ nodeOwner, ownerNft }) {
204
+ if (!validateOwner(nodeOwner)) {
205
+ throw new Error('Node owner is invalid');
206
+ }
207
+
208
+ const initialized = this.isInitialized({ nodeOwner });
209
+ if (this.notification && typeof this.notification.setDefaultReceiver === 'function') {
210
+ this.notification.setDefaultReceiver(nodeOwner.did);
211
+ }
212
+
213
+ const entities = { nodeOwner, initialized, initializedAt: initialized ? new Date() : null };
214
+ if (ownerNft) {
215
+ entities.ownerNft = ownerNft;
216
+ }
217
+
218
+ const updated = await this.update({ $set: entities });
219
+ this.emit(EVENTS.NODE_ADDED_OWNER, updated);
220
+ return updated;
221
+ }
222
+
223
+ async updateNftHolder(holder) {
224
+ if (!holder) {
225
+ throw new Error('NFT holder can not be empty');
226
+ }
227
+
228
+ const { ownerNft } = await this.read();
229
+ if (isEmpty(ownerNft)) {
230
+ throw new Error('ownerNft is empty');
231
+ }
232
+
233
+ ownerNft.holder = holder;
234
+
235
+ return this.update({ $set: { ownerNft } });
236
+ }
237
+
238
+ async enterMode(mode) {
239
+ if (Object.values(NODE_MODES).includes(mode) === false) {
240
+ throw new Error(`Can not enter unsupported mode: ${mode}`);
241
+ }
242
+
243
+ const info = await this.read();
244
+ if (info.mode === mode) {
245
+ return info;
246
+ }
247
+
248
+ return this.updateNodeInfo({ previousMode: info.mode, mode });
249
+ }
250
+
251
+ async exitMode(mode) {
252
+ if (Object.values(NODE_MODES).includes(mode) === false) {
253
+ throw new Error(`Can not exit unsupported mode: ${mode}`);
254
+ }
255
+
256
+ const info = await this.read();
257
+ if (!info.previousMode) {
258
+ throw new Error(`Can not exit ${mode} mode when previousMode is not set`);
259
+ }
260
+
261
+ if (info.mode !== mode) {
262
+ throw new Error(`Can not exit ${mode} mode because in ${info.mode} mode`);
263
+ }
264
+
265
+ return this.updateNodeInfo({ previousMode: '', mode: info.previousMode });
266
+ }
267
+
268
+ // eslint-disable-next-line require-await
269
+ async setMode(mode) {
270
+ if (Object.values(NODE_MODES).includes(mode) === false) {
271
+ throw new Error(`Can not update server to unsupported mode: ${mode}`);
272
+ }
273
+
274
+ return this.updateNodeInfo({ previousMode: '', mode });
275
+ }
276
+
277
+ getEnvironments() {
278
+ return this.read().then((info) => ({
279
+ ABT_NODE: info.version,
280
+ ABT_NODE_VERSION: info.version,
281
+ ABT_NODE_DID: info.did,
282
+ ABT_NODE_SK: info.sk,
283
+ ABT_NODE_PK: info.pk,
284
+ ABT_NODE_PORT: info.port,
285
+ ABT_NODE_SERVICE_PORT: process.env.ABT_NODE_SERVICE_PORT,
286
+ ABT_NODE_MODE: info.mode,
287
+ }));
288
+ }
289
+
290
+ async updateGateway(gateway) {
291
+ const { routing } = await this.read();
292
+ routing.requestLimit = gateway.requestLimit;
293
+ routing.cacheEnabled = gateway.cacheEnabled;
294
+
295
+ const doc = await this.update({
296
+ $set: { routing },
297
+ });
298
+
299
+ this.emit(EVENTS.RELOAD_GATEWAY, doc);
300
+ return doc.routing;
301
+ }
302
+
303
+ // eslint-disable-next-line require-await
304
+ async updateStatus(status) {
305
+ if (!Object.values(SERVER_STATUS).includes(status)) {
306
+ throw new Error('status is invalid');
307
+ }
308
+
309
+ return this.update({ $set: { status } });
310
+ }
311
+
312
+ // eslint-disable-next-line require-await
313
+ async resetStatus() {
314
+ return this.updateStatus(SERVER_STATUS.RUNNING);
315
+ }
316
+
317
+ async update(updates) {
318
+ await this.read(); // CAUTION: 这一行不要删,当 node state 不存在时,read() 会插入新数据
319
+ const [, [updated]] = await super.update({ did: this.config.nodeDid }, updates);
320
+ return updated;
321
+ }
322
+ }
323
+
324
+ module.exports = NodeState;
@@ -0,0 +1,81 @@
1
+ const logger = require('@abtnode/logger')('@abtnode/core:states:notification');
2
+ const { EVENTS } = require('@abtnode/constant');
3
+
4
+ const BaseState = require('./base');
5
+
6
+ /**
7
+ * @extends BaseState<import('@ohos-ports/models').NotificationState>
8
+ */
9
+ class NotificationState extends BaseState {
10
+ constructor(baseDir, config = {}) {
11
+ super(baseDir, { filename: 'notification.db', ...config });
12
+
13
+ this.defaultSender = config.defaultSender || '';
14
+ this.defaultReceiver = config.defaultReceiver || '';
15
+ }
16
+
17
+ setDefaultSender(sender) {
18
+ this.defaultSender = sender;
19
+ }
20
+
21
+ setDefaultReceiver(receiver) {
22
+ this.defaultReceiver = receiver;
23
+ }
24
+
25
+ async create(payload) {
26
+ ['description'].forEach((x) => {
27
+ if (!payload[x]) {
28
+ throw new Error(`Invalid notification payload: ${x} is required`);
29
+ }
30
+ });
31
+
32
+ const doc = await this.insert({
33
+ sender: payload.sender || this.defaultSender,
34
+ receiver: payload.receiver || this.defaultReceiver,
35
+ title: payload.title,
36
+ description: payload.description,
37
+ action: payload.action || '',
38
+ entityType: payload.entityType || '',
39
+ entityId: payload.entityId || '',
40
+ severity: payload.severity || 'info',
41
+ read: false,
42
+ });
43
+
44
+ if (!payload.teamDid) {
45
+ this.emit(EVENTS.NOTIFICATION_CREATE, {
46
+ ...payload,
47
+ ...doc,
48
+ });
49
+ }
50
+
51
+ return doc;
52
+ }
53
+
54
+ findPaginated({ read, paging, teamDid } = {}) {
55
+ const conditions = {};
56
+ if (typeof read === 'boolean') {
57
+ conditions.read = read;
58
+ }
59
+ if (teamDid) {
60
+ conditions.entityId = teamDid;
61
+ }
62
+ return this.paginate(conditions, { createdAt: -1 }, { ...paging, pageSize: 10 });
63
+ }
64
+
65
+ // eslint-disable-next-line no-unused-vars
66
+ async read({ id }, context) {
67
+ const idList = id.split(',').map((x) => x.trim());
68
+ logger.info('mark notification as read', { idList });
69
+ const [numAffected] = await this.update({ id: { $in: idList } }, { $set: { read: true } });
70
+ return numAffected;
71
+ }
72
+
73
+ // eslint-disable-next-line no-unused-vars
74
+ async unread({ id }, context) {
75
+ const idList = Array.isArray(id) ? id : [id];
76
+ const [numAffected] = await this.update({ id: { $in: idList } }, { $set: { read: false } });
77
+ return numAffected;
78
+ }
79
+ }
80
+
81
+ module.exports = NotificationState;
@@ -0,0 +1,8 @@
1
+ const BaseState = require('./base');
2
+
3
+ /**
4
+ * @extends BaseState<import('@ohos-ports/models').PassportState>
5
+ */
6
+ class Passport extends BaseState {}
7
+
8
+ module.exports = Passport;
@@ -0,0 +1,119 @@
1
+ const pickBy = require('lodash/pickBy');
2
+ const pick = require('lodash/pick');
3
+ const BaseState = require('./base');
4
+
5
+ const isUndefinedOrNull = (x) => x === undefined || x === null;
6
+
7
+ /**
8
+ * @extends BaseState<import('@ohos-ports/models').ProjectState>
9
+ */
10
+ class Project extends BaseState {
11
+ createProject({
12
+ type,
13
+ blockletDid,
14
+ blockletTitle,
15
+ componentDid,
16
+ tenantScope,
17
+ connectedStores,
18
+ createdBy,
19
+ messageId,
20
+ }) {
21
+ const doc = { id: blockletDid, type, blockletDid, blockletTitle, createdBy };
22
+ if (componentDid) {
23
+ doc.componentDid = componentDid;
24
+ }
25
+ if (tenantScope) {
26
+ doc.tenantScope = tenantScope;
27
+ }
28
+ if (connectedStores) {
29
+ doc.connectedStores = connectedStores;
30
+ }
31
+ if (messageId) {
32
+ if (messageId.length < 20) {
33
+ throw new Error('Invalid messageId');
34
+ }
35
+ doc.messageId = messageId;
36
+ }
37
+ return this.insert(doc);
38
+ }
39
+
40
+ async getProjects({ componentDid, tenantScope, showAccessToken, createdBy }) {
41
+ const query = {};
42
+ if (componentDid) {
43
+ query.componentDid = componentDid;
44
+ }
45
+ if (tenantScope) {
46
+ query.tenantScope = tenantScope;
47
+ }
48
+ if (createdBy) {
49
+ query.createdBy = createdBy;
50
+ }
51
+ const projects = await this.find(
52
+ query,
53
+ {},
54
+ {
55
+ createdAt: -1,
56
+ }
57
+ );
58
+ if (!showAccessToken) {
59
+ projects?.forEach((project) => {
60
+ project.connectedStores?.forEach((store) => {
61
+ store.accessToken = store.accessToken ? '__encrypted__' : '';
62
+ });
63
+ });
64
+ }
65
+ return projects;
66
+ }
67
+
68
+ async updateProject(id, params) {
69
+ const _params = pickBy(
70
+ pick(params, [
71
+ 'name',
72
+ 'blockletLogo',
73
+ 'blockletVersion',
74
+ 'blockletIntroduction',
75
+ 'blockletTitle',
76
+ 'blockletDescription',
77
+ 'blockletDid',
78
+ 'blockletScreenshots',
79
+ 'lastReleaseId',
80
+ 'lastReleaseFiles',
81
+ 'connectedStores',
82
+ 'autoUpload',
83
+ 'possibleSameStore',
84
+ ]),
85
+ (x) => !isUndefinedOrNull(x)
86
+ );
87
+ _params.type = params.blockletComponents?.length ? 'pack' : 'resource';
88
+ const [, [updated]] = await this.update({ id }, { $set: _params });
89
+ return updated;
90
+ }
91
+
92
+ async deleteConnectedStore({ projectId, storeId, createdBy }) {
93
+ const project = await this.findOne({ id: projectId });
94
+ if (!project) {
95
+ throw new Error('Project not found');
96
+ }
97
+ const index = (project.connectedStores || []).findIndex(
98
+ (x) => x.storeId === storeId && (createdBy ? x.createdBy === createdBy : true)
99
+ );
100
+ if (index === -1) {
101
+ return null;
102
+ }
103
+ project.connectedStores.splice(index, 1);
104
+ const [, [updated]] = await this.update({ id: projectId }, { $set: { connectedStores: project.connectedStores } });
105
+
106
+ return updated;
107
+ }
108
+
109
+ async getConnectedStore(id, storeId) {
110
+ const project = await this.findOne({ id });
111
+ if (!project) {
112
+ throw new Error('Project not found');
113
+ }
114
+
115
+ return project.connectedStores?.find((x) => x.storeId === storeId);
116
+ }
117
+ }
118
+
119
+ module.exports = Project;