fix(journey): retry unsent follower digests

Record pending entries per follower alongside the in-app announcement. Retry only unsettled deliveries and recheck current sharing and entry visibility before composing mail.
This commit is contained in:
Maurice
2026-12-06 16:05:09 +01:00
parent 36bf9fb223
commit a796383e3f
10 changed files with 236 additions and 81 deletions
@@ -15,6 +15,7 @@ export class JourneyShareSubscribers {
unsubscribe_token!: string;
last_notified_at?: string | null;
created_at?: string | null;
pending_digest_entries?: string | null;
}
export const JourneyShareSubscribersSchema = defineEntity({
@@ -36,5 +37,6 @@ export const JourneyShareSubscribersSchema = defineEntity({
unsubscribe_token: p.text(),
last_notified_at: p.type(DbTimestampType).nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
pending_digest_entries: p.text().nullable(),
},
});
+6
View File
@@ -121,6 +121,12 @@ export const USER_MFA_BACKUP_CODES: JsonColumn<unknown[]> = {
fallback: () => [],
};
export const JOURNEY_PENDING_DIGEST_ENTRIES: JsonColumn<number[]> = {
column: 'journey_share_subscribers.pending_digest_entries',
schema: z.array(z.number().int().positive()),
fallback: () => [],
};
/** A journey entry's tags. */
export const JOURNEY_ENTRY_TAGS: JsonColumn<string[]> = {
column: 'journey_entries.tags',
@@ -12,4 +12,5 @@ export interface JourneyShareSubscribersTable {
unsubscribe_token: string;
last_notified_at: InsertOptional<string | null>;
created_at: InsertOptional<string | null>;
pending_digest_entries: InsertOptional<string | null>;
}
@@ -0,0 +1,13 @@
import { engineDdl } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
export class Migration20200101046660_a_journey_keeps_unsent_digests extends Migration {
override name = 'Migration20200101046660_a_journey_keeps_unsent_digests';
override up(): void {
engineDdl(this, {
sqlite: ['ALTER TABLE journey_share_subscribers ADD COLUMN pending_digest_entries TEXT'],
postgres: ['alter table "journey_share_subscribers" add "pending_digest_entries" text null'],
});
}
}
@@ -836,21 +836,29 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
/** The entries of one journey that {@link listJourneysToAnnounce} found, in the journal's order. */
async listToAnnounce(journeyId: number): Promise<JourneyEntryToAnnounce[]> {
return await this.kysely<JourneyEntriesDateSortKyselyDB>()
return await this.announceEntries(journeyId).where('announced', '=', 0).execute();
}
/** Entries are checked again before an email retry, since a draft or deletion takes them off the link. */
async listPendingDigestEntries(journeyId: number, ids: number[]): Promise<JourneyEntryToAnnounce[]> {
if (ids.length === 0) return [];
return await this.announceEntries(journeyId).where('id', 'in', ids).execute();
}
private announceEntries(journeyId: number) {
return this.kysely<JourneyEntriesDateSortKyselyDB>()
.selectFrom('journey_entries')
.select(['id', 'title', 'entry_date', 'location_name', 'author_id'])
.where('journey_id', '=', journeyId)
.where('announced', '=', 0)
.where('type', '!=', 'skeleton')
.where('dismissed', '=', 0)
.where('is_draft', '=', 0)
.orderBy('entry_date', 'asc')
.orderBy('sort_order', 'asc')
.orderBy('id', 'asc')
.execute();
.orderBy('id', 'asc');
}
/** The digest spoke of these entries: never again, even if one goes back to a draft and returns. */
/** The entries were announced to the journey and added to the pending digests. */
async markAnnounced(ids: number[]): Promise<void> {
if (ids.length === 0) return;
await this.kysely<JourneyEntriesDateSortKyselyDB>()
@@ -14,6 +14,7 @@ interface JourneyShareSubscriberRow {
confirmed_at: string | null;
unsubscribe_token: string;
last_notified_at: string | null;
pending_digest_entries: string | null;
created_at: string | null;
}
@@ -108,16 +109,38 @@ export class JourneyShareSubscribersRepository extends TrekRepository<JourneySha
return await this.nativeDelete({ id, shareToken: shareTokenId });
}
/**
* The confirmed addresses of a link that got no digest since `cutoffAt`
* (canonical DATETIME text): at most one mail a day each.
*/
/** Keeps the entry ids an address still has to hear about. */
async setPendingDigest(id: number, entryIds: string | null): Promise<void> {
await this.db()
.updateTable('journey_share_subscribers')
.set({ pending_digest_entries: entryIds })
.where('id', '=', id)
.execute();
}
/** Journeys that have mail waiting for at least one recipient due a digest. */
async listDueJourneyIds(cutoffAt: string): Promise<number[]> {
const rows = await this.db()
.selectFrom('journey_share_subscribers as s')
.innerJoin('journey_share_tokens as t', 't.id', 's.share_token_id')
.select('t.journey_id')
.distinct()
.where('s.confirmed_at', 'is not', null)
.where('s.pending_digest_entries', 'is not', null)
.where((eb) => eb.or([eb('s.last_notified_at', 'is', null), eb('s.last_notified_at', '<', cutoffAt)]))
.orderBy('t.journey_id', 'asc')
.execute();
return rows.map((row) => row.journey_id);
}
/** Confirmed followers of a link who still have mail and are due a digest. */
async listDue(shareTokenId: number, cutoffAt: string): Promise<JourneyShareSubscriberRow[]> {
return await this.db()
.selectFrom('journey_share_subscribers')
.selectAll()
.where('share_token_id', '=', shareTokenId)
.where('confirmed_at', 'is not', null)
.where('pending_digest_entries', 'is not', null)
.where((eb) => eb.or([eb('last_notified_at', 'is', null), eb('last_notified_at', '<', cutoffAt)]))
.orderBy('id', 'asc')
.execute();
@@ -128,7 +151,7 @@ export class JourneyShareSubscribersRepository extends TrekRepository<JourneySha
if (ids.length === 0) return;
await this.db()
.updateTable('journey_share_subscribers')
.set({ last_notified_at: notifiedAt })
.set({ last_notified_at: notifiedAt, pending_digest_entries: null })
.where('id', 'in', ids)
.execute();
}
+105 -66
View File
@@ -3,14 +3,17 @@ import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
import { JourneyShareSubscribers } from '../../db/entities/JourneyShareSubscribers.entity';
import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity';
import { Journeys } from '../../db/entities/Journeys.entity';
import { JOURNEY_PENDING_DIGEST_ENTRIES } from '../../db/json-columns';
import type { JourneyEntriesRepository, JourneyEntryToAnnounce } from '../../db/repositories/JourneyEntries.repository';
import type { JourneyShareSubscribersRepository } from '../../db/repositories/JourneyShareSubscribers.repository';
import type { JourneyShareTokensRepository } from '../../db/repositories/JourneyShareTokens.repository';
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import { dbNow } from '../../db/types';
import { forEachInOrder } from '../../utils/for-each-in-order';
import { decodeJson, encodeJson } from '../../utils/json-column';
import { AddonsService } from '../addons/addons.service';
import { logError } from '../audit/audit-log.logger';
import { UnitOfWork } from '../database/unit-of-work';
import { MailerService } from '../notifications/mailer/mailer.service';
import { NotificationsService } from '../notifications/notifications.service';
import { shareLinkExpired } from './journey-share-access';
@@ -24,6 +27,13 @@ const DIGEST_MIN_GAP_MS = 20 * 60 * 60 * 1000;
/** How long an address may wait for its confirmation before it is forgotten. */
const UNCONFIRMED_KEEP_MS = 7 * 24 * 60 * 60 * 1000;
function entryBatches(ids: number[]): number[][] {
const size = 500;
return Array.from({ length: Math.ceil(ids.length / size) }, (_, index) =>
ids.slice(index * size, (index + 1) * size),
);
}
/** What one run of the digest did. */
export interface JourneyDigestResult {
journeys: number;
@@ -36,74 +46,77 @@ function message(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/**
* The daily digest of what was published in a journey (#1669).
*
* An entry counts once it is something a reader of the share link would see
* (published, not a skeleton, not a dismissed suggestion) and the digest has
* not spoken of it yet (`journey_entries.announced`). Once a day, for every
* journey holding such entries:
*
* - everyone on the journey hears about them in the app and on the channels
* they chose (`journey_entry_published`, their notification settings apply),
* unless every one of them is their own;
* - every confirmed follower of its share link gets one mail naming them, when
* the link allows following, still works, shows its timeline or its map,
* and the instance can send mail; each at most once a day, in the language
* they chose, with the link that stops the mails (a link behind a password
* only says that there is something new, without naming the entries);
* - and the entries are marked as told, so no digest names one twice, also
* when it goes back to a draft and comes out again.
*
* Every run also forgets the addresses that never confirmed within a week.
*/
/** Queues mail per confirmed follower as new entries are announced to the journey. */
@Injectable()
export class JourneyDigestService {
constructor(
private readonly addons: AddonsService,
private readonly notifications: NotificationsService,
private readonly mailer: MailerService,
private readonly uow: UnitOfWork,
@InjectRepository(JourneyEntries) private readonly entriesRepo: JourneyEntriesRepository,
@InjectRepository(Journeys) private readonly journeysRepo: JourneysRepository,
@InjectRepository(JourneyShareTokens) private readonly linksRepo: JourneyShareTokensRepository,
@InjectRepository(JourneyShareSubscribers) private readonly subscribersRepo: JourneyShareSubscribersRepository,
) {}
/**
* One run: every journey with something new, one after the other, so one
* that fails is logged and the others still go out.
*
* @txIndependent each journey is announced on its own, with mail sent between the writes.
*/
/** @txIndependent Pending mail and in-app announcements are recorded before sending. */
async run(now: Date = new Date()): Promise<JourneyDigestResult> {
const result: JourneyDigestResult = { journeys: 0, notified: 0, mailed: 0, purged: 0 };
if (!(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) return result;
const forgetBefore = dbNow(new Date(now.getTime() - UNCONFIRMED_KEEP_MS));
result.purged = await this.subscribersRepo.purgeUnconfirmed(forgetBefore);
const canMail = await this.mailer.isSmtpConfigured();
result.purged = await this.subscribersRepo.purgeUnconfirmed(dbNow(new Date(now.getTime() - UNCONFIRMED_KEEP_MS)));
const journeyIds = await this.entriesRepo.listJourneysToAnnounce();
await forEachInOrder(journeyIds, async (journeyId) => {
try {
const done = await this.announce(journeyId, now, canMail);
result.notified += await this.announce(journeyId, now);
result.journeys += 1;
result.notified += done.notified;
result.mailed += done.mailed;
} catch (err) {
logError(`[journey-digest] journey ${journeyId}: ${message(err)}`);
}
});
if (await this.mailer.isSmtpConfigured()) {
result.mailed = await this.sendPending(now);
}
return result;
}
/** @txIndependent the notifications and mails go out between the reads and the final mark. */
private async announce(journeyId: number, now: Date, canMail: boolean) {
const entries = await this.entriesRepo.listToAnnounce(journeyId);
const journey = await this.journeysRepo.findById(journeyId);
if (entries.length === 0 || !journey) return { notified: 0, mailed: 0 };
const notified = await this.notifyPeople(journeyId, journey.title, entries);
const mailed = canMail ? await this.mailFollowers(journeyId, journey.title, entries, now) : 0;
await this.entriesRepo.markAnnounced(entries.map((e) => e.id));
return { notified, mailed };
private async announce(journeyId: number, now: Date): Promise<number> {
const batch = await this.uow.transactional(async () => {
const entries = await this.entriesRepo.listToAnnounce(journeyId);
const journey = await this.journeysRepo.findById(journeyId);
if (entries.length === 0 || !journey) return null;
const ids = entries.map((entry) => entry.id);
await this.queueForFollowers(journeyId, ids, now);
await forEachInOrder(entryBatches(ids), (chunk) => this.entriesRepo.markAnnounced(chunk));
return { title: journey.title, entries };
});
return batch ? this.notifyPeople(journeyId, batch.title, batch.entries) : 0;
}
private async queueForFollowers(journeyId: number, ids: number[], now: Date): Promise<void> {
const link = await this.deliveryLink(journeyId, now);
if (!link) return;
const followers = await this.subscribersRepo.listForLink(link.id);
await forEachInOrder(followers, async (follower) => {
if (follower.confirmed_at === null) return;
const kept = decodeJson(JOURNEY_PENDING_DIGEST_ENTRIES, follower.pending_digest_entries, String(follower.id));
await this.subscribersRepo.setPendingDigest(
follower.id,
encodeJson(JOURNEY_PENDING_DIGEST_ENTRIES, [...kept, ...ids]),
);
});
}
private async deliveryLink(journeyId: number, now: Date) {
const link = await this.linksRepo.findByJourneyId(journeyId);
if (
!link?.allow_subscriptions ||
shareLinkExpired(link.expires_at, now) ||
(!link.share_timeline && !link.share_map)
) {
return null;
}
return link;
}
/** Everyone on the journey, unless every new entry is their own. */
@@ -128,35 +141,61 @@ export class JourneyDigestService {
return notified;
}
/**
* The confirmed followers of the journey's link that are due, one mail
* each, stamped once they went out.
*/
private async mailFollowers(
journeyId: number,
title: string,
entries: JourneyEntryToAnnounce[],
now: Date,
): Promise<number> {
const link = await this.linksRepo.findByJourneyId(journeyId);
if (!link || !link.allow_subscriptions || shareLinkExpired(link.expires_at, now)) return 0;
if (!link.share_timeline && !link.share_map) return 0;
const due = await this.subscribersRepo.listDue(link.id, dbNow(new Date(now.getTime() - DIGEST_MIN_GAP_MS)));
// A link behind a password names no entry in a mail: a follower keeps the
// mails after the owner changed the password, and a mail is no place for
// what the password guards. They only hear that there is something new.
const named = link.password_hash ? [] : entries;
const mailed: number[] = [];
await forEachInOrder(due, async (follower) => {
const mail = digestMail(follower.locale, title, named, {
private async sendPending(now: Date): Promise<number> {
const cutoff = dbNow(new Date(now.getTime() - DIGEST_MIN_GAP_MS));
const journeyIds = await this.subscribersRepo.listDueJourneyIds(cutoff);
let mailed = 0;
await forEachInOrder(journeyIds, async (journeyId) => {
try {
mailed += await this.mailFollowers(journeyId, cutoff, now);
} catch (err) {
logError(`[journey-digest] sending journey ${journeyId}: ${message(err)}`);
}
});
return mailed;
}
/** @txIndependent SMTP and its acknowledgement are independent for each address. */
private async mailFollowers(journeyId: number, cutoff: string, now: Date): Promise<number> {
const link = await this.deliveryLink(journeyId, now);
const journey = await this.journeysRepo.findById(journeyId);
if (!link || !journey) return 0;
const followers = await this.subscribersRepo.listDue(link.id, cutoff);
const entriesByBatch = new Map<string, JourneyEntryToAnnounce[]>();
let mailed = 0;
await forEachInOrder(followers, async (follower) => {
const pending = follower.pending_digest_entries;
if (pending === null) return;
let entries = entriesByBatch.get(pending);
if (!entries) {
entries = await this.pendingEntries(journeyId, pending);
entriesByBatch.set(pending, entries);
}
if (entries.length === 0) {
await this.subscribersRepo.setPendingDigest(follower.id, null);
return;
}
// A retry also respects a password the owner added after the original announcement.
const named = link.password_hash ? [] : entries;
const mail = digestMail(follower.locale, journey.title, named, {
link: link.token,
unsubscribe: follower.unsubscribe_token,
});
if (await this.mailer.sendStandaloneEmail(follower.email, mail, unsubscribeUrl(follower.unsubscribe_token))) {
mailed.push(follower.id);
await this.subscribersRepo.markNotified([follower.id], dbNow(now));
mailed += 1;
}
});
await this.subscribersRepo.markNotified(mailed, dbNow(now));
return mailed.length;
return mailed;
}
private async pendingEntries(journeyId: number, pending: string): Promise<JourneyEntryToAnnounce[]> {
const ids = decodeJson(JOURNEY_PENDING_DIGEST_ENTRIES, pending, `journey ${journeyId}`);
const entries: JourneyEntryToAnnounce[] = [];
await forEachInOrder(entryBatches(ids), async (chunk) => {
entries.push(...(await this.entriesRepo.listPendingDigestEntries(journeyId, chunk)));
});
return entries.sort((a, b) => a.entry_date.localeCompare(b.entry_date));
}
}
+44 -1
View File
@@ -409,7 +409,8 @@ describe('following a link by email', () => {
});
describe('the daily digest', () => {
const runDigest = () => withRequestContext(orm, () => app.get(JourneyDigestService, { strict: false }).run());
const runDigest = (now?: Date) =>
withRequestContext(orm, () => app.get(JourneyDigestService, { strict: false }).run(now));
it('JSOCIAL-E2E-030: the people hear of new entries, followers get one mail, nothing is told twice', async () => {
const send = mailWorks();
const { owner, editor, viewer, journey } = await journeyWithPeople();
@@ -470,4 +471,46 @@ describe('the daily digest', () => {
expect(mail.body).not.toContain('Furnas');
expect(mail.cta.href).toContain(`/public/journey/${token}`);
});
it('JSOCIAL-E2E-032: retries waiting mail without repeating successful or in-app notifications', async () => {
const { owner, editor, viewer, journey } = await journeyWithPeople();
const send = mailWorks();
const token = await share(journey.id, owner.id, { allow_subscriptions: true });
const addresses = ['successful@example.com', 'retry@example.com'];
await forEachInOrder(addresses, async (email) => {
await request(server).post(`/api/public/journey/${token}/subscribe`).send({ email }).expect(200);
const follower = must(await findRow(orm, JourneyShareSubscribers, { email }));
await request(server)
.post('/api/public/journey-subscriptions/confirm')
.send({ token: follower.confirm_token })
.expect(200);
});
send.mockClear();
const config = vi.spyOn(mailer, 'isSmtpConfigured').mockResolvedValue(false);
const entry = await makeJourneyEntry(orm, journey.id, editor.id, { title: 'After the storm' });
expect(await runDigest(new Date('2030-01-01T19:00:00Z'))).toMatchObject({ journeys: 1, notified: 2, mailed: 0 });
expect(send).not.toHaveBeenCalled();
expect((await findRow(orm, JourneyEntries, { id: entry.id }))?.announced).toBe(1);
config.mockResolvedValue(true);
send.mockImplementation(async (to) => to === addresses[0]);
expect(await runDigest(new Date('2030-01-02T19:00:00Z'))).toMatchObject({ journeys: 0, notified: 0, mailed: 1 });
expect(send.mock.calls.map(([to]) => to)).toEqual(addresses);
send.mockClear().mockResolvedValue(true);
expect(await runDigest(new Date('2030-01-03T19:00:00Z'))).toMatchObject({ journeys: 0, notified: 0, mailed: 1 });
expect(send).toHaveBeenCalledTimes(1);
const [to, mail] = must(send.mock.calls[0]);
expect(to).toBe(addresses[1]);
expect(mail.body).toContain('After the storm');
send.mockClear();
expect(await runDigest(new Date('2030-01-04T19:00:00Z'))).toMatchObject({ journeys: 0, notified: 0, mailed: 0 });
expect(send).not.toHaveBeenCalled();
await notifications.settled();
expect(
await countRows(orm, Notifications, { recipient: viewer.id, title_key: 'notif.journey_entry_published.title' }),
).toBe(1);
});
});
@@ -131,6 +131,7 @@ const UNNUMBERED = [
'Migration20200101046630_a_journey_gathers_comments_and_followers',
'Migration20200101046640_bahrain_flights_keep_bahrain_time',
'Migration20200101046650_trips_can_carry_custom_tags',
'Migration20200101046660_a_journey_keeps_unsent_digests',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -74,19 +74,26 @@ describe('JourneyShareSubscribersRepository', () => {
expect(await subscribers.findByConfirmToken('nothing-like-it-0000')).toBeUndefined();
});
it('JSUB-REPO-002: only confirmed addresses not mailed since the cutoff are due, and marking them stamps them', async () => {
const { link } = await linkOf();
await makeJourneySubscriber(t, link.id);
it('JSUB-REPO-002: only confirmed addresses with pending entries and no recent mail are due', async () => {
const { journey, link } = await linkOf();
await makeJourneySubscriber(t, link.id, { pending_digest_entries: '[11]' });
await makeJourneySubscriber(t, link.id, { confirmed_at: '2026-11-01 08:00:00' });
const fresh = await makeJourneySubscriber(t, link.id, { confirmed_at: '2026-11-01 08:00:00' });
await subscribers.setPendingDigest(fresh.id, '[11]');
const mailedLong = await makeJourneySubscriber(t, link.id, {
confirmed_at: '2026-11-01 08:00:00',
last_notified_at: '2026-11-28 08:00:00',
pending_digest_entries: '[11]',
});
await makeJourneySubscriber(t, link.id, {
confirmed_at: '2026-11-01 08:00:00',
last_notified_at: '2026-11-30 07:00:00',
pending_digest_entries: '[11]',
});
const other = await linkOf();
await makeJourneySubscriber(t, other.link.id, { confirmed_at: '2026-11-01 08:00:00' });
expect(await subscribers.listDueJourneyIds('2026-11-29 12:00:00')).toEqual([journey.id]);
const due = await subscribers.listDue(link.id, '2026-11-29 12:00:00');
expect(due.map((s) => s.id)).toEqual([fresh.id, mailedLong.id]);
@@ -95,7 +102,9 @@ describe('JourneyShareSubscribersRepository', () => {
t.clear();
expect(await findRow(t, JourneyShareSubscribers, { id: fresh.id })).toMatchObject({
last_notified_at: '2026-11-30 12:00:00',
pending_digest_entries: null,
});
expect((await subscribers.listDue(link.id, '2026-12-02 12:00:00')).map((s) => s.id)).not.toContain(fresh.id);
});
it('JSUB-REPO-003: an unsubscribe link and the owner each remove one address, and only on its own link', async () => {
@@ -134,7 +143,7 @@ describe('JourneyEntriesRepository, the entries a digest speaks of', () => {
const { user, journey } = await linkOf();
const published = await makeJourneyEntry(t, journey.id, user.id, { title: 'Alfama', entry_date: '2026-11-02' });
const earlier = await makeJourneyEntry(t, journey.id, user.id, { title: 'Belém', entry_date: '2026-11-01' });
await makeJourneyEntry(t, journey.id, user.id, { is_draft: 1 });
const draft = await makeJourneyEntry(t, journey.id, user.id, { is_draft: 1 });
await makeJourneyEntry(t, journey.id, user.id, { type: 'skeleton' });
await makeJourneyEntry(t, journey.id, user.id, { dismissed: 1 });
await makeJourneyEntry(t, journey.id, user.id, { announced: 1 });
@@ -146,6 +155,16 @@ describe('JourneyEntriesRepository, the entries a digest speaks of', () => {
await entries.markAnnounced(due.map((e) => e.id));
await entries.markAnnounced([]);
const other = await linkOf();
const unrelated = await makeJourneyEntry(t, other.journey.id, other.user.id, { announced: 1 });
const pending = await entries.listPendingDigestEntries(journey.id, [
published.id,
draft.id,
earlier.id,
unrelated.id,
]);
expect(pending.map((entry) => entry.id)).toEqual([earlier.id, published.id]);
expect(await entries.listPendingDigestEntries(journey.id, [])).toEqual([]);
expect(await entries.listToAnnounce(journey.id)).toEqual([]);
expect(await entries.listJourneysToAnnounce()).toEqual([]);
});