@jskit-ai/rewarded-core 0.2.8 → 0.2.10

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/rewarded-core",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -125,17 +125,17 @@
125
125
  }
126
126
  },
127
127
  "dependencies": {
128
- "@jskit-ai/crud-core": "0.2.7",
129
- "@jskit-ai/database-runtime": "0.1.256",
130
- "@jskit-ai/json-rest-api-core": "0.2.7",
131
- "@jskit-ai/resource-crud-core": "0.1.198",
132
- "@jskit-ai/users-core": "0.2.8",
133
- "@jskit-ai/workspaces-core": "0.2.8",
128
+ "@jskit-ai/crud-core": "0.2.9",
129
+ "@jskit-ai/database-runtime": "0.1.257",
130
+ "@jskit-ai/json-rest-api-core": "0.2.9",
131
+ "@jskit-ai/resource-crud-core": "0.1.199",
132
+ "@jskit-ai/users-core": "0.2.10",
133
+ "@jskit-ai/workspaces-core": "0.2.10",
134
134
  "json-rest-schema": "^1.0.17"
135
135
  },
136
136
  "peerDependencies": {
137
- "@jskit-ai/auth-core": "0.2.7",
138
- "@jskit-ai/http-runtime": "0.2.7",
139
- "@jskit-ai/kernel": "0.2.7"
137
+ "@jskit-ai/auth-core": "0.2.8",
138
+ "@jskit-ai/http-runtime": "0.2.8",
139
+ "@jskit-ai/kernel": "0.2.8"
140
140
  }
141
141
  }
@@ -1,9 +1,11 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
2
  import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
- import { simplifyJsonApiDocument } from "@jskit-ai/http-runtime/shared";
3
+ import { jsonApiNextCursor, simplifyJsonApiDocument } from "@jskit-ai/http-runtime/shared";
4
4
  import { resolveActionUser } from "@jskit-ai/users-core/server/resolveActionUser";
5
5
 
6
6
  const REWARDED_SURFACE = "app";
7
+ // json-rest-api's largest page.
8
+ const RECEIPT_PAGE_SIZE = 100;
7
9
 
8
10
  function normalizeRecordList(document) {
9
11
  const simplified = simplifyJsonApiDocument(document);
@@ -206,6 +208,28 @@ function createService({
206
208
  }, repositoryOptions);
207
209
  }
208
210
 
211
+ /**
212
+ * How many of the gate's receipts were granted since `since`, read a page at
213
+ * a time until no page follows or the count reaches the daily limit, so the
214
+ * count is exact for any daily limit.
215
+ * @param {RewardedRepositoryOptions} repositoryOptions
216
+ */
217
+ async function countReceiptsGrantedSince(gateKey, since, dailyLimit, repositoryOptions) {
218
+ let count = 0;
219
+ let cursor = null;
220
+ do {
221
+ const document = await rewardedUnlockReceiptsRepository.queryDocuments({
222
+ gateKey,
223
+ grantedSince: since.toISOString(),
224
+ limit: RECEIPT_PAGE_SIZE,
225
+ ...(cursor ? { cursor } : {})
226
+ }, repositoryOptions);
227
+ count += normalizeRecordList(document).length;
228
+ cursor = jsonApiNextCursor(document);
229
+ } while (cursor && count < dailyLimit);
230
+ return count;
231
+ }
232
+
209
233
  async function evaluateGate(input, context) {
210
234
  requireActor(context, input);
211
235
  const workspaceSlug = requireWorkspaceSlug(input);
@@ -296,11 +320,7 @@ function createService({
296
320
  }
297
321
 
298
322
  if (rule.dailyLimit != null) {
299
- const dayStart = startOfUtcDay(now);
300
- const todaysCount = receipts.filter((entry) => {
301
- const grantedAt = parseDate(entry?.grantedAt);
302
- return grantedAt && grantedAt.getTime() >= dayStart.getTime();
303
- }).length;
323
+ const todaysCount = await countReceiptsGrantedSince(gateKey, startOfUtcDay(now), rule.dailyLimit, { context });
304
324
  const remaining = Math.max(0, Number(rule.dailyLimit) - todaysCount);
305
325
  if (remaining < 1) {
306
326
  return {
@@ -91,6 +91,8 @@ const resource = defineCrudResource({
91
91
  searchSchema: {
92
92
  id: { type: "id", actualField: "id" },
93
93
  q: { type: "string", oneOf: ["gateKey"], filterOperator: "like", splitBy: " ", matchAll: true },
94
+ // Server-only: the rewarded service counts the receipts granted since a day began.
95
+ grantedSince: { type: "dateTime", actualField: "grantedAt", filterOperator: ">=" },
94
96
  },
95
97
  defaultSort: ["-createdAt"],
96
98
  autofilter: "workspace_user",
@@ -240,4 +240,29 @@ test(`rewarded grants use real resources and atomic transactions (${databaseUrl
240
240
  assert.equal(retry.session.status, "rewarded");
241
241
  assert.equal((await knex("rewarded_unlock_receipts").where({ watch_session_id: session.data.id }).select()).length, 1);
242
242
  });
243
+
244
+ await t.test("a daily limit above one page of receipts is counted exactly and reached", async () => {
245
+ await repositories.rewardedRules.createDocument({
246
+ gateKey: "daily", surface: "app", enabled: true,
247
+ unlockMinutes: 30, cooldownMinutes: 0, dailyLimit: 120,
248
+ title: "Daily", description: "Daily limit test"
249
+ }, { context });
250
+ const dayStart = new Date(new Date().setUTCHours(0, 0, 0, 0));
251
+ // Expired receipts: today's count against the limit, yesterday's and another user's do not.
252
+ const grantReceipt = (grantedAt, receiptContext = context) => repositories.rewardedUnlockReceipts.createDocument({
253
+ gateKey: "daily", grantedAt: grantedAt.toISOString(), unlockedUntil: dayStart.toISOString()
254
+ }, { context: receiptContext });
255
+ for (let index = 0; index < 119; index += 1) await grantReceipt(dayStart);
256
+ for (let index = 0; index < 5; index += 1) await grantReceipt(new Date(dayStart.getTime() - 3600000));
257
+ for (let index = 0; index < 5; index += 1) await grantReceipt(dayStart, actorContext("1", "8"));
258
+ const dailyGate = { workspaceSlug: "alpha", gateKey: "daily" };
259
+
260
+ const open = await service.getCurrentState(dailyGate, { context });
261
+ assert.equal(open.reason, "reward-required");
262
+ assert.equal(open.dailyLimitRemaining, 1);
263
+ await grantReceipt(dayStart);
264
+ const reached = await service.getCurrentState(dailyGate, { context });
265
+ assert.equal(reached.reason, "daily-limit-reached");
266
+ assert.equal(reached.dailyLimitRemaining, 0);
267
+ });
243
268
  });