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 servicestop
: An async function to clean up resourcesstatus
: (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:
Option | Type | Description | Example |
---|---|---|---|
restartOnFailure | boolean | Whether to automatically restart the service if it crashes | true |
Creating a New Service
- Create a new file in
src/services/
, e.g.myService.ts
. - Export your service using
defineService
as shown above. - 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.