@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,345 @@
1
+ /**
2
+ * @typedef {{
3
+ * appDid: string
4
+ * appPid: string,
5
+ * event: import('events').EventEmitter,
6
+ * userDid: string,
7
+ * referrer: string,
8
+ * locale: 'zh' | 'en',
9
+ * backup: import('@ohos-ports/models').BackupState,
10
+ * }} SpaceBackupInput
11
+ *
12
+ * @typedef {{
13
+ * signer: import('@ocap/wallet').WalletObject
14
+ * encrypt: (v: string) => string,
15
+ * decrypt: (v: string) => string,
16
+ * delegation: string,
17
+ * }} SecurityContext
18
+ */
19
+
20
+ const path = require('path');
21
+ const { isValid } = require('@arcblock/did');
22
+ const { BLOCKLET_CONFIGURABLE_KEY, BlockletEvents } = require('@blocklet/constant');
23
+ const { SpaceClient, IncrementalBackupBlockletCommand } = require('@blocklet/did-space-js');
24
+ const { ensureDirSync, existsSync, remove } = require('fs-extra');
25
+ const isEmpty = require('lodash/isEmpty');
26
+ const { join, basename } = require('path');
27
+ const { getAppName, getAppDescription } = require('@blocklet/meta/lib/util');
28
+ const logger = require('@abtnode/logger')('@abtnode/core:storage:backup');
29
+ const { default: axios } = require('axios');
30
+ const xbytes = require('xbytes');
31
+
32
+ const states = require('../../../states');
33
+ const { BaseBackup } = require('./base');
34
+ const { BlockletBackup } = require('./blocklet');
35
+ const { BlockletExtrasBackup } = require('./blocklet-extras');
36
+ const { BlockletsBackup } = require('./blocklets');
37
+ const { DataBackup } = require('./data');
38
+ const { RoutingRuleBackup } = require('./routing-rule');
39
+ const { translate } = require('../../../locales');
40
+ const { getFolderSize, formatMemoryUsage } = require('../utils/disk');
41
+ const { dockerExecChown } = require('../../../util/docker/docker-exec-chown');
42
+ const checkDockerRunHistory = require('../../../util/docker/check-docker-run-history');
43
+
44
+ /**
45
+ * @param {{ appDid: string, appPid: string }} params
46
+ * @returns {{ appDid: string, meta: { did: string } }}
47
+ */
48
+ const getAppId = (params) => ({ appDid: params.appDid, meta: { did: params.appPid } });
49
+
50
+ class SpacesBackup extends BaseBackup {
51
+ /**
52
+ *
53
+ * @type {SpaceBackupInput}
54
+ * @memberof SpacesBackup
55
+ */
56
+ input;
57
+
58
+ /**
59
+ * @description blocklet state 对象
60
+ * @type {import('@abtnode/client').BlockletState}
61
+ * @memberof SpacesBackup
62
+ */
63
+ blocklet;
64
+
65
+ /**
66
+ * @description 当前 blocklet 的数据目录
67
+ * @type {string}
68
+ * @memberof SpacesBackup
69
+ */
70
+ backupDir;
71
+
72
+ /**
73
+ *
74
+ * @description server 的数据目录
75
+ * @type {string}
76
+ * @memberof SpacesBackup
77
+ */
78
+ serverDir;
79
+
80
+ /**
81
+ *
82
+ * @description spaces 的 endpoint
83
+ * @type {string}
84
+ * @memberof SpacesBackup
85
+ */
86
+ spaceBackupEndpoint;
87
+
88
+ /**
89
+ *
90
+ * @description spaces 安全相关的上下文
91
+ * @type SecurityContext
92
+ * @memberof SpacesBackup
93
+ */
94
+ securityContext;
95
+
96
+ storages;
97
+
98
+ dataBackup;
99
+
100
+ /**
101
+ * @type {import('@did-space/core').Object[]}
102
+ * @description
103
+ * @memberof SpacesBackup
104
+ */
105
+ syncObjects;
106
+
107
+ /**
108
+ *
109
+ * @param {SpaceBackupInput} input
110
+ * @memberof SpacesBackup
111
+ */
112
+ constructor(input) {
113
+ super(input);
114
+ this.verify(input);
115
+ this.input = input;
116
+ this.storages = [
117
+ // @note: 我们不应该备份从 server 里面搜索出 audit log 文件,然后备份它。如果 audit log 文件过大,这会导致内存暴涨。 related: https://github.com/ArcBlock/blocklet-server/issues/9837#issuecomment-2370427184
118
+ new BlockletBackup(this.input),
119
+ new BlockletsBackup(this.input),
120
+ new BlockletExtrasBackup(this.input),
121
+ new RoutingRuleBackup(this.input),
122
+ ];
123
+ this.dataBackup = new DataBackup(this.input);
124
+ }
125
+
126
+ /**
127
+ * @param {SpaceBackupInput} input
128
+ * @returns {void}
129
+ * @memberof SpacesBackup
130
+ */
131
+ verify(input) {
132
+ if (isEmpty(input?.appDid) || !isValid(input?.appDid)) {
133
+ throw new Error(`input.appDid(${input?.appDid}) is not a valid did`);
134
+ }
135
+ }
136
+
137
+ /**
138
+ *
139
+ * @returns {Promise<void>}
140
+ * @memberof SpacesBackup
141
+ */
142
+ async backup() {
143
+ try {
144
+ const nodeInfo = await states.node.read();
145
+ if (checkDockerRunHistory(nodeInfo)) {
146
+ await dockerExecChown(`${this.input.appPid}-backup`, [
147
+ path.join(process.env.ABT_NODE_DATA_DIR, 'data', this.input.appPid),
148
+ ]);
149
+ }
150
+ // debug for remote
151
+ logger.info(this.input.appPid, 'initialize.before', formatMemoryUsage());
152
+ await this.initialize();
153
+ logger.info(this.input.appPid, 'initialize.after', formatMemoryUsage());
154
+
155
+ logger.info(this.input.appPid, 'export.before', formatMemoryUsage());
156
+ await this.export();
157
+ logger.info(this.input.appPid, 'export.after', formatMemoryUsage());
158
+
159
+ logger.info(this.input.appPid, 'verifySpace.before', formatMemoryUsage());
160
+ await this.verifySpace();
161
+ logger.info(this.input.appPid, 'verifySpace.after', formatMemoryUsage());
162
+
163
+ logger.info(this.input.appPid, 'syncToSpaces.before', formatMemoryUsage());
164
+ await this.syncToSpaces();
165
+ logger.info(this.input.appPid, 'syncToSpaces.after', formatMemoryUsage());
166
+ } catch (error) {
167
+ console.error(error);
168
+ throw error;
169
+ } finally {
170
+ await this.destroy();
171
+ }
172
+ }
173
+
174
+ async initialize() {
175
+ this.blocklet = await states.blocklet.getBlocklet(this.input.appDid);
176
+ if (isEmpty(this.blocklet)) {
177
+ throw new Error('blocklet cannot be empty');
178
+ }
179
+
180
+ this.serverDir = process.env.ABT_NODE_DATA_DIR;
181
+ this.backupDir = join(this.serverDir, 'tmp/backup', this.blocklet.appDid);
182
+ ensureDirSync(this.backupDir);
183
+
184
+ this.spaceBackupEndpoint = this.blocklet.environments.find(
185
+ (e) => e.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_BACKUP_ENDPOINT
186
+ )?.value;
187
+ if (isEmpty(this.spaceBackupEndpoint)) {
188
+ throw new Error('spaceEndpoint cannot be empty');
189
+ }
190
+
191
+ this.securityContext = await this._getSecurityContext(states);
192
+ }
193
+
194
+ async export() {
195
+ this.input.event.emit(BlockletEvents.backupProgress, {
196
+ ...getAppId(this.input),
197
+ message: 'Preparing data for backup...',
198
+ progress: 15,
199
+ completed: false,
200
+ });
201
+ await states.backup.progress(this.input.backup.id, {
202
+ message: 'Preparing data for backup...',
203
+ progress: 15,
204
+ });
205
+
206
+ this.syncObjects = await this.collectSyncObjects(this.dataBackup, this.storages);
207
+
208
+ this.input.event.emit(BlockletEvents.backupProgress, {
209
+ ...getAppId(this.input),
210
+ message: 'Data ready, start backup...',
211
+ progress: 20,
212
+ completed: false,
213
+ });
214
+ await states.backup.progress(this.input.backup.id, {
215
+ message: 'Data ready, start backup...',
216
+ progress: 20,
217
+ });
218
+ }
219
+
220
+ /**
221
+ * @description 验证 Space 的空间是否足够备份所需
222
+ * @memberof SpacesBackup
223
+ */
224
+ async verifySpace() {
225
+ const { headers } = await axios.head(`${this.spaceBackupEndpoint}?withExtras=true`, {
226
+ // @FIXME: 等到 space 的存储优化专项完成后,这里可以给出更小的超时时间
227
+ timeout: 1000 * 120,
228
+ headers: {
229
+ 'x-locale': this.input.locale,
230
+ },
231
+ });
232
+
233
+ const [spaceIsFull, spaceFreeCapacity, spaceIsAvailable, errorMessage] = [
234
+ headers['x-space-is-full'] === 'true',
235
+ +headers['x-space-free-capacity'],
236
+ headers['x-space-is-available'] === 'true',
237
+ headers['x-error-message'],
238
+ ];
239
+ const backupFolderSize = getFolderSize(this.backupDir);
240
+
241
+ logger.info('verifySpace', {
242
+ spaceIsAvailable,
243
+ spaceIsFull,
244
+ spaceFreeCapacity: xbytes(spaceFreeCapacity),
245
+ backupFolderSize: xbytes(backupFolderSize),
246
+ backupDir: this.backupDir,
247
+ });
248
+
249
+ if (spaceIsFull) {
250
+ throw new Error(translate(this.input.locale, 'backup.space.isFull'));
251
+ }
252
+
253
+ if (spaceFreeCapacity <= backupFolderSize) {
254
+ throw new Error(translate(this.input.locale, 'backup.space.lackOfSpace'));
255
+ }
256
+
257
+ if (spaceIsAvailable === false) {
258
+ const autoBackup = await this.input.event.getAutoBackup({ did: this.input.appDid });
259
+ if (autoBackup.enabled) {
260
+ await this.input.event.updateAutoBackup(
261
+ { did: this.input.appDid, autoBackup: { enabled: false } },
262
+ {
263
+ referrer: this.input.referrer,
264
+ user: { did: this.input.userDid, locale: this.input.locale },
265
+ }
266
+ );
267
+ }
268
+ throw new Error(decodeURIComponent(errorMessage));
269
+ }
270
+ }
271
+
272
+ async syncToSpaces() {
273
+ /**
274
+ * @type {import('@abtnode/client').NodeState}
275
+ */
276
+ const node = await states.node.read();
277
+ const serverDid = node.did;
278
+
279
+ const spaceClient = new SpaceClient({
280
+ endpoint: this.spaceBackupEndpoint,
281
+ wallet: this.securityContext.signer,
282
+ delegation: this.securityContext.delegation,
283
+ });
284
+
285
+ const { statusCode, statusMessage } = await spaceClient.send(
286
+ new IncrementalBackupBlockletCommand({
287
+ appDid: this.blocklet.appDid,
288
+ appName: getAppName(this.blocklet),
289
+ appDescription: getAppDescription(this.blocklet),
290
+ userDid: this.input.userDid,
291
+ referrer: this.input.referrer,
292
+ serverDid,
293
+ signerDid: this.securityContext.signer.address,
294
+
295
+ source: this.syncObjects,
296
+ debug: true,
297
+ concurrency: 2,
298
+ retryCount: 10,
299
+ filter: (object) => {
300
+ // FIXME: @yejianchao 这里需要更完整的黑名单,这一层应该内置于 @blocklet/did-space-js
301
+ return object.name !== '.DS_Store';
302
+ },
303
+ onAfterUpload: async (data) => {
304
+ // @note: 当备份失败时 && 偶然会存在一些其他的备份请求后来发送成功了,此时会造成备份进度紊乱(明明失败了,错误信息显示上传某个文件成功了)的情况,所以失败的备份不需要再发送事件了
305
+ const currentBackup = await states.backup.findOne({ id: this.input.backup.id });
306
+ if (currentBackup.status === 1) {
307
+ return;
308
+ }
309
+
310
+ logger.info('backup progress', { appDid: this.input.appDid, data });
311
+ const percent = (data.completed * 100) / data.total;
312
+ // 0.8 是因为上传文件到 spaces 占进度的 80%,+ 20 是因为需要累加之前的进度
313
+ const progress = +Math.floor(percent * 0.8).toFixed(2) + 20;
314
+ const progressMessage = `(${data.completed}/${data.total}) Uploading file ${basename(data.key)}`;
315
+
316
+ await states.backup.progress(this.input.backup.id, {
317
+ progress,
318
+ message: progressMessage,
319
+ });
320
+ this.input.event.emit(BlockletEvents.backupProgress, {
321
+ ...getAppId(this.input),
322
+ message: progressMessage,
323
+ // 0.8 是因为上传文件到 spaces 占进度的 80%,+ 20 是因为需要累加之前的进度
324
+ progress,
325
+ completed: false,
326
+ });
327
+ },
328
+ })
329
+ );
330
+
331
+ if (statusCode !== 200) {
332
+ throw new Error(statusMessage);
333
+ }
334
+ }
335
+
336
+ async destroy() {
337
+ if (existsSync(this.backupDir)) {
338
+ await remove(this.backupDir);
339
+ }
340
+ }
341
+ }
342
+
343
+ module.exports = {
344
+ SpacesBackup,
345
+ };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @typedef {{
3
+ * appDid: string; // --> appDid
4
+ * password: Buffer; // derived from (appSk, appDid)
5
+ * event: import('events').EventEmitter,
6
+ * }} BaseRestoreInput
7
+ */
8
+
9
+ class BaseRestore {
10
+ /**
11
+ *
12
+ * @type {BaseRestoreInput}
13
+ * @memberof BaseRestore
14
+ */
15
+ input;
16
+
17
+ /**
18
+ * @type {string}
19
+ * @memberof BaseRestore
20
+ */
21
+ restoreDir;
22
+
23
+ /**
24
+ *
25
+ * @description server 的数据目录
26
+ * @type {string}
27
+ * @memberof BaseRestore
28
+ */
29
+ serverDir;
30
+
31
+ constructor(input) {
32
+ this.input = input;
33
+ }
34
+
35
+ /**
36
+ *
37
+ *
38
+ * @param {BaseRestore} restore
39
+ * @memberof BaseRestore
40
+ */
41
+ ensureParams(restore) {
42
+ this.restoreDir = restore.restoreDir;
43
+ this.serverDir = restore.serverDir;
44
+ }
45
+
46
+ // eslint-disable-next-line
47
+ async import(params) {
48
+ throw new Error('not implemented');
49
+ }
50
+
51
+ /**
52
+ * Generate params for BlockletManager to install
53
+ *
54
+ * @return {object}
55
+ * @memberof BaseRestore
56
+ */
57
+ getInstallParams() {
58
+ return {};
59
+ }
60
+
61
+ /**
62
+ * Generate params for other restorers
63
+ *
64
+ * @return {object}
65
+ * @memberof BaseRestore
66
+ */
67
+ getImportParams() {
68
+ return {};
69
+ }
70
+ }
71
+
72
+ module.exports = {
73
+ BaseRestore,
74
+ };
@@ -0,0 +1,89 @@
1
+ const { removeSync, outputJsonSync, readJSONSync } = require('fs-extra');
2
+ const isEmpty = require('lodash/isEmpty');
3
+ const cloneDeep = require('lodash/cloneDeep');
4
+ const { join } = require('path');
5
+ const security = require('@abtnode/util/lib/security');
6
+ const { BLOCKLET_CONFIGURABLE_KEY } = require('@blocklet/constant');
7
+ const { BaseRestore } = require('./base');
8
+
9
+ class BlockletExtrasRestore extends BaseRestore {
10
+ filename = 'blocklet-extras.json';
11
+
12
+ import(params) {
13
+ const extras = this.cleanExtras(this.getExtras(), params);
14
+ removeSync(join(this.restoreDir, this.filename));
15
+ outputJsonSync(join(this.restoreDir, this.filename), extras);
16
+ }
17
+
18
+ /**
19
+ *
20
+ * @description
21
+ * @return {import('@abtnode/client').BlockletState}
22
+ * @memberof BlockletExtrasRestore
23
+ */
24
+ getExtras() {
25
+ /**
26
+ * @type {import('@abtnode/client').BlockletState}
27
+ */
28
+ return readJSONSync(join(this.restoreDir, this.filename));
29
+ }
30
+
31
+ /**
32
+ *
33
+ * @description 清理数据并加密
34
+ * @param {import('@abtnode/client').BlockletState} raw
35
+ * @returns {import('@abtnode/client').BlockletState}
36
+ * @memberof BlockletExtrasRestore
37
+ */
38
+ cleanExtras(raw, params) {
39
+ const blockletExtra = cloneDeep(raw);
40
+
41
+ const queue = [blockletExtra];
42
+ while (queue.length) {
43
+ const current = queue.pop();
44
+
45
+ // 加解密
46
+ this.decryptConfigs(current.configs, params);
47
+
48
+ if (current?.children) {
49
+ queue.push(...current.children);
50
+ }
51
+ }
52
+
53
+ return blockletExtra;
54
+ }
55
+
56
+ /**
57
+ *
58
+ * @description 解密加密的数据
59
+ * @param {import('@abtnode/client').ConfigEntry[]} configs
60
+ * @param {object} params
61
+ * @return {void}
62
+ * @memberof BlockletExtrasRestore
63
+ */
64
+ decryptConfigs(configs, params) {
65
+ if (isEmpty(configs)) {
66
+ return;
67
+ }
68
+
69
+ const { password } = this.input;
70
+ for (const config of configs) {
71
+ if (config.secure) {
72
+ config.value = security.decrypt(config.value, params.salt, password);
73
+ }
74
+ }
75
+
76
+ const skConfig = configs.find((x) => x.key === BLOCKLET_CONFIGURABLE_KEY.BLOCKLET_APP_SK);
77
+ if (skConfig) {
78
+ this.appSk = skConfig.value;
79
+ }
80
+ }
81
+
82
+ getInstallParams() {
83
+ return {
84
+ appSk: this.appSk,
85
+ };
86
+ }
87
+ }
88
+
89
+ module.exports = { BlockletExtrasRestore };
@@ -0,0 +1,56 @@
1
+ const { removeSync, outputJsonSync, readJSONSync } = require('fs-extra');
2
+ const { join } = require('path');
3
+ const { APP_STRUCT_VERSION } = require('@abtnode/constant');
4
+ const security = require('@abtnode/util/lib/security');
5
+
6
+ const { BaseRestore } = require('./base');
7
+
8
+ class BlockletRestore extends BaseRestore {
9
+ filename = 'blocklet.json';
10
+
11
+ import(params) {
12
+ const blocklet = this.decrypt(this.getBlocklet(), params);
13
+ removeSync(join(this.restoreDir, this.filename));
14
+ outputJsonSync(join(this.restoreDir, this.filename), blocklet);
15
+ }
16
+
17
+ /**
18
+ *
19
+ * @description
20
+ * @return {import('@abtnode/client').BlockletState}
21
+ * @memberof BlockletRestore
22
+ */
23
+ getBlocklet() {
24
+ return readJSONSync(join(this.restoreDir, this.filename));
25
+ }
26
+
27
+ /**
28
+ *
29
+ * @description 解密加密的数据
30
+ * @param {import('@abtnode/client').BlockletState} blocklet
31
+ * @return {import('@abtnode/client').BlockletState}
32
+ * @memberof BlockletRestore
33
+ */
34
+ decrypt(blocklet, params) {
35
+ const { password } = this.input;
36
+ if (Array.isArray(blocklet?.migratedFrom)) {
37
+ blocklet.migratedFrom = blocklet.migratedFrom.map((x) => {
38
+ x.appSk = security.decrypt(x.appSk, params.salt, password);
39
+ return x;
40
+ });
41
+ }
42
+
43
+ return blocklet;
44
+ }
45
+
46
+ getImportParams() {
47
+ const blocklet = this.getBlocklet();
48
+ if (blocklet.structVersion !== APP_STRUCT_VERSION) {
49
+ throw new Error('Only new version backup can be restored to this server');
50
+ }
51
+
52
+ return { salt: blocklet.appDid };
53
+ }
54
+ }
55
+
56
+ module.exports = { BlockletRestore };
@@ -0,0 +1,43 @@
1
+ const { existsSync, remove, ensureDirSync } = require('fs-extra');
2
+ const { join } = require('path');
3
+ const fg = require('fast-glob');
4
+ const { BaseRestore } = require('./base');
5
+ const { zipToDir } = require('../utils/zip');
6
+
7
+ class BlockletsRestore extends BaseRestore {
8
+ filename = 'blocklets';
9
+
10
+ async import() {
11
+ const blockletsDir = join(this.restoreDir, this.filename);
12
+
13
+ if (!existsSync(blockletsDir)) {
14
+ ensureDirSync(blockletsDir);
15
+ return;
16
+ }
17
+
18
+ const paths = await fg('**/*.zip', {
19
+ cwd: blockletsDir,
20
+ onlyFiles: true,
21
+ absolute: true,
22
+ });
23
+
24
+ const configs = paths.map((path) => {
25
+ return {
26
+ source: path,
27
+ target: path.replace(/.zip$/, ''),
28
+ };
29
+ });
30
+
31
+ await Promise.all(
32
+ configs.map(async ({ source, target }) => {
33
+ if (!existsSync(target)) {
34
+ ensureDirSync(target);
35
+ }
36
+ await zipToDir(source, target);
37
+ await remove(source);
38
+ })
39
+ );
40
+ }
41
+ }
42
+
43
+ module.exports = { BlockletsRestore };
@@ -0,0 +1,104 @@
1
+ const { isValid } = require('@arcblock/did');
2
+ const isEmpty = require('lodash/isEmpty');
3
+ const merge = require('lodash/merge');
4
+ const { ensureDirSync, existsSync, rmSync, copy } = require('fs-extra');
5
+
6
+ const { getBackupDirs } = require('../utils/disk');
7
+ const { BaseRestore } = require('./base');
8
+ const { BlockletExtrasRestore } = require('./blocklet-extras');
9
+ const { BlockletRestore } = require('./blocklet');
10
+ const { BlockletsRestore } = require('./blocklets');
11
+
12
+ class DiskRestore extends BaseRestore {
13
+ /**
14
+ *
15
+ * @type {import('./base').BaseRestoreInput}
16
+ * @memberof DiskRestore
17
+ */
18
+ input;
19
+
20
+ /**
21
+ * @type {string}
22
+ * @memberof DiskRestore
23
+ */
24
+ restoreDir;
25
+
26
+ /**
27
+ *
28
+ * @description server 的数据目录
29
+ * @type {string}
30
+ * @memberof DiskRestore
31
+ */
32
+ serverDir;
33
+
34
+ storages;
35
+
36
+ /**
37
+ *
38
+ * @param {import('./base').BaseRestoreInput} input
39
+ * @memberof DiskRestore
40
+ */
41
+ constructor(input) {
42
+ super(input);
43
+ this.verify(input);
44
+ this.input = input;
45
+ this.storages = [
46
+ new BlockletExtrasRestore(this.input),
47
+ new BlockletRestore(this.input),
48
+ new BlockletsRestore(this.input),
49
+ ];
50
+ }
51
+
52
+ /**
53
+ *
54
+ * @param {import('./base').BaseRestoreInput} input
55
+ * @returns {void}
56
+ * @memberof DiskRestore
57
+ */
58
+ verify(input) {
59
+ if (isEmpty(input?.appDid) || !isValid(input?.appDid)) {
60
+ throw new Error(`input.appDid(${input?.appDid}) is not a valid did`);
61
+ }
62
+ }
63
+
64
+ initialize() {
65
+ this.serverDir = process.env.ABT_NODE_DATA_DIR;
66
+ this.restoreDir = getBackupDirs(this.serverDir, this.input.appDid).restoreDir;
67
+ if (existsSync(this.restoreDir)) {
68
+ rmSync(this.restoreDir, { recursive: true });
69
+ }
70
+ ensureDirSync(this.restoreDir);
71
+
72
+ this.storages.map((x) => x.ensureParams(this));
73
+ }
74
+
75
+ async restore() {
76
+ await this.initialize();
77
+ await this.syncFromBackupDir();
78
+
79
+ const params = await Promise.all(this.storages.map((x) => x.getImportParams()));
80
+ await this.import(merge(...params));
81
+
82
+ return this.storages.map((x) => x.getInstallParams());
83
+ }
84
+
85
+ async syncFromBackupDir() {
86
+ const { appDid } = this.input;
87
+
88
+ const { backupDir } = getBackupDirs(this.serverDir, appDid);
89
+
90
+ await copy(backupDir, this.restoreDir);
91
+ }
92
+
93
+ async import(params) {
94
+ await Promise.all(
95
+ this.storages.map((storage) => {
96
+ return storage.import(params);
97
+ })
98
+ );
99
+ }
100
+ }
101
+
102
+ module.exports = {
103
+ DiskRestore,
104
+ };