@atproto/ozone 0.15.2 → 0.16.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 (87) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +2 -2
  3. package/dist/api/inbox/ackPushNotifications.d.ts.map +1 -1
  4. package/dist/api/inbox/ackPushNotifications.js +6 -3
  5. package/dist/api/inbox/ackPushNotifications.js.map +1 -1
  6. package/dist/api/inbox/appealActionedSubject.d.ts.map +1 -1
  7. package/dist/api/inbox/appealActionedSubject.js +25 -10
  8. package/dist/api/inbox/appealActionedSubject.js.map +1 -1
  9. package/dist/api/inbox/claimPushNotifications.d.ts.map +1 -1
  10. package/dist/api/inbox/claimPushNotifications.js +6 -3
  11. package/dist/api/inbox/claimPushNotifications.js.map +1 -1
  12. package/dist/api/inbox/getPushPreference.d.ts.map +1 -1
  13. package/dist/api/inbox/getPushPreference.js +6 -3
  14. package/dist/api/inbox/getPushPreference.js.map +1 -1
  15. package/dist/api/inbox/getReport.d.ts.map +1 -1
  16. package/dist/api/inbox/getReport.js +16 -6
  17. package/dist/api/inbox/getReport.js.map +1 -1
  18. package/dist/auth-verifier.d.ts +0 -7
  19. package/dist/auth-verifier.d.ts.map +1 -1
  20. package/dist/auth-verifier.js +0 -12
  21. package/dist/auth-verifier.js.map +1 -1
  22. package/dist/config/env.d.ts +0 -1
  23. package/dist/config/env.d.ts.map +1 -1
  24. package/dist/config/env.js +0 -1
  25. package/dist/config/env.js.map +1 -1
  26. package/dist/config/secrets.d.ts +0 -1
  27. package/dist/config/secrets.d.ts.map +1 -1
  28. package/dist/config/secrets.js +0 -1
  29. package/dist/config/secrets.js.map +1 -1
  30. package/dist/context.d.ts.map +1 -1
  31. package/dist/context.js +0 -1
  32. package/dist/context.js.map +1 -1
  33. package/dist/daemon/context.d.ts.map +1 -1
  34. package/dist/daemon/context.js +1 -3
  35. package/dist/daemon/context.js.map +1 -1
  36. package/dist/daemon/queue-router.d.ts.map +1 -1
  37. package/dist/daemon/queue-router.js +12 -11
  38. package/dist/daemon/queue-router.js.map +1 -1
  39. package/dist/db/migrations/20261117T214830339Z-index-unrouted-reports.d.ts +4 -0
  40. package/dist/db/migrations/20261117T214830339Z-index-unrouted-reports.d.ts.map +1 -0
  41. package/dist/db/migrations/20261117T214830339Z-index-unrouted-reports.js +9 -0
  42. package/dist/db/migrations/20261117T214830339Z-index-unrouted-reports.js.map +1 -0
  43. package/dist/db/migrations/index.d.ts +1 -0
  44. package/dist/db/migrations/index.d.ts.map +1 -1
  45. package/dist/db/migrations/index.js +1 -0
  46. package/dist/db/migrations/index.js.map +1 -1
  47. package/dist/inbox/appeal.d.ts +2 -3
  48. package/dist/inbox/appeal.d.ts.map +1 -1
  49. package/dist/inbox/appeal.js +6 -8
  50. package/dist/inbox/appeal.js.map +1 -1
  51. package/dist/inbox/appealable-events.d.ts +10 -0
  52. package/dist/inbox/appealable-events.d.ts.map +1 -0
  53. package/dist/inbox/appealable-events.js +101 -0
  54. package/dist/inbox/appealable-events.js.map +1 -0
  55. package/dist/inbox/report-subject-status.d.ts +12 -0
  56. package/dist/inbox/report-subject-status.d.ts.map +1 -0
  57. package/dist/inbox/report-subject-status.js +50 -0
  58. package/dist/inbox/report-subject-status.js.map +1 -0
  59. package/dist/inbox/subject-batch.d.ts.map +1 -1
  60. package/dist/inbox/subject-batch.js +9 -22
  61. package/dist/inbox/subject-batch.js.map +1 -1
  62. package/dist/inbox/views.d.ts +26 -2
  63. package/dist/inbox/views.d.ts.map +1 -1
  64. package/dist/inbox/views.js +46 -34
  65. package/dist/inbox/views.js.map +1 -1
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +0 -2
  68. package/dist/index.js.map +1 -1
  69. package/dist/lexicons/tools/ozone/inbox/getReport.defs.d.ts +36 -0
  70. package/dist/lexicons/tools/ozone/inbox/getReport.defs.d.ts.map +1 -1
  71. package/dist/lexicons/tools/ozone/inbox/getReport.defs.js +5 -1
  72. package/dist/lexicons/tools/ozone/inbox/getReport.defs.js.map +1 -1
  73. package/dist/mod-service/index.d.ts.map +1 -1
  74. package/dist/mod-service/index.js +7 -0
  75. package/dist/mod-service/index.js.map +1 -1
  76. package/dist/mod-service/status.d.ts.map +1 -1
  77. package/dist/mod-service/status.js +3 -1
  78. package/dist/mod-service/status.js.map +1 -1
  79. package/dist/queue/service.d.ts +18 -26
  80. package/dist/queue/service.d.ts.map +1 -1
  81. package/dist/queue/service.js +190 -276
  82. package/dist/queue/service.js.map +1 -1
  83. package/dist/report/create.d.ts +8 -0
  84. package/dist/report/create.d.ts.map +1 -0
  85. package/dist/report/create.js +32 -0
  86. package/dist/report/create.js.map +1 -0
  87. package/package.json +17 -17
