Antero Connect Docs

#Integrating a PMS

For the people who build the hotel-system side: a property management system, a front desk, a booking system of your own. This is the one loop to get right. Its aim: your system and every channel agree on how many rooms are free, and no room is ever sold twice, even when your program crashes, the network drops answers, or Antero Connect itself is restored from a backup.

#The idea in four lines

  1. Your system owns how many rooms are free. It pushes the number per room type and night (PUT …/availability). The property is pms_authoritative.
  2. Antero Connect tells your system what channels booked, through a numbered feed (GET …/reservation-feed).
  3. Until your system has counted a booking in its numbers, Antero Connect keeps one room back for it: a hold. A hold is never released by time, because selling a room twice is worse than selling it late.
  4. Your system says how far it got with feed_applied_through, in the push that counts those bookings. That is the only thing that releases holds.

#The cycle

Run it every minute, and also right after anything changes at your desk. If you use webhooks, run it when one arrives.

text
TAKE OVER                                  PUSH
  after = saved cursor                       if a push is pending: resend it (same bytes), done
  read the feed after `after`                else build items from your own state (free rooms per type per night)
  for each entry, in order:                  if items and cursor equal what was last accepted: stop (nothing to say)
     apply it to your system (idempotent)    version = last accepted version + 1
  save the bookings AND the cursor           pending = {version, body}        ← SAVE THIS FIRST
  together, in one write                     send pending, the same bytes every time
                                             on 200: last version = pending.version; pending = none; save

Order matters: apply, save, then push. Never push numbers that do not yet count a booking you claim to have taken over.

#The rules that make it crash-safe

Each rule has a test in Antero Connect's own test suite, where a reference hotel system is crashed at every point of its cycle, its answers are lost, and Antero Connect is made to fail, and both sides must end with the same numbers. Port the behaviour, not just the calls.

RuleWhy
Save the applied bookings and the new cursor in one atomic writea crash between them applies a booking twice, or never
Write the push down before sending it, and resend the same bytes until it is accepteda push whose answer was lost must not turn into a different push under the same version (409 version_conflict)
Take over the feed before pushingthe push's feed_applied_through must be true
Push even when the numbers did not change, if the cursor moveda booking can change no number (the room was already sold out) and its hold still has to go
Stop at a feed entry you cannot place (an unknown room type) and do not move the cursorconfirming a booking you did not count would release its room, and it would be sold twice. The room stays held: the safe side
Apply entries by external_id, never as "add one"the feed can be read again (a restore); the same entry twice must change nothing
A cancellation of a booking you never saw is recorded, not an errora channel may cancel before you ever read the booking
Where your system placed a guest (another room) wins over the channel's room: send it with PATCH …/placementyour system decides who sleeps where

#A complete, working loop

This is a whole program (under 200 lines, standard library only) that follows every rule above. It is the file examples/pms_loop.py; the guide shows the file that is actually tested. Replace the small rooms table with your real system.

python
#!/usr/bin/env python3
"""A small hotel system that keeps itself and Channel Manager in step. Standard library only.

It follows the eight rules of the guide "Integrating a PMS":
  - it takes the feed over first, saves the bookings AND the new cursor in one transaction, and only then pushes;
  - it writes the push down BEFORE it sends it, and sends the same bytes until Channel Manager accepts them;
  - it applies a feed entry by external_id (the same entry twice changes nothing);
  - it stops at an entry it cannot place and does not move its cursor past it.

Run:  CHANNEL_MANAGER=https://api.anteromas.com KEY=cm_live_... PROPERTY=<id> python3 pms_loop.py
It runs one cycle every 30 seconds. Its own rooms are in the `rooms` table; replace that with your real system.
"""
import json, os, sqlite3, sys, time, urllib.request, urllib.error, urllib.parse, random

CHANNEL_MANAGER = os.environ.get("CHANNEL_MANAGER", "http://127.0.0.1:8080").rstrip("/")
KEY = os.environ.get("KEY", "")
PROPERTY = os.environ.get("PROPERTY", "")
DB = os.environ.get("PMS_DB", "pms.sqlite")


class Unplaceable(Exception):
    """A feed entry for something this system does not know. The cycle stops here, and the room stays held (the safe side)."""


