Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions apps/web/lib/library/starters.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { countItems, digestFor, getMe, isEmptyDigest, updateSettings } from "@pluck/db";
import { countItems, digestFor, getMe, isEmptyDigest, listLists, updateSettings } from "@pluck/db";
import { twoUsers } from "@pluck/db/testing";
import { expect, test, vi } from "vitest";
import { addItems, browse, giveStarters, listsOf, newList, pluckAny, readList, readText, removeList } from "./index";
import { addItems, browse, giveStarters, listsOf, newList, pluckAny, readList, readText, removeList, startersBackfill } from "./index";

// The posts are Markdown the web app's bundler loads; here two short ones stand in.
vi.mock("../blog", () => ({
Expand Down Expand Up @@ -66,3 +66,18 @@ test("what an account starts with is never in the weekly email or counted as plu
expect(d.oldest.map((o) => o.title)).toEqual(["Mine"]);
expect(d.quietLists.map((l) => l.name)).toEqual(["Favourites"]);
});

test("the worker gives accounts from before their Lists unasked, but leaves one still signing up to its sign-up", async () => {
const { a, b } = await twoUsers();
const mine = await newList(b, { name: "Ideas" }); // b made its own Ideas before
// Made a moment ago: sign-up may still be at work, so the worker passes them by.
expect(await startersBackfill()).toBe(0);
expect(await listLists(a)).toEqual([]);
const later = new Date(Date.now() + 3_600_000);
while (await startersBackfill(later)) { /* every account, a few at a time, to the end */ }
expect(await startersBackfill(later)).toBe(0); // given once: nothing left to ask about
expect((await listLists(a)).map((l) => l.name).sort()).toEqual(["Favourites", "Ideas"]);
expect((await listLists(b)).map((l) => [l.name, l.id === mine.id])).toEqual(expect.arrayContaining([["Ideas", true], ["Favourites", false]]));
expect(await listLists(b)).toHaveLength(2); // no twin of the Ideas b already had
expect((await browse(a, { status: "inbox", sort: "newest", limit: 50 })).items).toEqual([]); // Lists only, no posts
});
12 changes: 11 additions & 1 deletion apps/web/lib/library/starters.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addToList, claimStarters, createList, editItem, getMe, listLists, markStarters, slugify } from "@pluck/db";
import { addToList, claimStarters, createList, editItem, getMe, listLists, markStarters, slugify, withoutStarters } from "@pluck/db";
import { DEFAULT_LOCALE, messagesFor, type Locale } from "@pluck/i18n";
import type { List } from "@pluck/shared-schemas";
import { log } from "../log";
Expand Down Expand Up @@ -51,6 +51,16 @@ export async function giveStarters(userId: string, { articles, locale, defer }:
await markStarters(userId, { listIds: made.map((l) => l.id), itemIds: posts });
}

// Accounts from before, given their Lists without waiting for them to open Lists: the share sheet, the extension and
// their AI tools show them too. Run from every tick (schedule.ts), a few accounts at a time.
// shortcut: asks the database on every tick for good; drop this and its call once every account has startersAt.
export async function startersBackfill(now = new Date(), limit = 20): Promise<number> {
const ids = await withoutStarters(limit, now);
for (const userId of ids)
await giveStarters(userId, { articles: false }).catch((e) => log("warn", "starter Lists not given", { userId, error: e instanceof Error ? e.message : String(e) }));
return ids.length;
}

// One of our posts, plucked for the account from the words this server already holds: nothing is fetched but its
// picture, after the response.
async function keepPost(userId: string, locale: Locale, slug: string, defer?: Defer): Promise<string | null> {
Expand Down
4 changes: 3 additions & 1 deletion apps/web/lib/schedule.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { claimOnce, foldAllHighlights, narrowAiGrants, runDueExpiry } from "@pluck/db";
import { FIRST_PARTY_REDIRECTS } from "./auth";
import { announceNewPosts } from "./indexnow";
import { pollInbound, purgeBinNow, queueDueDigests, sortBackfill, sweepTransfersNow } from "./library";
import { pollInbound, purgeBinNow, queueDueDigests, sortBackfill, startersBackfill, sweepTransfersNow } from "./library";
import { log } from "./log";

// Time-based work, run from every cron tick and the worker loop. Each piece is claimed in the
Expand All @@ -21,6 +21,8 @@ export async function runScheduled(now = new Date()): Promise<{ purged: number;
if (digests) log("info", "digests queued", { digests });
const inbound = await pollInbound();
const sorted = await sortBackfill(); // until every Item read before Previews has one; then a single lookup
const started = await startersBackfill(now);
if (started) log("info", "starter Lists given to accounts from before", { accounts: started });
const announced = await announceNewPosts(now);
if (announced) log("info", "new posts announced to IndexNow", { urls: announced });
return { purged, expired: expiry.archived, digests, inbound, sorted };
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ One Next.js app (`apps/web`) is the website, the signed-in app, the REST API for
- Only `packages/db` imports `mongodb` (an ESLint rule enforces it). Every new query gets a test with two people in it.
- Expiry and "Archive it all" set the Status to Archived. Items in a List are never expired (the `inList` field). Nothing is deleted by expiry or by an AI tool.
- Types start as Zod schemas in `packages/shared-schemas`.
- An account starts with two Lists, Favourites and Ideas, in its language (`apps/web/lib/library/starters.ts`). A new account also gets two of our own posts, kept from the Markdown this server holds with nothing fetched: one in the Inbox and one in Ideas. An account from before gets the Lists only, the first time its Lists are read (no script is run against the database): one it already has by that name is not made again, and the new ones sort under the Lists it uses. `startersAt` on the user makes it happen once, so deleting them is final. They are ordinary Lists and Items, marked (`starter`) only so the weekly email and the welcome email's "have they plucked yet" leave them out; a starter List counts as any other once the person uses it.
- An account starts with two Lists, Favourites and Ideas, in its language (`apps/web/lib/library/starters.ts`). A new account also gets two of our own posts, kept from the Markdown this server holds with nothing fetched: one in the Inbox and one in Ideas. An account from before gets the Lists only, from the worker within a few minutes of a deploy (`startersBackfill`, a few accounts each tick) or the first time its Lists are read, whichever is first (no script is run against the database): one it already has by that name is not made again, and the new ones sort under the Lists it uses. `startersAt` on the user makes it happen once, so deleting them is final. They are ordinary Lists and Items, marked (`starter`) only so the weekly email and the welcome email's "have they plucked yet" leave them out; a starter List counts as any other once the person uses it.
- A `#word` in a Note's text or in a note is a Tag on the Item (`hashTags` in `apps/web/lib/library/hashtags.ts`, `tagByWords` in `packages/db`), read on the server so every client gets it. A word that appears goes on. A Note saves as it is typed, so the Item remembers which tags its words put on lately (`wordTags`): for ten minutes, a word changed or taken out takes its tag with it (`#rec` on the way to `#recipes`, a slip, a change of mind), and a tag that slip made is dropped if nothing has it. After that, and for any tag put on by hand, taking the word out takes nothing off. Words an AI tool writes tag nothing (it has `tagIds`), and nor do words shared in from another app (the share sheet sends them without a Kind): only what a person typed in a composer.
- The connector is the only public API; the REST API is for our own clients and may change.
- A Note's text is Markdown, one line one block, and rich editing is a view over it ([ADR 0002](adr/0002-notes-are-markdown.md)). Both editors are `react-native-enriched-markdown` (the iPhone's native build, the web's DOM build), and each opens a Note only when it reads the text back the same (`sameNote`); otherwise the plain editor does. Titles, rows and excerpts are plain words (`plainLine`).
Expand Down
14 changes: 13 additions & 1 deletion packages/db/src/account.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ObjectId } from "mongodb";
import { expect, test } from "vitest";
import { getDb } from "./client.ts";
import {
aliasOf, claimStarters, createApiKey, createHighlight, createList, createTextItem, deleteAccountData, exportData, claimImportStart, createImport, getImport, getItem, importLink, updateImport, listApiKeys, recountTags,
aliasOf, claimStarters, withoutStarters, createApiKey, createHighlight, createList, createTextItem, deleteAccountData, exportData, claimImportStart, createImport, getImport, getItem, importLink, updateImport, listApiKeys, recountTags,
listTags, pluckLink, revokeApiKey, verifyApiKey, analyticsOf, countItems, getMe, setHeardFrom, setVia, updateSettings, finishExport, latestExport, startExport, sweepTransfers,
} from "./index.ts";
import { twoUsers } from "./testing.ts";
Expand Down Expand Up @@ -147,3 +147,15 @@ test("the starter Lists are claimed once per account, each account for itself",
expect(await claimStarters(b)).toBe(true); // a's claim is not b's
expect(await claimStarters(new ObjectId().toHexString())).toBe(false); // no such account: nothing to make
});

test("the accounts still without starter Lists are the unclaimed ones, and never one made in the last ten minutes", async () => {
const { a, b } = await twoUsers();
const later = new Date(Date.now() + 3_600_000);
expect(await withoutStarters(1000)).not.toEqual(expect.arrayContaining([a])); // just made: its sign-up is still at work
expect(await withoutStarters(1000, later)).toEqual(expect.arrayContaining([a, b]));
await claimStarters(a);
const left = await withoutStarters(1000, later);
expect(left).toContain(b);
expect(left).not.toContain(a); // a's claim takes a off the list, and leaves b on it
expect(await withoutStarters(0 + 1, later)).toHaveLength(1); // a few at a time
});
2 changes: 1 addition & 1 deletion packages/db/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export {
createList, listLists, markStarters, getListMeta, getList, updateList, deleteList, addToList, removeFromList, updateEntry, markEntries, reorderList, listsForItem,
setVisibility, listOwnedBy, type NewList, type ListEdit, type EntryEdit, type VisibilityResult,
} from "./lists.ts";
export { analyticsOf, claimStarters, getMe, markMcpCall, setHeardFrom, setName, setHandle, setVia, updateSettings, type HandleResult } from "./users.ts";
export { analyticsOf, claimStarters, getMe, markMcpCall, setHeardFrom, setName, setHandle, setVia, updateSettings, withoutStarters, type HandleResult } from "./users.ts";
export { expireItems, archiveStale, countExpiringSoon, runDueExpiry, claimOnce, localNow } from "./expiry.ts";
export { DEFAULT_SETTINGS, type SignUpVia, type UserSettings } from "./collections.ts";
export { publicList, publicListById, publicCoverKey, recordView, createReport, PUBLIC_ITEM_FIELDS, sharedList, listsSharedWith, sharedCoverKey } from "./public.ts";
Expand Down
7 changes: 7 additions & 0 deletions packages/db/src/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ export async function claimStarters(userId: string): Promise<boolean> {
return (await (await users()).updateOne({ _id: oid(userId), startersAt: { $exists: false } }, { $set: { startersAt: new Date() } })).modifiedCount > 0;
}

// Accounts that have not been given the starter Lists, a few at a time, for the worker to give them. Not one made in
// the last ten minutes: its sign-up is still giving it the Lists and the posts, and must win.
export async function withoutStarters(limit: number, now = new Date()): Promise<string[]> {
const docs = await (await users()).find({ startersAt: { $exists: false }, createdAt: { $lt: new Date(now.getTime() - 600_000) } }, { projection: { _id: 1 }, limit }).toArray();
return docs.map((d) => d._id.toHexString());
}

// What usage analytics may know of an account: its answer to the cookie question, and (for signed_up) when and how it began.
export async function analyticsOf(userId: string): Promise<{ consent: "yes" | "no" | null; createdAt: Date; via: SignUpVia | null } | null> {
const d = await (await users()).findOne({ _id: oid(userId) }, { projection: { "settings.analytics": 1, "settings.analyticsAt": 1, createdAt: 1, via: 1 } });
Expand Down
Loading