Skip to content

Open source CapCut alternative.

TypeScript

feat(site): promotions queue their segment a page at a time

David Le350867d2a3d3
diff --git a/docs/guides/config-and-experiments.md b/docs/guides/config-and-experiments.md
index fa300f51..dd5999c2 100644
--- a/docs/guides/config-and-experiments.md
+++ b/docs/guides/config-and-experiments.md
@@ -131,7 +131,7 @@ by variant as well.
## Promotions
A promotion is one email from su to an audience, minus anyone an earlier promotion reached; the Pro offers behind it (subscribe bonus, allowance multiplier) are Product-tab settings.
-Every outbound email is a row in one outbox, sent by one drainer in priority order under a daily cap shared by the whole site. A promotion queues its most recently active recipients first and stops at what the rest of the day is forecast to need for welcome and credit emails, and for mail sent by hand during work hours, then picks up the slots that go unused as the day runs down. The cap, the reserves and the work hours are the Daily email sends setting, and the order between kinds is the Email priorities setting.
+Every outbound email is a row in one outbox, sent by one drainer in priority order under the email plan's monthly allowance, shared by the whole site. A promotion is read from the accounts table a page at a time by a job, queues its most recently active recipients first, and stops at what the rest of the billing cycle is forecast to need for welcome and credit emails, and for mail sent by hand on the work days left, then picks up the slots that go unused as the cycle runs down. The allowance, the renewal day, the reserves and the work hours are the Email send budget setting, and the order between kinds is the Email priorities setting.
A credit promotion is a credit offer: one row that promises an account an
amount, the credit's life, and the window it can be claimed in, then records
diff --git a/site/prisma/Marketing.prisma b/site/prisma/Marketing.prisma
index 0a7efed8..54438343 100644
--- a/site/prisma/Marketing.prisma
+++ b/site/prisma/Marketing.prisma
@@ -84,7 +84,7 @@ model Promotion {
audience Json @default("{}")
// Earlier promotions whose recipients are skipped.
excludePromotionIds String[] @default([])
- // "draft" | "sending" | "paused" | "sent"
+ // "draft" | "queuing" | "sending" | "paused" | "sent"
status String @default("draft")
startedAt DateTime?
finishedAt DateTime?
diff --git a/site/src/app/api/su/promotions/[id]/cancel/route.ts b/site/src/app/api/su/promotions/[id]/cancel/route.ts
index ce85e9e9..4c9979a7 100644
--- a/site/src/app/api/su/promotions/[id]/cancel/route.ts
+++ b/site/src/app/api/su/promotions/[id]/cancel/route.ts
@@ -14,7 +14,7 @@ export const POST = withSuperUser(async (_request, { params }: Params) => {
if (!parsed.success) return notFoundResponse();
const promotion = await prisma.promotion.findUnique({ where: { id: parsed.data } });
if (!promotion) return notFoundResponse();
- if (promotion.status !== "sending") {
+ if (promotion.status !== "queuing" && promotion.status !== "sending") {
return invalidResponse([{ path: ["status"], message: "This promotion is not running." }]);
}
await prisma.promotion.update({ data: { status: "paused" }, where: { id: promotion.id } });
diff --git a/site/src/app/api/su/promotions/[id]/route.ts b/site/src/app/api/su/promotions/[id]/route.ts
index 5ce917e4..a3be2930 100644
--- a/site/src/app/api/su/promotions/[id]/route.ts
+++ b/site/src/app/api/su/promotions/[id]/route.ts
@@ -37,7 +37,7 @@ export const DELETE = withSuperUser(async (_request, { params }: Params) => {
if (!id.success) return notFoundResponse();
const existing = await prisma.promotion.findUnique({ select: { status: true }, where: { id: id.data } });
if (!existing) return notFoundResponse();
- if (existing.status === "sending") {
+ if (existing.status === "queuing" || existing.status === "sending") {
return invalidResponse([{ path: ["status"], message: "A promotion that is sending cannot be deleted." }]);
}
await prisma.promotion.delete({ where: { id: id.data } });
diff --git a/site/src/app/api/su/promotions/[id]/send/route.ts b/site/src/app/api/su/promotions/[id]/send/route.ts
index 463366a9..cb7a8e4f 100644
--- a/site/src/app/api/su/promotions/[id]/send/route.ts
+++ b/site/src/app/api/su/promotions/[id]/send/route.ts
@@ -3,27 +3,22 @@ import { z } from "zod";
import { invalidResponse } from "@/lib/config/experimentList";
import { notFoundResponse, withSuperUser } from "@/lib/donkey-api-auth";
-import { queueEmails } from "@/lib/email/outbox";
-import { byMostRecentlyActive, lastActiveByUser } from "@/lib/marketing/lastActive";
-import {
- listPromotions,
- promotionAudienceOf,
- resolvePromotionSegment,
-} from "@/lib/marketing/promotions";
+import { enqueueJob } from "@/lib/jobs/queue";
+import { listPromotions } from "@/lib/marketing/promotions";
import { prisma } from "@/lib/prisma";
-// Resolving a segment reads facts for every account, and without a queue the
-// job's first run happens inside this request, so the budget matches the
-// worker's.
+// Without a queue (local dev) the job's first run happens inside this
+// request, so the budget matches the worker's.
export const maxDuration = 300;
type Params = { params: Promise<{ id: string }> };
const idSchema = z.string().trim().min(1);
-// Starts a send: the segment is resolved into outbox rows once, here, and the
-// outbox drainer mails them under the day's quota. The rows are the send's
-// memory — a later promotion that excludes this one reads them, and a resumed
-// send adds only the accounts not already queued.
+// Starts a send: a job reads the segment a page at a time into outbox rows
+// while the promotion is queuing, moves it to sending once every recipient
+// is a row, and the outbox drainer mails the rows under the budget. The rows
+// are the send's memory — a later promotion that excludes this one reads
+// them, and a resumed send adds only the accounts not already queued.
export const POST = withSuperUser(async (request, { params }: Params) => {
const id = idSchema.safeParse((await params).id);
if (!id.success) return notFoundResponse();
@@ -33,35 +28,11 @@ export const POST = withSuperUser(async (request, { params }: Params) => {
return invalidResponse([{ path: ["status"], message: "This promotion has already been sent." }]);
}
- const segment = await resolvePromotionSegment({
- audience: promotionAudienceOf(promotion.audience),
- excludePromotionIds: promotion.excludePromotionIds,
- });
- if (segment.users.length === 0) {
- return invalidResponse([{ path: ["audience"], message: "Nobody is in this segment." }]);
- }
-
- // The people most recently using the product go first: a campaign that
- // outlasts the day's send quota reaches them before it reaches the
- // dormant.
- const ranked = byMostRecentlyActive(segment.users, await lastActiveByUser(segment.users.map((u) => u.id)));
await prisma.promotion.update({
- data: { startedAt: promotion.startedAt ?? new Date(), status: "sending" },
+ data: { startedAt: promotion.startedAt ?? new Date(), status: "queuing" },
where: { id: promotion.id },
});
- await queueEmails(
- ranked.map((user, rank) => ({
- idempotencyKey: `promotion:${promotion.id}:${user.id}`,
- kind: "promotion",
- payload: { promotionId: promotion.id },
- promotionId: promotion.id,
- rank,
- userId: user.id,
- })),
- );
+ await enqueueJob("promotion-queue", { promotionId: promotion.id }, request.donkey.userId);
- return NextResponse.json({
- promotions: await listPromotions(),
- recipients: segment.users.length,
- });
+ return NextResponse.json({ promotions: await listPromotions() });
});
diff --git a/site/src/app/su/promotions/page.tsx b/site/src/app/su/promotions/page.tsx
index 0feb32a5..e721cc40 100644
--- a/site/src/app/su/promotions/page.tsx
+++ b/site/src/app/su/promotions/page.tsx
@@ -32,6 +32,7 @@ type BadgeVariant = "default" | "secondary" | "outline" | "destructive";
const STATUS_VARIANT: Record<PromotionStatus, BadgeVariant> = {
draft: "outline",
+ queuing: "default",
sending: "default",
paused: "outline",
sent: "secondary",
@@ -174,7 +175,7 @@ function PromotionRow({
<Button size="sm" variant="outline" onClick={onDuplicate}>
Duplicate
</Button>
- {p.status === "sending" ? (
+ {p.status === "queuing" || p.status === "sending" ? (
<Button
size="sm"
variant="outline"
diff --git a/site/src/lib/config/audienceFacts.ts b/site/src/lib/config/audienceFacts.ts
index 87e7b5d5..d37b9a16 100644
--- a/site/src/lib/config/audienceFacts.ts
+++ b/site/src/lib/config/audienceFacts.ts
@@ -1,64 +1,94 @@
import { cutLimitsForTier } from "@/cut/server/cloud/limits";
-import { usageBytes } from "@/cut/server/cloud/usage";
import type { AudienceFact, AudienceFacts } from "@donkeycut/abexp";
+import { ACTIVE_PRO_STATUSES } from "@/lib/billing/pro-subscription";
import { PURCHASE_SOURCES } from "@/lib/config/purchases";
-import { getActiveProSubscription } from "@/lib/billing/pro-subscription";
import { prisma } from "@/lib/prisma";
-// Collects the facts an audience needs about one account, and only those: an
-// experiment over countries costs no billing query, and an account that
-// already holds every running experiment costs none at all.
+// Collects the facts an audience needs about a page of accounts, and only
+// those: an experiment over countries costs no billing query, and an account
+// that already holds every running experiment costs none at all. Each fact is
+// one set query over the page, so a segment of any size costs a handful of
+// statements per page and never one per person.
const clampPercent = (x: number) => Math.min(100, Math.max(0, x));
-export async function collectFacts(
- userId: string,
- known: { country: string | null; createdAt: Date },
+export type KnownUser = { id: string; country: string | null; createdAt: Date };
+
+export async function collectFactsFor(
+ users: KnownUser[],
needs: Set<AudienceFact>,
-): Promise<AudienceFacts> {
- const facts: AudienceFacts = {
- country: known.country,
- createdAt: known.createdAt,
- pro: false,
- paid: false,
- lastActiveAt: null,
- storageUsedPercent: null,
- creditsUsedPercent: null,
- };
+): Promise<Map<string, AudienceFacts>> {
+ const facts = new Map<string, AudienceFacts>();
+ for (const user of users) {
+ facts.set(user.id, {
+ country: user.country,
+ createdAt: user.createdAt,
+ pro: false,
+ paid: false,
+ lastActiveAt: null,
+ storageUsedPercent: null,
+ creditsUsedPercent: null,
+ });
+ }
+ if (users.length === 0) return facts;
+ const ids = users.map((u) => u.id);
const wantsPro = needs.has("pro") || needs.has("storageUsedPercent");
- const [pro, paid, session, storage, credits] = await Promise.all([
- wantsPro ? getActiveProSubscription(userId) : null,
+ const [pro, paid, sessions, storage, credits] = await Promise.all([
+ wantsPro
+ ? prisma.proSubscription.findMany({
+ select: { userId: true },
+ where: { status: { in: [...ACTIVE_PRO_STATUSES] }, userId: { in: ids } },
+ })
+ : [],
needs.has("paid")
- ? prisma.userCreditGrant.count({ where: { userId, source: { in: [...PURCHASE_SOURCES] } } })
- : 0,
+ ? prisma.userCreditGrant.findMany({
+ distinct: ["userId"],
+ select: { userId: true },
+ where: { source: { in: [...PURCHASE_SOURCES] }, userId: { in: ids } },
+ })
+ : [],
needs.has("lastActiveAt")
- ? prisma.session.findFirst({ where: { userId }, orderBy: { updatedAt: "desc" }, select: { updatedAt: true } })
- : null,
+ ? prisma.session.groupBy({ _max: { updatedAt: true }, by: ["userId"], where: { userId: { in: ids } } })
+ : [],
needs.has("storageUsedPercent")
? Promise.all([
- usageBytes(userId),
- prisma.user.findUnique({ where: { id: userId }, select: { superUser: true } }),
+ prisma.cutStorageUsage.findMany({ select: { bytes: true, userId: true }, where: { userId: { in: ids } } }),
+ prisma.user.findMany({ select: { id: true, superUser: true }, where: { id: { in: ids } } }),
])
: null,
needs.has("creditsUsedPercent")
- ? prisma.userCreditAccount.findUnique({
- where: { userId },
- select: { lifetimeGrantedMicros: true, lifetimeChargedMicros: true },
+ ? prisma.userCreditAccount.findMany({
+ select: { lifetimeChargedMicros: true, lifetimeGrantedMicros: true, userId: true },
+ where: { userId: { in: ids } },
})
- : null,
+ : [],
]);
- facts.pro = pro !== null;
- facts.paid = paid > 0;
- facts.lastActiveAt = session?.updatedAt ?? null;
+ for (const row of pro) facts.get(row.userId)!.pro = true;
+ for (const row of paid) facts.get(row.userId)!.paid = true;
+ for (const row of sessions) facts.get(row.userId)!.lastActiveAt = row._max.updatedAt;
if (storage) {
- const [bytes, user] = storage;
- const quota = cutLimitsForTier({ superUser: user?.superUser ?? false, pro: facts.pro }).storageBytes;
- facts.storageUsedPercent = quota === null ? null : clampPercent((100 * bytes) / quota);
+ const [usage, tiers] = storage;
+ const bytesBy = new Map(usage.map((row) => [row.userId, Number(row.bytes)]));
+ for (const tier of tiers) {
+ const fact = facts.get(tier.id)!;
+ const quota = cutLimitsForTier({ superUser: tier.superUser, pro: fact.pro }).storageBytes;
+ fact.storageUsedPercent = quota === null ? null : clampPercent((100 * (bytesBy.get(tier.id) ?? 0)) / quota);
+ }
}
- if (credits) {
- const granted = Number(credits.lifetimeGrantedMicros);
- const charged = Number(credits.lifetimeChargedMicros);
- facts.creditsUsedPercent = granted > 0 ? clampPercent((100 * charged) / granted) : null;
+ for (const row of credits) {
+ const granted = Number(row.lifetimeGrantedMicros);
+ const charged = Number(row.lifetimeChargedMicros);
+ facts.get(row.userId)!.creditsUsedPercent = granted > 0 ? clampPercent((100 * charged) / granted) : null;
}
return facts;
}
+
+/** The facts for one account, as a request resolving its experiments reads them. */
+export async function collectFacts(
+ userId: string,
+ known: { country: string | null; createdAt: Date },
+ needs: Set<AudienceFact>,
+): Promise<AudienceFacts> {
+ const facts = await collectFactsFor([{ id: userId, ...known }], needs);
+ return facts.get(userId)!;
+}
diff --git a/site/src/lib/jobs/promotion-queue.ts b/site/src/lib/jobs/promotion-queue.ts
new file mode 100644
index 00000000..8c5b2e79
--- /dev/null
+++ b/site/src/lib/jobs/promotion-queue.ts
@@ -0,0 +1,75 @@
+import { z } from "zod";
+
+import { queueEmails, scheduleDrain } from "@/lib/email/outbox";
+import { defineJob, JobFailure } from "@/lib/jobs/registry";
+import { activityRank, lastActiveByUser } from "@/lib/marketing/lastActive";
+import { promotionAudienceOf, resolvePromotionSegment } from "@/lib/marketing/promotions";
+import { prisma } from "@/lib/prisma";
+
+// Turns a promotion's segment into outbox rows, a page of accounts at a
+// time: the audience is resolved for the page, the page is ranked by when
+// each person last used the product, and its rows are queued. The promotion
+// is queuing throughout, so the drainer can send rows as they land without
+// finishing it early; once the whole list is read it moves to sending, and
+// the drainer finishes it when the last row goes. A run that runs out of
+// time queues its continuation from the last account read; a promotion
+// paused meanwhile stops where it is and a later send resumes it, the rows
+// already queued left as they are. Under the worker's 300 s maxDuration,
+// with room for the continuation's own writes.
+const BUDGET_MS = 200_000;
+
+export const promotionQueueJob = defineJob(
+ z.object({ promotionId: z.string().min(1), cursor: z.string().min(1).optional() }).strict(),
+ async ({ promotionId, cursor }) => {
+ const promotion = await prisma.promotion.findUnique({ where: { id: promotionId } });
+ if (!promotion) throw new JobFailure("The promotion no longer exists.");
+ if (promotion.status !== "queuing") return { queued: 0, stopped: true };
+
+ const now = new Date();
+ let queued = 0;
+ const result = await resolvePromotionSegment(
+ { audience: promotionAudienceOf(promotion.audience), excludePromotionIds: promotion.excludePromotionIds },
+ {
+ cursor,
+ deadline: Date.now() + BUDGET_MS,
+ now,
+ onPage: async (users) => {
+ const standing = await prisma.promotion.findUnique({ select: { status: true }, where: { id: promotionId } });
+ if (standing?.status !== "queuing") return false;
+ if (users.length === 0) return;
+ const lastActiveBy = await lastActiveByUser(users.map((u) => u.id));
+ queued += await queueEmails(
+ users.map((user) => ({
+ idempotencyKey: `promotion:${promotionId}:${user.id}`,
+ kind: "promotion",
+ payload: { promotionId },
+ promotionId,
+ rank: activityRank(now, lastActiveBy.get(user.id)),
+ userId: user.id,
+ })),
+ );
+ },
+ },
+ );
+
+ if (result.cursor !== null) {
+ const standing = await prisma.promotion.findUnique({ select: { status: true }, where: { id: promotionId } });
+ if (standing?.status !== "queuing") return { queued, stopped: true };
+ const { enqueueJob } = await import("@/lib/jobs/queue");
+ await enqueueJob("promotion-queue", { promotionId, cursor: result.cursor }, "system");
+ return { queued, continued: true };
+ }
+
+ // The whole list was read. Nothing outstanding — nobody was in the
+ // segment, or the drainer kept up — finishes it here; otherwise it is
+ // sending, and the drainer finishes it when the last row goes.
+ const owed = await prisma.emailSend.count({ where: { promotionId, state: { in: ["queued", "sending"] } } });
+ const moved = await prisma.promotion.updateMany({
+ data: owed === 0 ? { finishedAt: new Date(), status: "sent" } : { status: "sending" },
+ where: { id: promotionId, status: "queuing" },
+ });
+ if (moved.count === 0) return { queued, stopped: true };
+ if (owed > 0) await scheduleDrain(0);
+ return { queued };
+ },
+);
diff --git a/site/src/lib/jobs/registry.ts b/site/src/lib/jobs/registry.ts
index 972dfab4..6b1266ca 100644
--- a/site/src/lib/jobs/registry.ts
+++ b/site/src/lib/jobs/registry.ts
@@ -9,6 +9,7 @@ import { deleteUserJob } from "@/lib/jobs/delete-user";
import { experimentResultsJob } from "@/lib/jobs/experiment-results";
import { outreachScanJob } from "@/lib/jobs/outreach-scan";
import { emailDrainJob } from "@/lib/jobs/email-drain";
+import { promotionQueueJob } from "@/lib/jobs/promotion-queue";
// Thrown by an executor when the job can never succeed — the message lands on
// the job row as its error. Anything else thrown is transient: the claim is
@@ -48,4 +49,5 @@ export const jobKinds: Record<string, JobKind> = {
"email-drain": emailDrainJob,
"experiment-results": experimentResultsJob,
"outreach-scan": outreachScanJob,
+ "promotion-queue": promotionQueueJob,
};
diff --git a/site/src/lib/marketing/lastActive.ts b/site/src/lib/marketing/lastActive.ts
index 6e5a7ee0..0ede1adb 100644
--- a/site/src/lib/marketing/lastActive.ts
+++ b/site/src/lib/marketing/lastActive.ts
@@ -35,9 +35,13 @@ export async function lastActiveByUser(userIds: string[]): Promise<Map<string, D
return lastActiveBy;
}
-/** The ids most recently active first; accounts never seen using the
- * product come last, in the order given. */
-export function byMostRecentlyActive<T extends { id: string }>(users: T[], lastActiveBy: Map<string, Date>): T[] {
- const at = (user: T) => lastActiveBy.get(user.id)?.getTime() ?? 0;
- return [...users].sort((a, b) => at(b) - at(a));
+// The largest rank a row can hold: an account never seen using the product.
+const NEVER_ACTIVE_RANK = 2 ** 31 - 1;
+
+/** A promotion row's place in the queue: seconds since the account last used
+ * the product, so the people most recently active go first however many
+ * pages the segment was read in. */
+export function activityRank(now: Date, lastActiveAt: Date | undefined): number {
+ if (!lastActiveAt) return NEVER_ACTIVE_RANK;
+ return Math.min(NEVER_ACTIVE_RANK, Math.max(0, Math.floor((now.getTime() - lastActiveAt.getTime()) / 1000)));
}
diff --git a/site/src/lib/marketing/promotionInput.ts b/site/src/lib/marketing/promotionInput.ts
index ed8828fb..6cc97b62 100644
--- a/site/src/lib/marketing/promotionInput.ts
+++ b/site/src/lib/marketing/promotionInput.ts
@@ -8,7 +8,9 @@ import { CLAIM_URL_PLACEHOLDER, promotionOfferSchema, type PromotionOffer } from
export const PROMOTION_SENDERS = ["bulk", "personal"] as const;
export type PromotionSender = (typeof PROMOTION_SENDERS)[number];
-export const PROMOTION_STATUSES = ["draft", "sending", "paused", "sent"] as const;
+// "queuing" while a job reads the segment into outbox rows; "sending" once
+// every recipient is queued, so the drainer can finish it.
+export const PROMOTION_STATUSES = ["draft", "queuing", "sending", "paused", "sent"] as const;
export type PromotionStatus = (typeof PROMOTION_STATUSES)[number];
diff --git a/site/src/lib/marketing/promotions.ts b/site/src/lib/marketing/promotions.ts
index 176f5b5a..f6b21cfc 100644
--- a/site/src/lib/marketing/promotions.ts
+++ b/site/src/lib/marketing/promotions.ts
@@ -3,7 +3,7 @@ import { audienceNeeds, audienceSchema, matchesAudience, type Audience } from "@
import type { Prisma } from "@/generated/prisma/client";
import { DONKEY_LOGO_CID, DONKEY_LOGO_PNG_BASE64 } from "@/emails/_components/logo";
import PromotionEmail from "@/emails/promotion";
-import { collectFacts } from "@/lib/config/audienceFacts";
+import { collectFactsFor } from "@/lib/config/audienceFacts";
import { bulkFrom, emailFrom, type EmailMessage, type EmailUser } from "@/lib/email/resend";
import { PermanentSendError } from "@/lib/email/errors";
import { unsubscribeActionUrl, unsubscribePageUrl } from "@/lib/email/unsubscribe";
@@ -98,72 +98,84 @@ export function buildPromotionEmail(
export type PromotionSegment = { audience: Audience; excludePromotionIds: string[] };
-export type SegmentResolution = SegmentCount & { users: EmailUser[] };
+export type SegmentResolution = SegmentCount & {
+ // Where the walk stopped: the last account read when the deadline came,
+ // null once the whole list was seen. A caller resumes by passing it back.
+ cursor: string | null;
+};
+
+export type ResolveOptions = {
+ now?: Date;
+ // Resume from an earlier call's cursor.
+ cursor?: string;
+ // A time (ms since epoch) after which no further page is read.
+ deadline?: number;
+ // Receives each page of recipients as it is found. Returning false stops
+ // the walk, leaving the cursor on that page.
+ onPage?: (users: EmailUser[]) => Promise<boolean | void>;
+};
const USER_PAGE = 500;
-const FACTS_CONCURRENCY = 10;
/** Everyone a segment reaches: the accounts the audience rules admit, less
- * the unsubscribed, less the recipients of the excluded promotions. The
- * counts of those left out are taken inside the audience, so they describe
- * the segment. Country is never known here, so a countries rule admits
- * nobody. */
+ * the unsubscribed, less the recipients of the excluded promotions. The list
+ * is read a page at a time and every fact is one set query over the page,
+ * so a segment of any size costs a handful of statements per page and holds
+ * one page in memory. The counts describe the pages this call walked; those
+ * left out are taken inside the audience, so they describe the segment.
+ * Country is never known here, so a countries rule admits nobody. */
export async function resolvePromotionSegment(
segment: PromotionSegment,
- now = new Date(),
+ { now = new Date(), cursor, deadline, onPage }: ResolveOptions = {},
): Promise<SegmentResolution> {
- const [unsubscribedRows, receivedRows] = await Promise.all([
- prisma.userEmailSettings.findMany({
- select: { userId: true },
- where: { marketingUnsubscribedAt: { not: null } },
- }),
- segment.excludePromotionIds.length > 0
- ? prisma.emailSend.findMany({
- distinct: ["userId"],
- select: { userId: true },
- where: { promotionId: { in: segment.excludePromotionIds }, state: "sent" },
- })
- : Promise.resolve([]),
- ]);
- const unsubscribed = new Set(unsubscribedRows.map((r) => r.userId));
- const received = new Set(receivedRows.map((r) => r.userId));
const needs = audienceNeeds(segment.audience);
-
- const result: SegmentResolution = {
- users: [],
- recipients: 0,
- unsubscribed: 0,
- alreadyReceived: 0,
- outsideAudience: 0,
- };
- let cursor: string | undefined;
+ const result: SegmentResolution = { cursor: null, recipients: 0, unsubscribed: 0, alreadyReceived: 0, outsideAudience: 0 };
+ let last = cursor;
for (;;) {
const page = await prisma.user.findMany({
orderBy: { id: "asc" },
- select: { createdAt: true, email: true, id: true, name: true },
+ select: {
+ createdAt: true,
+ email: true,
+ emailSettings: { select: { marketingUnsubscribedAt: true } },
+ id: true,
+ name: true,
+ },
take: USER_PAGE,
- ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
+ ...(last ? { cursor: { id: last }, skip: 1 } : {}),
});
if (page.length === 0) break;
- cursor = page[page.length - 1].id;
-
- for (let i = 0; i < page.length; i += FACTS_CONCURRENCY) {
- const slice = page.slice(i, i + FACTS_CONCURRENCY);
- const matched = await Promise.all(
- slice.map(async (user) => {
- const facts = await collectFacts(user.id, { country: null, createdAt: user.createdAt }, needs);
- return matchesAudience(segment.audience, facts, now);
- }),
- );
- slice.forEach((user, j) => {
- if (!matched[j]) result.outsideAudience++;
- else if (unsubscribed.has(user.id)) result.unsubscribed++;
- else if (received.has(user.id)) result.alreadyReceived++;
- else result.users.push({ email: user.email, id: user.id, name: user.name });
- });
+ const ids = page.map((u) => u.id);
+ const [facts, receivedRows] = await Promise.all([
+ collectFactsFor(page.map((u) => ({ id: u.id, country: null, createdAt: u.createdAt })), needs),
+ segment.excludePromotionIds.length > 0
+ ? prisma.emailSend.findMany({
+ distinct: ["userId"],
+ select: { userId: true },
+ where: { promotionId: { in: segment.excludePromotionIds }, state: "sent", userId: { in: ids } },
+ })
+ : [],
+ ]);
+ const received = new Set(receivedRows.map((r) => r.userId));
+ const users: EmailUser[] = [];
+ for (const user of page) {
+ if (!matchesAudience(segment.audience, facts.get(user.id)!, now)) result.outsideAudience++;
+ else if (user.emailSettings?.marketingUnsubscribedAt) result.unsubscribed++;
+ else if (received.has(user.id)) result.alreadyReceived++;
+ else users.push({ email: user.email, id: user.id, name: user.name });
+ }
+ result.recipients += users.length;
+ last = page[page.length - 1].id;
+ if (onPage && (await onPage(users)) === false) {
+ result.cursor = last;
+ return result;
+ }
+ if (page.length < USER_PAGE) break;
+ if (deadline !== undefined && Date.now() >= deadline) {
+ result.cursor = last;
+ return result;
}
}
- result.recipients = result.users.length;
return result;
}
diff --git a/site/src/queries/promotions.ts b/site/src/queries/promotions.ts
index 8ffa8361..e8f6962f 100644
--- a/site/src/queries/promotions.ts
+++ b/site/src/queries/promotions.ts
@@ -36,7 +36,7 @@ export function usePromotions() {
queryFn: () => apiFetch<Body>("/api/su/promotions"),
queryKey: promotionsQueryKey,
refetchInterval: (query) =>
- query.state.data?.promotions.some((p) => p.status === "sending") ? 3000 : false,
+ query.state.data?.promotions.some((p) => p.status === "queuing" || p.status === "sending") ? 3000 : false,
});
}
@@ -69,10 +69,9 @@ export function useSendPromotion() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: string) =>
- apiFetch<{ recipients: number }>(
- `/api/su/promotions/${encodeURIComponent(id)}/send`,
- { method: "POST" },
- ),
+ apiFetch<{ promotions: PromotionSummary[] }>(`/api/su/promotions/${encodeURIComponent(id)}/send`, {
+ method: "POST",
+ }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: promotionsQueryKey }),
});
}