@meghjs/mcp 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +141 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +37 -0
- package/dist/docs/advanced/caching.md +72 -0
- package/dist/docs/advanced/database.md +328 -0
- package/dist/docs/advanced/events.md +169 -0
- package/dist/docs/advanced/file-uploads.md +141 -0
- package/dist/docs/advanced/health.md +81 -0
- package/dist/docs/advanced/logging.md +96 -0
- package/dist/docs/advanced/mail.md +439 -0
- package/dist/docs/advanced/orm/migrations.md +210 -0
- package/dist/docs/advanced/orm/models.md +291 -0
- package/dist/docs/advanced/orm/queries.md +169 -0
- package/dist/docs/advanced/orm/query-builder.md +120 -0
- package/dist/docs/advanced/orm/relations.md +179 -0
- package/dist/docs/advanced/orm/seeding.md +129 -0
- package/dist/docs/advanced/orm.md +145 -0
- package/dist/docs/advanced/plugins.md +90 -0
- package/dist/docs/advanced/queue.md +217 -0
- package/dist/docs/advanced/scheduler.md +253 -0
- package/dist/docs/advanced/testing.md +257 -0
- package/dist/docs/advanced/views.md +335 -0
- package/dist/docs/ai/mcp.md +162 -0
- package/dist/docs/cli/basic.md +133 -0
- package/dist/docs/cli/database.md +112 -0
- package/dist/docs/cli/generators.md +605 -0
- package/dist/docs/cli/scaffold/auth.md +172 -0
- package/dist/docs/cli/scaffold/domains.md +224 -0
- package/dist/docs/cli/scaffold/index.md +77 -0
- package/dist/docs/cli/scaffold/rbac.md +118 -0
- package/dist/docs/cli/scaffold/templates.md +235 -0
- package/dist/docs/core-concept/authentication.md +162 -0
- package/dist/docs/core-concept/configuration.md +268 -0
- package/dist/docs/core-concept/controller.md +350 -0
- package/dist/docs/core-concept/dependency-injection.md +213 -0
- package/dist/docs/core-concept/error-handling.md +185 -0
- package/dist/docs/core-concept/middleware.md +143 -0
- package/dist/docs/core-concept/request-context.md +110 -0
- package/dist/docs/core-concept/validation.md +355 -0
- package/dist/docs/getting-started/application.md +233 -0
- package/dist/docs/getting-started/installation.md +166 -0
- package/dist/docs/getting-started/introduction.md +136 -0
- package/dist/docs/getting-started/upgrading-0.4.md +125 -0
- package/dist/docs/getting-started/upgrading-0.5.md +293 -0
- package/dist/docs/getting-started/upgrading-0.6.md +251 -0
- package/dist/docs/getting-started/upgrading-0.7.md +225 -0
- package/dist/docs/getting-started/upgrading-megh.md +91 -0
- package/dist/docs/getting-started/upgrading-next.md +12 -0
- package/dist/docs/getting-started/upgrading.md +137 -0
- package/dist/docs/getting-started/usage.md +194 -0
- package/dist/docs/index.md +58 -0
- package/dist/docs/microservices/openapi.md +387 -0
- package/dist/docs/microservices/websocket.md +165 -0
- package/dist/docs/production/deployment.md +256 -0
- package/dist/docs/production/security.md +307 -0
- package/dist/docs/reference/api.md +999 -0
- package/dist/docs/reference/faq.md +227 -0
- package/dist/docs/reference/versioning.md +105 -0
- package/dist/docs.d.ts +30 -0
- package/dist/docs.js +126 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +22 -0
- package/dist/megh.d.ts +59 -0
- package/dist/megh.js +207 -0
- package/dist/prompts.d.ts +3 -0
- package/dist/prompts.js +47 -0
- package/dist/result.d.ts +18 -0
- package/dist/result.js +48 -0
- package/dist/server.d.ts +17 -0
- package/dist/server.js +40 -0
- package/dist/tools/context.d.ts +11 -0
- package/dist/tools/context.js +2 -0
- package/dist/tools/database.d.ts +8 -0
- package/dist/tools/database.js +58 -0
- package/dist/tools/docs.d.ts +3 -0
- package/dist/tools/docs.js +63 -0
- package/dist/tools/generate.d.ts +10 -0
- package/dist/tools/generate.js +177 -0
- package/dist/tools/project.d.ts +3 -0
- package/dist/tools/project.js +84 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +10 -0
- package/package.json +58 -4
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Queue
|
|
3
|
+
description: Background jobs with BullMQ.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Queue
|
|
7
|
+
|
|
8
|
+
Megh's queue is built on [BullMQ](https://docs.bullmq.io), which runs on
|
|
9
|
+
Redis. Both are optional peer dependencies:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm i bullmq ioredis
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
There are two ways to work with jobs: a **queue class**, which both produces and
|
|
16
|
+
consumes jobs, and a **worker class**, which only consumes a queue someone else
|
|
17
|
+
fills.
|
|
18
|
+
|
|
19
|
+
::: tip
|
|
20
|
+
For email you don't need your own queue: `mailer.to(user.email).queue(mail)`
|
|
21
|
+
uses a built-in mail queue. See [Mail](/advanced/mail#queueing-mail).
|
|
22
|
+
:::
|
|
23
|
+
|
|
24
|
+
::: tip Generate them
|
|
25
|
+
`npx megh make:queue OrderExport` and `npx megh make:worker Report --queue reports`
|
|
26
|
+
write a queue or worker to fill in. See [Generators](/cli/generators#queues-and-workers).
|
|
27
|
+
:::
|
|
28
|
+
|
|
29
|
+
## A queue
|
|
30
|
+
|
|
31
|
+
Extend `MeghQueue<T>` and decorate it with `@Queue`. `T` is the shape of the
|
|
32
|
+
job payload.
|
|
33
|
+
|
|
34
|
+
```ts [queues/email.queue.ts]
|
|
35
|
+
import { MeghQueue, Queue, JobHandler, Job } from '@meghjs/core';
|
|
36
|
+
|
|
37
|
+
export type EmailPayload = {
|
|
38
|
+
to: string;
|
|
39
|
+
subject: string;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
@Queue({
|
|
43
|
+
name: 'email',
|
|
44
|
+
adapter: { connection: { host: '127.0.0.1', port: 6379 } },
|
|
45
|
+
})
|
|
46
|
+
export class EmailQueue extends MeghQueue<EmailPayload> {
|
|
47
|
+
constructor() {
|
|
48
|
+
super();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
@JobHandler('welcome')
|
|
52
|
+
async sendWelcome(job: Job<EmailPayload>) {
|
|
53
|
+
console.log(`Sending welcome mail to ${job.data.to}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
@JobHandler('reset-password')
|
|
57
|
+
async sendReset(job: Job<EmailPayload>) {
|
|
58
|
+
console.log(`Sending reset mail to ${job.data.to}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
::: warning
|
|
64
|
+
In 0.3.0, a `@Queue` class must declare a constructor that calls
|
|
65
|
+
`super()`. Without one, resolving it through dependency injection gives it the
|
|
66
|
+
wrong queue name. Inject other services through the same constructor.
|
|
67
|
+
:::
|
|
68
|
+
|
|
69
|
+
Each `@JobHandler('name')` handles jobs added under that name. For jobs added
|
|
70
|
+
without a name — or with a name no handler matches — define a `handler` method
|
|
71
|
+
on the class, or pass `handler` in the decorator config.
|
|
72
|
+
|
|
73
|
+
### Registering
|
|
74
|
+
|
|
75
|
+
`useWorker` resolves the class through the container, which is what starts its
|
|
76
|
+
worker. Workers are closed automatically when the app shuts down.
|
|
77
|
+
|
|
78
|
+
```ts [app.ts]
|
|
79
|
+
import { Megh } from '@meghjs/core';
|
|
80
|
+
import { EmailQueue } from './queues/email.queue';
|
|
81
|
+
|
|
82
|
+
const app = Megh.createApplication();
|
|
83
|
+
|
|
84
|
+
app.useWorker([EmailQueue]);
|
|
85
|
+
|
|
86
|
+
export default app;
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Adding jobs
|
|
90
|
+
|
|
91
|
+
Inject the queue anywhere and call `add`:
|
|
92
|
+
|
|
93
|
+
```ts [services/signup.service.ts]
|
|
94
|
+
import { AppService } from '@meghjs/core';
|
|
95
|
+
import { EmailQueue } from '../queues/email.queue';
|
|
96
|
+
|
|
97
|
+
@AppService
|
|
98
|
+
export class SignupService {
|
|
99
|
+
constructor(private readonly emailQueue: EmailQueue) {}
|
|
100
|
+
|
|
101
|
+
async register(email: string) {
|
|
102
|
+
await this.emailQueue.add('welcome', {
|
|
103
|
+
to: email,
|
|
104
|
+
subject: 'Welcome aboard',
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Other producer methods:
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
// run 30 seconds from now
|
|
114
|
+
await emailQueue.delay('welcome', { to, subject }, 30_000);
|
|
115
|
+
|
|
116
|
+
// add with any BullMQ job option
|
|
117
|
+
await emailQueue.add('welcome', { to, subject }, { attempts: 3, backoff: 1000 });
|
|
118
|
+
|
|
119
|
+
// inspect and control
|
|
120
|
+
const job = await emailQueue.getJob(jobId);
|
|
121
|
+
await emailQueue.pause();
|
|
122
|
+
await emailQueue.resume();
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Producer-only queues
|
|
126
|
+
|
|
127
|
+
When another process consumes the jobs, pass `worker: false`. The queue only
|
|
128
|
+
adds jobs and never starts a worker:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
@Queue({ name: 'report', worker: false })
|
|
132
|
+
export class ReportProducer extends MeghQueue<ReportPayload> {
|
|
133
|
+
constructor() {
|
|
134
|
+
super();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## A worker
|
|
140
|
+
|
|
141
|
+
When the producer lives elsewhere, extend `MeghWorkerBase<T>` and point
|
|
142
|
+
`@MeghWorker` at the queue name. Implement `process`; the lifecycle hooks are
|
|
143
|
+
optional.
|
|
144
|
+
|
|
145
|
+
```ts [workers/report.worker.ts]
|
|
146
|
+
import { MeghWorker, MeghWorkerBase, Job } from '@meghjs/core';
|
|
147
|
+
|
|
148
|
+
export type ReportPayload = { reportId: number };
|
|
149
|
+
|
|
150
|
+
@MeghWorker({
|
|
151
|
+
queue: 'report',
|
|
152
|
+
concurrency: 5,
|
|
153
|
+
connection: { host: '127.0.0.1', port: 6379 },
|
|
154
|
+
})
|
|
155
|
+
export class ReportWorker extends MeghWorkerBase<ReportPayload> {
|
|
156
|
+
async process(job: Job<ReportPayload>) {
|
|
157
|
+
return { generated: job.data.reportId };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
onCompleted(job: Job<ReportPayload>, result: any) {
|
|
161
|
+
console.log(`Report ${job.data.reportId} done`, result);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
onFailed(job: Job<ReportPayload> | undefined, error: Error) {
|
|
165
|
+
console.error(`Report failed:`, error.message);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Register it the same way:
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
app.useWorker([EmailQueue, ReportWorker]);
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Since 0.3, decorating a class with `@MeghWorker` does not start it. A worker
|
|
177
|
+
starts when it is registered with `app.useWorker([...])` or when you call
|
|
178
|
+
`.start()` yourself.
|
|
179
|
+
|
|
180
|
+
Errors thrown by `onCompleted`, `onFailed` and `onError` are caught and logged,
|
|
181
|
+
so a faulty hook cannot crash the process. Failed jobs are always logged.
|
|
182
|
+
|
|
183
|
+
::: info
|
|
184
|
+
`bullmq` is loaded lazily, only when a queue or worker actually starts — so
|
|
185
|
+
importing `@meghjs/core` never requires Redis to be running.
|
|
186
|
+
:::
|
|
187
|
+
|
|
188
|
+
## Running without Redis
|
|
189
|
+
|
|
190
|
+
For tests and local development, switch to an in-memory driver. No `bullmq` or
|
|
191
|
+
Redis is needed:
|
|
192
|
+
|
|
193
|
+
| Driver | Behaviour |
|
|
194
|
+
|--------|-----------|
|
|
195
|
+
| `bullmq` | Default. Jobs go to Redis. |
|
|
196
|
+
| `memory` | Jobs run asynchronously in-process and honour `delay`. |
|
|
197
|
+
| `sync` | `add()` runs the job before it resolves and ignores `delay`. |
|
|
198
|
+
|
|
199
|
+
Megh picks a driver in this order: the `driver` option on `@Queue` or
|
|
200
|
+
`@MeghWorker`, then `setQueueDriver()`, then the `MEGH_QUEUE_DRIVER`
|
|
201
|
+
environment variable, then `bullmq`.
|
|
202
|
+
|
|
203
|
+
```ts [signup.service.test.ts]
|
|
204
|
+
import { setQueueDriver, waitForMemoryQueues, resetMemoryQueues } from '@meghjs/core';
|
|
205
|
+
|
|
206
|
+
beforeAll(() => setQueueDriver('memory'));
|
|
207
|
+
afterEach(() => resetMemoryQueues());
|
|
208
|
+
|
|
209
|
+
it('sends a welcome mail', async () => {
|
|
210
|
+
await signupService.register('a@example.com');
|
|
211
|
+
await waitForMemoryQueues(); // wait for queued jobs to finish
|
|
212
|
+
expect(mailer.sent).toHaveLength(1);
|
|
213
|
+
});
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
The memory driver supports `attempts`, concurrency, pause and resume, and keeps
|
|
217
|
+
failed jobs.
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Scheduler
|
|
3
|
+
description: Running methods on a cron schedule, a fixed interval, or once after startup.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Scheduler
|
|
7
|
+
|
|
8
|
+
Run code on a schedule with decorators. Mark a class with `@ScheduledTask()`,
|
|
9
|
+
then decorate its methods with `@Cron`, `@Interval` or `@Timeout`.
|
|
10
|
+
|
|
11
|
+
Cron support comes from [node-cron](https://github.com/node-cron/node-cron),
|
|
12
|
+
which is installed with `@meghjs/core`.
|
|
13
|
+
|
|
14
|
+
::: tip Generate one
|
|
15
|
+
`npx megh make:task CleanupTokens --cron "0 3 * * *"` writes a task class to
|
|
16
|
+
fill in. See [Generators](/cli/generators#scheduled-tasks).
|
|
17
|
+
:::
|
|
18
|
+
|
|
19
|
+
## A task class
|
|
20
|
+
|
|
21
|
+
```ts [src/tasks/report.task.ts]
|
|
22
|
+
import { Cron, Interval, ScheduledTask, Timeout } from '@meghjs/core';
|
|
23
|
+
import { ReportService } from '../services/report.service';
|
|
24
|
+
import { CacheWarmer } from '../services/cache-warmer.service';
|
|
25
|
+
|
|
26
|
+
@ScheduledTask()
|
|
27
|
+
export class ReportTask {
|
|
28
|
+
constructor(
|
|
29
|
+
private readonly reports: ReportService,
|
|
30
|
+
private readonly cache: CacheWarmer,
|
|
31
|
+
) {}
|
|
32
|
+
|
|
33
|
+
@Cron('0 8 * * 1-5', { timezone: 'Asia/Dhaka' }) // 08:00 on weekdays
|
|
34
|
+
async sendDailyReport() {
|
|
35
|
+
await this.reports.sendDaily();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
@Interval(60_000) // every minute
|
|
39
|
+
async pollPending() {
|
|
40
|
+
await this.reports.processPending();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
@Timeout(5_000) // once, 5 seconds after startup
|
|
44
|
+
async warmCache() {
|
|
45
|
+
await this.cache.warmUp();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`@ScheduledTask()` takes parentheses. A class can have any number of scheduled
|
|
51
|
+
methods, and one method can carry several decorators.
|
|
52
|
+
|
|
53
|
+
## Registering tasks
|
|
54
|
+
|
|
55
|
+
Pass the classes to `useScheduler`:
|
|
56
|
+
|
|
57
|
+
```ts [src/app.ts]
|
|
58
|
+
import { Megh } from '@meghjs/core';
|
|
59
|
+
import { ReportTask } from './tasks/report.task';
|
|
60
|
+
|
|
61
|
+
const app = Megh.createApplication();
|
|
62
|
+
app.useScheduler([ReportTask]);
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Or scan a folder:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
app.useScheduler({ path: 'src/tasks' });
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The scan works like controller auto-discovery:
|
|
72
|
+
|
|
73
|
+
- `src/tasks` is the conventional folder.
|
|
74
|
+
- Subfolders are scanned too. Files ending in `.test`, `.spec` or `.e2e-spec`
|
|
75
|
+
are skipped.
|
|
76
|
+
- Every exported class marked with `@ScheduledTask()` is registered. Other
|
|
77
|
+
exports are ignored.
|
|
78
|
+
- In a compiled app, the tsconfig `rootDir` (default `src`) is swapped for its
|
|
79
|
+
`outDir` (default `dist`) and `.js` files are loaded. When TypeScript runs
|
|
80
|
+
directly (ts-node, tsx), the `.ts` files in `src` are loaded. An absolute
|
|
81
|
+
path is used as-is.
|
|
82
|
+
- `useScheduler({})` and `useScheduler()` scan `src/tasks`.
|
|
83
|
+
- A missing folder logs a warning and the app starts without those tasks. A
|
|
84
|
+
file that fails to import stops startup.
|
|
85
|
+
|
|
86
|
+
A class registered in the list and found by the scan runs once, not twice.
|
|
87
|
+
Two different classes with the same name, in different files, both run.
|
|
88
|
+
|
|
89
|
+
## Decorators
|
|
90
|
+
|
|
91
|
+
| Decorator | Runs |
|
|
92
|
+
|-----------|------|
|
|
93
|
+
| `@Cron(expression, options?)` | On a cron expression |
|
|
94
|
+
| `@Interval(ms, options?)` | Every `ms` milliseconds, first run after `ms` |
|
|
95
|
+
| `@Timeout(ms, options?)` | Once, `ms` milliseconds after the scheduler starts |
|
|
96
|
+
|
|
97
|
+
The expression is a 5-field cron string, or 6 fields with seconds first:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
@Cron('0 0 * * *') // midnight every day
|
|
101
|
+
@Cron('*/5 * * * *') // every 5 minutes
|
|
102
|
+
@Cron('*/10 * * * * *') // every 10 seconds
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### Options
|
|
106
|
+
|
|
107
|
+
All three decorators take:
|
|
108
|
+
|
|
109
|
+
| Option | Default | Description |
|
|
110
|
+
|--------|---------|-------------|
|
|
111
|
+
| `name` | `ClassName#method` | Name shown in logs |
|
|
112
|
+
| `disabled` | `false` | Skip this job. It is logged as disabled and never runs |
|
|
113
|
+
|
|
114
|
+
`@Cron` also takes:
|
|
115
|
+
|
|
116
|
+
| Option | Default | Description |
|
|
117
|
+
|--------|---------|-------------|
|
|
118
|
+
| `timezone` | server time | IANA zone, such as `'Asia/Dhaka'` or `'Europe/London'` |
|
|
119
|
+
| `runOnInit` | `false` | Also run once when the scheduler starts |
|
|
120
|
+
|
|
121
|
+
The option types are exported as `BaseJobOptions` and `CronOptions`, so you
|
|
122
|
+
can build options outside the decorator:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import type { CronOptions } from '@meghjs/core';
|
|
126
|
+
|
|
127
|
+
const nightly: CronOptions = { timezone: 'Europe/London', name: 'nightly' };
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`disabled` is handy for feature flags:
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
@Cron('0 3 * * *', { disabled: process.env.NIGHTLY_CLEANUP !== 'true' })
|
|
134
|
+
async cleanup() { ... }
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Dependency injection
|
|
138
|
+
|
|
139
|
+
Task classes are resolved through [dependency injection](/core-concept/dependency-injection),
|
|
140
|
+
so constructor parameters and `inject()` both work. Each class is built once
|
|
141
|
+
when the scheduler starts, and that instance is shared with the rest of the
|
|
142
|
+
app.
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
@ScheduledTask()
|
|
146
|
+
export class CleanupTask {
|
|
147
|
+
private readonly sessions = inject(SessionService);
|
|
148
|
+
|
|
149
|
+
@Cron('0 * * * *')
|
|
150
|
+
async purge() {
|
|
151
|
+
await this.sessions.deleteExpired();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Scheduled methods are inherited. A subclass can override one by redeclaring
|
|
157
|
+
the method with the same kind of decorator (`@Cron`, `@Interval` or
|
|
158
|
+
`@Timeout`).
|
|
159
|
+
|
|
160
|
+
## When tasks run
|
|
161
|
+
|
|
162
|
+
Tasks start inside `app.run()`, after the `onInit` hooks (so MeghORM is
|
|
163
|
+
connected) and after routes are mapped, but before the server listens. They
|
|
164
|
+
stop in `app.close()`, right after the HTTP server stops. See
|
|
165
|
+
[Application](/getting-started/application) for the full order.
|
|
166
|
+
|
|
167
|
+
This means:
|
|
168
|
+
|
|
169
|
+
- `@Timeout(0)` and `runOnInit` jobs can run before the server accepts
|
|
170
|
+
requests and before `onReady`.
|
|
171
|
+
- Nothing runs if you never call `run()`, for example in tests.
|
|
172
|
+
- `close()` stops new runs and waits for a job that is in the middle of
|
|
173
|
+
running. On SIGTERM/SIGINT that wait counts toward `shutdownTimeout`, so
|
|
174
|
+
very long jobs can still be cut off.
|
|
175
|
+
- If startup fails after the tasks started (an error in `app.ready()`, the
|
|
176
|
+
port already in use), they are stopped before `run()` rejects.
|
|
177
|
+
|
|
178
|
+
An invalid cron expression throws when the scheduler starts, so `run()` fails
|
|
179
|
+
with `Invalid cron expression "..." on ReportTask#sendDailyReport`.
|
|
180
|
+
|
|
181
|
+
## Errors and overlapping runs
|
|
182
|
+
|
|
183
|
+
A job that throws or rejects is logged at `error` level and keeps its
|
|
184
|
+
schedule. It never crashes the process. Logs go through the
|
|
185
|
+
[logger](/advanced/logging):
|
|
186
|
+
|
|
187
|
+
```
|
|
188
|
+
[Megh Scheduler] Error in "ReportTask#sendDailyReport": SMTP timeout
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
If a run is still going when the next one is due, the new run is skipped with
|
|
192
|
+
a warning. A slow `@Interval(1000)` job never runs twice at once.
|
|
193
|
+
|
|
194
|
+
Handle errors you care about inside the job, for example to alert or retry.
|
|
195
|
+
|
|
196
|
+
## Multiple replicas
|
|
197
|
+
|
|
198
|
+
::: warning
|
|
199
|
+
Every process that calls `run()` runs every task. With three replicas behind a
|
|
200
|
+
load balancer, a daily report is sent three times. Megh has no distributed
|
|
201
|
+
locking yet.
|
|
202
|
+
:::
|
|
203
|
+
|
|
204
|
+
Until it does, pick one of these:
|
|
205
|
+
|
|
206
|
+
- Only register tasks in one process, using an environment variable:
|
|
207
|
+
|
|
208
|
+
```ts [src/app.ts]
|
|
209
|
+
if (process.env.RUN_SCHEDULER === 'true') {
|
|
210
|
+
app.useScheduler({ path: 'src/tasks' });
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
- Make the jobs idempotent, or take a lock yourself (a database row, a Redis
|
|
215
|
+
`SET NX`) at the start of each job.
|
|
216
|
+
- Have the task push work onto a [queue](/advanced/queue) with a fixed
|
|
217
|
+
`jobId`, such as the date, via `dispatch(name, data, 0, { jobId })`. BullMQ
|
|
218
|
+
ignores a job whose ID already exists.
|
|
219
|
+
|
|
220
|
+
See [Deployment](/production/deployment) for running replicas.
|
|
221
|
+
|
|
222
|
+
## `MeghScheduler`
|
|
223
|
+
|
|
224
|
+
`useScheduler` is enough for most apps. `MeghScheduler` is the class behind it,
|
|
225
|
+
for running tasks in a process without the HTTP app, such as a dedicated
|
|
226
|
+
scheduler container:
|
|
227
|
+
|
|
228
|
+
```ts [src/scheduler.ts]
|
|
229
|
+
import { MeghScheduler } from '@meghjs/core';
|
|
230
|
+
import { ReportTask } from './tasks/report.task';
|
|
231
|
+
import { CleanupTask } from './tasks/cleanup.task';
|
|
232
|
+
|
|
233
|
+
const scheduler = new MeghScheduler();
|
|
234
|
+
scheduler.addTaskClasses([ReportTask, CleanupTask]);
|
|
235
|
+
scheduler.start();
|
|
236
|
+
|
|
237
|
+
const stop = async () => {
|
|
238
|
+
await scheduler.stopAll(); // waits for runs in progress
|
|
239
|
+
process.exit(0);
|
|
240
|
+
};
|
|
241
|
+
process.once('SIGTERM', stop);
|
|
242
|
+
process.once('SIGINT', stop);
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
| Method | Description |
|
|
246
|
+
|--------|-------------|
|
|
247
|
+
| `addTaskClasses(classes)` | Add task classes. Adding the same class again is ignored |
|
|
248
|
+
| `start()` | Build each class and start its jobs. Call it once |
|
|
249
|
+
| `stopAll()` | Stop every job. Returns a promise that resolves when runs in progress finish |
|
|
250
|
+
|
|
251
|
+
Outside `app.run()` there are no lifecycle hooks, so anything the tasks need,
|
|
252
|
+
such as a database connection, must be set up before `start()`. A class
|
|
253
|
+
without `@ScheduledTask()` is skipped with a warning.
|