Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

13.1 KB
Raw Blame
import "server-only";

import { Prisma, prisma } from "@rallly/database";
import { nanoid } from "@rallly/utils/nanoid";
import { revalidatePath } from "next/cache";
import { recordPollActivities } from "@/features/activity/mutations";
import { parsePollConferencing } from "@/features/conferencing/data";
import type { PollConferencing } from "@/features/conferencing/schema";
import {
  assertOpenPollCapacity,
  countAdoptableOpenPolls,
  reportAdoptionOverLimit,
} from "@/features/poll/limit/mutations";
import type { AuthorizedSpaceId } from "@/features/space/types";
import { scheduleWebhookDispatch } from "@/features/webhook/mutations";

export type PollOption = {
  startTime: Date;
  duration: number;
};

export type CreatePollParams = {
  userId: string;
  title: string;
  description?: string;
  location?: string;
  conferencing?: PollConferencing;
  timeZone?: string;
  requireParticipantEmail?: boolean;
  hideParticipants?: boolean;
  hideScores?: boolean;
  disableComments?: boolean;
  allowTentativeVotes?: boolean;
  options: PollOption[];
  spaceId: AuthorizedSpaceId;
};

// The shape the API routes serialize; keep it in sync with
// `getPollWithOptions` in data.ts so create, close and get return one poll.
const pollResponseSelect = {
  id: true,
  title: true,
  description: true,
  location: true,
  conferencing: true,
  timeZone: true,
  status: true,
  kind: true,
  createdAt: true,
  updatedAt: true,
  requireParticipantEmail: true,
  hideParticipants: true,
  hideScores: true,
  disableComments: true,
  allowTentativeVotes: true,
  user: {
    select: {
      id: true,
      name: true,
      email: true,
      image: true,
    },
  },
  options: {
    select: {
      id: true,
      startTime: true,
      duration: true,
    },
    orderBy: {
      startTime: "asc",
    },
  },
  _count: {
    select: {
      participants: true,
    },
  },
} satisfies Prisma.PollSelect;

const toPollResponse = <
  T extends {
    id: string;
    conferencing: Prisma.JsonValue | null;
    _count: { participants: number };
  },
>({
  _count,
  conferencing,
  ...poll
}: T) => ({
  ...poll,
  conferencing: parsePollConferencing(conferencing, { pollId: poll.id }),
  participantCount: _count.participants,
});

export const createPoll = async ({
  userId,
  title,
  description,
  location,
  conferencing,
  timeZone,
  requireParticipantEmail,
  hideParticipants,
  hideScores,
  disableComments,
  allowTentativeVotes,
  options,
  spaceId,
}: CreatePollParams) => {
  const kind = options.some((o) => o.duration > 0) ? "time" : "date";

  const poll = await prisma.$transaction(async (tx) => {
    await assertOpenPollCapacity(tx, { userId, spaceId });

    const poll = await tx.poll.create({
      data: {
        id: nanoid(),
        title,
        description,
        location,
        conferencing,
        timeZone,
        requireParticipantEmail,
        hideParticipants,
        hideScores,
        disableComments,
        allowTentativeVotes,
        userId,
        spaceId,
        kind,
        options: { createMany: { data: options } },
      },
      select: pollResponseSelect,
    });

    await recordPollActivities(tx, [
      {
        pollId: poll.id,
        type: "poll_created",
        userId,
        payload: { title },
      },
    ]);
    scheduleWebhookDispatch({ pollId: poll.id });

    return poll;
  });

  return toPollResponse(poll);
};

/**
 * Closes a poll manually. Idempotent: closing an already-closed poll returns
 * the poll unchanged without altering its `closedReason` (so a poll auto-closed
 * by the cron job keeps `closedReason: "auto"`). A scheduled poll is final and
 * is returned unchanged too. Returns `null` when the poll
 * does not exist in the space, letting the caller surface a 404.
 *
 * `userId` attributes the activity event when the actor is known; API key
 * callers act as the space rather than a user and leave it unset.
 */
export const closePoll = async ({
  pollId,
  spaceId,
  userId,
}: {
  pollId: string;
  spaceId: AuthorizedSpaceId;
  userId?: string;
}) => {
  return prisma.$transaction(async (tx) => {
    const poll = await tx.poll.findFirst({
      where: {
        id: pollId,
        spaceId,
        deletedAt: null,
      },
      select: pollResponseSelect,
    });

    if (!poll) {
      return null;
    }

    if (poll.status === "closed" || poll.status === "scheduled") {
      return toPollResponse(poll);
    }

    const closedPoll = await tx.poll.update({
      where: { id: pollId },
      data: { status: "closed", closedReason: "manual" },
      select: pollResponseSelect,
    });

    await recordPollActivities(tx, [
      {
        pollId,
        type: "poll_closed",
        userId: userId ?? null,
        payload: { reason: "manual" },
      },
    ]);
    scheduleWebhookDispatch({ pollId: pollId });

    return toPollResponse(closedPoll);
  });
};

