#.

3 messages · Page 1 of 1 (latest)

crimson muskBOT
#

You've gone full bot mode! Let me fetch that AI answer for you ASAP.

crimson muskBOT
# crimson musk You've gone full bot mode! Let me fetch that AI answer for you ASAP.

To solve your problem—where only one machine can add a room to its allowed list, and you want the "later one" to win without errors, while also ensuring the machine is running at the time of the operation—you can use an optimistic concurrency control (OCC) pattern with a version field.

Key steps:

  1. Add a version field to your Machine model (e.g., version: Int).
  2. Read the machine and its current version.
  3. Check the machine state is On before proceeding.
  4. Attempt to update the allowed rooms and increment the version, but only if the version and state match what you read.
  5. If the update fails (count = 0), it means another operation won the race; you can simply return the latest allowed rooms.

Example (pseudo-code using Prisma):

const machine = await prisma.machine.findUnique({
  where: { id: machineId },
  select: { allowedRooms: true, machineState: true, version: true }
});

if (machine.machineState !== 'On') {
  throw new OperationNotAllowedException();
}

const result = await prisma.machine.updateMany({
  where: {
    id: machineId,
    version: machine.version,
    machineState: 'On'
  },
  data: {
    allowedRooms: { push: roomId },
    version: { increment: 1 }
  }
});

if (result.count === 0) {
  // Another operation won; fetch and return the latest allowedRooms
  const latest = await prisma.machine.findUnique({ where: { id: machineId } });
  return { allowedRooms: latest.allowedRooms };
}

return { allowedRooms: [...machine.allowedRooms, roomId] };

This approach ensures:

  • Only one machine can add the room (the "last write" wins).
  • The machine must be running at the time of the update.
  • No errors are thrown for race conditions; you just return the current state.

This pattern is described in the Prisma docs on optimistic concurrency control and the [cinema seat reservation example](<https://www.pri