Skip to content
Closed
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
7 changes: 6 additions & 1 deletion src/cli/numeric-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ export function configureNumericOptions(program: Command) {
throw new CliInputError(`${option.long} must be a finite number`);
}
} else if (name === "cacheTtl") {
if (!text || !Number.isFinite(number) || number < 0) {
if (
!text ||
!Number.isFinite(number) ||
!Number.isFinite(number * 1000) ||
number < 0
) {
throw new CliInputError(
`${option.long} must be a non-negative finite number`,
);
Expand Down
76 changes: 51 additions & 25 deletions src/cli/register-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,30 @@ export function registerSyncCommands({
.option("--cache-ttl <seconds>", "Live-cache freshness window", "120")
.option("--refresh", "Bypass live-cache freshness window")
.action(async (options) => {
const result = await syncHomeTimeline({
account: options.account,
mode: options.mode,
limit: Number(options.limit),
maxPages: Number(options.maxPages),
following: !options.forYou,
refresh: Boolean(options.refresh),
cacheTtlMs: Number(options.cacheTtl) * 1000,
});
await autoSyncAfterWrite();
print(result, true);
try {
const result = await syncHomeTimeline({
account: options.account,
mode: options.mode,
limit: Number(options.limit),
maxPages: Number(options.maxPages),
following: !options.forYou,
refresh: Boolean(options.refresh),
cacheTtlMs: Number(options.cacheTtl) * 1000,
});
await autoSyncAfterWrite();
print(result, true);
} catch (error) {
print(
{
ok: false,
kind: "timeline",
mode: options.mode,
error: errorMessage(error),
},
true,
);
process.exitCode = 1;
}
});

syncCommand
Expand Down Expand Up @@ -238,20 +251,33 @@ export function registerSyncCommands({
.option("--cache-ttl <seconds>", "Live-cache freshness window", "120")
.option("--refresh", "Bypass live-cache freshness window")
.action(async (options) => {
const result = await syncTimelineCollection({
kind,
account: options.account,
mode: options.mode as TimelineCollectionMode,
limit: Number(options.limit),
all: Boolean(options.all) || options.maxPages !== undefined,
maxPages: options.maxPages ? Number(options.maxPages) : undefined,
paginationToken: options.paginationToken,
refresh: Boolean(options.refresh),
cacheTtlMs: Number(options.cacheTtl) * 1000,
earlyStop: Boolean(options.earlyStop),
});
await autoSyncAfterWrite();
print(result, true);
try {
const result = await syncTimelineCollection({
kind,
account: options.account,
mode: options.mode as TimelineCollectionMode,
limit: Number(options.limit),
all: Boolean(options.all) || options.maxPages !== undefined,
maxPages: options.maxPages ? Number(options.maxPages) : undefined,
paginationToken: options.paginationToken,
refresh: Boolean(options.refresh),
cacheTtlMs: Number(options.cacheTtl) * 1000,
earlyStop: Boolean(options.earlyStop),
});
await autoSyncAfterWrite();
print(result, true);
} catch (error) {
print(
{
ok: false,
kind,
mode: options.mode,
error: errorMessage(error),
},
true,
);
process.exitCode = 1;
}
});
}

Expand Down
82 changes: 82 additions & 0 deletions src/cli/sync-contract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// @vitest-environment node
import { Command } from "commander";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createCommandContext } from "./command-context";
import { CliInputError, configureNumericOptions } from "./numeric-options";
import { registerSyncCommands } from "./register-sync";

const mocks = vi.hoisted(() => ({
timeline: vi.fn(),
collection: vi.fn(),
mentions: vi.fn(),
graph: vi.fn(),
}));
vi.mock("#/lib/timeline-live", () => ({ syncHomeTimeline: mocks.timeline }));
vi.mock("#/lib/timeline-collections-live", () => ({
syncTimelineCollection: mocks.collection,
}));
vi.mock("#/lib/mentions-live", () => ({ syncMentions: mocks.mentions }));
vi.mock("#/lib/follow-graph", () => ({ syncFollowGraph: mocks.graph }));

function fixture() {
const program = new Command().exitOverride();
const print = vi.fn();
const backup = vi.fn().mockResolvedValue(undefined);
configureNumericOptions(program);
registerSyncCommands({
...createCommandContext(program),
print,
autoSyncAfterWrite: backup,
});
return {
run: (args: string[]) =>
program.parseAsync(["sync", ...args], { from: "user" }),
print,
backup,
};
}

const initialExitCode = process.exitCode;
beforeEach(() => {
process.exitCode = 0;
for (const mock of Object.values(mocks))
mock.mockReset().mockResolvedValue({ ok: true, count: 1 });
});
afterEach(() => {
process.exitCode = initialExitCode;
});

describe("sync registration contracts", () => {
for (const kind of ["timeline", "likes", "bookmarks"] as const) {
it(
"prints structured " + kind + " transport failures without backup writes",
async () => {
const f = fixture();
const mock = kind === "timeline" ? mocks.timeline : mocks.collection;
mock.mockRejectedValue(new Error("transport unavailable"));
await expect(f.run([kind, "--mode", "bird"])).resolves.toBeInstanceOf(
Command,
);
expect(f.print).toHaveBeenCalledWith(
{ ok: false, kind, mode: "bird", error: "transport unavailable" },
true,
);
expect(process.exitCode).toBe(1);
expect(f.backup).not.toHaveBeenCalled();
process.exitCode = 0;
mock.mockResolvedValue({ ok: true });
await fixture().run([kind]);
expect(process.exitCode).toBe(0);
},
);
}

it("rejects overflowing --cache-ttl seconds in the shared numeric hook before sync or backup", async () => {
const f = fixture();
await expect(f.run(["timeline", "--cache-ttl", "1e308"])).rejects.toThrow(
new CliInputError("--cache-ttl must be a non-negative finite number"),
);
expect(mocks.timeline).not.toHaveBeenCalled();
expect(f.backup).not.toHaveBeenCalled();
});
});
65 changes: 65 additions & 0 deletions src/lib/link-insights.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,71 @@ describe("link insights", () => {
rmSync(homeDir, { recursive: true, force: true });
});

it.each(["@steipete", "steipete", " STEIPETE ", " acct_primary "])(
"Pass 11 resolves link insight selector %j across every membership path",
(account) => {
const db = insertAccountFixture();
db.prepare(
"update accounts set handle = '@steipete' where id = 'acct_primary'",
).run();
for (const id of ["direct", "edge", "collection", "other"]) {
insertTweet(db, {
id,
accountId: "acct_secondary",
authorProfileId: "profile_a",
text: id,
createdAt: localIso(),
});
insertExpansion(db, {
shortUrl: "https://t.co/" + id,
finalUrl: "https://example.com/" + id,
});
insertOccurrence(db, {
sourceKind: "tweet",
sourceId: id,
shortUrl: "https://t.co/" + id,
accountId: id === "direct" ? "acct_primary" : "acct_secondary",
createdAt: localIso(),
});
}
insertTweetAccountEdge(db, {
accountId: "acct_primary",
tweetId: "edge",
});
db.prepare(
"insert into tweet_collections (account_id, tweet_id, kind, collected_at, source, raw_json, updated_at) values ('acct_primary', 'collection', 'bookmarks', ?, 'test', '{}', ?)",
).run(localIso(), localIso());
insertDmMessage(db, {
id: "dm_link",
senderProfileId: "profile_b",
text: "https://t.co/dm",
createdAt: localIso(),
});
insertExpansion(db, {
shortUrl: "https://t.co/dm",
finalUrl: "https://example.com/dm",
});
insertOccurrence(db, {
sourceKind: "dm",
sourceId: "dm_link",
shortUrl: "https://t.co/dm",
createdAt: localIso(),
});
const query = { now: localDate(), range: "all" as const };
const expected = getLinkInsights({ ...query, account: "acct_primary" });
expect(expected.stats.occurrences).toBe(4);
expect(getLinkInsights({ ...query, account })).toEqual(expected);
expect(
getLinkInsights({ ...query, account: "all" }).stats.occurrences,
).toBe(5);
expect(getLinkInsights(query).stats.occurrences).toBe(5);
expect(
getLinkInsights({ ...query, account: "acct_secondary" }).stats
.occurrences,
).toBe(4);
},
);

it("keeps every video host form while rejecting URLs that only contain a host hint", () => {
const db = insertAccountFixture();
const suffixes = [
Expand Down
9 changes: 7 additions & 2 deletions src/lib/link-insights.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { profileSelect, type ProfileSqlRow } from "./profile-row";
import { parseJsonField } from "./json-codec";
import { getNativeDb } from "./db";
import { findOperationAccount } from "./account-selection";
import { isReadOnlyDeployment } from "./config";
import { ReadOnlyQueryCache } from "./read-only-query-cache";
import type { Database } from "./sqlite";
Expand Down Expand Up @@ -716,7 +717,11 @@ function buildLinkInsights(
conditions.push("o.source_kind = ?");
params.push(source);
}
if (query.account && query.account !== "all") {
const accountId =
query.account && query.account !== "all"
? (findOperationAccount(db, query.account)?.id ?? query.account)
: undefined;
if (accountId) {
conditions.push(`(
(o.source_kind = 'dm' and o.account_id = ?)
or (
Expand All @@ -738,7 +743,7 @@ function buildLinkInsights(
)
)
)`);
params.push(query.account, query.account, query.account, query.account);
params.push(accountId, accountId, accountId, accountId);
}
if (kind === "videos") {
addVideoUrlPrefilter(conditions);
Expand Down
Loading