/**
 * Muting is a per-owner notification preference, so the scope is the owner's
 * userId rather than a space.
 */
export const setPollMuted = async ({
  pollId,
  userId,
  muted,
}: {
  pollId: string;
  userId: string;
  muted: boolean;
}) => {
  const { count } = await prisma.poll.updateMany({
    where: {
      id: pollId,
      userId,
      deletedAt: null,
    },
    data: { muted },
  });

  if (count === 0) {
    return { ok: false as const, reason: "notFound" as const };
  }

  return { ok: true as const };
};

export const deletePoll = async (
  pollId: string,
  spaceId: AuthorizedSpaceId,
) => {
  return prisma.$transaction(async (tx) => {
    // Conditional so two concurrent deletes record one transition, not two.
    const { count } = await tx.poll.updateMany({
      where: { id: pollId, spaceId, deletedAt: null },
      data: { deleted: true, deletedAt: new Date() },
    });

    if (count === 0) {
      return null;
    }

    // API keys are space credentials, not a person, so the actor is unknown.
    await recordPollActivities(tx, [
      { pollId, type: "poll_deleted", userId: null, payload: {} },
    ]);
    scheduleWebhookDispatch({ pollId: pollId });

    return { id: pollId };
  });
};

/**
 * Assigns a user's space-less polls to the given space. Guest linking can
 * migrate polls before the user has a space (the linking runs ahead of
 * space provisioning on sign-up, and an existing account may have lost all
 * its spaces), so every place that creates a user's space adopts them.
 */
export async function adoptOrphanedPolls({
  userId,
  spaceId,
}: {
  userId: string;
  spaceId: string;
}) {
  const adoptedOpenCount = await countAdoptableOpenPolls({
    userId,
    spaceId: null,
  });

  await prisma.poll.updateMany({
    where: {
      userId,
      spaceId: null,
    },
    data: {
      spaceId,
    },
  });

  await reportAdoptionOverLimit({
    userId,
    spaceId,
    adoptedOpenCount,
    source: "setup",
  });
}

/**
 * Marks inactive polls as deleted. A poll is inactive when every date has
 * passed at least 30 days ago and there has been no activity (poll edits,
 * participant responses, new comments) in the last 30 days. This guarantees
 * polls are kept for at least 30 days after their final date, and activity
 * extends that.
 * Only marks polls as deleted if they belong to spaces without an active
 * subscription or if they don't have a space associated with them.
 */
export async function deleteInactivePolls() {
  // Define the 30-day threshold once
  const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

  // Mark inactive polls as deleted in a single query
  const { count: markedDeleted } = await prisma.poll.updateMany({
    where: {
      deleted: false,
      // All poll dates passed at least 30 days ago
      options: {
        none: {
          startTime: { gt: thirtyDaysAgo },
        },
      },
      // We don't delete polls that belong to a space with an active subscription
      OR: [
        { spaceId: null },
        {
          space: {
            tier: {
              not: "pro",
            },
          },
        },
      ],
      // Poll is inactive: not edited, and no participant activity (new or
      // updated responses) or new comments in the last 30 days
      updatedAt: { lt: thirtyDaysAgo },
      participants: {
        none: { updatedAt: { gte: thirtyDaysAgo } },
      },
      comments: {
        none: { createdAt: { gte: thirtyDaysAgo } },
      },
    },
    data: {
      deleted: true,
      deletedAt: new Date(),
    },
  });

  return markedDeleted;
}

const AUTO_CLOSE_POLLS_BATCH_SIZE = 500;
// Well inside the house-keeping route's maxDuration.
const AUTO_CLOSE_POLLS_BUDGET_MS = 120_000;

