Skip to content

Commit f686e37

Browse files
committed
add pinning
1 parent a4439ab commit f686e37

19 files changed

Lines changed: 322 additions & 16 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,10 +133,17 @@ held in a bounded ten-second memory cache keyed by discussion ID, so a recently
133133
deleted comment may remain visible briefly. Identical concurrent reads share an
134134
in-flight GitHub call.
135135

136-
This revision uses schema version 6. It does not migrate existing version 5
136+
This revision uses schema version 7. It does not migrate existing older
137137
databases. Remove the service's SQLite database files before starting this build;
138138
configured `known_discussions` are seeded again and counters refill from GitHub.
139139

140+
When `category_pins` is enabled for a site, the same batched counter response
141+
includes `pinnedToCategory` for each card. The service reads GitHub's public
142+
category page once per requested category per `pin_cache_seconds` (default one
143+
hour), using ETags when available. Concurrent requests share a refresh. Failed
144+
refreshes retain the last good snapshot and wait five minutes before retrying.
145+
This uses the category's pinned list, so repository-wide pins do not affect it.
146+
140147
`cache_fresh_seconds` is the age at which a requested tracked counter needs an
141148
authoritative GitHub refresh. The default is 60 seconds. A batched request
142149
refreshes only stale resources; recently refreshed resources in the same request

‎config/sites.dev.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ repository = "cppsocial/feedback"
1818
repository_id = "R_kgDOUc9png"
1919
installation_id = 162105624
2020
default_category = "general"
21-
intents = ["votes", "reactions", "discussion", "comments", "answers", "polls", "authors", "moderation", "comment_reactions", "labels", "github_link"]
21+
intents = ["votes", "reactions", "discussion", "comments", "answers", "polls", "authors", "moderation", "comment_reactions", "labels", "github_link", "category_pins"]
2222
reaction_counters = ["LAUGH", "HOORAY", "CONFUSED", "HEART", "ROCKET", "EYES"]
2323
known_discussions = [
2424
{ key = "feedback/example", id = "D_kwDOUc9pns4ApUHg", number = 1, category = "general", title = "feedback/example" },

‎config/sites.example.toml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@ discussion_body = "Discussion for [{title}]({url})."
2222
# cache_fresh_seconds = 60
2323
# refresh_cooldown_seconds = 60
2424
# refresh_sweep_seconds = 86400
25+
# pin_cache_seconds = 3600
2526
# max_batch_size = 100
26-
intents = ["votes", "reactions", "discussion", "comments", "answers", "polls", "authors", "moderation", "comment_reactions", "labels", "github_link"]
27+
intents = ["votes", "reactions", "discussion", "comments", "answers", "polls", "authors", "moderation", "comment_reactions", "labels", "github_link", "category_pins"]
2728
reaction_counters = ["LAUGH", "HOORAY", "CONFUSED", "HEART", "ROCKET", "EYES"]
2829
# Optional: pre-register discussions whose stable numeric and node IDs are known
2930
# so anonymous reads work immediately after starting with an empty database.
@@ -34,6 +35,7 @@ reaction_counters = ["LAUGH", "HOORAY", "CONFUSED", "HEART", "ROCKET", "EYES"]
3435
[sites.example.categories.articles]
3536
name = "Articles"
3637
id = "replace-with-articles-category-node-id"
38+
# slug = "articles" # Set when the GitHub URL slug differs from this key.
3739

3840
[sites.example.categories.tips]
3941
name = "Tips"

‎config/sites.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ repository_id = "R_kgDOUc9png"
1717
installation_id = 162105624
1818
default_category = "general"
1919
discussion_body = "Feedback for [{title}]({url})"
20-
intents = ["votes", "reactions", "discussion", "comments", "answers", "polls", "authors", "moderation", "comment_reactions", "labels", "github_link"]
20+
intents = ["votes", "reactions", "discussion", "comments", "answers", "polls", "authors", "moderation", "comment_reactions", "labels", "github_link", "category_pins"]
2121
reaction_counters = ["LAUGH", "HOORAY", "CONFUSED", "HEART", "ROCKET", "EYES"]
2222
known_discussions = [
2323
{ key = "feedback/example", id = "D_kwDOUc9pns4ApUHg", number = 1, category = "general", title = "feedback/example" },

‎docs/API.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ GitHub token after exchange and provides no general user-token proxy.
2525
| Principal | Permission used | Operation |
2626
| --- | --- | --- |
2727
| GitHub App installation | Discussions read | Find discussions, read threads, reactions, polls, labels, and author data |
28+
| No GitHub credential | Public category page read | Refresh category pin flags when `category_pins` is enabled |
2829
| GitHub App installation | Discussions write | Create a discussion after a signed creation grant |
2930
| Signed-in GitHub user | Discussions read/write on the target repository | Read viewer state; vote, react, comment, reply, edit, delete, and mark answers where GitHub permits |
3031
| Browser on an allowed site origin | Service read routes | Read public counters and threads without signing in |
@@ -61,10 +62,22 @@ in different categories should use category-qualified keys.
6162
| `comment_reactions` | Comment/reply reaction totals |
6263
| `labels` | Discussion labels |
6364
| `github_link` | Discussion/comment URLs and discussion number in counter results |
65+
| `category_pins` | `pinnedToCategory` boolean in batched counter results, available anonymously |
6466

65-
Ranking mode accepts only `votes` and `reactions`. Discussion metadata intents
67+
Ranking mode accepts `votes`, `reactions`, and `category_pins`. Discussion metadata intents
6668
require `discussion`; comment-specific metadata requires `comments`. Disabled
6769
features return 404 and do not add fields to GitHub queries or API responses.
70+
`reaction_counters` selects individual non-vote reaction fields; `github_link`
71+
selects link and number fields; `category_pins` selects the pin flag. A category
72+
may set `slug` when its GitHub URL slug differs from its local key.
73+
74+
GitHub's public GraphQL discussion schema does not expose category pins. When
75+
enabled, the service reads the pinned list from each requested category's public
76+
GitHub page, bounded to one page per category per hour by default. It requests
77+
only categories present in the card batch, uses ETags when available, coalesces
78+
concurrent refreshes, and keeps the last good snapshot on failure. Repository-wide
79+
pins are excluded. The page parser is a compatibility boundary; monitor the
80+
refresh warning if GitHub changes its HTML.
6881

6982
## HTTP routes
7083

‎runtime/src/api/client.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ interface CounterState {
1313
up: number;
1414
down: number;
1515
reactions?: Record<string, number>;
16+
pinnedToCategory?: boolean;
1617
}
1718

1819
export type ReactionState = CounterState;
@@ -344,6 +345,7 @@ function isCounterState(value: unknown): value is CounterState {
344345
Number.isSafeInteger(state.number) && state.number > 0) &&
345346
Number.isSafeInteger(state.up) && (state.up ?? -1) >= 0 &&
346347
Number.isSafeInteger(state.down) && (state.down ?? -1) >= 0 &&
348+
(state.pinnedToCategory === undefined || typeof state.pinnedToCategory === "boolean") &&
347349
(state.reactions === undefined || typeof state.reactions === "object")
348350
);
349351
}

