Skip to content

Commit

Permalink
make sure only a single instance of the server is the schedule executor
Browse files Browse the repository at this point in the history
  • Loading branch information
vieiralucas committed Nov 27, 2024
1 parent 66e69d0 commit 15bb275
Showing 1 changed file with 29 additions and 10 deletions.
39 changes: 29 additions & 10 deletions apps/api/src/schedule/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import * as yjs from '../yjs/v2/index.js'
import { AppPersistor } from '../yjs/v2/persistors.js'
import { ExecutionQueue } from '@briefer/editor'
import { updateAppState } from '../yjs/v2/documents.js'
import { acquireLock } from '../lock.js'

function convertToCron(schedule: ExecutionSchedule): string {
switch (schedule.type) {
Expand Down Expand Up @@ -199,19 +200,37 @@ export async function runSchedule(socketServer: IOServer) {

let stop = false
const loop = new Promise<void>(async (resolve) => {
while (true) {
try {
await updateSchedule()
} catch (err) {
logger().error({ err, module: 'schedule' }, 'Failed to update schedule')
}

logger().trace('Acquiring lock to be the schedule executor')
await acquireLock('schedule-executor', async () => {
if (stop) {
break
logger().trace(
'Schedule executor lock acquired but server is shutting down'
)
return
}

await new Promise((resolve) => setTimeout(resolve, 5000))
}
logger().trace('Schedule executor lock acquired')
while (true) {
if (stop) {
break
}

try {
await updateSchedule()
} catch (err) {
logger().error(
{ err, module: 'schedule' },
'Failed to update schedule'
)
}

if (stop) {
break
}

await new Promise((resolve) => setTimeout(resolve, 5000))
}
})

resolve()
})
Expand Down

0 comments on commit 15bb275

Please sign in to comment.