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
2 changes: 1 addition & 1 deletion docs/design/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ indexed and never extracted (`sources.config.extract`) [0036 d7].
A source may let its documents decay [RC-003](../decisions/re-cinq/RC-003-a-source-may-decay.md).
`PATCH` a source with `decay` to set it: an object turns it on (a missing field takes Lore's value, so
`{}` is Lore's behaviour), `null` turns it off, and leaving the field out changes nothing. A new
source decays nothing.
source decays nothing. In the web UI it is the "Let documents decay" switch in a source's settings.

Once a day a source that holds more live documents than its `max_items` is taken back to it: from the
documents older than `min_age_days`, the lowest scoring ones are deleted the way a person deletes them
Expand Down
10 changes: 10 additions & 0 deletions web/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,8 @@ export interface SourceView {
icon: string | null;
sync_interval_minutes: number | null;
sync_cron: string | null;
/** null = 文档不衰减;打开后的设置(RC-003),手写的对象可能缺字段,缺的取默认值 */
decay: Partial<DecaySettings> | null;
last_sync_at: string | null;
last_sync_status: "never" | "queued" | "running" | "ok" | "failed";
last_sync_error: string | null;
Expand All @@ -253,6 +255,14 @@ export interface SourceView {
rss_full_content: RssFullContentSummary | null;
}

/** 来源的衰减设置(RC-003):超过 max_items 就淘汰分最低的、至少 min_age_days 天的文档。 */
export interface DecaySettings {
max_items: number;
half_life_days: number;
stale_after_days: number;
min_age_days: number;
}

/** 一个 RSS 来源当前代的全文补全进度。五个计数一起读,所以一起给。 */
export interface RssFullContentSummary {
state: "pending" | "active" | "disabled";
Expand Down
11 changes: 11 additions & 0 deletions web/src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,17 @@ export const en = {
"Changing what this source fetches never deletes existing documents. " +
"Items the new configuration no longer returns are marked “Not in source” " +
"after the next sync. Switching to a different service entirely? Create a new source instead.",
decay: {
toggle: "Let documents decay",
hint:
"A document nobody retrieves loses score over time. Once the source holds more " +
"than the limit, the lowest-scoring old documents are deleted once a day. " +
"They can be restored from the trash.",
maxItems: "Keep at most (documents)",
halfLife: "Score halves every (days)",
staleAfter: "Rank lower after (days unread)",
minAge: "Never delete newer than (days)",
},
notInSource: "Not in source",
cleanupMissing: (n: number) => `Clean up ${n} missing`,
cleanupTitle: "Delete missing documents",
Expand Down
10 changes: 10 additions & 0 deletions web/src/i18n/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -736,6 +736,16 @@ export const zh: Strings = {
editKeepNote:
"改变这个来源抓取什么,绝不会删除已有文档。新配置不再返回的条目会在下次同步后" +
"标记为「已不在来源中」。要整个换成另一个服务?那就新建一个来源。",
decay: {
toggle: "让文档随时间衰减",
hint:
"没人检索的文档分数会随时间下降。来源里的文档超过上限后,每天删除分数最低的旧文档," +
"删掉的可以从回收站恢复。",
maxItems: "最多保留(篇)",
halfLife: "分数每隔多少天减半",
staleAfter: "多少天没人读就排后",
minAge: "不删比这新的(天)",
},
notInSource: "已不在来源中",
cleanupMissing: (n: number) => `清理 ${n} 篇缺失`,
cleanupTitle: "删除缺失的文档",
Expand Down
13 changes: 13 additions & 0 deletions web/src/pages/Library.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import { toast } from "../toast";
import { copyAndSay } from "../clipboard";
import { pushEndpoint } from "../pushEndpoint";
import { githubRepoConfig, globList } from "./githubRepoConfig";
import { SourceDecayFields } from "./SourceDecayFields";
import { decayChange, decayFormValue, decayIssue } from "./sourceDecay";
import {
Button,
Checkbox,
Expand Down Expand Up @@ -1897,6 +1899,8 @@ function SourceEditModal({
sync_interval_minutes: source.sync_interval_minutes,
sync_cron: source.sync_cron,
});
const [decayOn, setDecayOn] = useState(source.decay != null);
const [decay, setDecay] = useState(() => decayFormValue(source.decay));
const syncing = SYNCING_KINDS.has(kind);
const KindIcon = KIND_ICON[kind as keyof typeof KIND_ICON] ?? Upload;

Expand Down Expand Up @@ -1949,13 +1953,15 @@ function SourceEditModal({
...(kind === "custom" && icon ? { icon } : {}),
...(config ? { config } : {}),
...(syncing ? { schedule } : {}),
...decayChange(source.decay, decayOn, decay),
});
},
onSuccess: () => onDone(),
});

const valid =
name.trim() &&
!(decayOn && decayIssue(decay)) &&
(kind === "url"
? urls.trim()
: kind === "rss"
Expand Down Expand Up @@ -2151,6 +2157,13 @@ function SourceEditModal({
/>,
)}

<SourceDecayFields
enabled={decayOn}
onEnabled={setDecayOn}
value={decay}
onChange={setDecay}
/>

{save.isError && (
<p className="text-small text-danger mb-2">{(save.error as Error).message}</p>
)}
Expand Down
34 changes: 34 additions & 0 deletions web/src/pages/SourceDecayFields.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, it, vi } from "vitest";
import { SourceDecayFields } from "./SourceDecayFields";
import { DEFAULT_DECAY } from "./sourceDecay";

const render = (enabled: boolean, value = DEFAULT_DECAY) =>
renderToStaticMarkup(
createElement(SourceDecayFields, {
enabled,
onEnabled: vi.fn(),
value,
onChange: vi.fn(),
}),
);

it("shows only the switch when decay is off", () => {
const html = render(false);
expect(html).toContain("Let documents decay");
expect(html).not.toContain('type="number"');
});

it("shows the four numbers with their saved values when decay is on", () => {
const html = render(true, { ...DEFAULT_DECAY, max_items: 3 });
expect(html.match(/type="number"/g)).toHaveLength(4);
expect(html).toContain('value="3"');
expect(html).toContain("Keep at most (documents)");
});

it("marks the label of the field that is out of range", () => {
const html = render(true, { ...DEFAULT_DECAY, half_life_days: 400 });
expect(html).toMatch(/text-danger[^>]*>Score halves every/);
expect(html).not.toMatch(/text-danger[^>]*>Keep at most/);
});
59 changes: 59 additions & 0 deletions web/src/pages/SourceDecayFields.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { DecaySettings } from "../api";
import { S } from "../i18n";
import { Checkbox, cn, Input } from "../ui";
import { decayIssue } from "./sourceDecay";

const FIELDS: { key: keyof DecaySettings; label: () => string; min: number; max?: number }[] = [
{ key: "max_items", label: () => S.library.decay.maxItems, min: 1 },
{ key: "half_life_days", label: () => S.library.decay.halfLife, min: 1, max: 365 },
{ key: "stale_after_days", label: () => S.library.decay.staleAfter, min: 1 },
{ key: "min_age_days", label: () => S.library.decay.minAge, min: 0 },
];

/** 来源的衰减开关和四个数(RC-003)。数不合规就把那一格的标签标红,保存键由调用方按
* `decayIssue` 关掉 */
export function SourceDecayFields({
enabled,
onEnabled,
value,
onChange,
}: {
enabled: boolean;
onEnabled: (on: boolean) => void;
value: DecaySettings;
onChange: (next: DecaySettings) => void;
}) {
const issue = enabled ? decayIssue(value) : null;
return (
<div className="mb-3">
<Checkbox checked={enabled} onChange={onEnabled} label={S.library.decay.toggle} />
{enabled && (
<>
<p className="mb-2 mt-1 text-fine leading-relaxed text-ink-2">{S.library.decay.hint}</p>
<div className="grid grid-cols-2 gap-x-3 gap-y-2">
{FIELDS.map(({ key, label, min, max }) => (
<div key={key}>
<div
className={cn(
"mb-1 text-fine font-medium",
issue === key ? "text-danger" : "text-ink-2",
)}
>
{label()}
</div>
<Input
className="w-full u-num"
type="number"
min={min}
max={max}
value={value[key]}
onChange={(e) => onChange({ ...value, [key]: Number(e.target.value) })}
/>
</div>
))}
</div>
</>
)}
</div>
);
}
66 changes: 66 additions & 0 deletions web/src/pages/sourceDecay.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_DECAY,
decayChange,
decayFormValue,
decayIssue,
} from "./sourceDecay";

describe("decayFormValue", () => {
it("fills every missing field with Lore's value when the saved object is {}", () => {
expect(decayFormValue({})).toEqual(DEFAULT_DECAY);
});

it("keeps a saved field and fills the rest", () => {
expect(decayFormValue({ max_items: 3 })).toEqual({ ...DEFAULT_DECAY, max_items: 3 });
});

it("is the defaults when the source does not decay", () => {
expect(decayFormValue(null)).toEqual(DEFAULT_DECAY);
});
});

describe("decayIssue", () => {
it("is null for the defaults", () => {
expect(decayIssue(DEFAULT_DECAY)).toBeNull();
});

it.each([
[{ max_items: 0 }, "max_items"],
[{ max_items: 2.5 }, "max_items"],
[{ half_life_days: 0 }, "half_life_days"],
[{ half_life_days: 366 }, "half_life_days"],
[{ stale_after_days: 0 }, "stale_after_days"],
[{ min_age_days: -1 }, "min_age_days"],
])("names the field when %j is out of range", (change, field) => {
expect(decayIssue({ ...DEFAULT_DECAY, ...change })).toBe(field);
});

it("accepts 0 days for min_age_days and 365 for the half-life", () => {
expect(decayIssue({ ...DEFAULT_DECAY, min_age_days: 0, half_life_days: 365 })).toBeNull();
});
});

describe("decayChange", () => {
it("sends nothing for a source that does not decay and stays off", () => {
expect(decayChange(null, false, DEFAULT_DECAY)).toEqual({});
});

it("sends null when a decaying source is switched off", () => {
expect(decayChange({ max_items: 3 }, false, DEFAULT_DECAY)).toEqual({ decay: null });
});

it("sends the whole object when decay is switched on", () => {
expect(decayChange(null, true, DEFAULT_DECAY)).toEqual({ decay: DEFAULT_DECAY });
});

it("sends the whole object when one field changed", () => {
const form = { ...DEFAULT_DECAY, max_items: 10 };
expect(decayChange({ max_items: 3 }, true, form)).toEqual({ decay: form });
});

it("sends nothing when the form still equals what is saved, even a hand-written {}", () => {
expect(decayChange({}, true, DEFAULT_DECAY)).toEqual({});
expect(decayChange(DEFAULT_DECAY, true, DEFAULT_DECAY)).toEqual({});
});
});
42 changes: 42 additions & 0 deletions web/src/pages/sourceDecay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { DecaySettings } from "../api";

/** 后端的默认值(RC-003,Lore 的常数):缺的字段取这些,所以库里手写的 `{}` 也读得出 */
export const DEFAULT_DECAY: DecaySettings = {
max_items: 500,
half_life_days: 60,
stale_after_days: 30,
min_age_days: 30,
};

export const decayFormValue = (
saved: Partial<DecaySettings> | null | undefined,
): DecaySettings => ({ ...DEFAULT_DECAY, ...saved });

const whole = (n: number, min: number, max = Infinity) =>
Number.isInteger(n) && n >= min && n <= max;

/** 第一个越界的字段,没有就是 null。范围同后端 `DecaySettings::validate`;
* `min_age_days` 可以是 0(谁都可能被淘汰) */
export function decayIssue(form: DecaySettings): keyof DecaySettings | null {
if (!whole(form.max_items, 1)) return "max_items";
if (!whole(form.half_life_days, 1, 365)) return "half_life_days";
if (!whole(form.stale_after_days, 1)) return "stale_after_days";
if (!whole(form.min_age_days, 0)) return "min_age_days";
return null;
}

/** 保存时要带的 `decay`:没改就一个字都不带(后端「缺省 = 不动」),关掉写 null,
* 打开或改了就整份发过去 */
export function decayChange(
saved: Partial<DecaySettings> | null,
enabled: boolean,
form: DecaySettings,
): { decay?: DecaySettings | null } {
if (!enabled) return saved === null ? {} : { decay: null };
const unchanged =
saved !== null &&
(Object.keys(DEFAULT_DECAY) as (keyof DecaySettings)[]).every(
(key) => decayFormValue(saved)[key] === form[key],
);
return unchanged ? {} : { decay: form };
}
Loading