tspace-mysql 1.9.4 → 1.9.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +376 -72
- package/dist/cli/dump/db.js +3 -15
- package/dist/cli/dump/db.js.map +1 -1
- package/dist/cli/index.js +0 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/migrations/make-db.js +1 -1
- package/dist/cli/migrations/make-db.js.map +1 -1
- package/dist/cli/migrations/make-model.js +1 -6
- package/dist/cli/migrations/make-model.js.map +1 -1
- package/dist/lib/config/index.d.ts +6 -5
- package/dist/lib/config/index.js +18 -8
- package/dist/lib/config/index.js.map +1 -1
- package/dist/lib/constants/index.d.ts +1 -1
- package/dist/lib/constants/index.js +1 -1
- package/dist/lib/constants/index.js.map +1 -1
- package/dist/lib/core/Abstracts/AbstractBuilder.d.ts +2 -1
- package/dist/lib/core/Abstracts/AbstractDB.d.ts +5 -3
- package/dist/lib/core/Abstracts/AbstractDB.js.map +1 -1
- package/dist/lib/core/Abstracts/AbstractModel.d.ts +1 -2
- package/dist/lib/core/Abstracts/AbstractModel.js +0 -1
- package/dist/lib/core/Abstracts/AbstractModel.js.map +1 -1
- package/dist/lib/core/Abstracts/AbstractView.d.ts +2 -1
- package/dist/lib/core/Abstracts/AbstractView.js.map +1 -1
- package/dist/lib/core/Blueprint.d.ts +13 -3
- package/dist/lib/core/Blueprint.js +16 -1
- package/dist/lib/core/Blueprint.js.map +1 -1
- package/dist/lib/core/Builder.d.ts +172 -19
- package/dist/lib/core/Builder.js +564 -197
- package/dist/lib/core/Builder.js.map +1 -1
- package/dist/lib/core/Cache/DBCache.js +6 -5
- package/dist/lib/core/Cache/DBCache.js.map +1 -1
- package/dist/lib/core/Cache/index.js +1 -1
- package/dist/lib/core/Cache/index.js.map +1 -1
- package/dist/lib/core/Contracts/Audit.d.ts +5 -3
- package/dist/lib/core/Contracts/Audit.js +18 -2
- package/dist/lib/core/Contracts/Audit.js.map +1 -1
- package/dist/lib/core/DB.d.ts +148 -190
- package/dist/lib/core/DB.js +459 -525
- package/dist/lib/core/DB.js.map +1 -1
- package/dist/lib/core/Driver/index.d.ts +40 -15
- package/dist/lib/core/Driver/index.js +3 -0
- package/dist/lib/core/Driver/index.js.map +1 -1
- package/dist/lib/core/Driver/mariadb/MariadbDriver.d.ts +3 -2
- package/dist/lib/core/Driver/mariadb/MariadbDriver.js +7 -5
- package/dist/lib/core/Driver/mariadb/MariadbDriver.js.map +1 -1
- package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.d.ts +42 -17
- package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js +281 -154
- package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js.map +1 -1
- package/dist/lib/core/Driver/mongodb/MongodbDriver.d.ts +4 -3
- package/dist/lib/core/Driver/mongodb/MongodbDriver.js +7 -5
- package/dist/lib/core/Driver/mongodb/MongodbDriver.js.map +1 -1
- package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.d.ts +40 -15
- package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js +205 -157
- package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js.map +1 -1
- package/dist/lib/core/Driver/mysql/MysqlDriver.d.ts +3 -2
- package/dist/lib/core/Driver/mysql/MysqlDriver.js +6 -14
- package/dist/lib/core/Driver/mysql/MysqlDriver.js.map +1 -1
- package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.d.ts +42 -17
- package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js +251 -144
- package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js.map +1 -1
- package/dist/lib/core/Driver/postgres/PostgresDriver.d.ts +3 -2
- package/dist/lib/core/Driver/postgres/PostgresDriver.js +7 -5
- package/dist/lib/core/Driver/postgres/PostgresDriver.js.map +1 -1
- package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.d.ts +45 -19
- package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js +471 -287
- package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js.map +1 -1
- package/dist/lib/core/Driver/sqlite/SqliteDriver.d.ts +3 -2
- package/dist/lib/core/Driver/sqlite/SqliteDriver.js +8 -6
- package/dist/lib/core/Driver/sqlite/SqliteDriver.js.map +1 -1
- package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.d.ts +47 -19
- package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js +331 -203
- package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js.map +1 -1
- package/dist/lib/core/Model.d.ts +255 -52
- package/dist/lib/core/Model.js +459 -117
- package/dist/lib/core/Model.js.map +1 -1
- package/dist/lib/core/Package.d.ts +5 -0
- package/dist/lib/core/Package.js +7 -2
- package/dist/lib/core/Package.js.map +1 -1
- package/dist/lib/core/Pool.d.ts +1 -1
- package/dist/lib/core/Pool.js +53 -75
- package/dist/lib/core/Pool.js.map +1 -1
- package/dist/lib/core/Queue/index.d.ts +2 -11
- package/dist/lib/core/Queue/index.js +3 -3
- package/dist/lib/core/Queue/index.js.map +1 -1
- package/dist/lib/core/Queue/types.d.ts +32 -3
- package/dist/lib/core/Queue/worker-lock.d.ts +17 -0
- package/dist/lib/core/Queue/worker-lock.js +28 -0
- package/dist/lib/core/Queue/worker-lock.js.map +1 -0
- package/dist/lib/core/Queue/worker.d.ts +37 -23
- package/dist/lib/core/Queue/worker.js +385 -171
- package/dist/lib/core/Queue/worker.js.map +1 -1
- package/dist/lib/core/RelationManager.js +1 -1
- package/dist/lib/core/RelationManager.js.map +1 -1
- package/dist/lib/core/Repository.d.ts +164 -29
- package/dist/lib/core/Repository.js +181 -40
- package/dist/lib/core/Repository.js.map +1 -1
- package/dist/lib/core/Schema.d.ts +11 -7
- package/dist/lib/core/Schema.js +249 -80
- package/dist/lib/core/Schema.js.map +1 -1
- package/dist/lib/core/SqlLike.js +4 -4
- package/dist/lib/core/SqlLike.js.map +1 -1
- package/dist/lib/core/StateManager.d.ts +19 -0
- package/dist/lib/core/StateManager.js +9 -4
- package/dist/lib/core/StateManager.js.map +1 -1
- package/dist/lib/core/UtilityTypes.d.ts +17 -3
- package/dist/lib/core/UtilityTypes.js.map +1 -1
- package/dist/lib/core/View.d.ts +3 -1
- package/dist/lib/core/View.js +18 -25
- package/dist/lib/core/View.js.map +1 -1
- package/dist/lib/core/index.d.ts +2 -0
- package/dist/lib/core/index.js +3 -1
- package/dist/lib/core/index.js.map +1 -1
- package/dist/lib/types/index.d.ts +77 -90
- package/dist/lib/types/repository/index.d.ts +18 -26
- package/dist/lib/utils/index.d.ts +7 -3
- package/dist/lib/utils/index.js +99 -37
- package/dist/lib/utils/index.js.map +1 -1
- package/package.json +1 -2
- package/dist/cli/dump/table.d.ts +0 -4
- package/dist/cli/dump/table.js +0 -41
- package/dist/cli/dump/table.js.map +0 -1
|
@@ -5,6 +5,7 @@ const Blueprint_1 = require("../Blueprint");
|
|
|
5
5
|
const DB_1 = require("../DB");
|
|
6
6
|
;
|
|
7
7
|
const Model_1 = require("../Model");
|
|
8
|
+
const worker_lock_1 = require("./worker-lock");
|
|
8
9
|
const QUEUE_STATUS = {
|
|
9
10
|
dispatch: 'Dispatch',
|
|
10
11
|
receive: 'Receive',
|
|
@@ -14,6 +15,10 @@ const QUEUE_STATUS = {
|
|
|
14
15
|
wokeUp: 'Woke up',
|
|
15
16
|
failed: 'Failed',
|
|
16
17
|
waiting: 'Waiting',
|
|
18
|
+
cleanup: 'Cleanup',
|
|
19
|
+
currently: {
|
|
20
|
+
processing: 'Currently processing'
|
|
21
|
+
},
|
|
17
22
|
retry: {
|
|
18
23
|
attempts: 'Attempts',
|
|
19
24
|
failed: 'Retry Failed',
|
|
@@ -23,50 +28,67 @@ const QUEUE_STATUS = {
|
|
|
23
28
|
const STATUS = {
|
|
24
29
|
'pending': 'pending',
|
|
25
30
|
'active': 'active',
|
|
31
|
+
'sent': 'sent',
|
|
26
32
|
'completed': 'completed',
|
|
27
33
|
'failed': 'failed'
|
|
28
34
|
};
|
|
29
35
|
const schema = {
|
|
30
36
|
id: Blueprint_1.Blueprint.int().primary().autoIncrement(),
|
|
31
37
|
uuid: Blueprint_1.Blueprint.varchar(36).null(),
|
|
32
|
-
name: Blueprint_1.Blueprint.varchar(255)
|
|
38
|
+
name: Blueprint_1.Blueprint.varchar(255)
|
|
39
|
+
.notNull()
|
|
33
40
|
.index()
|
|
34
41
|
.compositeIndex([
|
|
35
42
|
"status", "available_at", "priority", "id"
|
|
36
43
|
]),
|
|
37
44
|
status: Blueprint_1.Blueprint
|
|
38
|
-
.enum(
|
|
45
|
+
.enum(STATUS)
|
|
39
46
|
.notNull()
|
|
40
|
-
.default(STATUS.pending)
|
|
41
|
-
.index(),
|
|
47
|
+
.default(STATUS.pending),
|
|
42
48
|
priority: Blueprint_1.Blueprint.int().default(0),
|
|
43
|
-
payload: Blueprint_1.Blueprint.
|
|
49
|
+
payload: Blueprint_1.Blueprint.text().null(),
|
|
44
50
|
result: Blueprint_1.Blueprint.text().null(),
|
|
45
51
|
error: Blueprint_1.Blueprint.text().null(),
|
|
46
52
|
metadata: Blueprint_1.Blueprint.text().null(),
|
|
53
|
+
unique_key: Blueprint_1.Blueprint.varchar(255).null(),
|
|
47
54
|
attempts: Blueprint_1.Blueprint.int().default(0),
|
|
48
55
|
max_attempts: Blueprint_1.Blueprint.int().default(3),
|
|
49
56
|
delay_ms: Blueprint_1.Blueprint.int().default(0),
|
|
50
57
|
locked_by: Blueprint_1.Blueprint.text().null(),
|
|
51
|
-
locked_at: Blueprint_1.Blueprint.
|
|
52
|
-
available_at: Blueprint_1.Blueprint.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
58
|
+
locked_at: Blueprint_1.Blueprint.timestamp().null(),
|
|
59
|
+
available_at: Blueprint_1.Blueprint.timestamp().notNull(),
|
|
60
|
+
sent_at: Blueprint_1.Blueprint.timestamp().null(),
|
|
61
|
+
completed_at: Blueprint_1.Blueprint.timestamp().null(),
|
|
62
|
+
created_at: Blueprint_1.Blueprint.timestamp().null(),
|
|
63
|
+
updated_at: Blueprint_1.Blueprint.timestamp().null()
|
|
56
64
|
};
|
|
57
65
|
class Worker extends Model_1.Model {
|
|
66
|
+
DRIVER = DB_1.DB.driver();
|
|
58
67
|
HOSTNAME = String(process.env?.hostname ?? 'unknown');
|
|
59
68
|
INSPECT_EXEC = false;
|
|
60
69
|
STOPPING = false;
|
|
61
70
|
IS_FLUSHING = false;
|
|
62
71
|
ACTIVE_JOBS = 0;
|
|
63
|
-
MAX_IDLE_RETRIES = 5;
|
|
64
72
|
BATCH_SIZE = 1000;
|
|
65
|
-
|
|
73
|
+
BATCH_WAIT_MS = 100;
|
|
74
|
+
CONCURRENCY = 1;
|
|
75
|
+
MAX_CONCURRENCY = 100;
|
|
76
|
+
LOCK_RECOVERY_MS = 5 * 60 * 1000;
|
|
77
|
+
CONNECTED_POOL = null;
|
|
78
|
+
JOB_TIMERS = new Map();
|
|
79
|
+
IDLE = {
|
|
80
|
+
maxRetry: 5,
|
|
81
|
+
interval: 1000
|
|
82
|
+
};
|
|
66
83
|
POLL = {
|
|
67
|
-
|
|
84
|
+
intervalId: null,
|
|
68
85
|
interval: 1000 * 60
|
|
69
86
|
};
|
|
87
|
+
CLEANUP = {
|
|
88
|
+
intervalId: null,
|
|
89
|
+
interval: 1000 * 60 * 60 * 24,
|
|
90
|
+
statuses: ['completed']
|
|
91
|
+
};
|
|
70
92
|
BUFFER = {
|
|
71
93
|
jobs: [],
|
|
72
94
|
timeout: null
|
|
@@ -79,13 +101,34 @@ class Worker extends Model_1.Model {
|
|
|
79
101
|
this.useSchema(schema);
|
|
80
102
|
this.useTable(this.$state.get("TABLE_JOB"));
|
|
81
103
|
}
|
|
104
|
+
WorkerRepository({ onTrx = false } = {}) {
|
|
105
|
+
const pool = this.CONNECTED_POOL;
|
|
106
|
+
return new Worker()
|
|
107
|
+
.when(!onTrx && pool != null, (q) => q.bind(pool));
|
|
108
|
+
}
|
|
109
|
+
WorkerLockRepository({ onTrx = false } = {}) {
|
|
110
|
+
const pool = this.CONNECTED_POOL;
|
|
111
|
+
return new worker_lock_1.WorkerLock()
|
|
112
|
+
.when(!onTrx && pool != null, (q) => q.bind(pool));
|
|
113
|
+
}
|
|
82
114
|
async initialize(opts = {}) {
|
|
83
|
-
|
|
84
|
-
|
|
115
|
+
if (opts.connection && Object.keys(opts.connection).length) {
|
|
116
|
+
if (typeof opts.connection.driver === 'function') {
|
|
117
|
+
this.CONNECTED_POOL = opts.connection;
|
|
118
|
+
this.DRIVER = opts.connection.driver();
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
this.CONNECTED_POOL = DB_1.DB.getConnection(opts.connection);
|
|
122
|
+
this.DRIVER = opts.connection.driver ?? 'mysql';
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (this.DRIVER === 'mongodb') {
|
|
85
126
|
throw new Error('Queue is not supported for MongoDB. Use a different driver or disable queue features.');
|
|
86
127
|
}
|
|
87
|
-
|
|
88
|
-
|
|
128
|
+
if (opts.lockRecoveryMs) {
|
|
129
|
+
this.LOCK_RECOVERY_MS = opts.lockRecoveryMs;
|
|
130
|
+
}
|
|
131
|
+
await this._initializeWorkers();
|
|
89
132
|
if (opts.inspect) {
|
|
90
133
|
this.INSPECT_EXEC = true;
|
|
91
134
|
console.log(`\x1b[34mQueue:\x1b[0m \x1b[32mJob processing started\x1b[0m`);
|
|
@@ -97,14 +140,21 @@ class Worker extends Model_1.Model {
|
|
|
97
140
|
this.HOSTNAME = opts.hostname;
|
|
98
141
|
}
|
|
99
142
|
if (opts.maxIdleRetries) {
|
|
100
|
-
this.
|
|
143
|
+
this.IDLE.maxRetry = opts.maxIdleRetries;
|
|
101
144
|
}
|
|
102
145
|
if (opts.poll?.enabled) {
|
|
103
146
|
this.POLL.interval = opts.poll?.interval ?? this.POLL.interval;
|
|
104
|
-
this.POLL.
|
|
147
|
+
this.POLL.intervalId = setInterval(() => {
|
|
105
148
|
this._pollWorkerJobs();
|
|
106
149
|
}, this.POLL.interval);
|
|
107
150
|
}
|
|
151
|
+
if (opts.cleanup?.enabled) {
|
|
152
|
+
this.CLEANUP.interval = opts.cleanup?.interval ?? this.CLEANUP.interval;
|
|
153
|
+
this.CLEANUP.statuses = opts.cleanup.statuses ?? ['completed'];
|
|
154
|
+
this.CLEANUP.intervalId = setInterval(() => {
|
|
155
|
+
this._cleanupWorkerJobs();
|
|
156
|
+
}, this.CLEANUP.interval);
|
|
157
|
+
}
|
|
108
158
|
return this;
|
|
109
159
|
}
|
|
110
160
|
async shutdown() {
|
|
@@ -112,16 +162,20 @@ class Worker extends Model_1.Model {
|
|
|
112
162
|
if (this.INSPECT_EXEC) {
|
|
113
163
|
console.log([
|
|
114
164
|
`\x1b[34mQueue:\x1b[0m`,
|
|
115
|
-
`\x1b[38;2;77;215;
|
|
165
|
+
`\x1b[38;2;77;215;240m${QUEUE_STATUS.currently.processing}\x1b[0m`,
|
|
116
166
|
`${this.ACTIVE_JOBS} job(s)`
|
|
117
167
|
].join(' '));
|
|
118
168
|
}
|
|
119
|
-
await this.
|
|
169
|
+
await this._waitMs(200);
|
|
170
|
+
}
|
|
171
|
+
await this._waitMs(2000);
|
|
172
|
+
if (this.POLL.intervalId) {
|
|
173
|
+
clearInterval(this.POLL.intervalId);
|
|
174
|
+
this.POLL.intervalId = null;
|
|
120
175
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
this.POLL.timeout = null;
|
|
176
|
+
if (this.CLEANUP.intervalId) {
|
|
177
|
+
clearInterval(this.CLEANUP.intervalId);
|
|
178
|
+
this.CLEANUP.intervalId = null;
|
|
125
179
|
}
|
|
126
180
|
this.STOPPING = true;
|
|
127
181
|
if (this.INSPECT_EXEC) {
|
|
@@ -129,8 +183,12 @@ class Worker extends Model_1.Model {
|
|
|
129
183
|
}
|
|
130
184
|
}
|
|
131
185
|
async flush() {
|
|
132
|
-
const jobs = await
|
|
133
|
-
|
|
186
|
+
const jobs = await this.WorkerRepository()
|
|
187
|
+
.count('id');
|
|
188
|
+
await this.WorkerRepository()
|
|
189
|
+
.truncate({ force: true, dropFK: true });
|
|
190
|
+
await this.WorkerLockRepository()
|
|
191
|
+
.truncate({ force: true, dropFK: true });
|
|
134
192
|
if (this.INSPECT_EXEC) {
|
|
135
193
|
console.log(`\x1b[34mQueue:\x1b[0m \x1b[31mFlush all jobs (${jobs} jobs)\x1b[0m`);
|
|
136
194
|
}
|
|
@@ -142,21 +200,23 @@ class Worker extends Model_1.Model {
|
|
|
142
200
|
q.where('name', 'LIKE', `%${DB_1.DB.escape(name)}%`);
|
|
143
201
|
return q;
|
|
144
202
|
};
|
|
145
|
-
const completed = await where(
|
|
146
|
-
const active = await where(
|
|
147
|
-
const pending = await where(
|
|
148
|
-
const failed = await where(
|
|
149
|
-
const
|
|
203
|
+
const completed = await where(this.WorkerRepository()).where('status', 'completed').count();
|
|
204
|
+
const active = await where(this.WorkerRepository()).where('status', 'active').count();
|
|
205
|
+
const pending = await where(this.WorkerRepository()).where('status', 'pending').count();
|
|
206
|
+
const failed = await where(this.WorkerRepository()).where('status', 'failed').count();
|
|
207
|
+
const sent = await where(this.WorkerRepository()).where('status', 'sent').count();
|
|
208
|
+
const total = await where(this.WorkerRepository()).count();
|
|
150
209
|
return {
|
|
151
210
|
total,
|
|
152
211
|
completed,
|
|
153
212
|
active,
|
|
154
213
|
pending,
|
|
155
214
|
failed,
|
|
215
|
+
sent
|
|
156
216
|
};
|
|
157
217
|
}
|
|
158
218
|
async getJobStats(name) {
|
|
159
|
-
const rows = await
|
|
219
|
+
const rows = await this.WorkerRepository()
|
|
160
220
|
.select('name', 'status')
|
|
161
221
|
.selectRaw('COUNT(1) AS total')
|
|
162
222
|
.when(name, (q) => q.where('name', 'LIKE', `%${DB_1.DB.escape(name)}%`))
|
|
@@ -175,6 +235,7 @@ class Worker extends Model_1.Model {
|
|
|
175
235
|
active: 0,
|
|
176
236
|
pending: 0,
|
|
177
237
|
failed: 0,
|
|
238
|
+
sent: 0,
|
|
178
239
|
});
|
|
179
240
|
}
|
|
180
241
|
const stats = map.get(name);
|
|
@@ -186,56 +247,69 @@ class Worker extends Model_1.Model {
|
|
|
186
247
|
stats.pending = total;
|
|
187
248
|
else if (status === 'failed')
|
|
188
249
|
stats.failed = total;
|
|
250
|
+
else if (status === 'sent')
|
|
251
|
+
stats.sent = total;
|
|
189
252
|
}
|
|
190
253
|
return Array.from(map.values());
|
|
191
254
|
}
|
|
192
255
|
async getJobs(name) {
|
|
193
|
-
const jobs = await
|
|
256
|
+
const jobs = await this.WorkerRepository()
|
|
194
257
|
.when(name != null, (q) => q.where('name', 'LIKE', `%${DB_1.DB.escape(name)}%`))
|
|
195
258
|
.findMany();
|
|
196
259
|
return jobs;
|
|
197
260
|
}
|
|
198
261
|
async getNames() {
|
|
199
|
-
return await
|
|
262
|
+
return await this.WorkerRepository()
|
|
263
|
+
.select('name')
|
|
264
|
+
.toArray('name');
|
|
200
265
|
}
|
|
201
266
|
async add(name, payload, opts = {}) {
|
|
202
267
|
return new Promise((resolve, reject) => {
|
|
203
268
|
const jobData = {
|
|
204
|
-
name,
|
|
205
|
-
payload: payload == null ? null : this._safeJsonStringify(payload),
|
|
269
|
+
name: name.slice(0, 255),
|
|
206
270
|
status: 'pending',
|
|
207
|
-
|
|
271
|
+
payload: payload == null ? null : this._safeJsonStringify(payload),
|
|
208
272
|
attempts: 0,
|
|
209
273
|
max_attempts: opts.maxAttempts ?? 3,
|
|
210
|
-
|
|
274
|
+
priority: opts.priority ?? 0,
|
|
211
275
|
delay_ms: opts.delayMs ?? 0,
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
276
|
+
unique_key: opts.uniqueKey?.slice(0, 255) ?? null,
|
|
277
|
+
metadata: opts.metadata
|
|
278
|
+
? this._safeJsonStringify(opts.metadata)
|
|
279
|
+
: null,
|
|
280
|
+
available_at: opts.delayMs
|
|
281
|
+
? this.$utils.timestamp(new Date(Date.now() + opts.delayMs))
|
|
282
|
+
: this.$utils.timestamp(new Date()),
|
|
215
283
|
};
|
|
216
284
|
this.BUFFER.jobs.push({ jobData, resolve, reject });
|
|
217
285
|
if (this.BUFFER.jobs.length >= this.BATCH_SIZE) {
|
|
218
286
|
this._flushBuffer();
|
|
219
287
|
}
|
|
220
288
|
else if (!this.BUFFER.timeout) {
|
|
221
|
-
this.BUFFER.timeout = setTimeout(() => this._flushBuffer(), this.
|
|
289
|
+
this.BUFFER.timeout = setTimeout(() => this._flushBuffer(), this.BATCH_WAIT_MS);
|
|
222
290
|
}
|
|
223
291
|
});
|
|
224
292
|
}
|
|
225
|
-
async process(name, handler, opts
|
|
226
|
-
interval
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
293
|
+
async process(name, handler, opts) {
|
|
294
|
+
if (opts.interval == null) {
|
|
295
|
+
opts.interval = this.IDLE.interval;
|
|
296
|
+
}
|
|
297
|
+
;
|
|
298
|
+
opts.concurrency = Math.min(opts.concurrency ?? this.CONCURRENCY, this.MAX_CONCURRENCY);
|
|
299
|
+
if (!this.WORKER_STATE.has(name)) {
|
|
300
|
+
this.WORKER_STATE.set(name, {
|
|
301
|
+
handler: handler,
|
|
302
|
+
idle: 0,
|
|
303
|
+
sleeping: false,
|
|
304
|
+
running: 0,
|
|
305
|
+
opts: {
|
|
306
|
+
concurrency: opts.concurrency,
|
|
307
|
+
interval: opts.interval,
|
|
308
|
+
onSuccess: opts.onSuccess,
|
|
309
|
+
onError: opts.onError,
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
}
|
|
239
313
|
if (this.INSPECT_EXEC) {
|
|
240
314
|
console.log([
|
|
241
315
|
'\x1b[34mQueue:\x1b[0m',
|
|
@@ -249,17 +323,19 @@ class Worker extends Model_1.Model {
|
|
|
249
323
|
const state = this.WORKER_STATE.get(name);
|
|
250
324
|
if (!state)
|
|
251
325
|
return;
|
|
252
|
-
if (state.running >=
|
|
253
|
-
const delayMs = opts.interval ?? 1000;
|
|
326
|
+
if (state.running >= opts.concurrency) {
|
|
254
327
|
state.running--;
|
|
255
|
-
setTimeout(dispatch,
|
|
328
|
+
setTimeout(dispatch, opts.interval);
|
|
256
329
|
return;
|
|
257
330
|
}
|
|
258
|
-
const capacity =
|
|
259
|
-
|
|
331
|
+
const capacity = opts.concurrency - state.running;
|
|
332
|
+
if (capacity <= 0) {
|
|
333
|
+
await this._waitMs(2000);
|
|
334
|
+
}
|
|
335
|
+
const jobs = await this._findJobs(name, capacity);
|
|
260
336
|
if (!jobs || jobs.length === 0) {
|
|
261
337
|
state.idle++;
|
|
262
|
-
if (state.idle
|
|
338
|
+
if (state.idle > this.IDLE.maxRetry) {
|
|
263
339
|
state.sleeping = true;
|
|
264
340
|
if (this.INSPECT_EXEC) {
|
|
265
341
|
console.log([
|
|
@@ -270,28 +346,28 @@ class Worker extends Model_1.Model {
|
|
|
270
346
|
}
|
|
271
347
|
return;
|
|
272
348
|
}
|
|
273
|
-
|
|
274
|
-
setTimeout(dispatch, delayMs);
|
|
349
|
+
setTimeout(dispatch, opts.interval);
|
|
275
350
|
return;
|
|
276
351
|
}
|
|
277
352
|
state.idle = 0;
|
|
278
|
-
await Promise.all(jobs.map(job => this._runJob(name, job, state)));
|
|
353
|
+
await Promise.all(jobs.map(job => this._runJob({ name, job, state })));
|
|
279
354
|
setImmediate(dispatch);
|
|
280
355
|
return;
|
|
281
356
|
};
|
|
282
|
-
return dispatch();
|
|
357
|
+
return await dispatch();
|
|
283
358
|
}
|
|
284
|
-
async publish(event, payload, opts
|
|
359
|
+
async publish(event, payload, opts) {
|
|
285
360
|
const subscribers = this.EVENT_SUBSCRIBERS.get(event);
|
|
286
361
|
if (!subscribers || subscribers.size === 0) {
|
|
287
362
|
return;
|
|
288
363
|
}
|
|
289
364
|
await Promise.all([...subscribers].map(name => this.add(name, payload, opts)));
|
|
290
365
|
}
|
|
291
|
-
async subscribe(event, name, handler, opts
|
|
292
|
-
interval
|
|
293
|
-
|
|
294
|
-
|
|
366
|
+
async subscribe(event, name, handler, opts) {
|
|
367
|
+
if (opts.interval == null) {
|
|
368
|
+
opts.interval = this.IDLE.interval;
|
|
369
|
+
}
|
|
370
|
+
opts.concurrency = Math.min(opts.concurrency ?? this.CONCURRENCY, this.MAX_CONCURRENCY);
|
|
295
371
|
const jobName = `${event}.${name}`;
|
|
296
372
|
if (!this.EVENT_SUBSCRIBERS.has(event)) {
|
|
297
373
|
this.EVENT_SUBSCRIBERS.set(event, new Set());
|
|
@@ -301,25 +377,20 @@ class Worker extends Model_1.Model {
|
|
|
301
377
|
.add(jobName);
|
|
302
378
|
await this.process(jobName, handler, opts);
|
|
303
379
|
}
|
|
304
|
-
async _runJob(name, job, state) {
|
|
380
|
+
async _runJob({ name, job, state }) {
|
|
305
381
|
state.running++;
|
|
306
382
|
this.ACTIVE_JOBS++;
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
state.running--;
|
|
313
|
-
this.ACTIVE_JOBS--;
|
|
314
|
-
}, job.__job.delay_ms);
|
|
315
|
-
return;
|
|
316
|
-
}
|
|
317
|
-
await this._executeJob({ name, job, state, startTime });
|
|
383
|
+
await this._executeJob({
|
|
384
|
+
name,
|
|
385
|
+
job,
|
|
386
|
+
state
|
|
387
|
+
});
|
|
318
388
|
state.running--;
|
|
319
389
|
this.ACTIVE_JOBS--;
|
|
320
390
|
return;
|
|
321
391
|
}
|
|
322
|
-
async _executeJob({ name, job, state
|
|
392
|
+
async _executeJob({ name, job, state }) {
|
|
393
|
+
const startTime = +new Date();
|
|
323
394
|
if (this.INSPECT_EXEC) {
|
|
324
395
|
console.log([
|
|
325
396
|
'\x1b[34mQueue:\x1b[0m',
|
|
@@ -329,13 +400,21 @@ class Worker extends Model_1.Model {
|
|
|
329
400
|
].join(' '));
|
|
330
401
|
}
|
|
331
402
|
try {
|
|
403
|
+
await this.WorkerRepository()
|
|
404
|
+
.where('id', job.id)
|
|
405
|
+
.update({
|
|
406
|
+
status: 'sent',
|
|
407
|
+
sent_at: this.$utils.timestamp()
|
|
408
|
+
})
|
|
409
|
+
.void()
|
|
410
|
+
.save();
|
|
332
411
|
const result = await state.handler({
|
|
333
412
|
id: job.id,
|
|
334
413
|
name: job.name,
|
|
335
414
|
status: job.status,
|
|
336
415
|
payload: job.payload
|
|
337
416
|
});
|
|
338
|
-
await
|
|
417
|
+
await this.WorkerRepository()
|
|
339
418
|
.where('id', job.id)
|
|
340
419
|
.update({
|
|
341
420
|
status: 'completed',
|
|
@@ -345,6 +424,11 @@ class Worker extends Model_1.Model {
|
|
|
345
424
|
})
|
|
346
425
|
.void()
|
|
347
426
|
.save();
|
|
427
|
+
if (job.__job.unique_key) {
|
|
428
|
+
await this.WorkerLockRepository()
|
|
429
|
+
.where('job_id', job.id)
|
|
430
|
+
.delete();
|
|
431
|
+
}
|
|
348
432
|
const endTime = +new Date();
|
|
349
433
|
if (this.INSPECT_EXEC) {
|
|
350
434
|
console.log([
|
|
@@ -355,6 +439,9 @@ class Worker extends Model_1.Model {
|
|
|
355
439
|
`(${endTime - startTime}ms)`,
|
|
356
440
|
].join(' '));
|
|
357
441
|
}
|
|
442
|
+
if (state.opts.onSuccess) {
|
|
443
|
+
await state.opts.onSuccess(job);
|
|
444
|
+
}
|
|
358
445
|
}
|
|
359
446
|
catch (err) {
|
|
360
447
|
if (this.INSPECT_EXEC) {
|
|
@@ -365,19 +452,22 @@ class Worker extends Model_1.Model {
|
|
|
365
452
|
`job \x1b[38;5;208m${job.id}\x1b[0m`,
|
|
366
453
|
].join(' '));
|
|
367
454
|
}
|
|
368
|
-
await
|
|
455
|
+
await this.WorkerRepository()
|
|
369
456
|
.where('id', job.id)
|
|
370
457
|
.update({
|
|
371
458
|
status: 'failed',
|
|
372
459
|
error: this._safeJsonStringify({
|
|
373
|
-
message: err
|
|
374
|
-
name: err
|
|
375
|
-
stack: err
|
|
376
|
-
code: err
|
|
460
|
+
message: err?.message ?? null,
|
|
461
|
+
name: err?.name ?? null,
|
|
462
|
+
stack: err?.stack ?? null,
|
|
463
|
+
code: err?.code ?? null,
|
|
377
464
|
})
|
|
378
465
|
})
|
|
379
466
|
.void()
|
|
380
467
|
.save();
|
|
468
|
+
if (state.opts.onError) {
|
|
469
|
+
await state.opts.onError(err, job);
|
|
470
|
+
}
|
|
381
471
|
const maxAttempts = job.__job.max_attempts;
|
|
382
472
|
let attempts = job.__job.attempts;
|
|
383
473
|
while (attempts < maxAttempts) {
|
|
@@ -386,11 +476,11 @@ class Worker extends Model_1.Model {
|
|
|
386
476
|
const startTime = +new Date();
|
|
387
477
|
const result = await state.handler(job);
|
|
388
478
|
const endTime = +new Date();
|
|
389
|
-
await
|
|
479
|
+
await this.WorkerRepository()
|
|
390
480
|
.where('id', job.id)
|
|
391
481
|
.update({
|
|
392
482
|
status: 'completed',
|
|
393
|
-
attempts,
|
|
483
|
+
attempts: attempts,
|
|
394
484
|
result: this._safeJsonStringify(result),
|
|
395
485
|
completed_at: this.$utils.timestamp(),
|
|
396
486
|
})
|
|
@@ -406,6 +496,9 @@ class Worker extends Model_1.Model {
|
|
|
406
496
|
`(${endTime - startTime}ms ${attempts}/${maxAttempts})`,
|
|
407
497
|
].join(' '));
|
|
408
498
|
}
|
|
499
|
+
if (state.opts.onSuccess) {
|
|
500
|
+
await state.opts.onSuccess(job);
|
|
501
|
+
}
|
|
409
502
|
break;
|
|
410
503
|
}
|
|
411
504
|
catch (err) {
|
|
@@ -420,17 +513,17 @@ class Worker extends Model_1.Model {
|
|
|
420
513
|
].join(' '));
|
|
421
514
|
}
|
|
422
515
|
if (attempts >= maxAttempts) {
|
|
423
|
-
await
|
|
516
|
+
await this.WorkerRepository()
|
|
424
517
|
.where('id', job.id)
|
|
425
518
|
.update({
|
|
426
519
|
status: 'failed',
|
|
427
520
|
attempts,
|
|
428
521
|
error: this._safeJsonStringify({
|
|
429
522
|
retry: true,
|
|
430
|
-
message: err?.message,
|
|
431
|
-
name: err?.name,
|
|
432
|
-
stack: err?.stack,
|
|
433
|
-
code: err?.code,
|
|
523
|
+
message: err?.message ?? null,
|
|
524
|
+
name: err?.name ?? null,
|
|
525
|
+
stack: err?.stack ?? null,
|
|
526
|
+
code: err?.code ?? null,
|
|
434
527
|
}),
|
|
435
528
|
})
|
|
436
529
|
.void()
|
|
@@ -445,6 +538,9 @@ class Worker extends Model_1.Model {
|
|
|
445
538
|
'(\x1b[33mmax attempts reached\x1b[0m)',
|
|
446
539
|
].join(' '));
|
|
447
540
|
}
|
|
541
|
+
if (state.opts.onError) {
|
|
542
|
+
await state.opts.onError(err, job);
|
|
543
|
+
}
|
|
448
544
|
break;
|
|
449
545
|
}
|
|
450
546
|
await new Promise((r) => setTimeout(r, 1_000 * 2));
|
|
@@ -452,30 +548,15 @@ class Worker extends Model_1.Model {
|
|
|
452
548
|
}
|
|
453
549
|
}
|
|
454
550
|
}
|
|
455
|
-
async
|
|
456
|
-
if (this.STOPPING)
|
|
551
|
+
async _findJobs(name, limit) {
|
|
552
|
+
if (this.STOPPING || limit <= 0)
|
|
457
553
|
return [];
|
|
458
554
|
const now = this.$utils.timestamp();
|
|
459
|
-
const
|
|
460
|
-
.
|
|
461
|
-
|
|
462
|
-
.whereQuery(query => {
|
|
463
|
-
return query
|
|
555
|
+
const claimed = await DB_1.DB.transaction(async (trx) => {
|
|
556
|
+
const jobs = await this.WorkerRepository({ onTrx: true })
|
|
557
|
+
.where('name', name)
|
|
464
558
|
.where('status', 'pending')
|
|
465
|
-
.where('
|
|
466
|
-
.whereNull('locked_at');
|
|
467
|
-
})
|
|
468
|
-
.latest('priority')
|
|
469
|
-
.oldest('delay_ms')
|
|
470
|
-
.oldest('id')
|
|
471
|
-
.limit(limit)
|
|
472
|
-
.findMany();
|
|
473
|
-
if (!findJobs.length) {
|
|
474
|
-
return [];
|
|
475
|
-
}
|
|
476
|
-
return await DB_1.DB.transaction(async (trx) => {
|
|
477
|
-
const jobs = await new Worker()
|
|
478
|
-
.whereIn('id', findJobs.map(v => v.id))
|
|
559
|
+
.where('available_at', '<=', now)
|
|
479
560
|
.latest('priority')
|
|
480
561
|
.oldest('delay_ms')
|
|
481
562
|
.oldest('id')
|
|
@@ -483,28 +564,67 @@ class Worker extends Model_1.Model {
|
|
|
483
564
|
.forUpdate({ skipLocked: true })
|
|
484
565
|
.bind(trx)
|
|
485
566
|
.findMany();
|
|
486
|
-
if (!jobs.length) {
|
|
567
|
+
if (!jobs.length || this.STOPPING) {
|
|
487
568
|
return [];
|
|
488
569
|
}
|
|
489
|
-
await
|
|
570
|
+
await this.WorkerRepository({ onTrx: true })
|
|
490
571
|
.whereIn('id', jobs.map(v => v.id))
|
|
572
|
+
.where('status', 'pending')
|
|
491
573
|
.updateMany({
|
|
492
574
|
status: 'active',
|
|
493
|
-
locked_at:
|
|
575
|
+
locked_at: now,
|
|
494
576
|
locked_by: this.HOSTNAME
|
|
495
577
|
})
|
|
496
|
-
.void()
|
|
497
578
|
.bind(trx)
|
|
498
|
-
.
|
|
579
|
+
.void()
|
|
499
580
|
.save();
|
|
500
|
-
return
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
581
|
+
return jobs;
|
|
582
|
+
}, { pool: this.CONNECTED_POOL });
|
|
583
|
+
if (!claimed.length) {
|
|
584
|
+
if (this.STOPPING)
|
|
585
|
+
return [];
|
|
586
|
+
const incomingJobs = await this.WorkerRepository()
|
|
587
|
+
.select('name', 'available_at')
|
|
588
|
+
.where('name', name)
|
|
589
|
+
.where('status', 'pending')
|
|
590
|
+
.where('available_at', '>', now)
|
|
591
|
+
.findMany();
|
|
592
|
+
if (!incomingJobs.length || this.STOPPING) {
|
|
593
|
+
return [];
|
|
594
|
+
}
|
|
595
|
+
let timers = this.JOB_TIMERS.get(name);
|
|
596
|
+
if (!timers) {
|
|
597
|
+
timers = new Map();
|
|
598
|
+
this.JOB_TIMERS.set(name, timers);
|
|
599
|
+
}
|
|
600
|
+
for (const job of incomingJobs) {
|
|
601
|
+
const availableAt = +new Date(this.$utils.timestamp(job.available_at));
|
|
602
|
+
if (timers.has(availableAt))
|
|
603
|
+
continue;
|
|
604
|
+
const delay = Math.max(0, availableAt - +new Date());
|
|
605
|
+
const timer = setTimeout(() => {
|
|
606
|
+
if (timers.get(availableAt) === timer) {
|
|
607
|
+
timers.delete(availableAt);
|
|
608
|
+
}
|
|
609
|
+
if (!timers.size) {
|
|
610
|
+
this.JOB_TIMERS.delete(name);
|
|
611
|
+
}
|
|
612
|
+
if (this.STOPPING)
|
|
613
|
+
return;
|
|
614
|
+
this._wakeWorker(job.name);
|
|
615
|
+
}, Math.min(delay, 2_147_483_647));
|
|
616
|
+
timer.unref();
|
|
617
|
+
timers.set(availableAt, timer);
|
|
618
|
+
}
|
|
619
|
+
return [];
|
|
620
|
+
}
|
|
621
|
+
return claimed.map(job => ({
|
|
622
|
+
id: job.id,
|
|
623
|
+
name: job.name,
|
|
624
|
+
status: 'active',
|
|
625
|
+
payload: this._safeJsonParse(job.payload),
|
|
626
|
+
__job: job
|
|
627
|
+
}));
|
|
508
628
|
}
|
|
509
629
|
async _flushBuffer() {
|
|
510
630
|
if (this.IS_FLUSHING || this.BUFFER.jobs.length === 0)
|
|
@@ -518,15 +638,11 @@ class Worker extends Model_1.Model {
|
|
|
518
638
|
this.BUFFER.jobs = [];
|
|
519
639
|
this.IS_FLUSHING = false;
|
|
520
640
|
try {
|
|
521
|
-
const
|
|
522
|
-
const insertedJobds = await new Worker()
|
|
523
|
-
.select('id', 'name')
|
|
524
|
-
.insertMany(jobsToInsert)
|
|
525
|
-
.save();
|
|
641
|
+
const insertedJobs = await this._insertJobs(currentBatch.map(b => b.jobData));
|
|
526
642
|
if (this.INSPECT_EXEC) {
|
|
527
|
-
const names = [...new Set(
|
|
643
|
+
const names = [...new Set(insertedJobs.map(job => job.name))];
|
|
528
644
|
for (const name of names) {
|
|
529
|
-
const ids =
|
|
645
|
+
const ids = insertedJobs.filter(v => v.name === name).map(v => v.id);
|
|
530
646
|
const preview = [
|
|
531
647
|
...ids.slice(0, 3),
|
|
532
648
|
...(ids.length > 3 ? ['...', ...ids.slice(Math.max(3, ids.length - 2))] : [])
|
|
@@ -569,11 +685,75 @@ class Worker extends Model_1.Model {
|
|
|
569
685
|
}
|
|
570
686
|
}
|
|
571
687
|
}
|
|
688
|
+
async _insertJobs(jobsToInsert) {
|
|
689
|
+
const hasSomeUniqueKey = jobsToInsert.some(v => v.unique_key);
|
|
690
|
+
if (!hasSomeUniqueKey) {
|
|
691
|
+
const inserteds = await this.WorkerRepository()
|
|
692
|
+
.select('id', 'name')
|
|
693
|
+
.insertMany(jobsToInsert)
|
|
694
|
+
.stopRetry()
|
|
695
|
+
.save();
|
|
696
|
+
return inserteds;
|
|
697
|
+
}
|
|
698
|
+
const insertedJobds = [];
|
|
699
|
+
const uniqueJobs = jobsToInsert
|
|
700
|
+
.reduce((acc, job) => {
|
|
701
|
+
if (job.unique_key == null ||
|
|
702
|
+
!acc.some(v => v.name === job.name &&
|
|
703
|
+
v.unique_key === job.unique_key)) {
|
|
704
|
+
acc.push(job);
|
|
705
|
+
}
|
|
706
|
+
return acc;
|
|
707
|
+
}, []);
|
|
708
|
+
for (const job of uniqueJobs) {
|
|
709
|
+
if (!job.unique_key) {
|
|
710
|
+
const inserted = await this.WorkerRepository()
|
|
711
|
+
.select('id', 'name')
|
|
712
|
+
.insert(job)
|
|
713
|
+
.stopRetry()
|
|
714
|
+
.save();
|
|
715
|
+
if (inserted) {
|
|
716
|
+
insertedJobds.push(inserted);
|
|
717
|
+
}
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
try {
|
|
721
|
+
const inserted = await DB_1.DB.transaction(async (trx) => {
|
|
722
|
+
const worker = await this.WorkerRepository({ onTrx: true })
|
|
723
|
+
.select('id', 'name')
|
|
724
|
+
.insert(job)
|
|
725
|
+
.stopRetry()
|
|
726
|
+
.bind(trx)
|
|
727
|
+
.save();
|
|
728
|
+
await this.WorkerLockRepository({ onTrx: true })
|
|
729
|
+
.insert({
|
|
730
|
+
name: job.name,
|
|
731
|
+
unique_key: job.unique_key,
|
|
732
|
+
job_id: worker.id,
|
|
733
|
+
})
|
|
734
|
+
.stopRetry()
|
|
735
|
+
.bind(trx)
|
|
736
|
+
.void()
|
|
737
|
+
.save();
|
|
738
|
+
return worker;
|
|
739
|
+
}, { pool: this.CONNECTED_POOL });
|
|
740
|
+
if (inserted) {
|
|
741
|
+
insertedJobds.push(inserted);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
catch (e) {
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
return insertedJobds;
|
|
749
|
+
}
|
|
572
750
|
async _wakeWorker(name) {
|
|
573
751
|
const state = this.WORKER_STATE.get(name);
|
|
574
752
|
if (!state || !state.sleeping || !state.handler)
|
|
575
753
|
return;
|
|
576
754
|
const isSleeping = state.sleeping;
|
|
755
|
+
if (!isSleeping)
|
|
756
|
+
return;
|
|
577
757
|
state.sleeping = false;
|
|
578
758
|
state.idle = 0;
|
|
579
759
|
if (this.INSPECT_EXEC) {
|
|
@@ -583,52 +763,86 @@ class Worker extends Model_1.Model {
|
|
|
583
763
|
`\x1b[36m${QUEUE_STATUS.wokeUp}\x1b[0m`,
|
|
584
764
|
].join(' '));
|
|
585
765
|
}
|
|
586
|
-
|
|
587
|
-
await this.process(name, state.handler, state.opts);
|
|
588
|
-
}
|
|
766
|
+
await this.process(name, state.handler, state.opts);
|
|
589
767
|
return;
|
|
590
768
|
}
|
|
591
769
|
async _pollWorkerJobs() {
|
|
592
|
-
const jobs = await this.
|
|
770
|
+
const jobs = await this._getRecoverableJobs();
|
|
593
771
|
for (const job of jobs) {
|
|
594
772
|
this._wakeWorker(job);
|
|
595
773
|
}
|
|
596
774
|
return;
|
|
597
775
|
}
|
|
598
|
-
async
|
|
599
|
-
const
|
|
600
|
-
|
|
601
|
-
return;
|
|
602
|
-
}
|
|
603
|
-
async _getPendingOrFailedJobs() {
|
|
604
|
-
const jobsToProcess = await new Worker()
|
|
776
|
+
async _cleanupWorkerJobs() {
|
|
777
|
+
const status = this.CLEANUP.statuses;
|
|
778
|
+
const jobs = await this.WorkerRepository()
|
|
605
779
|
.select('id')
|
|
606
|
-
.whereIn('status',
|
|
607
|
-
.where('available_at', '<=', this.$utils.timestamp())
|
|
780
|
+
.whereIn('status', status)
|
|
608
781
|
.findMany();
|
|
609
|
-
await
|
|
610
|
-
.
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
})
|
|
614
|
-
.whereIn('id', jobsToProcess.map(f => f.id))
|
|
615
|
-
.void()
|
|
616
|
-
.save();
|
|
617
|
-
const jobs = await new Worker()
|
|
618
|
-
.select('name')
|
|
619
|
-
.where('status', 'pending')
|
|
620
|
-
.where('available_at', '<=', this.$utils.timestamp())
|
|
621
|
-
.groupBy('name')
|
|
622
|
-
.toArray('name');
|
|
782
|
+
await this.WorkerRepository()
|
|
783
|
+
.whereIn('id', jobs.map(job => job.id))
|
|
784
|
+
.deleteMany()
|
|
785
|
+
.catch(() => null);
|
|
623
786
|
if (this.INSPECT_EXEC) {
|
|
624
787
|
console.log([
|
|
625
788
|
'\x1b[34mQueue:\x1b[0m',
|
|
626
|
-
|
|
627
|
-
`(${jobs.length} jobs)`,
|
|
789
|
+
`\x1b[38;2;77;215;240m${QUEUE_STATUS.cleanup}\x1b[0m ${jobs.length} job(s)`,
|
|
628
790
|
].join(' '));
|
|
629
791
|
}
|
|
630
|
-
;
|
|
631
|
-
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
async _initializeWorkers() {
|
|
795
|
+
await this.WorkerRepository()
|
|
796
|
+
.sync({ force: true, index: true })
|
|
797
|
+
.catch(() => null);
|
|
798
|
+
await this.WorkerLockRepository()
|
|
799
|
+
.sync({
|
|
800
|
+
force: true,
|
|
801
|
+
index: true,
|
|
802
|
+
unique: true,
|
|
803
|
+
foreign: this.DRIVER === 'sqlite' ? false : true,
|
|
804
|
+
})
|
|
805
|
+
.catch(() => null);
|
|
806
|
+
const jobs = await this._getRecoverableJobs();
|
|
807
|
+
await Promise.all(jobs.map(job => this._wakeWorker(job)));
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
_getLockExpiredAt() {
|
|
811
|
+
return this.$utils.timestamp(new Date(+new Date() - (this.LOCK_RECOVERY_MS)));
|
|
812
|
+
}
|
|
813
|
+
async _getRecoverableJobs() {
|
|
814
|
+
const names = await DB_1.DB.transaction(async (trx) => {
|
|
815
|
+
const now = this.$utils.timestamp();
|
|
816
|
+
const expiredJobs = await this.WorkerRepository()
|
|
817
|
+
.select('id')
|
|
818
|
+
.whereIn('status', ['active', 'sent'])
|
|
819
|
+
.where('locked_at', '<=', this._getLockExpiredAt())
|
|
820
|
+
.forUpdate({ skipLocked: true })
|
|
821
|
+
.bind(trx)
|
|
822
|
+
.findMany();
|
|
823
|
+
if (expiredJobs.length) {
|
|
824
|
+
await this.WorkerRepository()
|
|
825
|
+
.updateMany({
|
|
826
|
+
status: 'pending',
|
|
827
|
+
locked_at: null,
|
|
828
|
+
locked_by: null,
|
|
829
|
+
})
|
|
830
|
+
.whereIn('id', expiredJobs.map(v => v.id))
|
|
831
|
+
.whereIn('status', ['active', 'sent'])
|
|
832
|
+
.bind(trx)
|
|
833
|
+
.void()
|
|
834
|
+
.save();
|
|
835
|
+
}
|
|
836
|
+
const jobs = await this.WorkerRepository()
|
|
837
|
+
.select('id', 'name')
|
|
838
|
+
.where('status', 'pending')
|
|
839
|
+
.where('available_at', '<=', now)
|
|
840
|
+
.forUpdate({ skipLocked: true })
|
|
841
|
+
.bind(trx)
|
|
842
|
+
.get();
|
|
843
|
+
return [...new Set(jobs.map(v => v.name))];
|
|
844
|
+
}, { pool: this.CONNECTED_POOL });
|
|
845
|
+
return names;
|
|
632
846
|
}
|
|
633
847
|
_safeJsonParse(payload) {
|
|
634
848
|
try {
|
|
@@ -659,7 +873,7 @@ class Worker extends Model_1.Model {
|
|
|
659
873
|
return payload;
|
|
660
874
|
}
|
|
661
875
|
}
|
|
662
|
-
async
|
|
876
|
+
async _waitMs(ms) {
|
|
663
877
|
return await new Promise(r => setTimeout(r, ms));
|
|
664
878
|
}
|
|
665
879
|
}
|