def call(method, path, body=None, key=None, tries=6):
    """One request, retried on network errors, 429 and 5xx with growing pauses. The SAME Idempotency-Key and bytes every time."""
    data = None if body is None else json.dumps(body, separators=(",", ":"), sort_keys=True).encode()
    headers = {"Authorization": "Bearer " + KEY, "Accept": "application/json", "Content-Type": "application/json"}
    if key:
        headers["Idempotency-Key"] = key
    for attempt in range(tries):
        try:
            req = urllib.request.Request(CHANNEL_MANAGER + path, data=data, method=method, headers=headers)
            with urllib.request.urlopen(req, timeout=30) as r:
                return r.status, json.loads(r.read() or b"null")
        except urllib.error.HTTPError as e:
            payload = json.loads(e.read() or b"null")
            if e.code not in (429, 500, 502, 503, 504):
                return e.code, payload  # 4xx: do not repeat, the caller decides
            pause = int(e.headers.get("Retry-After", 0)) or min(60, 2 ** attempt)
        except (urllib.error.URLError, TimeoutError, ConnectionError):
            pause = min(60, 2 ** attempt)
        time.sleep(pause + random.random())  # a little randomness so many clients do not come back together
    raise RuntimeError(f"{method} {path}: no answer after {tries} tries")


def db():
    c = sqlite3.connect(DB, isolation_level=None)  # we begin and commit ourselves, so a transaction is only what we say it is
    c.executescript("""
      CREATE TABLE IF NOT EXISTS state (k TEXT PRIMARY KEY, v TEXT);
      CREATE TABLE IF NOT EXISTS rooms (room_type_id TEXT PRIMARY KEY, total INTEGER NOT NULL);
      CREATE TABLE IF NOT EXISTS bookings (external_id TEXT PRIMARY KEY, room_type_id TEXT, arrival TEXT, departure TEXT, rooms INTEGER, status TEXT);
    """)
    return c


def get(c, k, default=None):
    r = c.execute("SELECT v FROM state WHERE k=?", (k,)).fetchone()
    return json.loads(r[0]) if r else default


def put(c, k, v):
    c.execute("INSERT INTO state(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v", (k, json.dumps(v)))


# ---------------------------------------------------------------- 1. take over the feed
def take_over(c):
    cursor = get(c, "cursor", 0)
    while True:
        status, page = call("GET", f"/v1/properties/{PROPERTY}/reservation-feed?after={cursor}&limit=100")
        if status != 200:
            raise RuntimeError(f"feed: {status} {page}")
        entries = page["data"]
        if not entries:
            return
        c.execute("BEGIN")  # the bookings and the cursor are saved TOGETHER, or not at all
        try:
            for e in entries:
                apply_entry(c, e)
                cursor = e["seq"]
            put(c, "cursor", cursor)
            c.execute("COMMIT")
        except Unplaceable:
            c.execute("ROLLBACK")
            raise
        except BaseException:
            c.execute("ROLLBACK")
            raise
        if len(entries) < 100:
            return


def apply_entry(c, e):
    r = e.get("reservation") or {}
    ext = e["external_id"]
    if e["kind"] == "placement":
        return  # our own doing, echoed back: nothing to apply
    if e["kind"] == "cancelled":
        # recorded even if we never saw the booking: a channel can cancel before we read it
        c.execute("INSERT INTO bookings(external_id,status) VALUES(?, 'cancelled') ON CONFLICT(external_id) DO UPDATE SET status='cancelled'", (ext,))
        return
    if not c.execute("SELECT 1 FROM rooms WHERE room_type_id=?", (r.get("room_type_id"),)).fetchone():
        raise Unplaceable(f"{ext}: room type {r.get('room_type_id')} is not one of ours")
    # by external_id, never "add one": the same entry a second time changes nothing
    c.execute("""INSERT INTO bookings(external_id,room_type_id,arrival,departure,rooms,status) VALUES(?,?,?,?,?, 'confirmed')
                 ON CONFLICT(external_id) DO UPDATE SET room_type_id=excluded.room_type_id, arrival=excluded.arrival,
                 departure=excluded.departure, rooms=excluded.rooms, status='confirmed'""",
              (ext, r["room_type_id"], r["arrival"], r["departure"], r["rooms"]))


# ---------------------------------------------------------------- 2. say how many rooms are free
def free_rooms(c, days):
    """Rooms free per room type per night: our own count, from our own bookings."""
    out = {}
    for rt, total in c.execute("SELECT room_type_id, total FROM rooms"):
        for d in days:
            used = c.execute("SELECT COALESCE(SUM(rooms),0) FROM bookings WHERE room_type_id=? AND status='confirmed' AND arrival<=? AND departure>?", (rt, d, d)).fetchone()[0]
            out[(rt, d)] = max(0, total - used)
    return out