/**
 * Closes polls whose options have all ended — i.e. no option ends in the
 * future, where an option ends at start_time + duration (all-day options, with
 * duration 0, are treated as ending 24h after their start). Closing is
 * non-destructive: the poll becomes read-only but is preserved.
 *
 * Raw SQL because the option-end comparison (start_time + duration) can't be
 * expressed in a Prisma `where`. It also deliberately does not touch
 * `updated_at`, so closing a poll doesn't reset the inactivity clock that
 * delete-inactive-polls keys off. RETURNING feeds the activity writes, which
 * commit in the same transaction as the closes.
 *
 * Finding due polls probes the options of every open poll. That usually
 * takes seconds, but on a cold compute, or the first run after a mass close
 * leaves hint bits to set, it has taken close to a minute, so the scan runs
 * once, outside any transaction. The closes then go in batches by primary key, each its own
 * short transaction that re-checks the condition, so a poll reopened or given
 * a new option since the scan stays open. Short transactions also keep each
 * batch inside the webhook fan-out's overlap window. Stops starting batches
 * after `budgetMs`; any remainder is picked up by the next run.
 */
export async function autoClosePolls({
  batchSize = AUTO_CLOSE_POLLS_BATCH_SIZE,
  budgetMs = AUTO_CLOSE_POLLS_BUDGET_MS,
}: {
  batchSize?: number;
  budgetMs?: number;
} = {}) {
  const startedAt = Date.now();
  let totalClosed = 0;

  const isDue = Prisma.sql`
    p.status = 'open'
    AND p.deleted = false
    AND EXISTS (SELECT 1 FROM options o WHERE o.poll_id = p.id)
    AND NOT EXISTS (
      SELECT 1 FROM options o
      WHERE o.poll_id = p.id
        AND o.start_time + (CASE WHEN o.duration_minutes = 0
              THEN interval '24 hours'
              ELSE make_interval(mins => o.duration_minutes) END) > (now() AT TIME ZONE 'UTC')
    )
  `;

  const due = await prisma.$queryRaw<{ id: string }[]>`
    SELECT p.id FROM polls p WHERE ${isDue}
  `;

  for (let i = 0; i < due.length; i += batchSize) {
    if (Date.now() - startedAt >= budgetMs) {
      break;
    }

    const ids = due.slice(i, i + batchSize).map(({ id }) => id);

    const closed = await prisma.$transaction(
      async (tx) => {
        // FOR UPDATE conflicts with the KEY SHARE lock an option insert takes
        // on its poll, so this waits out in-flight inserts and the UPDATE's
        // fresh snapshot sees them. Ordered so overlapping runs can't deadlock.
        await tx.$queryRaw`
          SELECT p.id FROM polls p
          WHERE p.id = ANY(${ids})
          ORDER BY p.id
          FOR UPDATE
        `;

        const rows = await tx.$queryRaw<{ id: string }[]>`
        UPDATE polls p
        SET status = 'closed', closed_reason = 'auto'
        WHERE p.id = ANY(${ids}) AND ${isDue}
        RETURNING p.id
      `;

        await recordPollActivities(
          tx,
          rows.map(({ id }) => ({
            pollId: id,
            type: "poll_closed" as const,
            userId: null,
            payload: { reason: "auto" as const },
          })),
        );

        return rows.length;
      },
      { timeout: 30_000 },
    );

    totalClosed += closed;
  }

  return totalClosed;
}

const REMOVE_DELETED_POLLS_BATCH_SIZE = 100;

/**
 * Remove polls and corresponding data that have been marked deleted for more than 7 days.
 */
export async function removeDeletedPolls() {
  // First get the ids of all the polls that have been marked as deleted for at least 7 days
  let totalDeletedPolls = 0;
  let hasMore = true;

  const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);

  while (hasMore) {
    const batch = await prisma.poll.findMany({
      where: {
        deleted: true,
        deletedAt: {
          lt: sevenDaysAgo,
        },
      },
      select: { id: true },
      take: REMOVE_DELETED_POLLS_BATCH_SIZE,
    });

    if (batch.length === 0) {
      hasMore = false;
      break;
    }

    const deleted = await prisma.poll.deleteMany({
      where: {
        id: { in: batch.map((poll) => poll.id) },
      },
    });

    totalDeletedPolls += deleted.count;
  }

  return totalDeletedPolls;
}

/**
 * The two pages that render a poll's responses and comments. Nothing they
 * read is cached, so this only makes the action response carry a fresh
 * render of the page that called it and drops the router's copy of both.
 */
export function revalidatePollPages() {
  // "layout" so the nested /vote route is covered too; as a "page" it
  // would keep serving a response the viewer has just deleted.
  revalidatePath("/[locale]/invite/[urlId]", "layout");
  revalidatePath("/[locale]/(optional-space)/poll/[urlId]", "layout");
}