@abtnode/core 1.8.16 → 1.8.19

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.
@@ -56,7 +56,8 @@ const preStart = async (blocklet, options) => {
56
56
  return runUserHook(blocklet.env.processId, 'pre-start', options);
57
57
  };
58
58
 
59
+ const postStart = (processId, ...args) => runUserHook(processId, 'post-start', ...args);
59
60
  const preUninstall = (processId, ...args) => runUserHook(processId, 'pre-uninstall', ...args);
60
61
  const preStop = (processId, ...args) => runUserHook(processId, 'pre-stop', ...args);
61
62
 
62
- module.exports = { preDeploy, preInstall, postInstall, preStart, preUninstall, preStop, preConfig };
63
+ module.exports = { preDeploy, preInstall, postInstall, preStart, postStart, preUninstall, preStop, preConfig };
@@ -8,6 +8,8 @@ class BaseBlockletManager extends EventEmitter {
8
8
  constructor() {
9
9
  super();
10
10
 
11
+ this.setMaxListeners(100);
12
+
11
13
  // HACK: do not emit any events from CLI
12
14
  if (isCLI() && process.env.NODE_ENV !== 'test') {
13
15
  this.emit = (name) => logger.debug('stopped blocklet manager event in CLI', name);
@@ -385,17 +385,22 @@ class BlockletManager extends BaseBlockletManager {
385
385
  fs.mkdirSync(logsDir, { recursive: true });
386
386
  }
387
387
 
388
- // start process
389
- const nodeEnvironments = await states.node.getEnvironments();
390
- await startBlockletProcess(blocklet, {
391
- ...context,
392
- preStart: (b, { env }) =>
393
- hooks.preStart(b, {
388
+ const getHookFn =
389
+ (hookName) =>
390
+ (b, { env }) =>
391
+ hooks[hookName](b, {
394
392
  appDir: b.env.appDir,
395
393
  hooks: Object.assign(b.meta.hooks || {}, b.meta.scripts || {}),
396
394
  env,
397
395
  did, // root blocklet did,
398
- }),
396
+ });
397
+
398
+ // start process
399
+ const nodeEnvironments = await states.node.getEnvironments();
400
+ await startBlockletProcess(blocklet, {
401
+ ...context,
402
+ preStart: getHookFn('preStart'),
403
+ postStart: getHookFn('postStart'),
399
404
  nodeEnvironments,
400
405
  nodeInfo: await states.node.read(),
401
406
  e2eMode,
package/lib/index.js CHANGED
@@ -313,13 +313,13 @@ function ABTNode(options) {
313
313
  verifyChallenge: states.challenge.verify.bind(states.challenge),
314
314
 
315
315
  // Notifications
316
- getNotifications: states.notification.find.bind(states.notification),
316
+ getNotifications: states.notification.findPaginated.bind(states.notification),
317
317
  readNotifications: states.notification.read.bind(states.notification),
318
318
  unreadNotifications: states.notification.unread.bind(states.notification),
319
319
 
320
320
  // AuditLog
321
321
  createAuditLog: (params) => states.auditLog.create(params, instance),
322
- getAuditLogs: states.auditLog.find.bind(states.auditLog),
322
+ getAuditLogs: states.auditLog.findPaginated.bind(states.auditLog),
323
323
 
324
324
  // Routing
325
325
  routerManager,
@@ -394,7 +394,6 @@ function ABTNode(options) {
394
394
 
395
395
  const events = createEvents({
396
396
  blockletManager,
397
- blockletRegistry,
398
397
  ensureBlockletRouting,
399
398
  ensureBlockletRoutingForUpgrade,
400
399
  removeBlockletRouting,
@@ -19,13 +19,15 @@ const validatePassport = (passport) => {
19
19
  const getUserName = (context) => get(context, 'user.fullName', '');
20
20
 
21
21
  class AccessKeyState extends BaseState {
22
- constructor(baseDir, options = {}) {
23
- super(baseDir, { filename: 'access_key.db', ...options });
24
-
25
- this.db.ensureIndex({ fieldName: 'accessKeyId', unique: true }, (error) => {
26
- if (error) {
27
- logger.error('ensure unique index failed', { error });
28
- }
22
+ constructor(baseDir, config = {}) {
23
+ super(baseDir, { filename: 'access_key.db', ...config });
24
+
25
+ this.onReady(() => {
26
+ this.ensureIndex({ fieldName: 'accessKeyId', unique: true }, (error) => {
27
+ if (error) {
28
+ logger.error('ensure unique index failed', { error });
29
+ }
30
+ });
29
31
  });
30
32
  }
31
33
 
@@ -48,7 +50,7 @@ class AccessKeyState extends BaseState {
48
50
  data.createdBy = getUserName(context);
49
51
  data.updatedBy = getUserName(context);
50
52
 
51
- const doc = await this.asyncDB.insert(data);
53
+ const doc = await this.insert(data);
52
54
  return {
53
55
  ...doc,
54
56
  accessKeySecret: toBase58(wallet.secretKey),
@@ -67,7 +69,7 @@ class AccessKeyState extends BaseState {
67
69
  if (!accessKeyId) {
68
70
  throw new Error('accessKeyId should not be empty');
69
71
  }
70
- const doc = await this.asyncDB.findOne({ accessKeyId });
72
+ const doc = await this.findOne({ accessKeyId });
71
73
  return doc;
72
74
  }
73
75
 
@@ -82,7 +84,7 @@ class AccessKeyState extends BaseState {
82
84
  if (!accessKeyId) {
83
85
  throw new Error('accessKeyId should not be empty');
84
86
  }
85
- const doc = await this.asyncDB.findOne({ accessKeyId });
87
+ const doc = await this.findOne({ accessKeyId });
86
88
  if (!doc) {
87
89
  throw new Error(`Access Key Id ${accessKeyId} does not exist`);
88
90
  }
@@ -92,7 +94,7 @@ class AccessKeyState extends BaseState {
92
94
  doc.passport = passport;
93
95
  doc.updatedBy = getUserName(context);
94
96
 
95
- await this.asyncDB.update({ accessKeyId }, { $set: doc });
97
+ await super.update({ accessKeyId }, { $set: doc });
96
98
  return doc;
97
99
  }
98
100
 
@@ -101,12 +103,12 @@ class AccessKeyState extends BaseState {
101
103
  if (!accessKeyId) {
102
104
  throw new Error('accessKeyId should not be empty');
103
105
  }
104
- const doc = await this.asyncDB.findOne({ accessKeyId });
106
+ const doc = await this.findOne({ accessKeyId });
105
107
  if (!doc) {
106
108
  throw new Error(`Access Key Id ${accessKeyId} does not exist`);
107
109
  }
108
110
  doc.lastUsedAt = new Date();
109
- await this.asyncDB.update({ accessKeyId }, { $set: doc });
111
+ await super.update({ accessKeyId }, { $set: doc });
110
112
  return doc;
111
113
  }
112
114
 
@@ -116,7 +118,7 @@ class AccessKeyState extends BaseState {
116
118
  if (!accessKeyId) {
117
119
  throw new Error('accessKeyId should not be empty');
118
120
  }
119
- const num = await this.asyncDB.remove({ accessKeyId });
121
+ const num = await super.remove({ accessKeyId });
120
122
  if (num <= 0) {
121
123
  throw new Error(`Access Key Id ${accessKeyId} does not exist`);
122
124
  }
@@ -353,8 +353,8 @@ const fixActor = (actor) => {
353
353
  };
354
354
 
355
355
  class AuditLogState extends BaseState {
356
- constructor(baseDir, options = {}) {
357
- super(baseDir, { filename: 'audit-log.db', ...options });
356
+ constructor(baseDir, config = {}) {
357
+ super(baseDir, { filename: 'audit-log.db', ...config });
358
358
  }
359
359
 
360
360
  /**
@@ -409,7 +409,7 @@ class AuditLogState extends BaseState {
409
409
 
410
410
  fixActor(user);
411
411
 
412
- const data = await this.asyncDB.insert({
412
+ const data = await this.insert({
413
413
  scope: getScope(args) || info.did, // server or blocklet did
414
414
  action,
415
415
  category: await getLogCategory(action, args, context, result, info, node),
@@ -430,7 +430,7 @@ class AuditLogState extends BaseState {
430
430
  });
431
431
  }
432
432
 
433
- async find({ scope, category, paging } = {}) {
433
+ async findPaginated({ scope, category, paging } = {}) {
434
434
  const conditions = {};
435
435
  if (scope) {
436
436
  conditions.scope = scope;
@@ -439,7 +439,7 @@ class AuditLogState extends BaseState {
439
439
  conditions.category = category;
440
440
  }
441
441
 
442
- return this.paginate(conditions, { createdAt: -1 }, { pageSize: 20, ...paging });
442
+ return super.paginate(conditions, { createdAt: -1 }, { pageSize: 20, ...paging });
443
443
  }
444
444
  }
445
445
 
@@ -4,8 +4,8 @@ const logger = require('@abtnode/logger')('@abtnode/core:states');
4
4
  const { isCLI } = require('../util');
5
5
 
6
6
  class BaseState extends DB {
7
- constructor(baseDir, options) {
8
- super(baseDir, options);
7
+ constructor(baseDir, config) {
8
+ super(baseDir, config);
9
9
 
10
10
  // HACK: do not emit any events from CLI
11
11
  if (isCLI() && process.env.NODE_ENV !== 'test') {
@@ -12,8 +12,8 @@ const { mergeConfigs, parseConfigs } = require('../blocklet/extras');
12
12
  const noop = (k) => (v) => v[k];
13
13
 
14
14
  class BlockletExtrasState extends BaseState {
15
- constructor(baseDir, options = {}) {
16
- super(baseDir, { filename: 'blocklet_extras.db', ...options });
15
+ constructor(baseDir, config = {}) {
16
+ super(baseDir, { filename: 'blocklet_extras.db', ...config });
17
17
 
18
18
  this.extras = [
19
19
  // environment
@@ -82,10 +82,10 @@ class BlockletExtrasState extends BaseState {
82
82
  // eslint-disable-next-line no-param-reassign
83
83
  dids = [].concat(dids);
84
84
  const [rootDid, ...childDids] = dids;
85
- const { dek } = this.options;
85
+ const { dek } = this.config;
86
86
  const { name, afterGet = noop('data') } = extra;
87
87
 
88
- let item = await this.asyncDB.findOne({ did: rootDid });
88
+ let item = await this.findOne({ did: rootDid });
89
89
  while (item && childDids.length) {
90
90
  const did = childDids.shift();
91
91
  item = (item.children || []).find((x) => x.did === did);
@@ -104,9 +104,9 @@ class BlockletExtrasState extends BaseState {
104
104
  // eslint-disable-next-line no-param-reassign
105
105
  dids = [].concat(dids);
106
106
  const [rootDid, ...childDids] = dids;
107
- const { dek } = this.options;
107
+ const { dek } = this.config;
108
108
  const { name, beforeSet = noop('cur') } = extra;
109
- const exist = await this.asyncDB.findOne({ did: rootDid });
109
+ const exist = await this.findOne({ did: rootDid });
110
110
 
111
111
  const item = exist || { did: rootDid };
112
112
  let component = item;
@@ -126,7 +126,7 @@ class BlockletExtrasState extends BaseState {
126
126
  component[name] = newData;
127
127
 
128
128
  if (!exist) {
129
- await this.asyncDB.insert(item);
129
+ await this.insert(item);
130
130
  logger.info('create extra success', { name, dids });
131
131
  } else {
132
132
  await this.update(item._id, item);
@@ -143,7 +143,7 @@ class BlockletExtrasState extends BaseState {
143
143
  dids = [].concat(dids);
144
144
  const [rootDid, ...childDids] = dids;
145
145
  const { name } = extra;
146
- const item = await this.asyncDB.findOne({ did: rootDid });
146
+ const item = await this.findOne({ did: rootDid });
147
147
 
148
148
  if (!item) {
149
149
  return null;
@@ -170,9 +170,9 @@ class BlockletExtrasState extends BaseState {
170
170
 
171
171
  generateListFn(extra) {
172
172
  return async () => {
173
- const { dek } = this.options;
173
+ const { dek } = this.config;
174
174
  const { name, afterGet = noop('data') } = extra;
175
- const docs = await this.asyncDB.find({});
175
+ const docs = await this.find({});
176
176
  const list = docs
177
177
  .filter((x) => x[name])
178
178
  .map((x) => ({
@@ -79,14 +79,14 @@ class BlockletState extends BaseState {
79
79
  /**
80
80
  * Creates an instance of BlockletState
81
81
  * @param {string} baseDir
82
- * @param {object} options
83
- * @param {string} options.blockletPort - from which port to start new blocklets
82
+ * @param {object} config
83
+ * @param {string} config.blockletPort - from which port to start new blocklets
84
84
  * @memberof BlockletState
85
85
  */
86
- constructor(baseDir, options = {}) {
87
- super(baseDir, { filename: 'blocklet.db', ...options });
86
+ constructor(baseDir, config = {}) {
87
+ super(baseDir, { filename: 'blocklet.db', ...config });
88
88
 
89
- this.defaultPort = options.blockletPort || 5555;
89
+ this.defaultPort = config.blockletPort || 5555;
90
90
  }
91
91
 
92
92
  getBlocklet(did) {
@@ -95,12 +95,12 @@ class BlockletState extends BaseState {
95
95
  resolve(null);
96
96
  }
97
97
 
98
- this.db.findOne({ $or: [{ 'meta.did': did }, { appDid: did }] }, (err, doc) => {
98
+ this.findOne({ $or: [{ 'meta.did': did }, { appDid: did }] }, (err, doc) => {
99
99
  if (err) {
100
100
  return reject(err);
101
101
  }
102
102
 
103
- return resolve(doc ? formatBlocklet(doc, 'onRead', this.options.dek) : null);
103
+ return resolve(doc ? formatBlocklet(doc, 'onRead', this.config.dek) : null);
104
104
  });
105
105
  });
106
106
  }
@@ -111,7 +111,7 @@ class BlockletState extends BaseState {
111
111
  resolve(null);
112
112
  }
113
113
 
114
- this.db.findOne({ $or: [{ 'meta.did': did }, { appDid: did }] }, { status: 1 }, (err, doc) => {
114
+ this.findOne({ $or: [{ 'meta.did': did }, { appDid: did }] }, { status: 1 }, (err, doc) => {
115
115
  if (err) {
116
116
  return reject(err);
117
117
  }
@@ -127,7 +127,7 @@ class BlockletState extends BaseState {
127
127
  resolve(false);
128
128
  }
129
129
 
130
- this.db.count({ $or: [{ 'meta.did': did }, { appDid: did }] }, (err, count) => {
130
+ this.count({ $or: [{ 'meta.did': did }, { appDid: did }] }, (err, count) => {
131
131
  if (err) {
132
132
  return reject(err);
133
133
  }
@@ -139,15 +139,15 @@ class BlockletState extends BaseState {
139
139
 
140
140
  getBlocklets(query = {}, projection) {
141
141
  return new Promise((resolve, reject) => {
142
- this.db
143
- .find(query, projection)
144
- .sort('-createdAt')
145
- .exec((err, docs) => {
142
+ this.cursor(query)
143
+ .projection(projection)
144
+ .sort({ createdAt: -1 })
145
+ .exec((err, docs = []) => {
146
146
  if (err) {
147
147
  return reject(err);
148
148
  }
149
149
 
150
- return resolve(docs.filter(Boolean).map((doc) => formatBlocklet(doc, 'onRead', this.options.dek)));
150
+ return resolve(docs.filter(Boolean).map((doc) => formatBlocklet(doc, 'onRead', this.config.dek)));
151
151
  });
152
152
  });
153
153
  }
@@ -161,13 +161,13 @@ class BlockletState extends BaseState {
161
161
  return reject(new Error(`Try to remove non-existing blocklet ${did}`));
162
162
  }
163
163
 
164
- this.db.remove({ _id: doc._id }, (err) => {
164
+ this.remove({ _id: doc._id }, (err) => {
165
165
  if (err) {
166
166
  return reject(err);
167
167
  }
168
168
 
169
169
  this.emit('remove', doc);
170
- return resolve(formatBlocklet(doc, 'onRead', this.options.dek));
170
+ return resolve(formatBlocklet(doc, 'onRead', this.config.dek));
171
171
  });
172
172
  })
173
173
  );
@@ -209,7 +209,7 @@ class BlockletState extends BaseState {
209
209
  fixChildren(children);
210
210
 
211
211
  // add to db
212
- this.db.insert(
212
+ this.insert(
213
213
  {
214
214
  appDid: null, // will updated later when updating blocklet environments
215
215
  mode,
@@ -249,7 +249,7 @@ class BlockletState extends BaseState {
249
249
  }
250
250
 
251
251
  try {
252
- const formatted = formatBlocklet(cloneDeep(updates), 'onUpdate', this.options.dek);
252
+ const formatted = formatBlocklet(cloneDeep(updates), 'onUpdate', this.config.dek);
253
253
  const newDoc = await this.updateById(doc._id, { $set: formatted });
254
254
  resolve(newDoc);
255
255
  } catch (err) {
@@ -456,7 +456,7 @@ class BlockletState extends BaseState {
456
456
 
457
457
  const doc = await this.getBlocklet(did);
458
458
  if (doc.status === status && !children) {
459
- return formatBlocklet(doc, 'onRead', this.options.dek);
459
+ return formatBlocklet(doc, 'onRead', this.config.dek);
460
460
  }
461
461
 
462
462
  const updates = { status, startedAt: undefined, stoppedAt: undefined };
@@ -5,13 +5,15 @@ const BaseState = require('./base');
5
5
  * This db is used to save arbitrary cached data.
6
6
  */
7
7
  class CacheState extends BaseState {
8
- constructor(baseDir, options = {}) {
9
- super(baseDir, { filename: 'cache.db', ...options });
8
+ constructor(baseDir, config = {}) {
9
+ super(baseDir, { filename: 'cache.db', ...config });
10
10
 
11
- this.db.ensureIndex({ fieldName: 'key', unique: true }, (error) => {
12
- if (error) {
13
- logger.error('ensure index failed', { error });
14
- }
11
+ this.onReady(() => {
12
+ this.ensureIndex({ fieldName: 'key', unique: true }, (error) => {
13
+ if (error) {
14
+ logger.error('ensure index failed', { error });
15
+ }
16
+ });
15
17
  });
16
18
  }
17
19
 
@@ -9,17 +9,17 @@ class ChallengeState extends BaseState {
9
9
  /**
10
10
  * Creates an instance of ChallengeState
11
11
  * @param {string} baseDir
12
- * @param {object} options
12
+ * @param {object} config
13
13
  * @memberof ChallengeState
14
14
  */
15
- constructor(baseDir, options = {}) {
16
- super(baseDir, { filename: 'challenge.db', ...options });
15
+ constructor(baseDir, config = {}) {
16
+ super(baseDir, { filename: 'challenge.db', ...config });
17
17
  }
18
18
 
19
19
  generate() {
20
20
  return new Promise((resolve, reject) => {
21
21
  const challenge = stripHexPrefix(Mcrypto.getRandomBytes(16)).toUpperCase();
22
- this.db.insert({ challenge }, (err, data) => {
22
+ this.insert({ challenge }, (err, data) => {
23
23
  if (err) {
24
24
  logger.error('generating error', { error: err });
25
25
  return reject(err);
@@ -38,7 +38,7 @@ class ChallengeState extends BaseState {
38
38
  return;
39
39
  }
40
40
 
41
- this.db.findOne({ challenge }, (err, data) => {
41
+ this.findOne({ challenge }, (err, data) => {
42
42
  if (err) {
43
43
  logger.error('error find challenge', { error: err });
44
44
  }
@@ -12,19 +12,19 @@ const ExtrasState = require('./blocklet-extras');
12
12
  const CacheState = require('./cache');
13
13
  const AuditLogState = require('./audit-log');
14
14
 
15
- const init = (dataDirs, options) => {
16
- const notificationState = new NotificationState(dataDirs.core, options);
17
- const nodeState = new NodeState(dataDirs.core, options, dataDirs, notificationState);
18
- const blockletState = new BlockletState(dataDirs.core, options);
19
- const challengeState = new ChallengeState(dataDirs.core, options);
20
- const siteState = new SiteState(dataDirs.core, options);
21
- const accessKeyState = new AccessKeyState(dataDirs.core, options);
22
- const webhookState = new WebhookState(dataDirs.core, options);
23
- const migrationState = new MigrationState(dataDirs.core, options);
24
- const sessionState = new SessionState(dataDirs.core, options);
25
- const extrasState = new ExtrasState(dataDirs.core, options);
26
- const cacheState = new CacheState(dataDirs.core, options);
27
- const auditLogState = new AuditLogState(dataDirs.core, options);
15
+ const init = (dataDirs, config) => {
16
+ const notificationState = new NotificationState(dataDirs.core, config);
17
+ const nodeState = new NodeState(dataDirs.core, config, dataDirs, notificationState);
18
+ const blockletState = new BlockletState(dataDirs.core, config);
19
+ const challengeState = new ChallengeState(dataDirs.core, config);
20
+ const siteState = new SiteState(dataDirs.core, config);
21
+ const accessKeyState = new AccessKeyState(dataDirs.core, config);
22
+ const webhookState = new WebhookState(dataDirs.core, config);
23
+ const migrationState = new MigrationState(dataDirs.core, config);
24
+ const sessionState = new SessionState(dataDirs.core, config);
25
+ const extrasState = new ExtrasState(dataDirs.core, config);
26
+ const cacheState = new CacheState(dataDirs.core, config);
27
+ const auditLogState = new AuditLogState(dataDirs.core, config);
28
28
 
29
29
  return {
30
30
  node: nodeState,
@@ -4,14 +4,14 @@ const logger = require('@abtnode/logger')('@abtnode/core:states:migration');
4
4
  const BaseState = require('./base');
5
5
 
6
6
  class MigrationState extends BaseState {
7
- constructor(baseDir, options = {}) {
8
- super(baseDir, { filename: 'migration.db', ...options });
7
+ constructor(baseDir, config = {}) {
8
+ super(baseDir, { filename: 'migration.db', ...config });
9
9
  }
10
10
 
11
11
  // eslint-disable-next-line no-unused-vars
12
12
  async isExecuted({ script, version }, context) {
13
13
  try {
14
- const item = await this.asyncDB.findOne({ script, version });
14
+ const item = await this.findOne({ script, version });
15
15
  return !!item;
16
16
  } catch (err) {
17
17
  logger.error('failed to find migration', { script, version });
@@ -22,7 +22,7 @@ class MigrationState extends BaseState {
22
22
  // eslint-disable-next-line no-unused-vars
23
23
  async markExecuted({ script, version }, context) {
24
24
  try {
25
- const result = await this.asyncDB.insert({ script, version, executedAt: new Date() });
25
+ const result = await this.insert({ script, version, executedAt: new Date() });
26
26
  logger.info('mark executed', result);
27
27
  return result;
28
28
  } catch (error) {
@@ -15,23 +15,23 @@ class NodeState extends BaseState {
15
15
  /**
16
16
  * Creates an instance of NodeState.
17
17
  * @param {string} baseDir
18
- * @param {object} options
18
+ * @param {object} config
19
19
  * @memberof NodeState
20
20
  */
21
- constructor(baseDir, options = {}, dataDirs = {}, notification) {
22
- super(baseDir, { filename: 'node.db', ...options });
21
+ constructor(baseDir, config = {}, dataDirs = {}, notification) {
22
+ super(baseDir, { filename: 'node.db', ...config });
23
23
 
24
24
  // Initialize the store
25
- if (!options.nodeSk) {
25
+ if (!config.nodeSk) {
26
26
  throw new Error('Can not initialize node store without valid nodeSk');
27
27
  }
28
- if (!options.nodePk) {
28
+ if (!config.nodePk) {
29
29
  throw new Error('Can not initialize node store without valid nodePk');
30
30
  }
31
- if (!options.nodeDid) {
31
+ if (!config.nodeDid) {
32
32
  throw new Error('Can not initialize node store without valid nodeDid');
33
33
  }
34
- if (!isFromPublicKey(options.nodeDid, options.nodePk)) {
34
+ if (!isFromPublicKey(config.nodeDid, config.nodePk)) {
35
35
  throw new Error('Node pk and did does not match');
36
36
  }
37
37
 
@@ -39,7 +39,7 @@ class NodeState extends BaseState {
39
39
  this.notification = notification;
40
40
 
41
41
  this.onReady(() => {
42
- this.db.ensureIndex({ fieldName: 'did', unique: true }, (err) => {
42
+ this.ensureIndex({ fieldName: 'did', unique: true }, (err) => {
43
43
  if (err) {
44
44
  console.error('Failed to ensure unique index', err);
45
45
  }
@@ -62,8 +62,8 @@ class NodeState extends BaseState {
62
62
  */
63
63
  read() {
64
64
  return new Promise((resolve, reject) => {
65
- const { nodeDid, dek } = this.options;
66
- this.db.findOne({ did: this.options.nodeDid }, (err, record) => {
65
+ const { nodeDid, dek } = this.config;
66
+ this.findOne({ did: nodeDid }, (err, record) => {
67
67
  if (err) {
68
68
  // eslint-disable-next-line no-console
69
69
  console.error(err);
@@ -97,7 +97,7 @@ class NodeState extends BaseState {
97
97
  enablePassportIssuance = true,
98
98
  trustedPassports = [],
99
99
  webWalletUrl,
100
- } = this.options;
100
+ } = this.config;
101
101
 
102
102
  if (nodeOwner && !validateOwner(nodeOwner)) {
103
103
  return reject(new Error('Node owner is invalid'));
@@ -107,7 +107,7 @@ class NodeState extends BaseState {
107
107
 
108
108
  return getDefaultConfigs()
109
109
  .then((defaultConfigs) =>
110
- this.db.insert(
110
+ this.insert(
111
111
  {
112
112
  ...(defaultConfigs || {}),
113
113
  name,
@@ -5,11 +5,11 @@ const { EVENTS } = require('@abtnode/constant');
5
5
  const BaseState = require('./base');
6
6
 
7
7
  class NotificationState extends BaseState {
8
- constructor(baseDir, options = {}) {
9
- super(baseDir, { filename: 'notification.db', ...options });
8
+ constructor(baseDir, config = {}) {
9
+ super(baseDir, { filename: 'notification.db', ...config });
10
10
 
11
- this.defaultSender = options.defaultSender || '';
12
- this.defaultReceiver = options.defaultReceiver || '';
11
+ this.defaultSender = config.defaultSender || '';
12
+ this.defaultReceiver = config.defaultReceiver || '';
13
13
  }
14
14
 
15
15
  setDefaultSender(sender) {
@@ -28,7 +28,7 @@ class NotificationState extends BaseState {
28
28
  });
29
29
 
30
30
  return new Promise((resolve, reject) => {
31
- this.db.insert(
31
+ this.insert(
32
32
  {
33
33
  sender: payload.sender || this.defaultSender,
34
34
  receiver: payload.receiver || this.defaultReceiver,
@@ -54,7 +54,7 @@ class NotificationState extends BaseState {
54
54
  });
55
55
  }
56
56
 
57
- async find({ receiver, sender, read, paging } = {}, context) {
57
+ async findPaginated({ receiver, sender, read, paging } = {}, context) {
58
58
  const conditions = {};
59
59
  // eslint-disable-next-line no-param-reassign
60
60
  receiver = receiver || get(context, 'user.did');
@@ -81,7 +81,7 @@ class NotificationState extends BaseState {
81
81
  logger.info('mark notification as read', { idList });
82
82
 
83
83
  return new Promise((resolve, reject) => {
84
- this.db.update(
84
+ this.update(
85
85
  { _id: { $in: idList } },
86
86
  { $set: { read: true } },
87
87
  { multi: true, upsert: false, returnUpdatedDocs: false },
@@ -101,7 +101,7 @@ class NotificationState extends BaseState {
101
101
  const idList = Array.isArray(id) ? id : [id];
102
102
 
103
103
  return new Promise((resolve, reject) => {
104
- this.db.update(
104
+ this.update(
105
105
  { _id: { $in: idList } },
106
106
  { $set: { read: false } },
107
107
  { multi: true, upsert: false, returnUpdatedDocs: false },
@@ -5,24 +5,26 @@ const BaseState = require('./base');
5
5
  * This db is used to save session data generated in a http session. the session is NOT user auth session.
6
6
  */
7
7
  class SessionState extends BaseState {
8
- constructor(baseDir, options = {}) {
9
- super(baseDir, { filename: 'session.db', ...options });
8
+ constructor(baseDir, config = {}) {
9
+ super(baseDir, { filename: 'session.db', ...config });
10
10
 
11
- this.db.ensureIndex({ fieldName: 'createdAt' }, (error) => {
12
- if (error) {
13
- logger.error('ensure createdAt index failed', { error });
14
- }
15
- });
11
+ this.onReady(() => {
12
+ this.ensureIndex({ fieldName: 'createdAt' }, (error) => {
13
+ if (error) {
14
+ logger.error('ensure createdAt index failed', { error });
15
+ }
16
+ });
16
17
 
17
- this.db.ensureIndex({ fieldName: 'expireDate', expireAfterSeconds: 0 }, (error) => {
18
- if (error) {
19
- logger.error('ensure expireDate index failed', { error });
20
- }
18
+ this.ensureIndex({ fieldName: 'expireDate', expireAfterSeconds: 0 }, (error) => {
19
+ if (error) {
20
+ logger.error('ensure expireDate index failed', { error });
21
+ }
22
+ });
21
23
  });
22
24
  }
23
25
 
24
26
  async start(initialData) {
25
- const { _id, ...data } = await this.asyncDB.insert(initialData);
27
+ const { _id, ...data } = await this.insert(initialData);
26
28
  return { id: _id, ...data };
27
29
  }
28
30
 
@@ -35,7 +37,7 @@ class SessionState extends BaseState {
35
37
 
36
38
  // eslint-disable-next-line no-underscore-dangle
37
39
  delete exist._id;
38
- await this.asyncDB.update({ _id: id }, { $set: { ...exist, ...data } }, { multi: false, upsert: false });
40
+ await super.update({ _id: id }, { $set: { ...exist, ...data } }, { multi: false, upsert: false });
39
41
 
40
42
  return { id, ...exist, ...data };
41
43
  }
@@ -57,7 +59,7 @@ class SessionState extends BaseState {
57
59
  throw new Error(`Session does not exist: ${id}`);
58
60
  }
59
61
 
60
- await this.asyncDB.remove({ _id: id });
62
+ await this.remove({ _id: id });
61
63
 
62
64
  data.id = id;
63
65
  return data;
@@ -4,12 +4,12 @@ const { toSlotDomain } = require('@abtnode/router-provider/lib/util');
4
4
  const BaseState = require('./base');
5
5
 
6
6
  class SiteState extends BaseState {
7
- constructor(baseDir, options = {}) {
8
- super(baseDir, { filename: 'routing_rule.db', ...options });
7
+ constructor(baseDir, config = {}) {
8
+ super(baseDir, { filename: 'routing_rule.db', ...config });
9
9
  }
10
10
 
11
11
  async add(rule) {
12
- const result = await this.asyncDB.insert(rule);
12
+ const result = await this.insert(rule);
13
13
 
14
14
  const tmpRule = SiteState.renameIdFiledName(result);
15
15
  logger.info('rule created', { rule: tmpRule });
@@ -17,7 +17,7 @@ class SiteState extends BaseState {
17
17
  }
18
18
 
19
19
  async addRuleToSite(id, rule) {
20
- const addedCount = await this.asyncDB.update({ _id: id }, { $addToSet: { rules: rule } });
20
+ const addedCount = await this.update({ _id: id }, { $addToSet: { rules: rule } });
21
21
 
22
22
  logger.info('added rule to site', { count: addedCount });
23
23
  return addedCount;
@@ -26,21 +26,21 @@ class SiteState extends BaseState {
26
26
  async getSites(...args) {
27
27
  let result = null;
28
28
  if (args.length === 0) {
29
- result = await this.asyncDB.find({});
29
+ result = await this.find({});
30
30
  } else {
31
- result = await this.asyncDB.find(...args);
31
+ result = await this.find(...args);
32
32
  }
33
33
 
34
34
  return SiteState.renameIdFiledName(result);
35
35
  }
36
36
 
37
37
  async getSitesByBlocklet(did) {
38
- const rules = await this.asyncDB.find({ 'rules.to.did': did });
38
+ const rules = await this.find({ 'rules.to.did': did });
39
39
  return SiteState.renameIdFiledName(rules);
40
40
  }
41
41
 
42
42
  async getRuleById(id) {
43
- const site = await this.asyncDB.findOne({ 'rules.id': id });
43
+ const site = await this.findOne({ 'rules.id': id });
44
44
  if (!site) {
45
45
  return null;
46
46
  }
@@ -48,20 +48,8 @@ class SiteState extends BaseState {
48
48
  return site.rules.find((x) => x.id === id);
49
49
  }
50
50
 
51
- async update(...args) {
52
- return this.asyncDB.update(...args);
53
- }
54
-
55
- async count(...args) {
56
- return this.asyncDB.count(...args);
57
- }
58
-
59
- async remove(...args) {
60
- return this.asyncDB.remove(...args);
61
- }
62
-
63
51
  async findOne(...args) {
64
- const site = await this.asyncDB.findOne(...args);
52
+ const site = await super.findOne(...args);
65
53
  if (!site) {
66
54
  return site;
67
55
  }
@@ -80,7 +68,7 @@ class SiteState extends BaseState {
80
68
  async findOneByDomain(domain) {
81
69
  // eslint-disable-next-line no-param-reassign
82
70
  domain = toSlotDomain(domain);
83
- return this.asyncDB.findOne({
71
+ return this.findOne({
84
72
  $or: [{ domain }, { domainAliases: domain }, { 'domainAliases.value': domain }],
85
73
  });
86
74
  }
@@ -5,20 +5,18 @@ const { PASSPORT_STATUS } = require('@abtnode/constant');
5
5
  const BaseState = require('./base');
6
6
  const { validateOwner } = require('../util');
7
7
 
8
- const fixPassports = (doc) => {
9
- doc.passports = (doc.passports || []).filter((x) => x.id);
10
- };
11
-
12
8
  const isNullOrUndefined = (x) => x === undefined || x === null;
13
9
 
14
10
  class User extends BaseState {
15
- constructor(baseDir, options = {}) {
16
- super(baseDir, { filename: 'user.db', ...options });
17
-
18
- this.db.ensureIndex({ fieldName: 'did', unique: true }, (error) => {
19
- if (error) {
20
- logger.error('ensure index failed', { error });
21
- }
11
+ constructor(baseDir, config = {}) {
12
+ super(baseDir, { filename: 'user.db', ...config });
13
+
14
+ this.onReady(() => {
15
+ this.ensureIndex({ fieldName: 'did', unique: true }, (error) => {
16
+ if (error) {
17
+ logger.error('ensure index failed', { error });
18
+ }
19
+ });
22
20
  });
23
21
  }
24
22
 
@@ -120,10 +118,6 @@ class User extends BaseState {
120
118
  // get data
121
119
  const { list, paging } = await this.paginate(queryParam, sortParam, inputPaging);
122
120
 
123
- if (list) {
124
- list.forEach(fixPassports); // backward compatible
125
- }
126
-
127
121
  return {
128
122
  list,
129
123
  paging,
@@ -131,11 +125,7 @@ class User extends BaseState {
131
125
  }
132
126
 
133
127
  async getUser(did) {
134
- const doc = await super.findOne({ did });
135
- if (doc) {
136
- fixPassports(doc); // backward compatible
137
- }
138
-
128
+ const doc = await this.findOne({ did });
139
129
  return doc;
140
130
  }
141
131
 
@@ -145,7 +135,7 @@ class User extends BaseState {
145
135
  * @param {string} status passport status
146
136
  */
147
137
  async _setPassportStatusById({ did, id, status } = {}) {
148
- const exist = await super.findOne({ did });
138
+ const exist = await this.findOne({ did });
149
139
 
150
140
  if (!exist) {
151
141
  throw new Error('did does not exist');
@@ -4,8 +4,8 @@ const BaseState = require('./base');
4
4
  const { validateWebhook } = require('../validators/webhook');
5
5
 
6
6
  class WebhookState extends BaseState {
7
- constructor(baseDir, options = {}) {
8
- super(baseDir, { filename: 'webhook.db', ...options });
7
+ constructor(baseDir, config = {}) {
8
+ super(baseDir, { filename: 'webhook.db', ...config });
9
9
  }
10
10
 
11
11
  async create(info, { mock } = {}) {
@@ -30,7 +30,7 @@ class WebhookState extends BaseState {
30
30
  return data;
31
31
  }
32
32
 
33
- const webhook = await this.asyncDB.insert(data);
33
+ const webhook = await this.insert(data);
34
34
  return webhook;
35
35
  }
36
36
 
@@ -46,7 +46,7 @@ class WebhookState extends BaseState {
46
46
  throw new Error('webhookId should not be empty');
47
47
  }
48
48
  const webhook = await this.findOne(id);
49
- const num = await this.asyncDB.remove({ _id: id });
49
+ const num = await this.remove({ _id: id });
50
50
  if (num <= 0) {
51
51
  throw new Error(`${id} does not exist`);
52
52
  }
@@ -56,7 +56,7 @@ class WebhookState extends BaseState {
56
56
 
57
57
  async findOne(id) {
58
58
  try {
59
- const webhook = await this.asyncDB.findOne({ _id: id });
59
+ const webhook = await super.findOne({ _id: id });
60
60
 
61
61
  return webhook;
62
62
  } catch (error) {
@@ -76,6 +76,7 @@ const { isBeforeInstalled, expandBundle, findInterfacePortByName, validateBlockl
76
76
  const getBlockletEngineNameByPlatform = (blockletMeta) => getBlockletEngine(blockletMeta).interpreter;
77
77
 
78
78
  const noop = () => {};
79
+ const noopAsync = async () => {};
79
80
 
80
81
  const statusMap = {
81
82
  online: BlockletStatus.running,
@@ -86,7 +87,7 @@ const statusMap = {
86
87
  };
87
88
 
88
89
  const PRIVATE_NODE_ENVS = [
89
- // 'NEDB_MULTI_PORT', // FIXME: 排查 abtnode 对外提供的 SDK(比如 @abtnode/queue), SDK 中不要自动使用 NEDB_MULTI_PORT 环境变量
90
+ 'NEDB_MULTI_PORT',
90
91
  'ABT_NODE_UPDATER_PORT',
91
92
  'ABT_NODE_SESSION_TTL',
92
93
  'ABT_NODE_ROUTER_PROVIDER',
@@ -412,7 +413,7 @@ const getHealthyCheckTimeout = (blocklet, { checkHealthImmediately } = {}) => {
412
413
  */
413
414
  const startBlockletProcess = async (
414
415
  blocklet,
415
- { preStart = noop, nodeEnvironments, nodeInfo, e2eMode, skippedProcessIds = [] } = {}
416
+ { preStart = noop, postStart = noopAsync, nodeEnvironments, nodeInfo, e2eMode, skippedProcessIds = [] } = {}
416
417
  ) => {
417
418
  if (!blocklet) {
418
419
  throw new Error('blocklet should not be empty');
@@ -487,8 +488,12 @@ const startBlockletProcess = async (
487
488
  if (status === BlockletStatus.error) {
488
489
  throw new Error(`${processId} is not running within 5 seconds`);
489
490
  }
490
-
491
491
  logger.info('blocklet started', { processId, status });
492
+
493
+ // run hook
494
+ postStart(b, { env }).catch((err) => {
495
+ logger.error('blocklet post start failed', { processId, error: err });
496
+ });
492
497
  },
493
498
  { parallel: true }
494
499
  );
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.8.16",
6
+ "version": "1.8.19",
7
7
  "description": "",
8
8
  "main": "lib/index.js",
9
9
  "files": [
@@ -19,33 +19,31 @@
19
19
  "author": "wangshijun <wangshijun2010@gmail.com> (http://github.com/wangshijun)",
20
20
  "license": "MIT",
21
21
  "dependencies": {
22
- "@abtnode/auth": "1.8.16",
23
- "@abtnode/certificate-manager": "1.8.16",
24
- "@abtnode/constant": "1.8.16",
25
- "@abtnode/cron": "1.8.16",
26
- "@abtnode/db": "1.8.16",
27
- "@abtnode/logger": "1.8.16",
28
- "@abtnode/queue": "1.8.16",
29
- "@abtnode/rbac": "1.8.16",
30
- "@abtnode/router-provider": "1.8.16",
31
- "@abtnode/static-server": "1.8.16",
32
- "@abtnode/timemachine": "1.8.16",
33
- "@abtnode/util": "1.8.16",
34
- "@arcblock/did": "1.17.17",
22
+ "@abtnode/auth": "1.8.19",
23
+ "@abtnode/certificate-manager": "1.8.19",
24
+ "@abtnode/constant": "1.8.19",
25
+ "@abtnode/cron": "1.8.19",
26
+ "@abtnode/db": "1.8.19",
27
+ "@abtnode/logger": "1.8.19",
28
+ "@abtnode/queue": "1.8.19",
29
+ "@abtnode/rbac": "1.8.19",
30
+ "@abtnode/router-provider": "1.8.19",
31
+ "@abtnode/static-server": "1.8.19",
32
+ "@abtnode/timemachine": "1.8.19",
33
+ "@abtnode/util": "1.8.19",
34
+ "@arcblock/did": "1.17.19",
35
35
  "@arcblock/did-motif": "^1.1.10",
36
- "@arcblock/did-util": "1.17.17",
37
- "@arcblock/event-hub": "1.17.17",
38
- "@arcblock/jwt": "^1.17.17",
36
+ "@arcblock/did-util": "1.17.19",
37
+ "@arcblock/event-hub": "1.17.19",
38
+ "@arcblock/jwt": "^1.17.19",
39
39
  "@arcblock/pm2-events": "^0.0.5",
40
- "@arcblock/vc": "1.17.17",
41
- "@blocklet/meta": "1.8.16",
42
- "@blocklet/sdk": "1.8.16",
40
+ "@arcblock/vc": "1.17.19",
41
+ "@blocklet/meta": "1.8.19",
42
+ "@blocklet/sdk": "1.8.19",
43
43
  "@fidm/x509": "^1.2.1",
44
- "@nedb/core": "^1.3.4",
45
- "@nedb/multi": "^1.3.4",
46
- "@ocap/mcrypto": "1.17.17",
47
- "@ocap/util": "1.17.17",
48
- "@ocap/wallet": "1.17.17",
44
+ "@ocap/mcrypto": "1.17.19",
45
+ "@ocap/util": "1.17.19",
46
+ "@ocap/wallet": "1.17.19",
49
47
  "@slack/webhook": "^5.0.4",
50
48
  "axios": "^0.27.2",
51
49
  "axon": "^2.0.3",
@@ -82,5 +80,5 @@
82
80
  "express": "^4.18.1",
83
81
  "jest": "^27.5.1"
84
82
  },
85
- "gitHead": "2605cf6ebf2a0c3bb5524cb0f1385ad565fd85d6"
83
+ "gitHead": "19d3e21ad3658e79a3ec60394d6c77793af7deb3"
86
84
  }