Skip to main content

Services

A Service in an Andera Worker is a long-running component that manages resources or background processes, such as launching a browser or a server. Services are defined in the src/services/ directory and are auto-discovered and started at Worker startup.

Structure of a Service

A service is defined using defineService from @andera-top/worker-core. Each service specifies:

  • config: (optional) Service-specific configuration (e.g., restart on failure)
  • start: An async function to initialize the service
  • stop: An async function to clean up resources
  • status: (optional) A function to report service status

Example

import { defineService } from '@andera-top/worker-core'
import puppeteer from 'puppeteer'

let browser = null
export default defineService({
config: { restartOnFailure: true },
start: async () => {
browser = await puppeteer.launch({ headless: true })
// ...initialize resources
},
stop: async () => {
if (browser) await browser.close()
browser = null
},
status: async () => ({
browser: !!browser
})
})

Logging in Services

You can use the logging utilities to monitor your service lifecycle and errors (see Logging):

import { log, warn, error } from '@andera-top/worker-core/dist/utils/logger'

export default defineService({
start: async () => {
log('[MYSERVICE]', 'Service starting...')
// ...
},
stop: async () => {
log('[MYSERVICE]', 'Service stopping...')
// ...
},
status: async () => {
// ...
warn('[MYSERVICE]', 'Status check warning')
return { ok: true }
}
})

Service Config Options

The config object for a service can have the following options:

OptionTypeDescriptionExample
restartOnFailurebooleanWhether to automatically restart the service if it crashestrue

Creating a New Service

  1. Create a new file in src/services/, e.g. myService.ts.
  2. Export your service using defineService as shown above.
  3. The service will be auto-registered and started at Worker startup.

Service Lifecycle

  • Services are started automatically when the Worker starts.
  • They are stopped gracefully when the Worker shuts down.
  • If restartOnFailure is set, the Worker will attempt to restart the service if it crashes.