Skip to content

Order of initialization #49

@nicolashmln

Description

@nicolashmln

Hi,

When I use your package in dev mode everything is fine. But when I build and run it inside a docker image, I've got this error:

Error: connect ECONNREFUSED 127.0.0.1:6379
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1637:16)
    at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 6379
}

I checked, the redis URL is well set in the config.

After investigating, it seems the defineQueue is called before the connection is set, so it uses the default variable for the connection.

I tried the lazyConnect option, but i have the same error.

I edited src/runtime/server/handlers/defineQueue.ts like this

import type { Queue, QueueOptions, JobsOptions } from '../utils/workers'
import { $workers } from '../utils/workers'

type DefineQueueArgs<DefaultNameType extends string = string> = {
  name: DefaultNameType
  options?: Omit<QueueOptions, 'connection'> & { defaultJobOptions?: JobsOptions }
}

export function defineQueue<
  DataTypeOrJob = any,
  DefaultResultType = any,
  DefaultNameType extends string = string,
>({ name, options }: DefineQueueArgs<DefaultNameType>): Queue<DataTypeOrJob, DefaultResultType, DefaultNameType> {
  let queue: Queue<DataTypeOrJob, DefaultResultType, DefaultNameType> | null = null

  function getQueue() {
    if (!queue) {
      const { createQueue } = $workers()
      queue = createQueue<DataTypeOrJob, DefaultResultType, DefaultNameType>(name, options)
    }
    return queue
  }

  // Return a proxy that lazily creates the queue on first access
  return new Proxy({} as Queue<DataTypeOrJob, DefaultResultType, DefaultNameType>, {
    get(_target, prop, receiver) {
      return Reflect.get(getQueue(), prop, receiver)
    },
    has(_target, prop) {
      return Reflect.has(getQueue(), prop)
    },
  })
}

export default defineQueue

So the actual BullMQ Queue is only created when a method like .add() is first called, which happens well after the Nitro plugin has called setConnection().

I'm not sure if there is a better way of doing that?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions