@anthusai/papyrus 5.19.1 → 5.20.0

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.
Files changed (43) hide show
  1. package/amplify/data/resource.js +1 -0
  2. package/amplify/data/resource.ts +1 -0
  3. package/amplify/data/schema.js +1 -0
  4. package/amplify/data/schema.ts +1 -0
  5. package/amplify/functions/assignment-action/data-access.js +2 -0
  6. package/amplify/functions/assignment-action/data-access.ts +2 -0
  7. package/amplify/functions/assignment-action/handler.ts +1 -1
  8. package/amplify/functions/content-actions/handler.py +3 -0
  9. package/amplify/functions/shared/editorial-context.ts +63 -4
  10. package/amplify/plugins/reader-steering/config.js +111 -0
  11. package/amplify/plugins/reader-steering/config.ts +158 -0
  12. package/amplify/plugins/reader-steering/function/handler.py +544 -0
  13. package/amplify/plugins/reader-steering/function/resource.js +27 -0
  14. package/amplify/plugins/reader-steering/function/resource.ts +35 -0
  15. package/amplify/plugins/reader-steering/papyrus.plugin.js +139 -0
  16. package/amplify/plugins/reader-steering/papyrus.plugin.ts +162 -0
  17. package/amplify/plugins/reader-steering/schema.js +40 -0
  18. package/amplify/plugins/reader-steering/schema.ts +42 -0
  19. package/amplify/plugins/registry.js +2 -0
  20. package/amplify/plugins/registry.ts +2 -0
  21. package/amplify/plugins/types.ts +3 -0
  22. package/amplify/plugins/wire.js +1 -0
  23. package/amplify/plugins/wire.ts +1 -0
  24. package/app/api/reader/handle/route.ts +9 -0
  25. package/app/api/reader/me/route.ts +9 -0
  26. package/app/api/reader/rating/route.ts +9 -0
  27. package/app/api/reader/retired/route.ts +9 -0
  28. package/app/api/reader/vote/route.ts +9 -0
  29. package/components/reference-cyclotron-priming.tsx +54 -15
  30. package/infra/amplify-app-shell.js +15 -1
  31. package/infra/amplify-app-shell.ts +17 -1
  32. package/infra/site-config.js +12 -2
  33. package/infra/site-config.ts +19 -2
  34. package/lib/editorial-checks.ts +6 -2
  35. package/lib/prospectus-session.ts +1 -0
  36. package/lib/prospectus-sign-in-routes.ts +2 -2
  37. package/lib/prospectus-site-identity.ts +24 -1
  38. package/lib/reader-api.ts +143 -0
  39. package/lib/reader-retirement-route.ts +89 -0
  40. package/lib/reader-subject.md +29 -0
  41. package/lib/reader-subject.ts +53 -0
  42. package/package.json +9 -1
  43. package/routes.manifest.json +56 -1
