Upgrading to 0.8
The @meghjs packages share one version number. Upgrade them together:
npm i @meghjs/core@~0.8.0
npm i -D @meghjs/cli@~0.8.0
npm i @meghjs/ai@~0.8.0 # if you use @meghjs/ai0.8.0 has breaking changes. Read this page before upgrading, or let megh upgrade make most of them for you.
Upgrade with one command
Commit your work, then run:
npx @meghjs/cli@latest upgrademegh upgrade bumps the @meghjs packages, removes ioredis, bullmq and kafkajs if your code doesn't import them, and applies the changes below that it can make exactly: queue driver to transport, setQueueDriver(), QueueDriver, JobsOptions, queue adapter/connection to redis, the cache's redisOptions, new Redis(url) passed to the cache or rate limiter, MEGH_QUEUE_DRIVER in .env files, and @ApiController to @Controller. It lists the rest as manual steps with links to the sections here. Add --dry-run to see the changes first.
0.8.0 adds messaging: one transport layer (memory, redis or rabbitmq) for distributed events, @Listener classes, retries, dead letters, dedupe and a transactional outbox. Queues, the Redis cache and the Redis rate limit store move onto the same connection options, and ioredis is gone.
Each item below says how to tell whether it affects you.
@ApiController is now @Controller
There is one controller decorator, @Controller. It takes the same arguments as @ApiController did, and its routes can return anything: JSON, Results.View, Results.Inertia, redirects, streams and downloads. @ApiController is removed.
Affects you if any class uses @ApiController. Rename the decorator and its import:
// Before
import { ApiController, Get } from '@meghjs/core';
@ApiController('/users')
export class UserController {}
// After
import { Controller, Get } from '@meghjs/core';
@Controller('/users')
export class UserController {}Search for it with grep -rn ApiController src.
Dependencies
BullMQ, the Redis client (@redis/client) and the RabbitMQ client (amqplib) are now dependencies of @meghjs/core. bullmq, ioredis and kafkajs are no longer peer dependencies, and Megh no longer uses ioredis.
Affects you if you installed bullmq or ioredis for Megh. Remove them, unless your own code imports them:
npm uninstall bullmq ioredisQueues
driver is now transport
Queues run on the messaging transports. bullmq is now redis, sync is now an option of memory, and rabbitmq is new.
| Before | After |
|---|---|
driver: 'bullmq' | transport: 'redis' |
driver: 'memory' | transport: 'memory' |
driver: 'sync' | transport: 'memory', sync: true |
MEGH_QUEUE_DRIVER=bullmq | MEGH_QUEUE_TRANSPORT=redis |
setQueueDriver('sync') | setQueueTransport('memory', { sync: true }) |
resolveQueueDriver() | resolveQueueTransport() |
QueueDriver type | TransportName |
Affects you if you set driver, MEGH_QUEUE_DRIVER or call setQueueDriver():
// before
@Queue({ name: 'email', driver: 'bullmq' })
beforeAll(() => setQueueDriver('sync'));
// after
@Queue({ name: 'email', transport: 'redis' })
beforeAll(() => setQueueTransport('memory', { sync: true }));MEGH_QUEUE_DRIVER is ignored now. Without MEGH_QUEUE_TRANSPORT, queues follow MEGH_MESSAGING_TRANSPORT.
The default is memory, and production refuses it
Queues used to default to BullMQ on Redis. They now default to memory, so npm run start:dev needs no Redis. With NODE_ENV=production, a queue refuses to start on a memory transport it didn't ask for, instead of losing jobs on restart.
Affects you if your production app relied on the BullMQ default. Set the transport in its environment:
MEGH_QUEUE_TRANSPORT=redis
MEGH_REDIS_URL=rediss://default:secret@redis.internal:6379adapter and connection are now redis
Queues take Megh's Redis connection options instead of BullMQ's. @Queue's adapter and @MeghWorker's connection and options are gone.
Affects you if you pass any of them:
// before
@Queue({ name: 'email', adapter: { connection: { host: '10.0.0.5', port: 6379 } } })
@MeghWorker({ queue: 'report', connection: { host: '10.0.0.5', port: 6379 } })
// after
@Queue({ name: 'email', redis: { host: '10.0.0.5', port: 6379 } })
@MeghWorker({ queue: 'report', redis: { url: process.env.REDIS_URL } })redis takes { url?, host?, port?, username?, password?, db?, tls?, prefix? }. Left out, it comes from MEGH_REDIS_URL, then MEGH_MESSAGING_URL when messaging runs on Redis, then 127.0.0.1:6379.
Jobs keep BullMQ's default bull: key prefix, so jobs already waiting in Redis are still processed after the upgrade. With redis.prefix set, keys go under <prefix>:bull: instead.
In production a queue's Redis connection follows the same TLS rule as messaging: a redis:// URL (or host) to a remote server is refused. Use rediss:// or tls: true, or set MEGH_ALLOW_INSECURE_BROKER=true on a private network you trust.
A subclass that calls the MeghQueue constructor with arguments passes an options object now:
// before
super('email', { connection }, { concurrency: 5 }, 'bullmq');
// after
super('email', { transport: 'redis', redis: { url }, worker: { concurrency: 5 } });Megh's own job types
Job and JobOptions are Megh types now, the same on every transport. BullMQ types are no longer exported.
Affects you if you import JobsOptions, or use BullMQ-only fields of a job:
// before
import type { Job, JobsOptions } from '@meghjs/core';
// after
import type { Job, JobOptions } from '@meghjs/core';JobOptions has delay, attempts, backoff, jobId, priority, removeOnComplete and removeOnFail. A job has id, name, data, queueName, attemptsMade, timestamp, opts, updateProgress() and log(). For anything else, use raw() (below).
getQueue() and getWorker() are gone
| Before | After |
|---|---|
queue.getQueue() | queue.raw() |
queue.getWorker() (to check it started) | queue.hasWorker() |
worker.getWorker() on a MeghWorkerBase | worker.isRunning() |
this.worker in a MeghWorkerBase subclass | no replacement |
Affects you if you call them. raw() returns BullMQ's Queue on Redis, but it is outside Megh's compatibility promise.
attemptsMade counts the current attempt
On Redis, job.attemptsMade was 0 during the first run. It is now 1, as on the memory and RabbitMQ transports.
Affects you if a handler compares attemptsMade, for example to give up on the last try:
// before
if (job.attemptsMade + 1 >= (job.opts.attempts ?? 1)) { /* last try */ }
// after
if (job.attemptsMade >= (job.opts.attempts ?? 1)) { /* last try */ }Mail queue options
useMail({ queue }) takes the same transport, sync and redis as a queue. adapter and driver are gone.
Affects you if you set them:
// before
app.useMail({
queue: { adapter: { connection: { host: '127.0.0.1', port: 6379 } }, driver: 'bullmq' },
});
// after
app.useMail({
queue: { transport: 'redis', redis: { host: '127.0.0.1', port: 6379 } },
});Cache: redisOptions is now redis
useCache() takes Redis connection options as redis. Megh opens the connection and closes it on shutdown. Passing an ioredis client is no longer possible.
Affects you if you use the Redis cache:
// before
app.useCache({ provider: 'redis', redisOptions: { host: '127.0.0.1', port: 6379 } });
new CacheManager({ provider: 'redis', redis: new Redis() });
// after
app.useCache({ provider: 'redis', redis: { host: '127.0.0.1', port: 6379 } });
new CacheManager({ provider: 'redis', redis: { url: process.env.REDIS_URL } });Rate limits: redis takes connection options
useRateLimit({ redis }) and RedisRateLimitStore take connection options instead of an ioredis client. Megh opens the connection, and closes it on shutdown for a store it created. RedisEvalClient is gone.
Affects you if you count rate limits in Redis:
// before
import Redis from 'ioredis';
app.useRateLimit({ redis: new Redis(process.env.REDIS_URL!) });
app.useRateLimit({ store: new RedisRateLimitStore(new Redis(), { prefix: 'rl:' }) });
// after
app.useRateLimit({ redis: { url: process.env.REDIS_URL } });
app.useRateLimit({ store: new RedisRateLimitStore({ url: process.env.REDIS_URL }, { prefix: 'rl:' }) });A store you build yourself has close().
Scheduler jobs run once across replicas
@Cron and @Interval jobs used to run in every replica. They now run once per tick across all of them. The replicas agree through a lock in Redis (with the redis messaging transport) or in the megh_locks table (with Megh ORM and megh make:messaging). @Timeout still runs on each instance.
Affects you if you run several replicas:
If you worked around it with a
RUN_SCHEDULERflag or your own lock, you can drop that once a lock store is set up.A job meant to run in each replica, such as clearing a local cache, needs
perInstance: true:ts// before @Interval(60_000) // after @Interval(60_000, { perInstance: true })With neither Redis messaging nor the
megh_lockstable, every replica still runs every job, and Megh logs a warning in production.
Replicas recognise a job by its name, or ClassName#method. See Scheduler: Multiple replicas.
Events: Kafka and RabbitMQ broadcast
dispatch(event, { broadcast: { type: 'kafka' } }) and type: 'rabbitmq' still throw: broadcast is only for Socket.IO. To send events to other services, mark them with @DistributedEvent and use the rabbitmq (or redis) messaging transport. Kafka is not supported.
Affects you if you planned on broadcast for this. Nothing changes for existing code.
scaffold:auth hashes passwords with Hash
megh scaffold:auth no longer writes src/auth/password.ts. The generated AuthService injects Hash from @meghjs/core instead, and rehashes a password at sign-in when hash.needsRehash() says so. New hashes use scrypt with stronger settings (N = 2^17), in the format scrypt$<N>$<r>$<p>$<salt>$<hash>.
Affects you if you ran scaffold:auth before 0.8.0. Nothing breaks: your password.ts keeps working, and Hash.check() reads the hashes it wrote (scrypt$<salt hex>$<hash hex>). To move over, replace hashPassword() and verifyPassword() with Hash, then delete src/auth/password.ts:
// before
import { hashPassword, verifyPassword } from '../auth/password';
const valid = await verifyPassword(input.password, user.password);
// after
import { Hash } from '@meghjs/core';
constructor(private readonly hash: Hash) {}
const valid = !!user.password && (await this.hash.check(input.password, user.password));Existing users' hashes are upgraded the next time they sign in if you add the needsRehash() check; see Upgrading old hashes.
New in 0.8.0
- More
Results.Accepted,Created(data, location), error results with the error handler's body (BadRequest,Unauthorized,Forbidden,Conflict,UnprocessableEntity,TooManyRequests,Error(status, ...)), raw bodies (Json,Text,Html,Status), and files (Fileshows one in the browser,Downloaddownloads it, from a path, Buffer or stream). Every result takes.header(name, value). See Returning responses. - Hashing.
Hash(injectable, orHash.make()/hash.make()) hashes and checks passwords with scrypt (the default, no install), bcrypt or argon2id.app.useHashing({ driver: 'argon2' })picks the driver, andcheck()reads every driver's hashes.megh make:hashprints or checks a hash from the command line. See Hashing. - Notifications. Extend
Notification, pick channels invia()(mail,broadcast), and send withnotifier.send(user, notification).Notifier.fake()records them in tests. See Notifications. - Tracing.
app.useTracing()creates an OpenTelemetry span per request, named after the route and continuing an incomingtraceparent. Needs@opentelemetry/api. See Tracing. - Monitoring.
app.useMonitor()plusmegh monitopens a live dashboard: metrics charts, a log stream, routes, services and health. See Monitoring. - Messaging.
app.useMessaging(), orMEGH_MESSAGING_TRANSPORTandMEGH_MESSAGING_URL, picksmemory,redis(Redis Streams) orrabbitmq. Messages travel as CloudEvents 1.0. See Messaging. - Distributed events.
@DistributedEvent('order.placed')makesdispatch()publish the event, and@Listener(OrderPlaced, { group })classes handle it on one replica per group, with retries, dead letters and dedupe. @Listenerfor local events registers a DI-resolved listener class atapp.run(), without callingEventRegistryby hand.- Transactional outbox. With
useMessaging({ outbox: true })and Megh ORM, events dispatched in a transaction are published after it commits. - Jobs on RabbitMQ.
transport: 'rabbitmq'runs queue jobs through the broker. Messaging.fake()records events, messages and jobs for tests:expectDispatched,expectPublished,expectQueuedand more. See Testing.- CLI.
megh make:messagingwrites the migration formegh_outbox,megh_locksandmegh_dedupe.megh messaging:failedlists, retries and discards dead letters. - Storage disks.
app.useStorage()sets up named disks:local,s3(and S3-compatible services such as R2, MinIO, Spaces, B2 and Wasabi),azureandgcs, each withput,get,list,url,temporaryUrland more. InjectStorageor@InjectDisk('s3'), and useStorage.fake()in tests.FileStorage.save()takes adiskoption, and its result now also haspathanddisk. Once you calluseStorage(), uploads that name no disk go to the default disk instead of<cwd>/public, unlessconfigure({ baseDir })was called. See Storage. - Secure defaults. In production, Megh refuses non-TLS URLs to remote brokers (unless
allowInsecure), the memory transport for distributed listeners, and messages over 256 KiB.