@@ -1,73 +1,34 @@
1
1
  import { sql } from 'kysely';
2
2
  import { currentDatetimeString, isDidString } from '@atproto/lex-schema';
3
- import { AtUri } from '@atproto/syntax';
4
3
  import { InvalidRequestError } from '@atproto/xrpc-server';
5
4
  import { TimeIdKeyset, paginate } from '../db/pagination.js';
6
5
  import { jsonb } from '../db/types.js';
7
- import { com, tools } from '../lexicons/index.js';
6
+ import { tools } from '../lexicons/index.js';
7
+ import { reportRowFromEvent } from '../report/create.js';
8
8
  import { handleReportUpdate } from '../report/handle-report-update.js';
9
9
  import { ReportStatsService } from '../report/stats.js';
10
10
  import { viewQueueStats } from '../report/views.js';
11
11
  import { PolicyListSettingKey } from '../setting/constants.js';
12
12
  import { resolveReportPriorities } from '../setting/report.js';
13
13
  import { SettingService } from '../setting/service.js';
14
- function subjectTypeFromEvent(event) {
15
- if (event.subjectMessageId)
16
- return 'message';
17
- if (event.subjectConvoId)
18
- return 'conversation';
19
- if (event.subjectUri)
20
- return 'record';
21
- return 'account';
22
- }
23
- function reportRowFromEvent({ event, reportType, assignment, priority, createdAt, actionEventIds = null, }) {
24
- let recordPath = '';
25
- if (event.subjectUri) {
26
- const uri = new AtUri(event.subjectUri);
27
- recordPath = `${uri.collection}/${uri.rkey}`;
28
- }
29
- return {
30
- eventId: event.id,
31
- reporterDid: event.createdBy,
32
- queueId: assignment.queueId,
33
- queuedAt: assignment.queuedAt,
34
- actionEventIds: actionEventIds === null ? null : jsonb(actionEventIds),
35
- actionNote: null,
36
- isMuted: !!event.meta?.isReporterMuted || !!event.meta?.isSubjectMuted,
37
- isAutomated: parseModTool(event.modTool).isAutomated,
38
- status: assignment.status,
39
- reportType,
40
- priorityLevel: priority?.level ?? null,
41
- priorityScore: priority?.score ?? null,
42
- priorityTargetMinutes: priority?.targetResolutionMinutes ?? null,
43
- did: event.subjectDid,
44
- recordPath,
45
- subjectMessageId: event.subjectMessageId,
46
- subjectConvoId: event.subjectConvoId,
47
- createdAt,
48
- updatedAt: createdAt,
49
- };
50
- }
51
14
  /**
52
15
  * Find queue to route a report to.
53
16
  */