@@ -0,0 +1,139 @@
1
+ import { ArnPrincipal, Effect, PolicyStatement, Role, ServicePrincipal } from "aws-cdk-lib/aws-iam";
2
+ import { Duration, Stack } from "aws-cdk-lib";
3
+ import { Rule, RuleTargetInput, Schedule } from "aws-cdk-lib/aws-events";
4
+ import { LambdaFunction as LambdaFunctionTarget } from "aws-cdk-lib/aws-events-targets";
5
+ import { resolveReaderSteeringConfig } from "./config.js";
6
+ import { readerActions } from "./function/resource.js";
7
+ import { readerSteeringSchemaDefinitions } from "./schema.js";
8
+ export { resolveReaderSteeringConfig };
9
+ export const READER_STEERING_OUTPUT_KEY = "readerSteering";
10
+ export const SNAPSHOT_SCHEDULE_PREFIX = "papyrus-reader-snapshot-";
11
+ export const READER_SNAPSHOT_TASK = { projectionTask: { task: "reader-snapshot" } };
12
+ export const READER_SCHEDULED_SNAPSHOT_TASK = { projectionTask: { task: "reader-snapshot", retirementPoll: true } };
13
+ export const READER_POLL_SECRET_PARAMETER_ENV = "PAPYRUS_READER_POLL_SECRET_PARAMETER";
14
+ export const readerSteeringManifest = {
15
+ name: "reader-steering",
16
+ contract: 1,
17
+ models: ["ReaderProfile", "ReaderHandle", "ReaderVote"],
18
+ mutations: [],
19
+ guest: { mutations: [] },
20
+ newsroomPanels: [],
21
+ staticAssets: ["_plugins/papyrus-reader@1.js", "_plugins/papyrus-reader@1.css"],
22
+ };
23
+ /** What the reader-actions function reads from `PAPYRUS_READER_SETTINGS`. */
24
+ export function readerActionsSettings(config, allowInterimSubjects) {
25
+ return {
26
+ dimensions: config.dimensions,
27
+ limits: config.limits,
28
+ reservedHandles: config.reservedHandles,
29
+ allowInterimSubjects,
30
+ snapshotDebounceSeconds: 60,
31
+ };
32
+ }
33
+ /** What the `reader-snapshot` projection task reads from `PAPYRUS_READER_SNAPSHOT_SETTINGS`. */
34
+ export function readerSnapshotSettings(config) {
35
+ return {
36
+ dimensions: config.dimensions,
37
+ karma: config.karma,
38
+ ranking: config.ranking,
39
+ hypeMinimum: config.snapshot.hypeMinimum,
40
+ ...(config.hypeGap ? { hypeGap: config.hypeGap } : {}),
41
+ retirementPoll: config.retirementPoll,
42
+ };
43
+ }
44
+ export function interimSubjectsAllowedAtSynth(environment = process.env) {
45
+ return ["development", "test"].includes((environment.SITE_ENV ?? "").trim()) && environment.NODE_ENV !== "production";
46
+ }
47
+ /**
48
+ * The scheduled run polls Prospectus through the CMS route /api/reader/retired (docs/reader-steering.md), so it needs the
49
+ * site origin and the poll secret parameter that the app-shell stack generates (`cms.readerRetirementPoll`); both reach the
50
+ * backend build as branch variables. It also deletes and re-keys rows, and keeps its cursor in the rate table.
51
+ */
52
+ function wireRetirementPoll(readerLambda, contentActions, tables) {
53
+ const origin = (process.env.PAPYRUS_SITE_ORIGIN ?? "").trim();
54
+ const parameterName = (process.env[READER_POLL_SECRET_PARAMETER_ENV] ?? "").trim();
55
+ if (!origin.startsWith("https://") || !parameterName.startsWith("/")) {
56
+ throw new Error("reader-steering retirementPoll needs PAPYRUS_SITE_ORIGIN (an https origin) and PAPYRUS_READER_POLL_SECRET_PARAMETER (an SSM parameter name). The app-shell template sets both on the production branch when site.json has cms.readerRetirementPoll: true; see docs/reader-steering.md.");
57
+ }
58
+ const rateTable = readerLambda.node.scope?.node.tryFindChild("PapyrusReaderRateWindows");
59
+ if (!rateTable)
60
+ throw new Error("reader-steering retirementPoll could not find the reader-actions rate table to keep its cursor in");
61
+ tables.ReaderVote.grantReadWriteData(contentActions);
62
+ tables.ReaderHandle.grantReadWriteData(contentActions);
63
+ rateTable.grantReadWriteData(contentActions);
64
+ contentActions.addEnvironment("PAPYRUS_READER_RATE_TABLE", rateTable.tableName);
65
+ contentActions.addEnvironment("PAPYRUS_READER_POLL_URL", origin);
66
+ contentActions.addEnvironment(READER_POLL_SECRET_PARAMETER_ENV, parameterName);
67
+ const stack = Stack.of(contentActions);
68
+ contentActions.addToRolePolicy(new PolicyStatement({
69
+ effect: Effect.ALLOW,
70
+ actions: ["ssm:GetParameter"],
71
+ resources: [`arn:${stack.partition}:ssm:${stack.region}:${stack.account}:parameter${parameterName}`],
72
+ }));
73
+ }
74
+ export const readerSteeringPlugin = {
75
+ manifest: readerSteeringManifest,
76
+ resolveConfig: resolveReaderSteeringConfig,
77
+ functions: () => ({ readerActions }),
78
+ schemaDefinitions: readerSteeringSchemaDefinitions,
79
+ publicSettings: (config) => ({ contract: readerSteeringManifest.contract, dimensions: config.dimensions }),
80
+ wire(backend, config, context) {
81
+ const lambda = backend.readerActions.resources.lambda;
82
+ const tables = backend.data.resources.tables;
83
+ const contentActions = context.contentActionsLambda;
84
+ for (const [variable, model] of [
85
+ ["PAPYRUS_READER_PROFILE_TABLE", "ReaderProfile"],
86
+ ["PAPYRUS_READER_HANDLE_TABLE", "ReaderHandle"],
87
+ ["PAPYRUS_READER_VOTE_TABLE", "ReaderVote"],
88
+ ]) {
89
+ tables[model].grantReadWriteData(lambda);
90
+ lambda.addEnvironment(variable, tables[model].tableName);
91
+ contentActions.addEnvironment(variable, tables[model].tableName);
92
+ }
93
+ tables.PublishedItem.grantReadData(lambda);
94
+ lambda.addEnvironment("PAPYRUS_READER_PUBLISHED_ITEM_TABLE", tables.PublishedItem.tableName);
95
+ tables.ReaderVote.grantReadData(contentActions);
96
+ tables.ReaderProfile.grantReadWriteData(contentActions);
97
+ lambda.addEnvironment("PAPYRUS_READER_SETTINGS", JSON.stringify(readerActionsSettings(config, interimSubjectsAllowedAtSynth())));
98
+ if (config.reservedConcurrency !== undefined) {
99
+ lambda.node.defaultChild.addPropertyOverride("ReservedConcurrentExecutions", config.reservedConcurrency);
100
+ }
101
+ // Trailing-edge debounce: the first write in a window creates a one-off EventBridge Scheduler schedule at the end of
102
+ // the window (docs/reader-steering.md). The schedule invokes content-actions as this role; reader-actions may create
103
+ // schedules named for this feature, and pass exactly this role.
104
+ const schedulerRole = new Role(Stack.of(lambda), "ReaderSnapshotSchedulerRole", {
105
+ assumedBy: new ServicePrincipal("scheduler.amazonaws.com"),
106
+ description: "Lets one-off schedules created by reader-actions invoke the reader-snapshot run.",
107
+ });
108
+ contentActions.grantInvoke(schedulerRole);
109
+ const stack = Stack.of(lambda); // the role lives with the function, so the stacks keep their existing one-way dependency
110
+ lambda.addToRolePolicy(new PolicyStatement({
111
+ effect: Effect.ALLOW,
112
+ actions: ["scheduler:CreateSchedule"],
113
+ resources: [`arn:${stack.partition}:scheduler:${stack.region}:${stack.account}:schedule/default/${SNAPSHOT_SCHEDULE_PREFIX}*`],
114
+ }));
115
+ lambda.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ["iam:PassRole"], resources: [schedulerRole.roleArn] }));
116
+ lambda.addEnvironment("PAPYRUS_READER_SNAPSHOT_FUNCTION_ARN", contentActions.functionArn);
117
+ lambda.addEnvironment("PAPYRUS_READER_SCHEDULER_ROLE_ARN", schedulerRole.roleArn);
118
+ contentActions.addEnvironment("PAPYRUS_READER_SNAPSHOT_SETTINGS", JSON.stringify(readerSnapshotSettings(config)));
119
+ lambda.addPermission("InvokeFromCmsCompute", {
120
+ principal: new ArnPrincipal(config.computeRoleArn),
121
+ action: "lambda:InvokeFunction",
122
+ });
123
+ if (config.retirementPoll)
124
+ wireRetirementPoll(lambda, contentActions, tables);
125
+ if (config.snapshot.schedule) {
126
+ new Rule(context.createStack("reader-steering-schedule"), "ReaderSnapshotSchedule", {
127
+ description: "Rebuilds the reader snapshot (time decay, Rising) and, when enabled, applies Prospectus subject retirements.",
128
+ schedule: Schedule.rate(Duration.hours(config.snapshot.intervalHours)),
129
+ targets: [
130
+ new LambdaFunctionTarget(contentActions, {
131
+ event: RuleTargetInput.fromObject(config.retirementPoll ? READER_SCHEDULED_SNAPSHOT_TASK : READER_SNAPSHOT_TASK),
132
+ retryAttempts: 0,
133
+ }),
134
+ ],
135
+ });
136
+ }
137
+ backend.addOutput({ custom: { [READER_STEERING_OUTPUT_KEY]: { actionsFunction: lambda.functionName } } });
138
+ },
139
+ };
@@ -0,0 +1,162 @@
1
+ import { ArnPrincipal, Effect, PolicyStatement, Role, ServicePrincipal } from "aws-cdk-lib/aws-iam";
2
+ import { Duration, Stack } from "aws-cdk-lib";
3
+ import type { ITable } from "aws-cdk-lib/aws-dynamodb";
4
+ import { Rule, RuleTargetInput, Schedule } from "aws-cdk-lib/aws-events";
5
+ import { LambdaFunction as LambdaFunctionTarget } from "aws-cdk-lib/aws-events-targets";
6
+ import { CfnFunction, type Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
7
+ import type { PapyrusPlugin, PluginManifest, PluginWiringContext } from "../types";
8
+ import { resolveReaderSteeringConfig, type ReaderSteeringConfig } from "./config";
9
+ import { readerActions } from "./function/resource";
10
+ import { readerSteeringSchemaDefinitions } from "./schema";
11
+
12
+ export { resolveReaderSteeringConfig };
13
+ export type { ReaderSteeringConfig };
14
+
15
+ export const READER_STEERING_OUTPUT_KEY = "readerSteering";
16
+ export const SNAPSHOT_SCHEDULE_PREFIX = "papyrus-reader-snapshot-";
17
+ export const READER_SNAPSHOT_TASK = { projectionTask: { task: "reader-snapshot" } };
18
+ export const READER_SCHEDULED_SNAPSHOT_TASK = { projectionTask: { task: "reader-snapshot", retirementPoll: true } };
19
+ export const READER_POLL_SECRET_PARAMETER_ENV = "PAPYRUS_READER_POLL_SECRET_PARAMETER";
20
+
21
+ export const readerSteeringManifest: PluginManifest = {
22
+ name: "reader-steering",
23
+ contract: 1,
24
+ models: ["ReaderProfile", "ReaderHandle", "ReaderVote"],
25
+ mutations: [],
26
+ guest: { mutations: [] },
27
+ newsroomPanels: [],
28
+ staticAssets: ["_plugins/papyrus-reader@1.js", "_plugins/papyrus-reader@1.css"],
29
+ };
30
+
31
+ /** What the reader-actions function reads from `PAPYRUS_READER_SETTINGS`. */
32
+ export function readerActionsSettings(config: ReaderSteeringConfig, allowInterimSubjects: boolean) {
33
+ return {
34
+ dimensions: config.dimensions,
35
+ limits: config.limits,
36
+ reservedHandles: config.reservedHandles,
37
+ allowInterimSubjects,
38
+ snapshotDebounceSeconds: 60,
39
+ };
40
+ }
41
+
42
+ /** What the `reader-snapshot` projection task reads from `PAPYRUS_READER_SNAPSHOT_SETTINGS`. */
43
+ export function readerSnapshotSettings(config: ReaderSteeringConfig) {
44
+ return {
45
+ dimensions: config.dimensions,
46
+ karma: config.karma,
47
+ ranking: config.ranking,
48
+ hypeMinimum: config.snapshot.hypeMinimum,
49
+ ...(config.hypeGap ? { hypeGap: config.hypeGap } : {}),
50
+ retirementPoll: config.retirementPoll,
51
+ };
52
+ }
53
+
54
+ export function interimSubjectsAllowedAtSynth(environment: Record<string, string | undefined> = process.env): boolean {
55
+ return ["development", "test"].includes((environment.SITE_ENV ?? "").trim()) && environment.NODE_ENV !== "production";
56
+ }
57
+
58
+ /**
59
+ * The scheduled run polls Prospectus through the CMS route /api/reader/retired (docs/reader-steering.md), so it needs the
60
+ * site origin and the poll secret parameter that the app-shell stack generates (`cms.readerRetirementPoll`); both reach the
61
+ * backend build as branch variables. It also deletes and re-keys rows, and keeps its cursor in the rate table.
62
+ */
63
+ function wireRetirementPoll(readerLambda: LambdaFunction, contentActions: LambdaFunction, tables: Record<string, ITable>) {
64
+ const origin = (process.env.PAPYRUS_SITE_ORIGIN ?? "").trim();
65
+ const parameterName = (process.env[READER_POLL_SECRET_PARAMETER_ENV] ?? "").trim();
66
+ if (!origin.startsWith("https://") || !parameterName.startsWith("/")) {
67
+ throw new Error(
68
+ "reader-steering retirementPoll needs PAPYRUS_SITE_ORIGIN (an https origin) and PAPYRUS_READER_POLL_SECRET_PARAMETER (an SSM parameter name). The app-shell template sets both on the production branch when site.json has cms.readerRetirementPoll: true; see docs/reader-steering.md.",
69
+ );
70
+ }
71
+ const rateTable = readerLambda.node.scope?.node.tryFindChild("PapyrusReaderRateWindows") as ITable | undefined;
72
+ if (!rateTable) throw new Error("reader-steering retirementPoll could not find the reader-actions rate table to keep its cursor in");
73
+ tables.ReaderVote.grantReadWriteData(contentActions);
74
+ tables.ReaderHandle.grantReadWriteData(contentActions);
75
+ rateTable.grantReadWriteData(contentActions);
76
+ contentActions.addEnvironment("PAPYRUS_READER_RATE_TABLE", rateTable.tableName);
77
+ contentActions.addEnvironment("PAPYRUS_READER_POLL_URL", origin);
78
+ contentActions.addEnvironment(READER_POLL_SECRET_PARAMETER_ENV, parameterName);
79
+ const stack = Stack.of(contentActions);
80
+ contentActions.addToRolePolicy(
81
+ new PolicyStatement({
82
+ effect: Effect.ALLOW,
83
+ actions: ["ssm:GetParameter"],
84
+ resources: [`arn:${stack.partition}:ssm:${stack.region}:${stack.account}:parameter${parameterName}`],
85
+ }),
86
+ );
87
+ }
88
+
89
+ export const readerSteeringPlugin: PapyrusPlugin<ReaderSteeringConfig, { readerActions: typeof readerActions }> = {
90
+ manifest: readerSteeringManifest,
91
+ resolveConfig: resolveReaderSteeringConfig,
92
+ functions: () => ({ readerActions }),
93
+ schemaDefinitions: readerSteeringSchemaDefinitions,
94
+ publicSettings: (config) => ({ contract: readerSteeringManifest.contract, dimensions: config.dimensions }),
95
+ wire(backend, config, context: PluginWiringContext) {
96
+ const lambda = backend.readerActions.resources.lambda as LambdaFunction;
97
+ const tables = backend.data.resources.tables as Record<string, ITable>;
98
+ const contentActions = context.contentActionsLambda;
99
+
100
+ for (const [variable, model] of [
101
+ ["PAPYRUS_READER_PROFILE_TABLE", "ReaderProfile"],
102
+ ["PAPYRUS_READER_HANDLE_TABLE", "ReaderHandle"],
103
+ ["PAPYRUS_READER_VOTE_TABLE", "ReaderVote"],
104
+ ] as const) {
105
+ tables[model].grantReadWriteData(lambda);
106
+ lambda.addEnvironment(variable, tables[model].tableName);
107
+ contentActions.addEnvironment(variable, tables[model].tableName);
108
+ }
109
+ tables.PublishedItem.grantReadData(lambda);
110
+ lambda.addEnvironment("PAPYRUS_READER_PUBLISHED_ITEM_TABLE", tables.PublishedItem.tableName);
111
+ tables.ReaderVote.grantReadData(contentActions);
112
+ tables.ReaderProfile.grantReadWriteData(contentActions);
113
+
114
+ lambda.addEnvironment("PAPYRUS_READER_SETTINGS", JSON.stringify(readerActionsSettings(config, interimSubjectsAllowedAtSynth())));
115
+ if (config.reservedConcurrency !== undefined) {
116
+ (lambda.node.defaultChild as CfnFunction).addPropertyOverride("ReservedConcurrentExecutions", config.reservedConcurrency);
117
+ }
118
+
119
+ // Trailing-edge debounce: the first write in a window creates a one-off EventBridge Scheduler schedule at the end of
120
+ // the window (docs/reader-steering.md). The schedule invokes content-actions as this role; reader-actions may create
121
+ // schedules named for this feature, and pass exactly this role.
122
+ const schedulerRole = new Role(Stack.of(lambda), "ReaderSnapshotSchedulerRole", {
123
+ assumedBy: new ServicePrincipal("scheduler.amazonaws.com"),
124
+ description: "Lets one-off schedules created by reader-actions invoke the reader-snapshot run.",
125
+ });
126
+ contentActions.grantInvoke(schedulerRole);
127
+ const stack = Stack.of(lambda); // the role lives with the function, so the stacks keep their existing one-way dependency
128
+ lambda.addToRolePolicy(
129
+ new PolicyStatement({
130
+ effect: Effect.ALLOW,
131
+ actions: ["scheduler:CreateSchedule"],
132
+ resources: [`arn:${stack.partition}:scheduler:${stack.region}:${stack.account}:schedule/default/${SNAPSHOT_SCHEDULE_PREFIX}*`],
133
+ }),
134
+ );
135
+ lambda.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ["iam:PassRole"], resources: [schedulerRole.roleArn] }));
136
+ lambda.addEnvironment("PAPYRUS_READER_SNAPSHOT_FUNCTION_ARN", contentActions.functionArn);
137
+ lambda.addEnvironment("PAPYRUS_READER_SCHEDULER_ROLE_ARN", schedulerRole.roleArn);
138
+ contentActions.addEnvironment("PAPYRUS_READER_SNAPSHOT_SETTINGS", JSON.stringify(readerSnapshotSettings(config)));
139
+
140
+ lambda.addPermission("InvokeFromCmsCompute", {
141
+ principal: new ArnPrincipal(config.computeRoleArn),
142
+ action: "lambda:InvokeFunction",
143
+ });
144
+
145
+ if (config.retirementPoll) wireRetirementPoll(lambda, contentActions, tables);
146
+
147
+ if (config.snapshot.schedule) {
148
+ new Rule(context.createStack("reader-steering-schedule"), "ReaderSnapshotSchedule", {
149
+ description: "Rebuilds the reader snapshot (time decay, Rising) and, when enabled, applies Prospectus subject retirements.",
150
+ schedule: Schedule.rate(Duration.hours(config.snapshot.intervalHours)),
151
+ targets: [
152
+ new LambdaFunctionTarget(contentActions, {
153
+ event: RuleTargetInput.fromObject(config.retirementPoll ? READER_SCHEDULED_SNAPSHOT_TASK : READER_SNAPSHOT_TASK),
154
+ retryAttempts: 0,
155
+ }),
156
+ ],
157
+ });
158
+ }
159
+
160
+ backend.addOutput({ custom: { [READER_STEERING_OUTPUT_KEY]: { actionsFunction: lambda.functionName } } });
161
+ },
162
+ };
@@ -0,0 +1,40 @@
1
+ import { a } from "@aws-amplify/backend";
2
+ /**
3
+ * Staff and IAM only: no guest, API key or reader rule on any model. The reader-actions function writes the
4
+ * tables directly with its own role, and editors may list them; admins may delete. `id` is the lookup key:
5
+ * the siteSubject for a profile, the lowercase handle for a claim and `subjectKey#readerId#dimension` for a vote.
6
+ */
7
+ const staffOnly = (allow) => [allow.group("editor").to(["read"]), allow.group("admin").to(["read", "delete"])];
8
+ export function readerSteeringSchemaDefinitions() {
9
+ return {
10
+ ReaderProfile: a
11
+ .model({
12
+ id: a.id().required(),
13
+ siteSubject: a.string().required(),
14
+ readerId: a.string().required(),
15
+ handle: a.string(),
16
+ state: a.string().required(),
17
+ karma: a.integer(),
18
+ })
19
+ .disableOperations(["subscriptions"])
20
+ .authorization(staffOnly),
21
+ ReaderHandle: a
22
+ .model({
23
+ id: a.id().required(),
24
+ readerId: a.string().required(),
25
+ })
26
+ .disableOperations(["subscriptions"])
27
+ .authorization(staffOnly),
28
+ ReaderVote: a
29
+ .model({
30
+ id: a.id().required(),
31
+ subjectKey: a.string().required(),
32
+ readerId: a.string().required(),
33
+ dimension: a.string().required(),
34
+ value: a.integer().required(),
35
+ voterRole: a.string().required(),
36
+ })
37
+ .disableOperations(["subscriptions"])
38
+ .authorization(staffOnly),
39
+ };
40
+ }
@@ -0,0 +1,42 @@
1
+ import { a } from "@aws-amplify/backend";
2
+
3
+ /**
4
+ * Staff and IAM only: no guest, API key or reader rule on any model. The reader-actions function writes the
5
+ * tables directly with its own role, and editors may list them; admins may delete. `id` is the lookup key:
6
+ * the siteSubject for a profile, the lowercase handle for a claim and `subjectKey#readerId#dimension` for a vote.
7
+ */
8
+ const staffOnly = (allow: any) => [allow.group("editor").to(["read"]), allow.group("admin").to(["read", "delete"])];
9
+
10
+ export function readerSteeringSchemaDefinitions() {
11
+ return {
12
+ ReaderProfile: a
13
+ .model({
14
+ id: a.id().required(),
15
+ siteSubject: a.string().required(),
16
+ readerId: a.string().required(),
17
+ handle: a.string(),
18
+ state: a.string().required(),
19
+ karma: a.integer(),
20
+ })
21
+ .disableOperations(["subscriptions"])
22
+ .authorization(staffOnly),
23
+ ReaderHandle: a
24
+ .model({
25
+ id: a.id().required(),
26
+ readerId: a.string().required(),
27
+ })
28
+ .disableOperations(["subscriptions"])
29
+ .authorization(staffOnly),
30
+ ReaderVote: a
31
+ .model({
32
+ id: a.id().required(),
33
+ subjectKey: a.string().required(),
34
+ readerId: a.string().required(),
35
+ dimension: a.string().required(),
36
+ value: a.integer().required(),
37
+ voterRole: a.string().required(),
38
+ })
39
+ .disableOperations(["subscriptions"])
40
+ .authorization(staffOnly),
41
+ };
42
+ }
@@ -1,6 +1,8 @@
1
+ import { readerSteeringPlugin } from "./reader-steering/papyrus.plugin.js";
1
2
  import { signupPlugin } from "./signup/papyrus.plugin.js";
