feedkeeper 0.35.8 → 0.36.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server/dist/api/v1/index.js +4 -0
- package/server/dist/api/v1/resources.js +26 -0
- package/server/dist/feeds/batchSubscribe.js +94 -0
- package/server/dist/feeds/discovery.js +2 -2
- package/server/dist/feeds/fetcher.js +16 -3
- package/server/dist/feeds/pollQueue.js +7 -4
- package/server/dist/feeds/poller.js +42 -16
- package/server/dist/feeds/requestGate.js +23 -4
- package/server/dist/mcp/server.js +5 -28
- package/server/package.json +1 -1
package/package.json
CHANGED
|
@@ -13,6 +13,7 @@ import { ResyncRequired, currentSeq, listChanges } from "../../sync/changeLog.js
|
|
|
13
13
|
import { applyMutations } from "../../sync/mutations.js";
|
|
14
14
|
import { getUserCapabilities, requireCapability } from "../../auth/capabilities.js";
|
|
15
15
|
import { resourcesRouter } from "./resources.js";
|
|
16
|
+
import { MAX_SUBSCRIPTION_BATCH } from "../../feeds/batchSubscribe.js";
|
|
16
17
|
/** The API for native apps. See docs/design/native-api.md for the contract and what is still to come. */
|
|
17
18
|
export const v1Router = Router();
|
|
18
19
|
// Features grow with the implementation; clients look here instead of guessing from the version.
|
|
@@ -49,6 +50,7 @@ const FEATURES = [
|
|
|
49
50
|
"mcp",
|
|
50
51
|
"inbox",
|
|
51
52
|
"feed-lists",
|
|
53
|
+
"subscriptions.batch",
|
|
52
54
|
];
|
|
53
55
|
v1Router.get("/meta", (_req, res) => {
|
|
54
56
|
const retention = getRetentionSettings();
|
|
@@ -58,6 +60,8 @@ v1Router.get("/meta", (_req, res) => {
|
|
|
58
60
|
features: FEATURES,
|
|
59
61
|
limits: {
|
|
60
62
|
maxMutationsPerRequest: 200,
|
|
63
|
+
// Feeds one `POST /subscriptions/batch` takes; longer lists go in several requests.
|
|
64
|
+
maxSubscriptionBatch: MAX_SUBSCRIPTION_BATCH,
|
|
61
65
|
// Kept for clients that only know the maximum age.
|
|
62
66
|
retentionDays: retention.retentionMaxDays,
|
|
63
67
|
// Deletions caused by retention are not announced through /sync, so clients apply the same rules
|
|
@@ -17,6 +17,7 @@ import { saveToInbox, deleteInboxItem } from "../../feeds/inbox.js";
|
|
|
17
17
|
import { changeFeedUrl, FeedError, MultipleFeedsFoundError, subscribeToFeed, unsubscribeFromFeed, updateFeedSettings } from "../../feeds/service.js";
|
|
18
18
|
import { SsrfBlockedError, normalizeUrlCandidate } from "../../feeds/ssrfGuard.js";
|
|
19
19
|
import { blockedUrlBody } from "../../feeds/blockedHosts.js";
|
|
20
|
+
import { MAX_SUBSCRIPTION_BATCH, fetchStatusFor, subscribeBatch } from "../../feeds/batchSubscribe.js";
|
|
20
21
|
import { buildOverview } from "../../mcp/digest.js";
|
|
21
22
|
import { decodeCursor, encodeCursor } from "../../mcp/items.js";
|
|
22
23
|
import { readingPositions, serializeItem, serializeSubscriptionDetail } from "./serialize.js";
|
|
@@ -71,6 +72,31 @@ resourcesRouter.post("/subscriptions", requireCapability("sync"), async (req, re
|
|
|
71
72
|
res.status(400).json({ error: "invalid_feed", message: error instanceof Error ? error.message : String(error) });
|
|
72
73
|
}
|
|
73
74
|
});
|
|
75
|
+
const batchSchema = z.object({
|
|
76
|
+
items: z.array(z.object({
|
|
77
|
+
url: z.string().min(1).max(2048),
|
|
78
|
+
label: z.string().max(200).nullable().optional(),
|
|
79
|
+
folder: z.string().max(100).nullable().optional(),
|
|
80
|
+
})).min(1).max(MAX_SUBSCRIPTION_BATCH),
|
|
81
|
+
});
|
|
82
|
+
// Many feeds at once, e.g. an OPML file or a list of recommended feeds. The feeds are stored and queued, not read first; see subscribeBatch.
|
|
83
|
+
resourcesRouter.post("/subscriptions/batch", requireCapability("sync"), async (req, res) => {
|
|
84
|
+
const parsed = batchSchema.safeParse(req.body);
|
|
85
|
+
if (!parsed.success)
|
|
86
|
+
return invalid(res, parsed.error.flatten());
|
|
87
|
+
const results = await subscribeBatch(req.user.id, parsed.data.items);
|
|
88
|
+
const count = (status) => results.filter((result) => result.status === status).length;
|
|
89
|
+
res.json({ results, added: count("added"), exists: count("exists"), invalid: count("invalid") });
|
|
90
|
+
});
|
|
91
|
+
// How far the first fetch of freshly added feeds has come: counts only, cheap enough to ask every few seconds during a big import.
|
|
92
|
+
resourcesRouter.get("/subscriptions/status", (req, res) => {
|
|
93
|
+
const raw = typeof req.query.ids === "string" ? req.query.ids.split(",") : [];
|
|
94
|
+
const ids = [...new Set(raw.map(Number))];
|
|
95
|
+
if (raw.length === 0 || ids.length > MAX_SUBSCRIPTION_BATCH * 5 || ids.some((id) => !Number.isInteger(id) || id <= 0)) {
|
|
96
|
+
return invalid(res, `ids must list 1 to ${MAX_SUBSCRIPTION_BATCH * 5} subscription ids`);
|
|
97
|
+
}
|
|
98
|
+
res.json(fetchStatusFor(req.user.id, ids));
|
|
99
|
+
});
|
|
74
100
|
const reorderSchema = z.object({ ids: z.array(z.number().int().positive()) });
|
|
75
101
|
resourcesRouter.put("/subscriptions/order", (req, res) => {
|
|
76
102
|
const parsed = reorderSchema.safeParse(req.body);
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { config } from "../config.js";
|
|
2
|
+
import { db } from "../db/index.js";
|
|
3
|
+
import { assertPublicFeedUrl, blockedUrlBody } from "./blockedHosts.js";
|
|
4
|
+
import { requestFeedPoll } from "./poller.js";
|
|
5
|
+
import { createFeed, createFolder, findFeedByUrl, isUserSubscribed, subscribe } from "./repository.js";
|
|
6
|
+
import { SsrfBlockedError, normalizeUrlCandidate } from "./ssrfGuard.js";
|
|
7
|
+
/** Most feeds one request may carry; clients send longer lists in several requests. */
|
|
8
|
+
export const MAX_SUBSCRIPTION_BATCH = 200;
|
|
9
|
+
const MAX_FOLDER_NAME_LENGTH = 100;
|
|
10
|
+
const MAX_LABEL_LENGTH = 200;
|
|
11
|
+
/** Address checks resolve names, so they run a few at a time instead of one after the other. */
|
|
12
|
+
const CHECK_CONCURRENCY = 8;
|
|
13
|
+
async function checkAddress(raw) {
|
|
14
|
+
let candidate;
|
|
15
|
+
try {
|
|
16
|
+
candidate = new URL(normalizeUrlCandidate(raw)).toString();
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return { reason: "invalid_url" };
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
return { url: (await assertPublicFeedUrl(candidate)).toString() };
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
return { reason: error instanceof SsrfBlockedError ? blockedUrlBody(error).error : "url_validation_failed" };
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
async function checkAll(items) {
|
|
29
|
+
const checked = new Array(items.length);
|
|
30
|
+
let next = 0;
|
|
31
|
+
await Promise.all(Array.from({ length: Math.min(CHECK_CONCURRENCY, items.length) }, async () => {
|
|
32
|
+
while (next < items.length) {
|
|
33
|
+
const index = next++;
|
|
34
|
+
checked[index] = await checkAddress(items[index].url);
|
|
35
|
+
}
|
|
36
|
+
}));
|
|
37
|
+
return checked;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Subscribes to many feeds in one go. Addresses are checked like a single subscription, but a feed is not read first: it is stored and
|
|
41
|
+
* its first fetch joins the durable poll queue, so the answer comes in seconds, whatever the sources do, and the work goes on if the
|
|
42
|
+
* client goes away. A feed that cannot be read shows its error on the subscription like any other failing feed and is retried on the
|
|
43
|
+
* usual schedule. Sending the same list again changes nothing (`exists`).
|
|
44
|
+
*/
|
|
45
|
+
export async function subscribeBatch(userId, items) {
|
|
46
|
+
const checked = await checkAll(items);
|
|
47
|
+
const created = [];
|
|
48
|
+
const results = db.transaction(() => {
|
|
49
|
+
const folders = new Map();
|
|
50
|
+
return items.map((item, index) => {
|
|
51
|
+
const check = checked[index];
|
|
52
|
+
if ("reason" in check)
|
|
53
|
+
return { url: item.url, status: "invalid", reason: check.reason };
|
|
54
|
+
let feed = findFeedByUrl(check.url);
|
|
55
|
+
const isNew = !feed;
|
|
56
|
+
feed ??= createFeed(check.url, Math.max(config.minPollIntervalMinutes, 15));
|
|
57
|
+
if (isUserSubscribed(userId, feed.id))
|
|
58
|
+
return { url: item.url, status: "exists", subscriptionId: feed.id };
|
|
59
|
+
const folderName = item.folder?.trim().slice(0, MAX_FOLDER_NAME_LENGTH);
|
|
60
|
+
let folderId = null;
|
|
61
|
+
if (folderName) {
|
|
62
|
+
folderId = folders.get(folderName) ?? createFolder(userId, folderName).id;
|
|
63
|
+
folders.set(folderName, folderId);
|
|
64
|
+
}
|
|
65
|
+
subscribe(userId, feed.id, item.label?.trim().slice(0, MAX_LABEL_LENGTH) || null, folderId);
|
|
66
|
+
// A feed that other accounts already read is up to date; only a new one needs its first fetch.
|
|
67
|
+
if (isNew || !feed.last_success_at)
|
|
68
|
+
created.push(feed);
|
|
69
|
+
return { url: item.url, status: "added", subscriptionId: feed.id };
|
|
70
|
+
});
|
|
71
|
+
})();
|
|
72
|
+
for (const feed of created)
|
|
73
|
+
requestFeedPoll(feed);
|
|
74
|
+
return results;
|
|
75
|
+
}
|
|
76
|
+
/** How far the first fetch of the given subscriptions (feed ids) has come, as counts, so a client can show progress cheaply. */
|
|
77
|
+
export function fetchStatusFor(userId, ids) {
|
|
78
|
+
const status = { total: 0, loaded: 0, failed: 0, waiting: 0 };
|
|
79
|
+
if (ids.length === 0)
|
|
80
|
+
return status;
|
|
81
|
+
const rows = db.prepare(`SELECT f.last_success_at, f.last_error FROM subscriptions s JOIN feeds f ON f.id = s.feed_id
|
|
82
|
+
WHERE s.user_id = ? AND s.feed_id IN (${ids.map(() => "?").join(",")})`).all(userId, ...ids);
|
|
83
|
+
for (const row of rows) {
|
|
84
|
+
status.total++;
|
|
85
|
+
if (row.last_success_at)
|
|
86
|
+
status.loaded++;
|
|
87
|
+
else if (row.last_error)
|
|
88
|
+
status.failed++;
|
|
89
|
+
else
|
|
90
|
+
status.waiting++;
|
|
91
|
+
}
|
|
92
|
+
return status;
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=batchSubscribe.js.map
|
|
@@ -30,7 +30,7 @@ function sameUrl(a, b) {
|
|
|
30
30
|
}
|
|
31
31
|
async function parseFeedAt(url) {
|
|
32
32
|
try {
|
|
33
|
-
const fetched = await fetchFeed(url);
|
|
33
|
+
const fetched = await fetchFeed(url, { priority: "interactive" });
|
|
34
34
|
const finalUrl = fetched.finalUrl || url;
|
|
35
35
|
try {
|
|
36
36
|
const parsed = await rssParser.parseString(fetched.body);
|
|
@@ -76,7 +76,7 @@ async function platformFeed(url) {
|
|
|
76
76
|
const podcastId = applePodcastId(url);
|
|
77
77
|
if (podcastId) {
|
|
78
78
|
try {
|
|
79
|
-
const lookup = await fetchFeed(`https://itunes.apple.com/lookup?id=${podcastId}&entity=podcast
|
|
79
|
+
const lookup = await fetchFeed(`https://itunes.apple.com/lookup?id=${podcastId}&entity=podcast`, { priority: "interactive" });
|
|
80
80
|
const feedUrl = feedUrlFromAppleLookup(lookup.body);
|
|
81
81
|
if (feedUrl)
|
|
82
82
|
candidates.push((await assertPublicFeedUrl(feedUrl)).toString());
|
|
@@ -76,18 +76,29 @@ async function validateUrl(url, signal) {
|
|
|
76
76
|
assertPublicFeedUrl(url).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
77
77
|
});
|
|
78
78
|
}
|
|
79
|
-
// Re-validate every redirect hop and bound headers, body
|
|
79
|
+
// Re-validate every redirect hop and bound headers, body and DNS together with one deadline. The deadline starts when the download gets
|
|
80
|
+
// its first slot in the shared gate, so a busy gate cannot use it up; waiting for a slot has its own limit (the poll attempt deadline).
|
|
80
81
|
async function downloadPublic(url, opts) {
|
|
81
82
|
let currentUrl = url;
|
|
82
83
|
const controller = new AbortController();
|
|
83
|
-
const
|
|
84
|
+
const settings = readPollSettings();
|
|
85
|
+
let timeout;
|
|
86
|
+
let slotWait;
|
|
84
87
|
const signal = opts.signal ? AbortSignal.any([controller.signal, opts.signal]) : controller.signal;
|
|
85
88
|
const dispatcher = createPublicDispatcher();
|
|
86
89
|
try {
|
|
87
90
|
for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
|
|
88
91
|
const candidate = new URL(normalizeUrlCandidate(currentUrl));
|
|
89
92
|
const host = sourceHost(candidate.href);
|
|
90
|
-
|
|
93
|
+
slotWait = setTimeout(() => controller.abort(new DOMException("Download deadline exceeded", "TimeoutError")), settings.attemptTimeoutMs);
|
|
94
|
+
let release;
|
|
95
|
+
try {
|
|
96
|
+
release = await feedRequests.acquire(host, signal, opts.priority);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
clearTimeout(slotWait);
|
|
100
|
+
}
|
|
101
|
+
timeout ??= setTimeout(() => controller.abort(new DOMException("Download deadline exceeded", "TimeoutError")), settings.requestTimeoutMs);
|
|
91
102
|
try {
|
|
92
103
|
const validated = await validateUrl(candidate.href, signal);
|
|
93
104
|
signal.throwIfAborted();
|
|
@@ -154,6 +165,7 @@ async function downloadPublic(url, opts) {
|
|
|
154
165
|
throw new Error("Too many redirects while fetching feed");
|
|
155
166
|
}
|
|
156
167
|
finally {
|
|
168
|
+
clearTimeout(slotWait);
|
|
157
169
|
clearTimeout(timeout);
|
|
158
170
|
await dispatcher.destroy();
|
|
159
171
|
}
|
|
@@ -166,6 +178,7 @@ export async function fetchFeed(url, opts = {}) {
|
|
|
166
178
|
etag: opts.etag,
|
|
167
179
|
lastModified: opts.lastModified,
|
|
168
180
|
signal: opts.signal,
|
|
181
|
+
priority: opts.priority,
|
|
169
182
|
});
|
|
170
183
|
if (download.notModified) {
|
|
171
184
|
return { notModified: true, body: "", finalUrl: download.finalUrl, contentType: download.contentType };
|
|
@@ -178,12 +178,14 @@ export class PollQueue {
|
|
|
178
178
|
while (!this.stopped && this.active.size < this.settings.concurrency) {
|
|
179
179
|
const blockedHosts = [...new Set([...this.active.values()].map(entry => entry.host))]
|
|
180
180
|
.filter(host => [...this.active.values()].filter(entry => entry.host === host).length >= this.settings.hostConcurrency);
|
|
181
|
+
// Feeds somebody is waiting for come first; everything else keeps its order of arrival.
|
|
181
182
|
const job = db.prepare(`SELECT j.* FROM feed_poll_jobs j
|
|
182
183
|
WHERE j.available_at <= ?
|
|
183
184
|
AND j.feed_id NOT IN (SELECT value FROM json_each(?))
|
|
184
185
|
AND j.host NOT IN (SELECT value FROM json_each(?))
|
|
185
186
|
AND NOT EXISTS (SELECT 1 FROM feed_poll_hosts h WHERE h.host = j.host AND h.retry_at > ?)
|
|
186
|
-
ORDER BY
|
|
187
|
+
ORDER BY CASE WHEN j.feed_id IN (SELECT value FROM json_each(?)) THEN 0 ELSE 1 END, j.enqueued_at, j.feed_id LIMIT 1`)
|
|
188
|
+
.get(Date.now(), JSON.stringify([...this.active.keys()]), JSON.stringify(blockedHosts), Date.now(), JSON.stringify([...this.waiters.keys()]));
|
|
187
189
|
if (!job)
|
|
188
190
|
break;
|
|
189
191
|
const feed = findFeedById(job.feed_id);
|
|
@@ -209,6 +211,7 @@ export class PollQueue {
|
|
|
209
211
|
const waiter = this.waiters.get(feed.id);
|
|
210
212
|
if (waiter)
|
|
211
213
|
clearTimeout(waiter.timer);
|
|
214
|
+
const interactive = waiter !== undefined;
|
|
212
215
|
const controller = new AbortController();
|
|
213
216
|
const timeout = setTimeout(() => controller.abort(new DOMException("Poll deadline exceeded", "TimeoutError")), this.settings.attemptTimeoutMs);
|
|
214
217
|
const started = Date.now();
|
|
@@ -216,7 +219,7 @@ export class PollQueue {
|
|
|
216
219
|
const lag = Math.max(0, started - dueAt);
|
|
217
220
|
this.counters.startLagMs += lag;
|
|
218
221
|
this.counters.maxStartLagMs = Math.max(this.counters.maxStartLagMs, lag);
|
|
219
|
-
const promise = this.run(job, feed, controller.signal).catch(() => {
|
|
222
|
+
const promise = this.run(job, feed, controller.signal, interactive).catch(() => {
|
|
220
223
|
console.error(JSON.stringify({ event: "feed_poll_queue_error", code: "attempt_storage_failure" }));
|
|
221
224
|
// A storage failure leaves the durable job intact. Stop admission until process restart.
|
|
222
225
|
this.stopped = true;
|
|
@@ -234,9 +237,9 @@ export class PollQueue {
|
|
|
234
237
|
void promise.then(result => this.resolve(feed.id, result));
|
|
235
238
|
}
|
|
236
239
|
}
|
|
237
|
-
async run(job, feed, signal) {
|
|
240
|
+
async run(job, feed, signal, interactive) {
|
|
238
241
|
try {
|
|
239
|
-
const result = await this.attempt(feed, signal);
|
|
242
|
+
const result = await this.attempt(feed, signal, interactive);
|
|
240
243
|
db.prepare("DELETE FROM feed_poll_jobs WHERE feed_id = ?").run(feed.id);
|
|
241
244
|
if (!result.error) {
|
|
242
245
|
this.counters.succeeded++;
|
|
@@ -12,6 +12,7 @@ import { configurePollHostCooldowns, PollQueue } from "./pollQueue.js";
|
|
|
12
12
|
import { feedRequests, PollDeferredError, sourceHost } from "./requestGate.js";
|
|
13
13
|
import { normalizePublishedAt } from "./dates.js";
|
|
14
14
|
import { authorLine } from "./author.js";
|
|
15
|
+
import { readPollSettings } from "./pollSettings.js";
|
|
15
16
|
configurePollHostCooldowns();
|
|
16
17
|
function mediaAttribute(value, key) {
|
|
17
18
|
if (typeof value !== "object" || value === null)
|
|
@@ -127,9 +128,42 @@ export function itemLink(item) {
|
|
|
127
128
|
return unwrapRedirectLink(item.link);
|
|
128
129
|
return item.guid && /^https?:\/\//i.test(item.guid) ? unwrapRedirectLink(item.guid) : undefined;
|
|
129
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* Checks the feed's icon when it is due. The check starts right away but is not awaited, has its own deadline, and cannot retry or
|
|
133
|
+
* fail a committed feed; downloads join the shared request limit as background work.
|
|
134
|
+
*/
|
|
135
|
+
function scheduleIconMaintenance(feed, parsed) {
|
|
136
|
+
if (!iconCheckDue(feed.icon_checked_at))
|
|
137
|
+
return;
|
|
138
|
+
updateFeedIcon(feed.id, feed.icon_url);
|
|
139
|
+
const signal = AbortSignal.timeout(readPollSettings().attemptTimeoutMs);
|
|
140
|
+
const task = (async () => {
|
|
141
|
+
try {
|
|
142
|
+
const siteUrl = parsed?.link || feed.site_url;
|
|
143
|
+
const htmlUrls = siteUrl ? await discoverIconUrls(siteUrl, signal) : [];
|
|
144
|
+
const feedUrls = extractFeedIconUrls(parsed, siteUrl || feed.url);
|
|
145
|
+
signal.throwIfAborted();
|
|
146
|
+
await refreshFeedIcon(feed.id, siteUrl, [...htmlUrls, ...feedUrls.icons], signal, feedUrls.logos);
|
|
147
|
+
}
|
|
148
|
+
catch { /* Keep the successful poll; icon failures are best effort. */ }
|
|
149
|
+
})();
|
|
150
|
+
iconChecks.add(task);
|
|
151
|
+
void task.finally(() => iconChecks.delete(task));
|
|
152
|
+
}
|
|
153
|
+
const iconChecks = new Set();
|
|
154
|
+
/** Resolves once the icon checks started so far are done; used by shutdown and by tests that look at the stored icon. */
|
|
155
|
+
export async function settleIconChecks() {
|
|
156
|
+
while (iconChecks.size)
|
|
157
|
+
await Promise.allSettled([...iconChecks]);
|
|
158
|
+
}
|
|
130
159
|
/** One attempt; the queue owns retries, admission, single-flight and the total deadline. */
|
|
131
|
-
async function pollAttempt(feed, signal) {
|
|
132
|
-
const fetched = await fetchFeed(feed.url, {
|
|
160
|
+
async function pollAttempt(feed, signal, interactive) {
|
|
161
|
+
const fetched = await fetchFeed(feed.url, {
|
|
162
|
+
etag: feed.etag ?? undefined,
|
|
163
|
+
lastModified: feed.last_modified ?? undefined,
|
|
164
|
+
signal,
|
|
165
|
+
priority: interactive ? "interactive" : "background",
|
|
166
|
+
});
|
|
133
167
|
const parsed = fetched.notModified ? null : await parser.parseString(fetched.body);
|
|
134
168
|
signal.throwIfAborted();
|
|
135
169
|
const current = findFeedById(feed.id);
|
|
@@ -160,19 +194,9 @@ async function pollAttempt(feed, signal) {
|
|
|
160
194
|
})();
|
|
161
195
|
// Push is committed above and dispatched independently of the feed deadline.
|
|
162
196
|
startPushOutbox();
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
if (iconCheckDue(feed.icon_checked_at)) {
|
|
167
|
-
updateFeedIcon(feed.id, feed.icon_url);
|
|
168
|
-
const siteUrl = parsed?.link || feed.site_url;
|
|
169
|
-
const htmlUrls = siteUrl ? await discoverIconUrls(siteUrl, signal) : [];
|
|
170
|
-
const feedUrls = extractFeedIconUrls(parsed, siteUrl || feed.url);
|
|
171
|
-
signal.throwIfAborted();
|
|
172
|
-
await refreshFeedIcon(feed.id, siteUrl, [...htmlUrls, ...feedUrls.icons], signal, feedUrls.logos);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
catch { /* Keep the successful poll; icon failures are best effort. */ }
|
|
197
|
+
// Icon upkeep is best effort. It runs after this result is returned: the poll slot is free again, and a new subscription that is
|
|
198
|
+
// waiting for the first fetch is answered as soon as the feed is stored, not after the publisher's home page and icons.
|
|
199
|
+
scheduleIconMaintenance(feed, parsed);
|
|
176
200
|
return { newItems, error: null };
|
|
177
201
|
}
|
|
178
202
|
let queue;
|
|
@@ -211,7 +235,7 @@ export function requestFeedPoll(feed) {
|
|
|
211
235
|
export function pollingMetrics() { return pollingQueue().metrics(); }
|
|
212
236
|
/** Fetch and parse a feed without storing anything, to validate a URL before switching to it. */
|
|
213
237
|
export async function probeFeed(url) {
|
|
214
|
-
const fetched = await fetchFeed(url);
|
|
238
|
+
const fetched = await fetchFeed(url, { priority: "interactive" });
|
|
215
239
|
const parsed = await parser.parseString(fetched.body);
|
|
216
240
|
return { title: parsed.title ?? null, itemCount: parsed.items.length };
|
|
217
241
|
}
|
|
@@ -243,6 +267,8 @@ export async function stopPollingScheduler() {
|
|
|
243
267
|
await stopImageCache();
|
|
244
268
|
await Promise.all([queue?.stop(), stopPushOutbox()]);
|
|
245
269
|
feedRequests.stop();
|
|
270
|
+
// Waiting icon downloads were just turned away; the ones in flight end with their own deadline.
|
|
271
|
+
await settleIconChecks();
|
|
246
272
|
}
|
|
247
273
|
/** Graceful shutdown for server integrations; process-manager grace should be >= 45 seconds. */
|
|
248
274
|
export function installPollingShutdown(server) {
|
|
@@ -34,7 +34,7 @@ export class RequestGate {
|
|
|
34
34
|
}
|
|
35
35
|
get limits() { return this.settings ??= readPollSettings(); }
|
|
36
36
|
get stats() { return { running: this.running, waiting: this.waiting.length }; }
|
|
37
|
-
acquire(host, signal) {
|
|
37
|
+
acquire(host, signal, priority = "background") {
|
|
38
38
|
if (this.stopped)
|
|
39
39
|
return Promise.reject(new PollShutdownError());
|
|
40
40
|
if (signal.aborted)
|
|
@@ -42,18 +42,37 @@ export class RequestGate {
|
|
|
42
42
|
const until = this.cooldown(host);
|
|
43
43
|
if (until > Date.now())
|
|
44
44
|
return Promise.reject(new PollDeferredError(until, host));
|
|
45
|
-
if (this.waiting.length >= this.limits.maxWaiters)
|
|
45
|
+
if (this.waiting.length >= this.limits.maxWaiters && !this.makeRoomFor(priority))
|
|
46
46
|
return Promise.reject(new RequestQueueFullError());
|
|
47
47
|
return new Promise((resolve, reject) => {
|
|
48
|
-
const waiter = { host, signal, resolve, reject, abort: () => {
|
|
48
|
+
const waiter = { host, signal, priority, resolve, reject, abort: () => {
|
|
49
49
|
this.waiting = this.waiting.filter(entry => entry !== waiter);
|
|
50
50
|
reject(signal.reason);
|
|
51
51
|
} };
|
|
52
52
|
signal.addEventListener("abort", waiter.abort, { once: true });
|
|
53
|
-
|
|
53
|
+
// Interactive requests queue behind earlier interactive ones but ahead of all background work.
|
|
54
|
+
const index = priority === "interactive" ? this.waiting.findIndex(entry => entry.priority === "background") : -1;
|
|
55
|
+
if (index === -1)
|
|
56
|
+
this.waiting.push(waiter);
|
|
57
|
+
else
|
|
58
|
+
this.waiting.splice(index, 0, waiter);
|
|
54
59
|
this.pump();
|
|
55
60
|
});
|
|
56
61
|
}
|
|
62
|
+
/** A full queue still admits an interactive request by turning away the most recent background one. */
|
|
63
|
+
makeRoomFor(priority) {
|
|
64
|
+
if (priority !== "interactive")
|
|
65
|
+
return false;
|
|
66
|
+
for (let i = this.waiting.length - 1; i >= 0; i--) {
|
|
67
|
+
if (this.waiting[i].priority !== "background")
|
|
68
|
+
continue;
|
|
69
|
+
const [evicted] = this.waiting.splice(i, 1);
|
|
70
|
+
evicted.signal.removeEventListener("abort", evicted.abort);
|
|
71
|
+
evicted.reject(new RequestQueueFullError());
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
57
76
|
pump() {
|
|
58
77
|
for (let i = 0; i < this.waiting.length;) {
|
|
59
78
|
const waiter = this.waiting[i];
|
|
@@ -12,8 +12,6 @@ import { SsrfBlockedError, normalizeUrlCandidate } from "../feeds/ssrfGuard.js";
|
|
|
12
12
|
import { generateOpml, importOpmlFeeds } from "../feeds/opml.js";
|
|
13
13
|
import { pollFeed } from "../feeds/poller.js";
|
|
14
14
|
import { discoverFeeds } from "../feeds/discovery.js";
|
|
15
|
-
import { findUserById } from "../auth/users.js";
|
|
16
|
-
import { getDatabaseStats, runCleanup } from "../feeds/cleanup.js";
|
|
17
15
|
import { APP_VERSION } from "../version.js";
|
|
18
16
|
import { dismissEdition, editionCandidates, ensureEditionSchema, getEdition, getEditionState, publishCuratedEdition, publishEditionFields } from "../native/editions.js";
|
|
19
17
|
import { getNativePreferences, patchNativePreferences, preferencePatchSchema } from "../native/preferences.js";
|
|
@@ -111,7 +109,7 @@ export function createMcpServerForUser(userId, scope) {
|
|
|
111
109
|
if (scope === "write")
|
|
112
110
|
server.registerTool("unsubscribe_feed", {
|
|
113
111
|
title: "Unsubscribe from a feed",
|
|
114
|
-
description: "
|
|
112
|
+
description: "Unsubscribes the current user from a feed. Feeds and other users' subscriptions are unaffected.",
|
|
115
113
|
inputSchema: { feedId: z.number().int().positive() },
|
|
116
114
|
}, async ({ feedId }) => {
|
|
117
115
|
try {
|
|
@@ -241,7 +239,7 @@ export function createMcpServerForUser(userId, scope) {
|
|
|
241
239
|
if (scope === "write")
|
|
242
240
|
server.registerTool("delete_folder", {
|
|
243
241
|
title: "Delete folder",
|
|
244
|
-
description: "Deletes a folder. Its feeds
|
|
242
|
+
description: "Deletes a folder category. Its subscribed feeds remain intact and are moved to the root level (unfiled).",
|
|
245
243
|
inputSchema: { folderId: z.number().int().positive() },
|
|
246
244
|
}, async ({ folderId }) => {
|
|
247
245
|
if (!findFolderById(userId, folderId))
|
|
@@ -414,9 +412,9 @@ export function createMcpServerForUser(userId, scope) {
|
|
|
414
412
|
inputSchema: { keyword: z.string().min(1).max(100) },
|
|
415
413
|
}, async ({ keyword }) => textResult(addMutedKeyword(userId, keyword)));
|
|
416
414
|
if (scope === "write")
|
|
417
|
-
server.registerTool("
|
|
418
|
-
title: "
|
|
419
|
-
description: "Unmutes a keyword by its ID.",
|
|
415
|
+
server.registerTool("unmute_keyword", {
|
|
416
|
+
title: "Unmute keyword",
|
|
417
|
+
description: "Unmutes a previously muted keyword by its ID (removes the keyword filter rule).",
|
|
420
418
|
inputSchema: { keywordId: z.number().int().positive() },
|
|
421
419
|
}, async ({ keywordId }) => {
|
|
422
420
|
removeMutedKeyword(userId, keywordId);
|
|
@@ -538,27 +536,6 @@ export function createMcpServerForUser(userId, scope) {
|
|
|
538
536
|
description: "Explicitly dismisses the current edition, including curated issues, using a revision and stable UUID requestId. Automatic scheduling waits until the next time slot; generate_edition with force=true can start a new issue immediately.",
|
|
539
537
|
inputSchema: { requestId: z.uuid(), expectedRevision: z.number().int().min(0) },
|
|
540
538
|
}, async (input) => editionAction(() => dismissEdition(userId, input)));
|
|
541
|
-
const currentUser = findUserById(userId);
|
|
542
|
-
if (scope === "write" && currentUser?.role === "admin") {
|
|
543
|
-
server.registerTool("cleanup_database", {
|
|
544
|
-
title: "Clean up database and retention",
|
|
545
|
-
description: "Admin tool: runs item retention cleanup and VACUUM to purge old/read items and reclaim disk space.",
|
|
546
|
-
inputSchema: {
|
|
547
|
-
retentionReadDays: z.number().int().min(0).optional().describe("Override read items retention in days"),
|
|
548
|
-
retentionMaxDays: z.number().int().min(0).optional().describe("Override total item age retention in days"),
|
|
549
|
-
retentionMaxItemsPerFeed: z.number().int().min(0).optional().describe("Override maximum items per feed cap"),
|
|
550
|
-
},
|
|
551
|
-
}, async (args) => {
|
|
552
|
-
try {
|
|
553
|
-
const result = runCleanup(args);
|
|
554
|
-
const stats = getDatabaseStats();
|
|
555
|
-
return textResult({ result, stats });
|
|
556
|
-
}
|
|
557
|
-
catch (error) {
|
|
558
|
-
return errorResult(error instanceof Error ? error.message : String(error));
|
|
559
|
-
}
|
|
560
|
-
});
|
|
561
|
-
}
|
|
562
539
|
registerPromptsAndResources(server, userId, scope);
|
|
563
540
|
return server;
|
|
564
541
|
}
|