iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / dummy-petshop / src / google-records.tsmain at aacbc74

/**
 * What the Google fake keeps of one account's mailbox and of its primary calendar (google.ts,
 * google-calendar.ts), and each change to it as one step from the record as it was to the record
 * as it is. The store (state.ts) keeps each record as a stored value of its own and runs one step
 * inside one call, so two requests never change a record at once.
 *
 * Everything here is bounded: a mailbox keeps its newest fifty history records, a calendar its
 * newest `CALENDAR_EVENTS_KEPT` events and its five newest channels. What a record no longer
 * keeps, it says it no longer has, as Google does: a place in a mailbox's history before the
 * kept records answers 404, and a sync token from before a dropped event 410.
 */

const CALENDAR_EVENTS_KEPT = 50;

/** One mail of a mailbox, as much of it as Gmail's `format=metadata` answers. */
export interface GmailMessage {
  id: string;
  labelIds: string[];
  snippet: string;
  /** When it arrived, epoch ms. */
  internalDate: number;
  /** The headers Gmail would answer, in their order: From, To, Subject, Date, Message-ID. */
  headers: { name: string; value: string }[];
}

export interface GmailMailbox {
  /** `users.watch`: the Pub/Sub topic the mailbox's changes are published to, and when the watch
   *  ends (epoch ms). */
  watch?: { topicName: string; expiration: number };
  /** The mailbox's newest history id. A mailbox starts at 1. */
  historyId: number;
  /** The lowest `startHistoryId` the history still answers: a lower one is gone (404). */
  historyFrom: number;
  /** One record for each message that arrived, oldest first; a record's id is the mailbox's
   *  history id from that message on. */
  history: { id: number; message: GmailMessage }[];
}

export type GmailAction =
  /** `users.watch` and `users.stop`. */
  | { watch: { topicName: string; expiration: number } | null }
  /** One message arrives, when the mailbox is watched. */
  | { arrives: GmailMessage }
  /** The history is gone: every place before the newest answers 404. */
  | { forget: true };

/** One step of a mailbox. `done` is false for a message that did not arrive: nobody watches the
 *  mailbox, and Gmail publishes only what `users.watch` asked for. */
export function gmailChanged(
  before: GmailMailbox | undefined,
  action: GmailAction,
  now: number,
): { mailbox: GmailMailbox; done: boolean } {
  const mailbox = before || { historyId: 1, historyFrom: 1, history: [] };
  if ("watch" in action) {
    const { watch: _replaced, ...rest } = mailbox;
    return { mailbox: action.watch ? { ...rest, watch: action.watch } : rest, done: true };
  }
  if ("forget" in action)
    return { mailbox: { ...mailbox, history: [], historyFrom: mailbox.historyId }, done: true };
  if (!mailbox.watch || mailbox.watch.expiration <= now) return { mailbox, done: false };
  const historyId = mailbox.historyId + 1;
  // the newest fifty records: one for each message that arrived
  const history = [...mailbox.history, { id: historyId, message: action.arrives }].slice(-50);
  return {
    mailbox: {
      ...mailbox,
      historyId,
      history,
      // the place just before the oldest record that is kept
      historyFrom: Math.max(mailbox.historyFrom, history[0]!.id - 1),
    },
    done: true,
  };
}

/** One event of a calendar. `version` is the calendar's version at the event's last change. */
export interface CalendarEvent {
  id: string;
  status: "confirmed" | "cancelled";
  summary: string;
  /** RFC 3339, as Google's `dateTime`. */
  start: string;
  end: string;
  updated: string;
  version: number;
}

/** One notification channel of a calendar (`events.watch`): where its pushes go, the token they
 *  carry, when it ends (epoch ms), and the number of its last message. Google's first message on
 *  a channel is `sync`, number 1, which the fake does not send: a channel starts at 1. */
export interface CalendarChannel {
  id: string;
  resourceId: string;
  address: string;
  token?: string;
  expiration: number;
  messageNumber: number;
}

export interface GoogleCalendar {
  /** Rises with each change. A sync token names the version it was given at. */
  version: number;
  /** The lowest version a sync token may name: an older token is gone (410). */
  syncFrom: number;
  /** In the order they were made. A cancelled event stays, so that a read by token lists it. */
  events: CalendarEvent[];
  channels: CalendarChannel[];
}

export type CalendarAction =
  /** `events.watch`: a channel of the same id is replaced. */
  | { watch: Omit<CalendarChannel, "messageNumber"> }
  /** `channels.stop`, by the channel's id. */
  | { stop: string }
  /** A new event, or the event of that id cancelled, at `at` (RFC 3339). */
  | { add: Pick<CalendarEvent, "id" | "summary" | "start" | "end">; at: string }
  | { cancel: string; at: string }
  /** Every sync token given so far is gone. */
  | { forget: true };

/** One step of a calendar. `refused` says why nothing changed: no channel of that id to stop, no
 *  live channel to push a change to, or no event of that id to cancel. A change answers the event
 *  as it is now and the live channels, each with the number of the message to send. */
export function calendarChanged(
  before: GoogleCalendar | undefined,
  action: CalendarAction,
  now: number,
): {
  calendar: GoogleCalendar;
  refused?: "no_such_channel" | "not_watched" | "no_such_event";
  event?: CalendarEvent;
  channels?: CalendarChannel[];
} {
  const calendar = before || { version: 0, syncFrom: 0, events: [], channels: [] };
  const live = calendar.channels.filter((channel) => channel.expiration > now);
  if ("watch" in action) {
    const others = live.filter((channel) => channel.id !== action.watch.id);
    return {
      calendar: {
        ...calendar,
        // the five newest: a mind makes a new channel a day and stops the old one
        channels: [...others, { ...action.watch, messageNumber: 1 }].slice(-5),
      },
    };
  }
  if ("stop" in action) {
    const others = calendar.channels.filter((channel) => channel.id !== action.stop);
    return others.length === calendar.channels.length
      ? { calendar, refused: "no_such_channel" }
      : { calendar: { ...calendar, channels: others } };
  }
  if ("forget" in action) {
    const version = calendar.version + 1;
    return { calendar: { ...calendar, version, syncFrom: version } };
  }
  if (live.length === 0) return { calendar, refused: "not_watched" };
  const version = calendar.version + 1;
  let event: CalendarEvent;
  let events: CalendarEvent[];
  if ("cancel" in action) {
    const cancelled = calendar.events.find(
      (each) => each.id === action.cancel && each.status === "confirmed",
    );
    if (!cancelled) return { calendar, refused: "no_such_event" };
    event = { ...cancelled, status: "cancelled", updated: action.at, version };
    events = calendar.events.map((each) => (each === cancelled ? event : each));
  } else {
    event = { ...action.add, status: "confirmed", updated: action.at, version };
    events = [...calendar.events, event];
  }
  const dropped = events.slice(0, -CALENDAR_EVENTS_KEPT);
  const channels = live.map((channel) => ({
    ...channel,
    messageNumber: channel.messageNumber + 1,
  }));
  return {
    calendar: {
      version,
      // a token from before a dropped event's last change would miss that change
      syncFrom: Math.max(calendar.syncFrom, ...dropped.map((each) => each.version)),
      events: events.slice(-CALENDAR_EVENTS_KEPT),
      channels,
    },
    event,
    channels,
  };
}