54
- function resolveAssignment(subjectType, collection, reportType, queues, now, explicitQueueId, reporterTags, accountTags) {
17
+ function resolveAssignment(subjectType, collection, reportType, queues, explicitQueueId, reporterTags, accountTags) {
55
18
  if (explicitQueueId !== undefined) {
56
19
  const target = queues.find((q) => q.id === explicitQueueId);
57
20
  if (target)
58
- return { queueId: target.id, queuedAt: now, status: 'queued' };
59
- return { queueId: -1, queuedAt: null, status: 'open' };
21
+ return { queueId: target.id };
22
+ return { queueId: -1 };
60
23
  }
61
24
  const matched = findMatchingQueue(queues, subjectType, collection, reportType, reporterTags, accountTags);
62
25
  if (matched) {
63
26
  return {
64
27
  queueId: matched.id,
65
- queuedAt: now,
66
- status: 'queued',
67
28
  routingNote: getQueueRoutingNote(matched, reporterTags, accountTags),
68
29
  };
69
30
  }
70
- return { queueId: -1, queuedAt: null, status: 'open' };
31
+ return { queueId: -1 };
71
32
  }
72
33
  /**
73
34
  * Parse routing info from modTool
@@ -88,31 +49,29 @@ export class QueueService {
88
49
  static creator(serviceDid) {
89
50
  return (db) => new QueueService(db, serviceDid);
90
51
  }
91
- /** Insert an immediately routed report in the caller's transaction. */
92
- async insertReportFromEvent({ event, reportType, queueId, queuedAt, actionEventIds, routingNote, }) {
52
+ /** Set the initial queue and action links in an appeal creation transaction. */
53
+ async assignReportFromEvent({ event, reportType, queueId, queuedAt, actionEventIds, routingNote, }) {
93
54
  this.db.assertTransaction();
94
55
  const priorities = await resolveReportPriorities(this.db, [reportType]);
95
- const assignment = {
56
+ const priority = priorities.get(reportType);
57
+ const report = await this.db.db
58
+ .updateTable('report')
59
+ .set({
96
60
  queueId,
97
61
  queuedAt,
98
62
  status: queueId > 0 ? 'queued' : 'open',
99
- };
100
- const inserted = await this.db.db
101
- .insertInto('report')
102
- .values(reportRowFromEvent({
103
- event,
104
- reportType,
105
- assignment,
106
- priority: priorities.get(reportType),
107
- createdAt: event.createdAt,
108
- actionEventIds,
109
- }))
63
+ actionEventIds: actionEventIds == null ? null : jsonb(actionEventIds),
64
+ priorityLevel: priority?.level ?? null,
65
+ priorityScore: priority?.score ?? null,
66
+ priorityTargetMinutes: priority?.targetResolutionMinutes ?? null,
67
+ })
68
+ .where('eventId', '=', event.id)
110
69
  .returning('id')
111
70
  .executeTakeFirstOrThrow();
112
71
  if (routingNote) {
113
- await this.insertRoutingNotes([{ reportId: inserted.id, internalNote: routingNote }], event.createdAt);
72
+ await this.insertRoutingNotes([{ reportId: report.id, internalNote: routingNote }], event.createdAt);
114
73
  }
115
- return inserted.id;
74
+ return report.id;
116
75
  }
117
76
  /**
118
77
  * Insert internal routing notes for reports.
@@ -377,190 +336,187 @@ export class QueueService {
377
336
  .execute();
378
337
  return new Map(accounts.map((account) => [account.did, account.tags ?? []]));
379
338
  }
339
+ /** Re-route active, unassigned reports in an explicit ID range. */
340
+ async assignReportBatch(params, opts) {
341
+ return this.db.transaction((txn) => new QueueService(txn, this.serviceDid).assignReports(params, opts));
342
+ }
343
+ /** Route pending reports, including reports closed before initial routing. */
344
+ async assignUnroutedReports(limit) {
345
+ return this.assignReports({ limit }, { includeClosed: true });
346
+ }
380
347
  /**
381
- * Re-route unassigned reports and refresh their priority from current settings.
382
- * Used by the manual `tools.ozone.queue.routeReports` endpoint to pick up
383
- * reports after queues are created or modified. New reports are inserted
384
- * by the daemon via `insertReportsFromEvents`, not here.
348
+ * Assign reports to queues based on routing rules and priorities.
385
349
  */
386
- async assignReportBatch(params, opts) {
387
- return this.db.transaction(async (dbTxn) => {
388
- const queueService = new QueueService(dbTxn, this.serviceDid);
389
- const { queues } = await queueService.list({ limit: 1000, enabled: true });
390
- let query = dbTxn.db
391
- .selectFrom('report as r')
392
- .innerJoin('moderation_event as me', 'me.id', 'r.eventId')
393
- .select([
394
- 'r.id',
395
- 'r.status',
396
- 'r.reportType',
397
- 'r.did',
398
- 'r.reporterDid',
399
- 'r.recordPath',
400
- 'r.subjectMessageId',
401
- 'r.subjectConvoId',
402
- 'me.modTool',
403
- 'me.createdBy as eventReporterDid',
404
- ])
405
- .where('r.status', '!=', 'closed')
406
- .where('r.id', '>=', params.start)
407
- .where('r.id', '<=', params.end)
408
- .orderBy('r.id', 'asc')
409
- .limit(params.limit)
410
- .forUpdate('r');
411
- if (opts?.includeUnmatched) {
412
- query = query.where((eb) => eb.or([eb('r.queueId', 'is', null), eb('r.queueId', '=', -1)]));
350
+ async assignReports(params, opts) {
351
+ this.db.assertTransaction();
352
+ const { queues } = await this.list({ limit: 1000, enabled: true });
353
+ let query = this.db.db
354
+ .selectFrom('report as r')
355
+ .innerJoin('moderation_event as me', 'me.id', 'r.eventId')
356
+ .select([
357
+ 'r.id',
358
+ 'r.status',
359
+ 'r.reportType',
360
+ 'r.did',
361
+ 'r.reporterDid',
362
+ 'r.recordPath',
363
+ 'r.subjectMessageId',
364
+ 'r.subjectConvoId',
365
+ 'me.modTool',
366
+ 'me.createdBy as eventReporterDid',
367
+ ])
368
+ .orderBy('r.id', 'asc')
369
+ .limit(params.limit)
370
+ .forUpdate('r');
371
+ if (opts?.includeClosed !== true) {
372
+ query = query.where('r.status', '!=', 'closed');
373
+ }
374
+ if (params.start !== undefined)
375
+ query = query.where('r.id', '>=', params.start);
376
+ if (params.end !== undefined)
377
+ query = query.where('r.id', '<=', params.end);
378
+ if (opts?.includeUnmatched) {
379
+ query = query.where((eb) => eb.or([eb('r.queueId', 'is', null), eb('r.queueId', '=', -1)]));
380
+ }
381
+ else {
382
+ query = query.where('r.queueId', 'is', null);
383
+ }
384
+ const reports = await query.execute();
385
+ if (!reports.length) {
386
+ return { processed: 0, assigned: 0, unmatched: 0, maxId: 0 };
387
+ }
388
+ const accountTags = await this.loadAccountTags(queues, reports.flatMap((report) => [
389
+ report.did,
390
+ report.reporterDid ?? report.eventReporterDid,
391
+ ]));
392
+ const priorities = await resolveReportPriorities(this.db, reports.map((report) => report.reportType));
393
+ const prioritiesByType = jsonb(Object.fromEntries(priorities));
394
+ const priorityUpdates = {
395
+ priorityLevel: sql `${prioritiesByType} -> "reportType" ->> 'level'`,
396
+ priorityScore: sql `(${prioritiesByType} -> "reportType" ->> 'score')::integer`,
397
+ priorityTargetMinutes: sql `(${prioritiesByType} -> "reportType" ->> 'targetResolutionMinutes')::integer`,
398
+ };
399
+ const now = currentDatetimeString();
400
+ const matchedByQueue = new Map();
401
+ const unmatchedIds = [];
402
+ let maxReportId = 0;
403
+ for (const report of reports) {
404
+ const subjectType = report.subjectMessageId
405
+ ? 'message'
406
+ : report.subjectConvoId
407
+ ? 'conversation'
408
+ : report.recordPath
409
+ ? 'record'
410
+ : 'account';
411
+ // recordPath is 'collection/rkey' for records, '' for accounts
412
+ const slashIdx = report.recordPath.indexOf('/');
413
+ const collection = slashIdx > 0 ? report.recordPath.slice(0, slashIdx) : null;
414
+ const tool = parseModTool(report.modTool);
415
+ const reporterTags = accountTags.get(report.reporterDid ?? report.eventReporterDid) ?? [];
416
+ const subjectTags = accountTags.get(report.did) ?? [];
417
+ const assignment = resolveAssignment(subjectType, collection, report.reportType, queues, tool.queueId, reporterTags, subjectTags);
418
+ if (assignment.queueId !== -1) {
419
+ // @NOTE Queue assignment must preserve closure and active review state.
420
+ const result = handleReportUpdate(report.status, { type: 'queue' });
421
+ const group = matchedByQueue.get(assignment.queueId) ?? [];
422
+ group.push({
423
+ id: report.id,
424
+ queueId: assignment.queueId,
425
+ nextStatus: result.nextStatus,
426
+ activity: result.activity,
427
+ routingNote: assignment.routingNote,
428
+ });
429
+ matchedByQueue.set(assignment.queueId, group);
413
430
  }
414
431
  else {
415
- query = query.where('r.queueId', 'is', null);
416
- }
417
- const reports = await query.execute();
418
- if (!reports.length) {
419
- return { processed: 0, assigned: 0, unmatched: 0, maxId: 0 };
432
+ unmatchedIds.push(report.id);
420
433
  }
421
- const accountTags = await queueService.loadAccountTags(queues, reports.flatMap((report) => [
422
- report.did,
423
- report.reporterDid ?? report.eventReporterDid,
424
- ]));
425
- const priorities = await resolveReportPriorities(dbTxn, reports.map((report) => report.reportType));
426
- const prioritiesByType = jsonb(Object.fromEntries(priorities));
427
- const priorityUpdates = {
428
- priorityLevel: sql `${prioritiesByType} -> "reportType" ->> 'level'`,
429
- priorityScore: sql `(${prioritiesByType} -> "reportType" ->> 'score')::integer`,
430
- priorityTargetMinutes: sql `(${prioritiesByType} -> "reportType" ->> 'targetResolutionMinutes')::integer`,
431
- };
432
- const now = currentDatetimeString();
433
- const matchedByQueue = new Map();
434
- const unmatchedIds = [];
435
- let maxReportId = 0;
436
- for (const report of reports) {
437
- const subjectType = report.subjectMessageId
438
- ? 'message'
439
- : report.subjectConvoId
440
- ? 'conversation'
441
- : report.recordPath
442
- ? 'record'
443
- : 'account';
444
- // recordPath is 'collection/rkey' for records, '' for accounts
445
- const slashIdx = report.recordPath.indexOf('/');
446
- const collection = slashIdx > 0 ? report.recordPath.slice(0, slashIdx) : null;
447
- const tool = parseModTool(report.modTool);
448
- const assignment = resolveAssignment(subjectType, collection, report.reportType, queues, now, tool.queueId, accountTags.get(report.reporterDid ?? report.eventReporterDid) ?? [], accountTags.get(report.did) ?? []);
449
- if (assignment.queueId !== -1) {
450
- // Existing-row UPDATE path uses handleReportUpdate so that already
451
- // escalated/closed/etc. reports keep their status — only open → queued
452
- // transitions emit a status change and an activity row.
453
- const result = handleReportUpdate(report.status, { type: 'queue' });
454
- const group = matchedByQueue.get(assignment.queueId) ?? [];
455
- group.push({
456
- id: report.id,
457
- queueId: assignment.queueId,
458
- nextStatus: result.nextStatus,
459
- activity: result.activity,
460
- routingNote: assignment.routingNote,
461
- });
462
- matchedByQueue.set(assignment.queueId, group);
463
- }
464
- else {
465
- unmatchedIds.push(report.id);
466
- }
467
- if (report.id > maxReportId)
468
- maxReportId = report.id;
469
- }
470
- // Bulk UPDATE matched reports — split by whether status should change.
471
- // handleReportUpdate returns nextStatus only for open → queued;
472
- // other statuses keep their current status but still get routed.
473
- for (const [queueId, group] of matchedByQueue) {
474
- const withTransition = group
475
- .filter((r) => r.nextStatus !== null)
476
- .map((r) => r.id);
477
- const withoutTransition = group
478
- .filter((r) => r.nextStatus === null)
479
- .map((r) => r.id);
480
- if (withTransition.length) {
481
- await dbTxn.db
482
- .updateTable('report')
483
- .set({
484
- ...priorityUpdates,
485
- queueId,
486
- queuedAt: now,
487
- status: 'queued',
488
- updatedAt: now,
489
- })
490
- .where('id', 'in', withTransition)
491
- .execute();
492
- }
493
- if (withoutTransition.length) {
494
- await dbTxn.db
495
- .updateTable('report')
496
- .set({ ...priorityUpdates, queueId, queuedAt: now, updatedAt: now })
497
- .where('id', 'in', withoutTransition)
498
- .execute();
499
- }
500
- }
501
- // Bulk UPDATE unmatched reports — status stays unchanged
502
- if (unmatchedIds.length) {
503
- await dbTxn.db
434
+ if (report.id > maxReportId)
435
+ maxReportId = report.id;
436
+ }
437
+ // Bulk UPDATE matched reports — split by whether status should change.
438
+ // handleReportUpdate returns nextStatus only for open → queued;
439
+ // other statuses keep their current status but still get routed.
440
+ for (const [queueId, group] of matchedByQueue) {
441
+ const withTransition = group
442
+ .filter((r) => r.nextStatus !== null)
443
+ .map((r) => r.id);
444
+ const withoutTransition = group
445
+ .filter((r) => r.nextStatus === null)
446
+ .map((r) => r.id);
447
+ if (withTransition.length) {
448
+ await this.db.db
504
449
  .updateTable('report')
505
450
  .set({
506
451
  ...priorityUpdates,
507
- queueId: -1,
508
- queuedAt: null,
452
+ queueId,
453
+ queuedAt: now,
454
+ status: 'queued',
509
455
  updatedAt: now,
510
456
  })
511
- .where('id', 'in', unmatchedIds)
457
+ .where('id', 'in', withTransition)
512
458
  .execute();
513
459
  }
514
- // Bulk INSERT activities for matched reports that changed status.
515
- if (opts?.serviceDid) {
516
- const withActivities = [...matchedByQueue.values()]
517
- .flat()
518
- .filter((r) => r.activity !== null);
519
- if (withActivities.length) {
520
- await dbTxn.db
521
- .insertInto('report_activity')
522
- .values(withActivities.map((r) => ({
523
- reportId: r.id,
524
- activityType: r.activity.activityType,
525
- previousStatus: r.activity.previousStatus,
526
- internalNote: null,
527
- publicNote: null,
528
- meta: null,
529
- isAutomated: true,
530
- createdBy: opts.serviceDid,
531
- createdAt: now,
532
- })))
533
- .execute();
534
- }
460
+ if (withoutTransition.length) {
461
+ await this.db.db
462
+ .updateTable('report')
463
+ .set({ ...priorityUpdates, queueId, queuedAt: now, updatedAt: now })
464
+ .where('id', 'in', withoutTransition)
465
+ .execute();
535
466
  }
536
- await queueService.insertRoutingNotes([...matchedByQueue.values()]
467
+ }
468
+ // Bulk UPDATE unmatched reports — status stays unchanged
469
+ if (unmatchedIds.length) {
470
+ await this.db.db
471
+ .updateTable('report')
472
+ .set({
473
+ ...priorityUpdates,
474
+ queueId: -1,
475
+ queuedAt: null,
476
+ updatedAt: now,
477
+ })
478
+ .where('id', 'in', unmatchedIds)
479
+ .execute();
480
+ }
481
+ // Bulk INSERT activities for matched reports that changed status.
482
+ if (opts?.serviceDid) {
483
+ const withActivities = [...matchedByQueue.values()]
537
484
  .flat()
538
- .flatMap((report) => report.routingNote
539
- ? [{ reportId: report.id, internalNote: report.routingNote }]
540
- : []), now);
541
- const assigned = [...matchedByQueue.values()].reduce((sum, g) => sum + g.length, 0);
542
- return {
543
- processed: reports.length,
544
- assigned,
545
- unmatched: unmatchedIds.length,
546
- maxId: maxReportId,
547
- };
548
- });
485
+ .filter((r) => r.activity !== null);
486
+ if (withActivities.length) {
487
+ await this.db.db
488
+ .insertInto('report_activity')
489
+ .values(withActivities.map((r) => ({
490
+ reportId: r.id,
491
+ activityType: r.activity.activityType,
492
+ previousStatus: r.activity.previousStatus,
493
+ internalNote: null,
494
+ publicNote: null,
495
+ meta: null,
496
+ isAutomated: true,
497
+ createdBy: opts.serviceDid,
498
+ createdAt: now,
499
+ })))
500
+ .execute();
501
+ }
502
+ }
503
+ // Bulk INSERT routing notes for reports that have them
504
+ await this.insertRoutingNotes([...matchedByQueue.values()]
505
+ .flat()
506
+ .flatMap((report) => report.routingNote
507
+ ? [{ reportId: report.id, internalNote: report.routingNote }]
508
+ : []), now);
509
+ const assigned = [...matchedByQueue.values()].reduce((sum, g) => sum + g.length, 0);
510
+ return {
511
+ processed: reports.length,
512
+ assigned,
513
+ unmatched: unmatchedIds.length,
514
+ maxId: maxReportId,
515
+ };
549
516
  }
550
- /**
551
- * Read newly-created modEventReport rows from `moderation_event` and
552
- * insert corresponding `report` rows with `queueId` already resolved.
553
- * Used by the queue-router daemon. On conflict, a null reporter DID is
554
- * repaired from the source event while existing report state is preserved.
555
- *
556
- * Even when no queues are configured, report rows are still inserted with
557
- * `queueId = -1` so the invariant "every modEventReport has a `report` row"
558
- * holds.
559
- * Expected to be called within a database transaction.
560
- */
517
+ /** Insert pending reports for events from writers that do not create report rows. */
561
518
  async insertReportsFromEvents(params) {
562
519
  this.db.assertTransaction();
563
- const { queues } = await this.list({ limit: 1000, enabled: true });
564
520
  let query = this.db.db
565
521
  .selectFrom('moderation_event')
566
522
  .select([
@@ -582,53 +538,16 @@ export class QueueService {
582
538
  }
583
539
  const events = await query.execute();
584
540
  if (!events.length) {
585
- return { processed: 0, assigned: 0, unmatched: 0, maxEventId: 0 };
541
+ return { processed: 0, inserted: 0, maxEventId: 0 };
586
542
  }
587
- const accountTags = await this.loadAccountTags(queues, events.flatMap((event) => [event.createdBy, event.subjectDid]));
588
- const now = currentDatetimeString();
589
- let maxEventId = 0;
590
- let assigned = 0;
591
- let unmatched = 0;
592
- const reportTypes = events.map((event) => event.meta?.reportType ??
593
- com.atproto.moderation.defs.ReasonOther);
594
- const priorities = await resolveReportPriorities(this.db, reportTypes);
595
- const routingNotes = new Map();
596
- const rows = events.map((event) => {
597
- const subjectType = subjectTypeFromEvent(event);
598
- let collection = null;
599
- if (event.subjectUri) {
600
- const uri = new AtUri(event.subjectUri);
601
- collection = uri.collection;
602
- }
603
- const reportType = event.meta?.reportType ??
604
- com.atproto.moderation.defs.ReasonOther;
605
- const priority = priorities.get(reportType);
606
- const tool = parseModTool(event.modTool);
607
- const assignment = resolveAssignment(subjectType, collection, reportType, queues, now, tool.queueId, accountTags.get(event.createdBy) ?? [], accountTags.get(event.subjectDid) ?? []);
608
- if (assignment.queueId === -1)
609
- unmatched++;
610
- else
611
- assigned++;
612
- if (event.id > maxEventId)
613
- maxEventId = event.id;
614
- if (assignment.routingNote) {
615
- routingNotes.set(event.id, assignment.routingNote);
616
- }
617
- return reportRowFromEvent({
618
- event,
619
- reportType,
620
- assignment,
621
- priority,
622
- createdAt: now,
623
- });
624
- });
543
+ const rows = events.map(reportRowFromEvent);
625
544
  const inserted = await this.db.db
626
545
  .insertInto('report')
627
546
  .values(rows)
628
547
  .onConflict((oc) => oc.column('eventId').doNothing())
629
548
  .returning(['id', 'eventId'])
630
549
  .execute();
631
- // @NOTE Keep repairs separate so only new reports receive routing notes.
550
+ // @NOTE Replays may repair the reporter without changing report lifecycle state.
632
551
  if (inserted.length < rows.length) {
633
552
  await this.db.db
634
553
  .updateTable('report')
@@ -639,15 +558,10 @@ export class QueueService {
639
558
  .where('report.reporterDid', 'is', null)
640
559
  .execute();
641
560
  }
642
- await this.insertRoutingNotes(inserted.flatMap((report) => {
643
- const internalNote = routingNotes.get(report.eventId);
644
- return internalNote ? [{ reportId: report.id, internalNote }] : [];
645
- }), now);
646
561
  return {
647
562
  processed: events.length,
648
- assigned,
649
- unmatched,
650
- maxEventId,
563
+ inserted: inserted.length,
564
+ maxEventId: events[events.length - 1].id,
651
565
  };
652
566
  }
653
567
  }
@@ -655,7 +569,7 @@ export class QueueService {
655
569
  export function hasTagCriteria(queue) {
656
570
  return !!(queue.reporterTags?.length || queue.accountTags?.length);
657
571
  }
658
- /** Snapshot the mutable tag values that matched an automatic destination. */
572
+ /** Get a routing note for a report. Currently used for tagging-based routing. */
659
573
  export function getQueueRoutingNote(queue, reporterTags, accountTags) {
660
574
  const matches = [
661
575
  ['reporterTags', queue.reporterTags ?? [], reporterTags],