def build_push(c, days, cursor, version):
    items = [{"room_type_id": rt, "date_from": d, "date_to": d, "available": n} for (rt, d), n in sorted(free_rooms(c, days).items())]
    return {"items": items, "feed_applied_through": cursor, "pms_version": version}


def push(c, days):
    pending = get(c, "pending")
    if pending is None:
        cursor = get(c, "cursor", 0)
        version = get(c, "version", 0) + 1
        body = build_push(c, days, cursor, version)
        # nothing new to say? then do not push (unless the cursor moved: that alone has to be said, it releases holds)
        last = get(c, "last_pushed")
        if last and last["items"] == body["items"] and last["cursor"] == cursor:
            return
        pending = {"version": version, "body": body}
        put(c, "pending", pending)  # WRITE IT DOWN FIRST. Whatever happens next, the same bytes will be sent.
    while True:
        status, answer = call("PUT", f"/v1/properties/{PROPERTY}/availability", pending["body"], key=f"push-{pending['version']}")
        if status == 200:
            put(c, "version", pending["version"])
            put(c, "last_pushed", {"items": pending["body"]["items"], "cursor": pending["body"]["feed_applied_through"]})
            c.execute("DELETE FROM state WHERE k='pending'")
            return
        if status == 409 and answer["error"]["code"] == "stale_version":
            # Channel Manager holds a newer picture than we thought (a restored backup, a second instance): continue from its number
            put(c, "version", answer["error"]["current_version"])
            c.execute("DELETE FROM state WHERE k='pending'")
            return push(c, days)
        raise RuntimeError(f"push refused: {status} {answer}")  # 400s: our request is wrong; a person must look


def cycle(days):
    c = db()
    try:
        take_over(c)
        push(c, days)
    except Unplaceable as e:
        print("STOPPED, a person must look:", e, file=sys.stderr)  # the cursor did not move, the room stays held
    finally:
        c.close()


if __name__ == "__main__":
    if not (KEY and PROPERTY):
        sys.exit("set KEY and PROPERTY (and CHANNEL_MANAGER)")
    window = [time.strftime("%Y-%m-%d", time.gmtime(time.time() + 86400 * n)) for n in range(0, 60)]
    while True:
        cycle(window)
        time.sleep(30)

It is checked against a real server by scripts/test-pms-loop.py, which makes the loop recover from a version it was behind on, take over a booking and release its hold, lose an answer and resend it byte for byte, take a cancellation, and stop at a room type it does not know.

#Versions: recovering from the unexpected

Every push carries pms_version, a whole number that only goes up. Antero Connect answers:

AnswerMeaning
200applied, or a replay: the same version with the same bytes does nothing twice
409 stale_versionolder than what Antero Connect already holds. The error carries current_version: continue from it (current_version + 1) with a fresh push of the whole picture. This is how a PMS recovers from a lost disk, a restored backup or a second instance
409 version_conflictthis version was already used with different bytes: you did not resend the pending push unchanged

#Errors and retries

AnswerMeaningWhat to do
network error, timeout, cut connectionunknown whether it was appliedsend the same request again: it is safe, it is a replay
429, 500, 502, 503, 504Antero Connect is busy or downwait (honour Retry-After), send the same request again; keep the push pending
400 feed_applied_through_requiredthe property has a feed and the push did not say how far you gotsend feed_applied_through
400 feed_applied_through_aheadyour number is above the feed's newestyour cursor is wrong (was Antero Connect restored?). Do not guess; alert a person
409 stale_feed_applied_throughbelow what you confirmed beforeyou pushed before catching up: take over first
any other 4xxyour request is wrongdo not repeat it; fix it

#What to show the hotel

  • "Last heard from your PMS", and "waiting for your PMS to confirm N bookings": Antero Connect's panel shows them (GET …/pms-link).
  • A PMS that is silent for hours is shown as a warning at 2 hours and critical at 12 hours, and its holds stay: Antero Connect sells less, never more, while it waits. Your own system should alarm too if its cycle has not completed for a few minutes.

#Also report your own bookings

Bookings made at your front desk can be reported to Antero Connect so its panel shows who stays, comes and goes. They are for display only; your own numbers already count them. See Reservations.

#Not covered yet

Payment information on bookings (virtual cards), no-show and cancellation reports from the PMS, occupancy-based and length-of-stay pricing, and child pricing. They will be added without changing what is on this page.