2
3
  /** Plugins are packaged with Papyrus and pinned by its version: there is no registry to fetch from. */
3
4
  export const KNOWN_PLUGINS = {
5
+ "reader-steering": readerSteeringPlugin,
4
6
  signup: signupPlugin,
5
7
  };
6
8
  export function resolvePlugins(requests) {
@@ -1,8 +1,10 @@
1
1
  import type { PapyrusPlugin, PluginRequest } from "./types";
2
+ import { readerSteeringPlugin } from "./reader-steering/papyrus.plugin";
2
3
  import { signupPlugin } from "./signup/papyrus.plugin";
3
4
 
4
5
  /** Plugins are packaged with Papyrus and pinned by its version: there is no registry to fetch from. */
5
6
  export const KNOWN_PLUGINS: Record<string, PapyrusPlugin<any, any>> = {
7
+ "reader-steering": readerSteeringPlugin,
6
8
  signup: signupPlugin,
7
9
  };
8
10
 
@@ -1,3 +1,4 @@
1
+ import type { Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
1
2
  import type { Construct } from "constructs";
2
3
 
3
4
  /** How a site asks for a plugin in `papyrus.config.ts`: `plugins: ["signup"]` or `plugins: [{ name: "signup", forms: ["news"] }]`. */
@@ -22,6 +23,8 @@ export type PluginWiringContext = {
22
23
  createStack: (name: string) => Construct;
23
24
  graphqlApiId: string;
24
25
  graphqlEndpoint: string;
26
+ /** The site's `content-actions` function: it runs the projection tasks a plugin may add (for example `reader-snapshot`). */
27
+ contentActionsLambda: LambdaFunction;
25
28
  };
26
29
 
27
30
  export type PapyrusPlugin<Config, Functions = unknown> = {
@@ -12,6 +12,7 @@ export function wirePlugins(backend, plugins, contentActionsLambda) {
12
12
  createStack: (name) => backend.createStack(name),
13
13
  graphqlApiId: graphqlApi.apiId,
14
14
  graphqlEndpoint: backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl,
15
+ contentActionsLambda,
15
16
  };
16
17
  for (const { plugin, config } of plugins)
17
18
  plugin.wire(backend, config, context);
@@ -15,6 +15,7 @@ export function wirePlugins(backend: any, plugins: ResolvedPlugin[], contentActi
15
15
  createStack: (name: string) => backend.createStack(name),
16
16
  graphqlApiId: graphqlApi.apiId as string,
17
17
  graphqlEndpoint: backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string,
18
+ contentActionsLambda,
18
19
  };
19
20
  for (const { plugin, config } of plugins) plugin.wire(backend, config, context);
20
21
  contentActionsLambda.addEnvironment(PLUGINS_ENVIRONMENT_VARIABLE, plugins.map(({ plugin }) => plugin.manifest.name).join(","));
@@ -0,0 +1,9 @@
1
+ import type { NextRequest } from "next/server";
2
+ import { handleReaderRequest } from "../../../../lib/reader-api";
3
+
4
+ export const dynamic = "force-dynamic";
5
+ export const runtime = "nodejs";
6
+
7
+ export function POST(request: NextRequest) {
8
+ return handleReaderRequest(request, "handle");
9
+ }
@@ -0,0 +1,9 @@
1
+ import type { NextRequest } from "next/server";
2
+ import { handleReaderRequest } from "../../../../lib/reader-api";
3
+
4
+ export const dynamic = "force-dynamic";
5
+ export const runtime = "nodejs";
6
+
7
+ export function GET(request: NextRequest) {
8
+ return handleReaderRequest(request, "me");
9
+ }
@@ -0,0 +1,9 @@
1
+ import type { NextRequest } from "next/server";
2
+ import { handleReaderRequest } from "../../../../lib/reader-api";
3
+
4
+ export const dynamic = "force-dynamic";
5
+ export const runtime = "nodejs";
6
+
7
+ export function POST(request: NextRequest) {
8
+ return handleReaderRequest(request, "rating");
9
+ }
@@ -0,0 +1,9 @@
1
+ import type { NextRequest } from "next/server";
2
+ import { handleReaderRetiredSubjects } from "../../../../lib/reader-retirement-route";
3
+
4
+ export const dynamic = "force-dynamic";
5
+ export const runtime = "nodejs";
6
+
7
+ export function GET(request: NextRequest) {
8
+ return handleReaderRetiredSubjects(request);
9
+ }
@@ -0,0 +1,9 @@
1
+ import type { NextRequest } from "next/server";
2
+ import { handleReaderRequest } from "../../../../lib/reader-api";
3
+
4
+ export const dynamic = "force-dynamic";
5
+ export const runtime = "nodejs";
6
+
7
+ export function POST(request: NextRequest) {
8
+ return handleReaderRequest(request, "vote");
9
+ }
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
 
3
- import { useState } from "react";
3
+ import { useId, useRef, useState, type KeyboardEvent } from "react";
4
4
  import { primingStateText, type PrimingRequestView } from "../lib/relevance-status";
5
5
 
6
6
  export type PrimingFormInput = { url: string; label: string; explanation: string };
@@ -23,6 +23,19 @@ export function ReferenceCyclotronPriming({
23
23
  const [explanation, setExplanation] = useState("");
24
24
  const [message, setMessage] = useState<string | null>(null);
25
25
 
26
+ const ratingLabelId = useId();
27
+ const buttons = useRef<Array<HTMLButtonElement | null>>([]);
28
+
29
+ function moveSelection(event: KeyboardEvent<HTMLButtonElement>, index: number) {
30
+ const forward = event.key === "ArrowRight" || event.key === "ArrowDown";
31
+ const backward = event.key === "ArrowLeft" || event.key === "ArrowUp";
32
+ if (!forward && !backward) return;
33
+ event.preventDefault();
34
+ const next = (index + (forward ? 1 : -1) + labels.length) % labels.length;
35
+ setLabel(labels[next]);
36
+ buttons.current[next]?.focus();
37
+ }
38
+
26
39
  async function submit() {
27
40
  setMessage("Adding…");
28
41
  try {
@@ -38,13 +51,13 @@ export function ReferenceCyclotronPriming({
38
51
  return (
39
52
  <div className="space-y-2 text-sm" data-reference-cyclotron-priming>
40
53
  <form
41
- className="flex flex-wrap items-end gap-3"
54
+ className="flex flex-col gap-3"
42
55
  onSubmit={(event) => {
43
56
  event.preventDefault();
44
57
  void submit();
45
58
  }}
46
59
  >
47
- <label className="flex min-w-64 flex-1 flex-col gap-1">
60
+ <label className="flex flex-col gap-1">
48
61
  <span className="text-xs text-muted-foreground">Web page address</span>
49
62
  <input
50
63
  aria-label="Reference URL"
@@ -55,20 +68,46 @@ export function ReferenceCyclotronPriming({
55
68
  value={url}
56
69
  />
57
70
  </label>
71
+ <div className="flex flex-col gap-1">
72
+ <span className="text-xs text-muted-foreground" id={ratingLabelId}>Should Papyrus include or exclude pages like this?</span>
73
+ <div aria-labelledby={ratingLabelId} className="flex flex-wrap gap-2" role="radiogroup">
74
+ {labels.map((choice, index) => {
75
+ const checked = choice === label;
76
+ return (
77
+ <button
78
+ aria-checked={checked}
79
+ className={`min-w-32 flex-1 rounded border px-4 py-3 text-base font-semibold capitalize ${checked ? "border-foreground bg-foreground text-background" : "border-border bg-transparent"}`}
80
+ data-rating-choice={choice}
81
+ key={choice}
82
+ onClick={() => setLabel(choice)}
83
+ onKeyDown={(event) => moveSelection(event, index)}
84
+ ref={(node) => { buttons.current[index] = node; }}
85
+ role="radio"
86
+ tabIndex={checked || (!labels.includes(label) && index === 0) ? 0 : -1}
87
+ type="button"
88
+ >
89
+ {choice}
90
+ </button>
91
+ );
92
+ })}
93
+ </div>
94
+ </div>
58
95
  <label className="flex flex-col gap-1">
59
- <span className="text-xs text-muted-foreground">Include or exclude</span>
60
- <select aria-label="Include or exclude" onChange={(event) => setLabel(event.target.value)} value={label}>
61
- {labels.map((choice) => (
62
- <option key={choice} value={choice}>{choice}</option>
63
- ))}
64
- </select>
65
- </label>
66
- <label className="flex min-w-48 flex-1 flex-col gap-1">
67
- <span className="text-xs text-muted-foreground">Why (optional)</span>
68
- <input aria-label="Reason" onChange={(event) => setExplanation(event.target.value)} type="text" value={explanation} />
96
+ <span className="text-sm font-medium">Why?</span>
97
+ <textarea
98
+ aria-label="Reason"
99
+ className="w-full"
100
+ onChange={(event) => setExplanation(event.target.value)}
101
+ placeholder="Why? A sentence or two helps Papyrus learn what you want."
102
+ rows={4}
103
+ value={explanation}
104
+ />
105
+ <span className="text-xs text-muted-foreground">Optional, but a short reason helps Papyrus learn what you want.</span>
69
106
  </label>
70
- <button className="cyclotron-review-secondary" type="submit">Add reference</button>
71
- {message ? <p className="basis-full text-xs" role="status">{message}</p> : null}
107
+ <div>
108
+ <button className="cyclotron-review-secondary" type="submit">Add reference</button>
109
+ </div>
110
+ {message ? <p className="text-xs" role="status">{message}</p> : null}
72
111
  </form>
73
112
  {requests.length ? (
74
113
  <ul aria-label="Added references" className="space-y-1 text-xs text-muted-foreground">
@@ -4,7 +4,7 @@ import * as amplify from "aws-cdk-lib/aws-amplify";
4
4
  import { SecureStringParameter } from "./secure-string-parameter.js";
5
5
  import { GITHUB_OIDC_PROVIDER_HOST } from "./github-oidc-provider.js";
6
6
  import { cmsProductionBuildSpec, cmsStagingBuildSpec, readerBuildSpec } from "./build-specs.js";
7
- import { PROSPECTUS_PAPYRUS_SITE_ROUTES, hasCmsApp, isStagingEnabled, resolveRedirectSubDomainPrefix, resolveCmsHostName, resolveSiteOrigin, githubOidcSubjects, resolveGithubRepository, resolveProspectusAccountsEndpoint, resolveProspectusSessionSealingParameterName, resolveRevalidateSecretParameterName, resolveStackName, resolveStagingDomainName, resolveStoragePreviewPrefix } from "./site-config.js";
7
+ import { PROSPECTUS_PAPYRUS_SITE_ROUTES, hasCmsApp, isStagingEnabled, resolveRedirectSubDomainPrefix, resolveCmsHostName, resolveSiteOrigin, githubOidcSubjects, resolveGithubRepository, resolveProspectusAccountsEndpoint, resolveProspectusSessionSealingParameterName, resolveReaderPollSecretParameterName, resolveRevalidateSecretParameterName, resolveStackName, resolveStagingDomainName, resolveStoragePreviewPrefix } from "./site-config.js";
8
8
  function environmentVariables(variables) {
9
9
  return Object.entries(variables).map(([name, value]) => ({ name, value }));
10
10
  }
@@ -123,6 +123,20 @@ export class AmplifyAppShellStack extends Stack {
123
123
  resources: [prospectusSessionSealing.parameterArn],
124
124
  }));
125
125
  }
126
+ if (prospectusAccountsApiStageArn && config.cms.readerRetirementPoll) {
127
+ // Prospectus admits one caller per site, this compute role, so the scheduled snapshot run reaches the retired-subject
128
+ // route through the CMS route /api/reader/retired, which it authenticates with this secret.
129
+ const readerPollSecret = new SecureStringParameter(this, "ReaderPollSecretParameter", {
130
+ parameterName: resolveReaderPollSecretParameterName(config),
131
+ description: `Authorizes the scheduled reader snapshot run to call the retired-subject route of ${cmsAppName}`,
132
+ });
133
+ prospectusEnvironment.PAPYRUS_READER_POLL_SECRET_PARAMETER = readerPollSecret.parameterName;
134
+ computeRole.addToPolicy(new iam.PolicyStatement({
135
+ sid: "ReadReaderPollSecret",
136
+ actions: ["ssm:GetParameter"],
137
+ resources: [readerPollSecret.parameterArn],
138
+ }));
139
+ }
126
140
  if (prospectusAccountsApiStageArn) {
127
141
  computeRole.addToPolicy(new iam.PolicyStatement({
128
142
  sid: "InvokeProspectusAccountsAsRegisteredSite",