RoomDefinition: onHibernate() hook

Available since @irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room host

The onHibernate() hook of a room definition runs before the room saves its room state and leaves its room host.

Syntax

defineRoom({
  onHibernate(room) {},
});

Parameters

room
The Room that’s hibernating.

Return value

None, or a Promise. The room hibernates once onHibernate has run, or once the promise it returned resolves.

Exceptions

If onHibernate throws, or its promise rejects, the room stops instead of hibernating.

Description

A room hibernates 30 seconds after its last connection closes, when it calls room.requestHibernate(), when its room host drains, and when it goes to sleep. See When a room hibernates.

Before onHibernate:

  • Server API messages the room is still answering finish.
  • In an ordinary hibernation, onLeave() runs for each open connection, then onPlayerLeave() for every person still in presence.
  • When the room goes to sleep, no one leaves: the owner writes the room holds are applied through writes instead.

What onHibernate writes to room state is saved. room.data, module variables and timers aren’t, and a replay recording stops after onHibernate. Room state is already streamed out as the room runs, so onHibernate isn’t needed to save it, and it doesn’t run when a room host crashes.

Examples

Pausing a round clock

A round’s time left is kept in room state while the room hibernates, so it carries on from there after the wake rather than running out while no one is there.

// round-clock.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";

const Round = entity("round", { endsAt: "f64", leftMs: "f64" });

export default defineRoom({
  schema: defineSchema({ state: Round }),
  onCreate(room) {
    room.state.endsAt = room.now() + 5 * 60_000;
  },
  onHibernate(room) {
    room.state.leftMs = Math.max(0, room.state.endsAt - room.now());
  },
  onWake(room) {
    room.state.endsAt = room.now() + room.state.leftMs;
  },
});

See also

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
onHibernate()0.10.10.10.1