‎runtime/src/example/page.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const apiOrigin = apiParameter === null
1717
? "https://feedback-api.cpp.social"
1818
: trustedOrigin(apiParameter, "example API origin");
1919
const keys = [...new Set(
20-
(parameters.get("keys") ?? parameters.get("key") ?? "feedback/example,feedback/documentation,poll/test,q-and-a/foo,q-and-a/test,feedback/not-created")
20+
(parameters.get("keys") ?? parameters.get("key") ?? "feedback/example,feedback/documentation,feedback/navigation,feedback/design,poll/test,q-and-a/foo,q-and-a/test,feedback/not-created")
2121
.split(",").map((value) => value.trim()).filter(Boolean),
2222
)];
2323
const githubMode = parameters.get("github") ?? "link";
@@ -237,11 +237,13 @@ async function render(force = false): Promise<void> {
237237
function renderRankingCards(states: ReadonlyMap<string, ReactionState>): void {
238238
const root = required("cards");
239239
root.replaceChildren();
240-
for (const key of keys) {
240+
for (const key of [...keys].sort((a, b) =>
241+
Number(states.get(b)?.pinnedToCategory === true) - Number(states.get(a)?.pinnedToCategory === true))) {
241242
const state = states.get(key);
242243
const card = document.createElement("article");
243244
card.className = "ranking-card";
244245
appendText(card, "h3", key);
246+
if (state?.pinnedToCategory) appendText(card, "small", "Pinned to category");
245247
const votes = document.createElement("div");
246248
votes.className = "card-votes";
247249
for (const direction of ["up", "down"] as const) {

‎src/feedback/api/endpoints/reactions.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ async def get_reactions(request: Request) -> Response:
2020
cached = context.database.reactions(keys)
2121
with suppress(GitHubError):
2222
await context.runtime.refresh_stale(context.site, cached)
23+
await context.runtime.refresh_pins(context.site, keys)
2324
payload = {
2425
"v": 1,
2526
"site": context.site.id,

‎src/feedback/app.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from feedback.protocol.github.client import GitHubClient
2222
from feedback.protocol.github.discussions import GitHubDiscussions
2323
from feedback.protocol.github.oauth import OAuthClient
24+
from feedback.service.category_pins import CategoryPinRefresher
2425
from feedback.service.discussions import DiscussionService
2526
from feedback.service.oauth_state import CreationGrantSigner, StateSigner
2627
from feedback.service.reaction_cache import ReactionRefresher
@@ -45,6 +46,7 @@ def create_app(
4546
refresher: ReactionRefresher | None = None,
4647
grants: CreationGrantSigner | None = None,
4748
discussions: DiscussionService | None = None,
49+
pins: CategoryPinRefresher | None = None,
4850
verbose: bool = False,
4951
) -> Starlette:
5052
if oauth is not None and grants is None:
@@ -58,6 +60,7 @@ async def lifespan(application: Starlette) -> AsyncIterator[None]:
5860
resolved_refresher: ReactionRefresher | None
5961
resolved_grants: CreationGrantSigner | None
6062
resolved_discussions: DiscussionService | None
63+
resolved_pins: CategoryPinRefresher | None
6164
if secret_files is not None:
6265
owned_http = httpx.AsyncClient(
6366
timeout=httpx.Timeout(
@@ -74,11 +77,13 @@ async def lifespan(application: Starlette) -> AsyncIterator[None]:
7477
github = _github_client(loaded, owned_http, clock, secret_files.github_app_private_key)
7578
resolved_refresher = ReactionRefresher(github, clock=clock)
7679
resolved_discussions = DiscussionService(GitHubDiscussions(github), clock=clock)
80+
resolved_pins = CategoryPinRefresher(owned_http, clock=clock)
7781
else:
7882
resolved_oauth = oauth
7983
resolved_refresher = refresher
8084
resolved_grants = grants
8185
resolved_discussions = discussions
86+
resolved_pins = pins
8287
databases = {
8388
site_id: SiteDatabase(loaded.service.data_directory / f"{site_id}.sqlite3")
8489
for site_id in loaded.sites
@@ -109,6 +114,7 @@ async def lifespan(application: Starlette) -> AsyncIterator[None]:
109114
refresher=resolved_refresher,
110115
grants=resolved_grants,
111116
discussions=resolved_discussions,
117+
pins=resolved_pins,
112118
)
113119
application.state.services = services
114120
services.start_sweeps()

‎src/feedback/config.py‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ class ConfigError(ValueError):
3535
"comment_reactions",
3636
"labels",
3737
"github_link",
38+
"category_pins",
3839
}
3940
)
4041
_SERVICE_KEYS = frozenset(
@@ -66,6 +67,7 @@ class ConfigError(ValueError):
6667
"refresh_sweep_seconds",
6768
"max_batch_size",
6869
"reaction_counters",
70+
"pin_cache_seconds",
6971
"intents",
7072
}
7173
)
@@ -88,6 +90,7 @@ class CategoryConfig:
8890
key: str
8991
name: str
9092
node_id: str
93+
slug: str | None = None
9194

9295

9396
@dataclass(frozen=True, slots=True)
@@ -117,6 +120,7 @@ class SiteConfig:
117120
refresh_sweep_seconds: int = 86_400
118121
max_batch_size: int = 100
119122
reaction_counters: tuple[str, ...] = ()
123+
pin_cache_seconds: int = 3600
120124
intents: frozenset[str] = frozenset({"votes"})
121125

122126
@property
@@ -195,7 +199,9 @@ def load_config(path: Path | str, *, data_directory: Path | None = None) -> Conf
195199
if mapping not in _MAPPINGS:
196200
raise ConfigError(f"sites.{site_id}.mapping is unsupported")
197201
repository = _string(value, "repository")
198-
if repository.count("/") != 1 or any(not part for part in repository.split("/")):
202+
if repository.count("/") != 1 or any(
203+
not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", part) for part in repository.split("/")
204+
):
199205
raise ConfigError(f"sites.{site_id}.repository must be owner/name")
200206
categories_raw = _table(value, "categories")
201207
if not categories_raw:
@@ -207,12 +213,16 @@ def load_config(path: Path | str, *, data_directory: Path | None = None) -> Conf
207213
if not isinstance(category_value, dict):
208214
raise ConfigError(f"sites.{site_id}.categories.{category_key} must be a table")
209215
_reject_keys(
210-
category_value, {"name", "id"}, f"sites.{site_id}.categories.{category_key}"
216+
category_value, {"name", "id", "slug"}, f"sites.{site_id}.categories.{category_key}"
211217
)
218+
slug = _string(category_value, "slug") if "slug" in category_value else category_key
219+
if not _SITE_ID.fullmatch(slug):
220+
raise ConfigError(f"sites.{site_id}.categories.{category_key}.slug is invalid")
212221
categories[category_key] = CategoryConfig(
213222
category_key,
214223
_string(category_value, "name"),
215224
_string(category_value, "id"),
225+
slug,
216226
)
217227
if len({category.name for category in categories.values()}) != len(categories):
218228
raise ConfigError(f"sites.{site_id}.categories contains duplicate names")
@@ -275,15 +285,15 @@ def load_config(path: Path | str, *, data_directory: Path | None = None) -> Conf
275285
intents = frozenset(_string_list(value, "intents"))
276286
if not intents or not intents <= _INTENTS:
277287
raise ConfigError(f"sites.{site_id}.intents contains an unsupported intent")
278-
if (intents - {"votes", "reactions"}) and "discussion" not in intents:
288+
if (intents - {"votes", "reactions", "category_pins"}) and "discussion" not in intents:
279289
raise ConfigError(
280290
f"sites.{site_id}.intents requires discussion for discussion metadata"
281291
)
282292
if (
283293
{"answers", "authors", "moderation", "comment_reactions"} & intents
284294
) and "comments" not in intents:
285295
raise ConfigError(f"sites.{site_id}.intents requires comments for comment metadata")
286-
if mode == "ranking" and not intents <= {"votes", "reactions"}:
296+
if mode == "ranking" and not intents <= {"votes", "reactions", "category_pins"}:
287297
raise ConfigError(f"sites.{site_id}.intents is incompatible with ranking mode")
288298
if reaction_counters and "reactions" not in intents:
289299
raise ConfigError(f"sites.{site_id}.reaction_counters requires reactions intent")
@@ -307,6 +317,7 @@ def load_config(path: Path | str, *, data_directory: Path | None = None) -> Conf
307317
),
308318
max_batch_size=_bounded_int(value, "max_batch_size", 1, 100, 100),
309319
reaction_counters=reaction_counters,
320+
pin_cache_seconds=_bounded_int(value, "pin_cache_seconds", 300, 86_400, 3600),
310321
intents=intents,
311322
)
312323

0 commit comments

Comments
 (0)