@atproto/ozone 0.2.23 → 0.2.24
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/CHANGELOG.md +20 -0
- package/dist/api/report/createReport.js +7 -5
- package/dist/api/report/createReport.js.map +1 -1
- package/dist/api/util.d.ts.map +1 -1
- package/dist/api/util.js.map +1 -1
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +0 -2
- package/dist/db/index.js.map +1 -1
- package/dist/db/types.d.ts.map +1 -1
- package/dist/db/types.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -3
- package/dist/index.js.map +1 -1
- package/dist/jetstream/service.d.ts +4 -3
- package/dist/jetstream/service.d.ts.map +1 -1
- package/dist/jetstream/service.js +46 -22
- package/dist/jetstream/service.js.map +1 -1
- package/dist/lexicon/lexicons.d.ts +60 -8
- package/dist/lexicon/lexicons.d.ts.map +1 -1
- package/dist/lexicon/lexicons.js +30 -4
- package/dist/lexicon/lexicons.js.map +1 -1
- package/dist/lexicon/types/app/bsky/actor/defs.d.ts +5 -0
- package/dist/lexicon/types/app/bsky/actor/defs.d.ts.map +1 -1
- package/dist/lexicon/types/app/bsky/actor/defs.js.map +1 -1
- package/dist/lexicon/types/app/bsky/ageassurance/begin.d.ts.map +1 -1
- package/dist/lexicon/types/app/bsky/ageassurance/begin.js.map +1 -1
- package/dist/lexicon/types/app/bsky/ageassurance/defs.d.ts.map +1 -1
- package/dist/lexicon/types/app/bsky/ageassurance/defs.js.map +1 -1
- package/dist/lexicon/types/app/bsky/draft/defs.d.ts.map +1 -1
- package/dist/lexicon/types/app/bsky/draft/defs.js.map +1 -1
- package/dist/lexicon/types/app/bsky/feed/defs.d.ts.map +1 -1
- package/dist/lexicon/types/app/bsky/feed/defs.js.map +1 -1
- package/dist/lexicon/types/app/bsky/graph/muteActor.d.ts +4 -0
- package/dist/lexicon/types/app/bsky/graph/muteActor.d.ts.map +1 -1
- package/dist/lexicon/types/app/bsky/graph/muteActor.js.map +1 -1
- package/dist/lexicon/types/app/bsky/unspecced/defs.d.ts +5 -1
- package/dist/lexicon/types/app/bsky/unspecced/defs.d.ts.map +1 -1
- package/dist/lexicon/types/app/bsky/unspecced/defs.js.map +1 -1
- package/dist/lexicon/types/chat/bsky/convo/defs.d.ts.map +1 -1
- package/dist/lexicon/types/chat/bsky/convo/defs.js.map +1 -1
- package/dist/lexicon/types/chat/bsky/group/createGroup.d.ts +1 -0
- package/dist/lexicon/types/chat/bsky/group/createGroup.d.ts.map +1 -1
- package/dist/lexicon/types/chat/bsky/group/createGroup.js.map +1 -1
- package/dist/lexicon/types/chat/bsky/group/enableJoinLink.d.ts.map +1 -1
- package/dist/lexicon/types/chat/bsky/group/enableJoinLink.js.map +1 -1
- package/dist/lexicon/types/com/atproto/repo/applyWrites.d.ts.map +1 -1
- package/dist/lexicon/types/com/atproto/repo/applyWrites.js.map +1 -1
- package/dist/lexicon/types/com/atproto/sync/defs.d.ts.map +1 -1
- package/dist/lexicon/types/com/atproto/sync/defs.js.map +1 -1
- package/dist/lexicon/types/com/atproto/temp/checkHandleAvailability.d.ts.map +1 -1
- package/dist/lexicon/types/com/atproto/temp/checkHandleAvailability.js.map +1 -1
- package/dist/lexicon/types/tools/ozone/moderation/defs.d.ts.map +1 -1
- package/dist/lexicon/types/tools/ozone/moderation/defs.js.map +1 -1
- package/dist/lexicon/types/tools/ozone/moderation/queryEvents.d.ts.map +1 -1
- package/dist/lexicon/types/tools/ozone/moderation/queryEvents.js.map +1 -1
- package/dist/lexicon/types/tools/ozone/moderation/queryStatuses.d.ts.map +1 -1
- package/dist/lexicon/types/tools/ozone/moderation/queryStatuses.js.map +1 -1
- package/dist/lexicon/types/tools/ozone/queue/createQueue.d.ts.map +1 -1
- package/dist/lexicon/types/tools/ozone/queue/createQueue.js.map +1 -1
- package/dist/lexicon/types/tools/ozone/queue/defs.d.ts.map +1 -1
- package/dist/lexicon/types/tools/ozone/queue/defs.js.map +1 -1
- package/dist/lexicon/types/tools/ozone/report/defs.d.ts.map +1 -1
- package/dist/lexicon/types/tools/ozone/report/defs.js.map +1 -1
- package/dist/lexicon/types/tools/ozone/report/queryReports.d.ts.map +1 -1
- package/dist/lexicon/types/tools/ozone/report/queryReports.js.map +1 -1
- package/dist/mod-service/index.d.ts +0 -39
- package/dist/mod-service/index.d.ts.map +1 -1
- package/dist/mod-service/index.js +0 -11
- package/dist/mod-service/index.js.map +1 -1
- package/dist/mod-service/subject.d.ts.map +1 -1
- package/dist/mod-service/subject.js.map +1 -1
- package/dist/mod-service/types.d.ts.map +1 -1
- package/dist/mod-service/types.js.map +1 -1
- package/dist/mod-service/views.d.ts.map +1 -1
- package/dist/mod-service/views.js.map +1 -1
- package/dist/report/stats.js +3 -3
- package/dist/report/stats.js.map +1 -1
- package/dist/sequencer/sequencer.d.ts.map +1 -1
- package/dist/sequencer/sequencer.js.map +1 -1
- package/package.json +11 -11
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# @atproto/ozone
|
|
2
2
|
|
|
3
|
+
## 0.2.24
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#5300](https://github.com/bluesky-social/atproto/pull/5300) [`2cbbb5d`](https://github.com/bluesky-social/atproto/commit/2cbbb5d16ccb1597e0391aa674349f795b404b8b) Thanks [@foysalit](https://github.com/foysalit)! - Fix createReport reporter validation to only consult the reporter's account-level moderation status. Previously a takedown or pending appeal on any of the reporter's records (posts, lists, etc.) could incorrectly block them from submitting reports or appeals.
|
|
8
|
+
|
|
9
|
+
- [#5285](https://github.com/bluesky-social/atproto/pull/5285) [`d12f6ac`](https://github.com/bluesky-social/atproto/commit/d12f6ac6e2cb2590446bf9f2051287bac058c092) Thanks [@devinivy](https://github.com/devinivy)! - Migrate the internal Jetstream client to `@atproto/ws-client`. `Jetstream.close()` now resolves once the stream has fully stopped rather than returning immediately.
|
|
10
|
+
|
|
11
|
+
- [#5301](https://github.com/bluesky-social/atproto/pull/5301) [`8c07338`](https://github.com/bluesky-social/atproto/commit/8c07338232aa69427aa65322a555f70e0211d6d7) Thanks [@43081j](https://github.com/43081j)! - Switch from destructured default imports to named imports of CommonJS dependencies.
|
|
12
|
+
|
|
13
|
+
- Updated dependencies [[`5a222b0`](https://github.com/bluesky-social/atproto/commit/5a222b05da5f9c0d32d41fb1c4437ea188aa2c32), [`6a3d607`](https://github.com/bluesky-social/atproto/commit/6a3d6073cb66c527b5b109242049c85c36b9658c), [`ee4a0cf`](https://github.com/bluesky-social/atproto/commit/ee4a0cf0ebb3e078a014bef882720f46aca5cb89), [`29dcbc0`](https://github.com/bluesky-social/atproto/commit/29dcbc091ca72cb9dda7a2cea846f3eb4bfcef6c), [`a8186e7`](https://github.com/bluesky-social/atproto/commit/a8186e7cdb5ea3d8a88c2e9283d742de1bc0bba6), [`8c07338`](https://github.com/bluesky-social/atproto/commit/8c07338232aa69427aa65322a555f70e0211d6d7), [`d12f6ac`](https://github.com/bluesky-social/atproto/commit/d12f6ac6e2cb2590446bf9f2051287bac058c092), [`d12f6ac`](https://github.com/bluesky-social/atproto/commit/d12f6ac6e2cb2590446bf9f2051287bac058c092)]:
|
|
14
|
+
- @atproto/xrpc-server@0.12.0
|
|
15
|
+
- @atproto/syntax@0.7.3
|
|
16
|
+
- @atproto/api@0.20.37
|
|
17
|
+
- @atproto/ws-client@0.2.0
|
|
18
|
+
- @atproto/common@0.7.4
|
|
19
|
+
- @atproto/lexicon@0.7.10
|
|
20
|
+
- @atproto/identity@0.5.8
|
|
21
|
+
- @atproto/xrpc@0.8.9
|
|
22
|
+
|
|
3
23
|
## 0.2.23
|
|
4
24
|
|
|
5
25
|
### Patch Changes
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ForbiddenError } from '@atproto/xrpc-server';
|
|
2
|
-
import { subjectFromInput } from '../../mod-service/subject.js';
|
|
2
|
+
import { RepoSubject, subjectFromInput } from '../../mod-service/subject.js';
|
|
3
3
|
import { TagService } from '../../tag-service/index.js';
|
|
4
4
|
import { getTagForReport } from '../../tag-service/util.js';
|
|
5
5
|
import { isAppealReport } from '../util.js';
|
|
@@ -39,14 +39,16 @@ export default function (server, ctx) {
|
|
|
39
39
|
});
|
|
40
40
|
}
|
|
41
41
|
const assertValidReporter = async (modService, reasonType, did) => {
|
|
42
|
-
|
|
42
|
+
// Only the account-level status matters here: a takedown or appeal on one of
|
|
43
|
+
// the reporter's records must not block them from reporting
|
|
44
|
+
const reporterStatus = await modService.getStatus(new RepoSubject(did));
|
|
43
45
|
// If we don't have a mod status for the reporter, no need to do further checks
|
|
44
|
-
if (!reporterStatus
|
|
46
|
+
if (!reporterStatus) {
|
|
45
47
|
return;
|
|
46
48
|
}
|
|
47
49
|
// For appeals, we just need to make sure that the account does not have pending appeal
|
|
48
50
|
if (isAppealReport(reasonType)) {
|
|
49
|
-
if (reporterStatus
|
|
51
|
+
if (reporterStatus.appealed) {
|
|
50
52
|
throw new ForbiddenError('Awaiting decision on previous appeal', 'AlreadyAppealed');
|
|
51
53
|
}
|
|
52
54
|
return;
|
|
@@ -54,7 +56,7 @@ const assertValidReporter = async (modService, reasonType, did) => {
|
|
|
54
56
|
// For non appeals, we need to make sure the reporter account is not already in takendown status
|
|
55
57
|
// This is necessary because we allow takendown accounts call createReport but that's only meant for appeals
|
|
56
58
|
// and we need to make sure takendown accounts don't abuse this endpoint
|
|
57
|
-
if (reporterStatus
|
|
59
|
+
if (reporterStatus.takendown) {
|
|
58
60
|
throw new ForbiddenError('Report not accepted from takendown account', 'AccountTakedown');
|
|
59
61
|
}
|
|
60
62
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createReport.js","sourceRoot":"","sources":["../../../src/api/report/createReport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAKrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAA;
|
|
1
|
+
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F;IACvF,IAAI,cAAc,CAAC,UAAU,CAAC,EAAE,CAAC;QAC/B,IAAI,cAAc,CAAC,QAAQ,EAAE,CAAC;YAC5B,MAAM,IAAI,cAAc,CACtB,sCAAsC,EACtC,iBAAiB,CAClB,CAAA;QACH,CAAC;QACD,OAAM;IACR,CAAC;IAED,gGAAgG;IAChG,4GAA4G;IAC5G,wEAAwE;IACxE,IAAI,cAAc,CAAC,SAAS,EAAE,CAAC;QAC7B,MAAM,IAAI,cAAc,CACtB,4CAA4C,EAC5C,iBAAiB,CAClB,CAAA;IACH,CAAC;AACH,CAAC,CAAA","sourcesContent":["import { ForbiddenError } from '@atproto/xrpc-server'\nimport type { AppContext } from '../../context.js'\nimport type { Server } from '../../lexicon/index.js'\nimport type { ReasonType } from '../../lexicon/types/com/atproto/moderation/defs.js'\nimport type { ModerationService } from '../../mod-service/index.js'\nimport { RepoSubject, subjectFromInput } from '../../mod-service/subject.js'\nimport { TagService } from '../../tag-service/index.js'\nimport { getTagForReport } from '../../tag-service/util.js'\nimport { isAppealReport } from '../util.js'\n\nexport default function (server: Server, ctx: AppContext) {\n server.com.atproto.moderation.createReport({\n auth: ctx.authVerifier.standard,\n handler: async ({ input, auth }) => {\n const requester =\n 'iss' in auth.credentials ? auth.credentials.iss : ctx.cfg.service.did\n const { reasonType, reason, modTool } = input.body\n const subject = subjectFromInput(input.body.subject)\n\n // If the report is an appeal, the requester must be the author of the subject\n if (isAppealReport(reasonType) && requester !== subject.did) {\n throw new ForbiddenError('You cannot appeal this report')\n }\n\n const db = ctx.db\n\n await ctx.moderationServiceProfile().validateReasonType(reasonType)\n await assertValidReporter(ctx.modService(db), reasonType, requester)\n\n const report = await db.transaction(async (dbTxn) => {\n const moderationTxn = ctx.modService(dbTxn)\n const { event: reportEvent, subjectStatus } =\n await moderationTxn.report({\n reason,\n subject,\n reasonType,\n reportedBy: requester || ctx.cfg.service.did,\n modTool,\n })\n\n const tagService = new TagService(\n subject,\n subjectStatus,\n ctx.cfg.service.did,\n moderationTxn,\n )\n await tagService.evaluateForSubject([getTagForReport(reasonType)])\n\n return reportEvent\n })\n\n const body = ctx.modService(db).views.formatReport(report)\n return {\n encoding: 'application/json',\n body,\n }\n },\n })\n}\n\nconst assertValidReporter = async (\n modService: ModerationService,\n reasonType: ReasonType,\n did: string,\n) => {\n // Only the account-level status matters here: a takedown or appeal on one of\n // the reporter's records must not block them from reporting\n const reporterStatus = await modService.getStatus(new RepoSubject(did))\n\n // If we don't have a mod status for the reporter, no need to do further checks\n if (!reporterStatus) {\n return\n }\n\n // For appeals, we just need to make sure that the account does not have pending appeal\n if (isAppealReport(reasonType)) {\n if (reporterStatus.appealed) {\n throw new ForbiddenError(\n 'Awaiting decision on previous appeal',\n 'AlreadyAppealed',\n )\n }\n return\n }\n\n // For non appeals, we need to make sure the reporter account is not already in takendown status\n // This is necessary because we allow takendown accounts call createReport but that's only meant for appeals\n // and we need to make sure takendown accounts don't abuse this endpoint\n if (reporterStatus.takendown) {\n throw new ForbiddenError(\n 'Report not accepted from takendown account',\n 'AccountTakedown',\n )\n }\n}\n"]}
|
package/dist/api/util.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../src/api/util.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AAC5E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAI/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4CAA4C,CAAA;AAE7E,OAAO,EAKL,KAAK,QAAQ,EACb,KAAK,cAAc,EACpB,MAAM,iDAAiD,CAAA;AASxD,eAAO,MAAM,UAAU,SACf,eAAe,GAAG,gBAAgB,cAC5B,MAAM,KACjB,MAAM,GAAG,SAMX,CAAA;AAED,eAAO,MAAM,kBAAkB,QACxB,UAAU,QACT,MAAM,EAAE,KACb,OAAO,CAAC,GAAG,CAAC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CAAA;AAC9D,CAAC,CAAA;AAOD,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAA;AACnD,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC,CAAA;AAC/D,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC,CAAA;AACrE,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC,CAAA;AAE3E,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,MAAc,EAAuB,EAAE;IAC5E,IAAI,oBAAoB,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;QACrC,OAAO,MAA6B,CAAA;IACtC,CAAC;IACD,MAAM,IAAI,mBAAmB,CAAC,+BAA+B,CAAC,CAAA;AAChE,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,CACtC,MAAc,EACS,EAAE;IACzB,IAAI,uBAAuB,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;QACxC,OAAO,MAA+B,CAAA;IACxC,CAAC;IACD,MAAM,IAAI,mBAAmB,CAAC,iCAAiC,CAAC,CAAA;AAClE,CAAC,CAAA;AASD,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAA;AAClD,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAAC;IACtC,SAAS;IACT,UAAU;IACV,WAAW;IACX,QAAQ;CACT,CAAC,CAAA","sourcesContent":["import { InvalidRequestError } from '@atproto/xrpc-server'\nimport type { AdminTokenOutput, ModeratorOutput } from '../auth-verifier.js'\nimport type { AppContext } from '../context.js'\nimport type { Member } from '../db/schema/member.js'\nimport type { ModerationEvent } from '../db/schema/moderation_event.js'\nimport { ids } from '../lexicon/lexicons.js'\nimport type { AccountView } from '../lexicon/types/com/atproto/admin/defs.js'\nimport { REASONAPPEAL } from '../lexicon/types/com/atproto/moderation/defs.js'\nimport {\n REVIEWCLOSED,\n REVIEWESCALATED,\n REVIEWNONE,\n REVIEWOPEN,\n type RepoView,\n type RepoViewDetail,\n} from '../lexicon/types/tools/ozone/moderation/defs.js'\nimport {\n ROLEADMIN,\n ROLEMODERATOR,\n ROLETRIAGE,\n ROLEVERIFIER,\n} from '../lexicon/types/tools/ozone/team/defs.js'\nimport type { ModerationSubjectStatusRow } from '../mod-service/types.js'\n\nexport const getAuthDid = (\n auth: ModeratorOutput | AdminTokenOutput,\n serviceDid: string,\n): string | undefined => {\n return auth.credentials.type === 'moderator'\n ? auth.credentials.iss\n : auth.credentials.type === 'admin_token'\n ? serviceDid\n : undefined\n}\n\nexport const getPdsAccountInfos = async (\n ctx: AppContext,\n dids: string[],\n): Promise<Map<string, AccountView | null>> => {\n const results = new Map<string, AccountView | null>()\n\n const agent = ctx.pdsAgent\n if (!agent || !dids.length) return results\n\n const auth = await ctx.pdsAuth(ids.ComAtprotoAdminGetAccountInfos)\n if (!auth) return results\n\n try {\n const res = await agent.com.atproto.admin.getAccountInfos({ dids }, auth)\n res.data.infos.forEach((info) => {\n results.set(info.did, info)\n })\n return results\n } catch {\n return results\n }\n}\n\nfunction un$type<T extends object>(obj: T): Omit<T, '$type'> {\n if ('$type' in obj) {\n const { $type: _, ...rest } = obj\n return rest\n }\n return obj\n}\n\nexport const addAccountInfoToRepoViewDetail = (\n repoView: RepoView | RepoViewDetail,\n accountInfo: AccountView | null,\n includeEmail = false,\n): RepoViewDetail => {\n if (!accountInfo) {\n return un$type({\n ...repoView,\n moderation: un$type(repoView.moderation),\n })\n }\n\n const {\n email,\n deactivatedAt,\n emailConfirmedAt,\n inviteNote,\n invitedBy,\n invites,\n invitesDisabled,\n threatSignatures,\n // pick some duplicate/unwanted details out\n $type: _accountType,\n did: _did,\n handle: _handle,\n indexedAt: _indexedAt,\n relatedRecords: _relatedRecords,\n ...otherAccountInfo\n } = accountInfo\n return {\n ...otherAccountInfo,\n ...un$type(repoView),\n moderation: un$type(repoView.moderation),\n email: includeEmail ? email : undefined,\n invitedBy,\n invitesDisabled,\n inviteNote,\n invites,\n emailConfirmedAt,\n deactivatedAt,\n threatSignatures,\n }\n}\n\nexport const addAccountInfoToRepoView = (\n repoView: RepoView,\n accountInfo: AccountView | null,\n includeEmail = false,\n): RepoView => {\n if (!accountInfo) return repoView\n return {\n ...repoView,\n email: includeEmail ? accountInfo.email : undefined,\n invitedBy: accountInfo.invitedBy,\n invitesDisabled: accountInfo.invitesDisabled,\n inviteNote: accountInfo.inviteNote,\n deactivatedAt: accountInfo.deactivatedAt,\n threatSignatures: accountInfo.threatSignatures,\n }\n}\n\nexport const getEventType = (type: string) => {\n if (eventTypes.has(type)) {\n return type as ModerationEvent['action']\n }\n throw new InvalidRequestError('Invalid event type')\n}\n\nexport const getReviewState = (reviewState?: string) => {\n if (!reviewState) return undefined\n if (reviewStates.has(reviewState)) {\n return reviewState as ModerationSubjectStatusRow['reviewState']\n }\n throw new InvalidRequestError('Invalid review state')\n}\n\nconst reviewStates = new Set([\n REVIEWCLOSED,\n REVIEWESCALATED,\n REVIEWOPEN,\n REVIEWNONE,\n])\n\nconst eventTypes = new Set([\n 'tools.ozone.moderation.defs#modEventTakedown',\n 'tools.ozone.moderation.defs#modEventAcknowledge',\n 'tools.ozone.moderation.defs#modEventEscalate',\n 'tools.ozone.moderation.defs#modEventComment',\n 'tools.ozone.moderation.defs#modEventLabel',\n 'tools.ozone.moderation.defs#modEventReport',\n 'tools.ozone.moderation.defs#modEventMute',\n 'tools.ozone.moderation.defs#modEventUnmute',\n 'tools.ozone.moderation.defs#modEventMuteReporter',\n 'tools.ozone.moderation.defs#modEventUnmuteReporter',\n 'tools.ozone.moderation.defs#modEventReverseTakedown',\n 'tools.ozone.moderation.defs#modEventEmail',\n 'tools.ozone.moderation.defs#modEventResolveAppeal',\n 'tools.ozone.moderation.defs#modEventTag',\n 'tools.ozone.moderation.defs#modEventDivert',\n 'tools.ozone.moderation.defs#accountEvent',\n 'tools.ozone.moderation.defs#identityEvent',\n 'tools.ozone.moderation.defs#recordEvent',\n 'tools.ozone.moderation.defs#modEventPriorityScore',\n 'tools.ozone.moderation.defs#ageAssuranceEvent',\n 'tools.ozone.moderation.defs#ageAssuranceOverrideEvent',\n 'tools.ozone.moderation.defs#ageAssurancePurgeEvent',\n 'tools.ozone.moderation.defs#revokeAccountCredentialsEvent',\n 'tools.ozone.moderation.defs#scheduleTakedownEvent',\n 'tools.ozone.moderation.defs#cancelScheduledTakedownEvent',\n])\n\nexport const getMemberRole = (role: string) => {\n if (memberRoles.has(role)) {\n return role as Member['role']\n }\n throw new InvalidRequestError('Invalid member role')\n}\n\nconst memberRoles = new Set([\n ROLEADMIN,\n ROLEMODERATOR,\n ROLETRIAGE,\n ROLEVERIFIER,\n])\n\nexport const OZONE_APPEAL_REASON_TYPE = 'tools.ozone.report.defs#reasonAppeal'\nconst APPEAL_REASON_TYPES = [REASONAPPEAL, OZONE_APPEAL_REASON_TYPE]\nexport const isAppealReport = (reasonType?: string): boolean => {\n return !!reasonType && APPEAL_REASON_TYPES.includes(reasonType)\n}\n\nexport const getSafelinkPattern = (pattern: string): SafelinkPatternType => {\n if (safelinkPatterns.has(pattern)) {\n return pattern as SafelinkPatternType\n }\n throw new InvalidRequestError('Invalid safelink pattern type')\n}\n\nexport const getSafelinkAction = (action: string): SafelinkActionType => {\n if (safelinkActions.has(action)) {\n return action as SafelinkActionType\n }\n throw new InvalidRequestError('Invalid safelink action type')\n}\n\nexport const getSafelinkReason = (reason: string): SafelinkReasonType => {\n if (safelinkReasons.has(reason)) {\n return reason as SafelinkReasonType\n }\n throw new InvalidRequestError('Invalid safelink reason type')\n}\n\nexport const getSafelinkEventType = (eventType: string): SafelinkEventType => {\n if (safelinkEventTypes.has(eventType)) {\n return eventType as SafelinkEventType\n }\n throw new InvalidRequestError('Invalid safelink event type')\n}\n\nexport type SafelinkEventType = 'addRule' | 'updateRule' | 'removeRule'\nexport type SafelinkPatternType = 'domain' | 'url'\nexport type SafelinkActionType = 'block' | 'warn' | 'whitelist'\nexport type SafelinkReasonType = 'csam' | 'spam' | 'phishing' | 'none'\n\nconst safelinkPatterns = new Set(['domain', 'url'])\nconst safelinkActions = new Set(['block', 'warn', 'whitelist'])\nconst safelinkReasons = new Set(['csam', 'spam', 'phishing', 'none'])\nconst safelinkEventTypes = new Set(['addRule', 'updateRule', 'removeRule'])\n\nexport const getScheduledActionType = (action: string): ScheduledActionType => {\n if (scheduledActionTypes.has(action)) {\n return action as ScheduledActionType\n }\n throw new InvalidRequestError('Invalid scheduled action type')\n}\n\nexport const getScheduledActionStatus = (\n status: string,\n): ScheduledActionStatus => {\n if (scheduledActionStatuses.has(status)) {\n return status as ScheduledActionStatus\n }\n throw new InvalidRequestError('Invalid scheduled action status')\n}\n\nexport type ScheduledActionType = 'takedown'\nexport type ScheduledActionStatus =\n | 'pending'\n | 'executed'\n | 'cancelled'\n | 'failed'\n\nconst scheduledActionTypes = new Set(['takedown'])\nconst scheduledActionStatuses = new Set([\n 'pending',\n 'executed',\n 'cancelled',\n 'failed',\n])\n"]}
|
|
1
|
+
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/api/util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAA;AAK1D,OAAO,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAA;AAE5C,OAAO,EAAE,YAAY,EAAE,MAAM,iDAAiD,CAAA;AAC9E,OAAO,EACL,YAAY,EACZ,eAAe,EACf,UAAU,EACV,UAAU,GAGX,MAAM,iDAAiD,CAAA;AACxD,OAAO,EACL,SAAS,EACT,aAAa,EACb,UAAU,EACV,YAAY,GACb,MAAM,2CAA2C,CAAA;AAGlD,MAAM,CAAC,MAAM,UAAU,GAAG,CACxB,IAAwC,EACxC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;AAClD,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAAC;IACtC,SAAS;IACT,UAAU;IACV,WAAW;IACX,QAAQ;CACT,CAAC,CAAA","sourcesContent":["import { InvalidRequestError } from '@atproto/xrpc-server'\nimport type { AdminTokenOutput, ModeratorOutput } from '../auth-verifier.js'\nimport type { AppContext } from '../context.js'\nimport type { Member } from '../db/schema/member.js'\nimport type { ModerationEvent } from '../db/schema/moderation_event.js'\nimport { ids } from '../lexicon/lexicons.js'\nimport type { AccountView } from '../lexicon/types/com/atproto/admin/defs.js'\nimport { REASONAPPEAL } from '../lexicon/types/com/atproto/moderation/defs.js'\nimport {\n REVIEWCLOSED,\n REVIEWESCALATED,\n REVIEWNONE,\n REVIEWOPEN,\n type RepoView,\n type RepoViewDetail,\n} from '../lexicon/types/tools/ozone/moderation/defs.js'\nimport {\n ROLEADMIN,\n ROLEMODERATOR,\n ROLETRIAGE,\n ROLEVERIFIER,\n} from '../lexicon/types/tools/ozone/team/defs.js'\nimport type { ModerationSubjectStatusRow } from '../mod-service/types.js'\n\nexport const getAuthDid = (\n auth: ModeratorOutput | AdminTokenOutput,\n serviceDid: string,\n): string | undefined => {\n return auth.credentials.type === 'moderator'\n ? auth.credentials.iss\n : auth.credentials.type === 'admin_token'\n ? serviceDid\n : undefined\n}\n\nexport const getPdsAccountInfos = async (\n ctx: AppContext,\n dids: string[],\n): Promise<Map<string, AccountView | null>> => {\n const results = new Map<string, AccountView | null>()\n\n const agent = ctx.pdsAgent\n if (!agent || !dids.length) return results\n\n const auth = await ctx.pdsAuth(ids.ComAtprotoAdminGetAccountInfos)\n if (!auth) return results\n\n try {\n const res = await agent.com.atproto.admin.getAccountInfos({ dids }, auth)\n res.data.infos.forEach((info) => {\n results.set(info.did, info)\n })\n return results\n } catch {\n return results\n }\n}\n\nfunction un$type<T extends object>(obj: T): Omit<T, '$type'> {\n if ('$type' in obj) {\n const { $type: _, ...rest } = obj\n return rest\n }\n return obj\n}\n\nexport const addAccountInfoToRepoViewDetail = (\n repoView: RepoView | RepoViewDetail,\n accountInfo: AccountView | null,\n includeEmail = false,\n): RepoViewDetail => {\n if (!accountInfo) {\n return un$type({\n ...repoView,\n moderation: un$type(repoView.moderation),\n })\n }\n\n const {\n email,\n deactivatedAt,\n emailConfirmedAt,\n inviteNote,\n invitedBy,\n invites,\n invitesDisabled,\n threatSignatures,\n // pick some duplicate/unwanted details out\n $type: _accountType,\n did: _did,\n handle: _handle,\n indexedAt: _indexedAt,\n relatedRecords: _relatedRecords,\n ...otherAccountInfo\n } = accountInfo\n return {\n ...otherAccountInfo,\n ...un$type(repoView),\n moderation: un$type(repoView.moderation),\n email: includeEmail ? email : undefined,\n invitedBy,\n invitesDisabled,\n inviteNote,\n invites,\n emailConfirmedAt,\n deactivatedAt,\n threatSignatures,\n }\n}\n\nexport const addAccountInfoToRepoView = (\n repoView: RepoView,\n accountInfo: AccountView | null,\n includeEmail = false,\n): RepoView => {\n if (!accountInfo) return repoView\n return {\n ...repoView,\n email: includeEmail ? accountInfo.email : undefined,\n invitedBy: accountInfo.invitedBy,\n invitesDisabled: accountInfo.invitesDisabled,\n inviteNote: accountInfo.inviteNote,\n deactivatedAt: accountInfo.deactivatedAt,\n threatSignatures: accountInfo.threatSignatures,\n }\n}\n\nexport const getEventType = (type: string) => {\n if (eventTypes.has(type)) {\n return type as ModerationEvent['action']\n }\n throw new InvalidRequestError('Invalid event type')\n}\n\nexport const getReviewState = (reviewState?: string) => {\n if (!reviewState) return undefined\n if (reviewStates.has(reviewState)) {\n return reviewState as ModerationSubjectStatusRow['reviewState']\n }\n throw new InvalidRequestError('Invalid review state')\n}\n\nconst reviewStates = new Set([\n REVIEWCLOSED,\n REVIEWESCALATED,\n REVIEWOPEN,\n REVIEWNONE,\n])\n\nconst eventTypes = new Set([\n 'tools.ozone.moderation.defs#modEventTakedown',\n 'tools.ozone.moderation.defs#modEventAcknowledge',\n 'tools.ozone.moderation.defs#modEventEscalate',\n 'tools.ozone.moderation.defs#modEventComment',\n 'tools.ozone.moderation.defs#modEventLabel',\n 'tools.ozone.moderation.defs#modEventReport',\n 'tools.ozone.moderation.defs#modEventMute',\n 'tools.ozone.moderation.defs#modEventUnmute',\n 'tools.ozone.moderation.defs#modEventMuteReporter',\n 'tools.ozone.moderation.defs#modEventUnmuteReporter',\n 'tools.ozone.moderation.defs#modEventReverseTakedown',\n 'tools.ozone.moderation.defs#modEventEmail',\n 'tools.ozone.moderation.defs#modEventResolveAppeal',\n 'tools.ozone.moderation.defs#modEventTag',\n 'tools.ozone.moderation.defs#modEventDivert',\n 'tools.ozone.moderation.defs#accountEvent',\n 'tools.ozone.moderation.defs#identityEvent',\n 'tools.ozone.moderation.defs#recordEvent',\n 'tools.ozone.moderation.defs#modEventPriorityScore',\n 'tools.ozone.moderation.defs#ageAssuranceEvent',\n 'tools.ozone.moderation.defs#ageAssuranceOverrideEvent',\n 'tools.ozone.moderation.defs#ageAssurancePurgeEvent',\n 'tools.ozone.moderation.defs#revokeAccountCredentialsEvent',\n 'tools.ozone.moderation.defs#scheduleTakedownEvent',\n 'tools.ozone.moderation.defs#cancelScheduledTakedownEvent',\n])\n\nexport const getMemberRole = (role: string) => {\n if (memberRoles.has(role)) {\n return role as Member['role']\n }\n throw new InvalidRequestError('Invalid member role')\n}\n\nconst memberRoles = new Set([\n ROLEADMIN,\n ROLEMODERATOR,\n ROLETRIAGE,\n ROLEVERIFIER,\n])\n\nexport const OZONE_APPEAL_REASON_TYPE = 'tools.ozone.report.defs#reasonAppeal'\nconst APPEAL_REASON_TYPES = [REASONAPPEAL, OZONE_APPEAL_REASON_TYPE]\nexport const isAppealReport = (reasonType?: string): boolean => {\n return !!reasonType && APPEAL_REASON_TYPES.includes(reasonType)\n}\n\nexport const getSafelinkPattern = (pattern: string): SafelinkPatternType => {\n if (safelinkPatterns.has(pattern)) {\n return pattern as SafelinkPatternType\n }\n throw new InvalidRequestError('Invalid safelink pattern type')\n}\n\nexport const getSafelinkAction = (action: string): SafelinkActionType => {\n if (safelinkActions.has(action)) {\n return action as SafelinkActionType\n }\n throw new InvalidRequestError('Invalid safelink action type')\n}\n\nexport const getSafelinkReason = (reason: string): SafelinkReasonType => {\n if (safelinkReasons.has(reason)) {\n return reason as SafelinkReasonType\n }\n throw new InvalidRequestError('Invalid safelink reason type')\n}\n\nexport const getSafelinkEventType = (eventType: string): SafelinkEventType => {\n if (safelinkEventTypes.has(eventType)) {\n return eventType as SafelinkEventType\n }\n throw new InvalidRequestError('Invalid safelink event type')\n}\n\nexport type SafelinkEventType = 'addRule' | 'updateRule' | 'removeRule'\nexport type SafelinkPatternType = 'domain' | 'url'\nexport type SafelinkActionType = 'block' | 'warn' | 'whitelist'\nexport type SafelinkReasonType = 'csam' | 'spam' | 'phishing' | 'none'\n\nconst safelinkPatterns = new Set(['domain', 'url'])\nconst safelinkActions = new Set(['block', 'warn', 'whitelist'])\nconst safelinkReasons = new Set(['csam', 'spam', 'phishing', 'none'])\nconst safelinkEventTypes = new Set(['addRule', 'updateRule', 'removeRule'])\n\nexport const getScheduledActionType = (action: string): ScheduledActionType => {\n if (scheduledActionTypes.has(action)) {\n return action as ScheduledActionType\n }\n throw new InvalidRequestError('Invalid scheduled action type')\n}\n\nexport const getScheduledActionStatus = (\n status: string,\n): ScheduledActionStatus => {\n if (scheduledActionStatuses.has(status)) {\n return status as ScheduledActionStatus\n }\n throw new InvalidRequestError('Invalid scheduled action status')\n}\n\nexport type ScheduledActionType = 'takedown'\nexport type ScheduledActionStatus =\n 'pending' | 'executed' | 'cancelled' | 'failed'\n\nconst scheduledActionTypes = new Set(['takedown'])\nconst scheduledActionStatuses = new Set([\n 'pending',\n 'executed',\n 'cancelled',\n 'failed',\n])\n"]}
|
package/dist/db/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/db/index.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;
|
|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AA6BvB,KAAK,UAAU,GAAG,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;AAEjD,KAAK,SAAS,GAAG;IACf,MAAM,EAAE,MAAM,IAAI,CAAA;CACnB,CAAA"}
|
package/dist/db/index.js
CHANGED
|
@@ -2,9 +2,7 @@ import assert from 'node:assert';
|
|
|
2
2
|
import { EventEmitter } from 'node:events';
|
|
3
3
|
import { Kysely, PostgresDialect, } from 'kysely';
|
|
4
4
|
import { Migrator } from 'kysely/migration';
|
|
5
|
-
// eslint-disable-next-line import/default
|
|
6
5
|
import pg from 'pg';
|
|
7
|
-
// eslint-disable-next-line import/no-named-as-default-member
|
|
8
6
|
const { Pool: PgPool, types: pgTypes } = pg;
|
|
9
7
|
import { dbLogger } from '../logger.js';
|
|
10
8
|
import * as migrations from './migrations/index.js';
|
package/dist/db/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/db/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,OAAO,EACL,MAAM,EAIN,eAAe,GAIhB,MAAM,QAAQ,CAAA;AACf,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC3C,0CAA0C;AAC1C,OAAO,EAAE,MAAM,IAAI,CAAA;AACnB,6DAA6D;AAC7D,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,CAAA;AAG3C,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,KAAK,UAAU,MAAM,uBAAuB,CAAA;AACnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAA;AAI/D,oEAAoE;AACpE,iEAAiE;AACjE,MAAM,CAAC,MAAM,sBAAsB,GAAG,SAAS,CAAA;AAC/C,MAAM,CAAC,MAAM,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M,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAA;QACtC,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAA;IAClB,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,IAA+B;QAE/B,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;CACF;AAQD,MAAM,SAAS,GAAG,KAAK,IAAI,EAAE,GAAE,CAAC,CAAA","sourcesContent":["import assert from 'node:assert'\nimport { EventEmitter } from 'node:events'\nimport {\n Kysely,\n type KyselyPlugin,\n type PluginTransformQueryArgs,\n type PluginTransformResultArgs,\n PostgresDialect,\n type QueryResult,\n type RootOperationNode,\n type UnknownRow,\n} from 'kysely'\nimport { Migrator } from 'kysely/migration'\n// eslint-disable-next-line import/default\nimport pg from 'pg'\n// eslint-disable-next-line import/no-named-as-default-member\nconst { Pool: PgPool, types: pgTypes } = pg\ntype PgPool = InstanceType<typeof PgPool>\nimport type TypedEmitter from 'typed-emitter'\nimport { dbLogger } from '../logger.js'\nimport * as migrations from './migrations/index.js'\nimport { CtxMigrationProvider } from './migrations/provider.js'\nimport type { DatabaseSchema, DatabaseSchemaType } from './schema/index.js'\nimport type { PgOptions } from './types.js'\n\n// Stable pg advisory lock IDs used to coordinate daemon work across\n// instances. Centralized here so IDs can never silently collide.\nexport const STATS_COMPUTER_LOCK_ID = 7_239_401\nexport const MATERIALIZED_VIEW_REFRESH_LOCK_ID = 7_239_402\n\nexport class Database {\n pool: PgPool\n db: DatabaseSchema\n migrator: Migrator\n txEvt = new EventEmitter() as TxnEmitter\n destroyed = false\n isPrimary = false\n\n constructor(\n public opts: PgOptions,\n instances?: { db: DatabaseSchema; pool: PgPool },\n ) {\n // if instances are provided, use those\n if (instances) {\n this.db = instances.db\n this.pool = instances.pool\n } else {\n // else create a pool & connect\n const { schema, url } = opts\n const pool =\n opts.pool ??\n new PgPool({\n connectionString: url,\n max: opts.poolSize,\n maxUses: opts.poolMaxUses,\n idleTimeoutMillis: opts.poolIdleTimeoutMs,\n })\n\n // Select count(*) and other pg bigints as js integer\n pgTypes.setTypeParser(pgTypes.builtins.INT8, (n) => parseInt(n, 10))\n\n // Setup schema usage, primarily for test parallelism (each test suite runs in its own pg schema)\n if (schema && !/^[a-z_]+$/i.test(schema)) {\n throw new Error(\n `Postgres schema must only contain [A-Za-z_]: ${schema}`,\n )\n }\n\n pool.on('error', onPoolError)\n pool.on('connect', (client) => {\n client.on('error', onClientError)\n // Used for trigram indexes, e.g. on actor search\n client.query('SET pg_trgm.word_similarity_threshold TO .4;')\n if (schema) {\n // Shared objects such as extensions will go in the public schema\n client.query(`SET search_path TO \"${schema}\",public;`)\n }\n })\n\n this.pool = pool\n this.db = new Kysely<DatabaseSchemaType>({\n dialect: new PostgresDialect({ pool }),\n })\n }\n\n this.migrator = new Migrator({\n db: this.db,\n migrationTableSchema: opts.schema,\n provider: new CtxMigrationProvider(migrations, 'pg'),\n })\n }\n\n get schema(): string | undefined {\n return this.opts.schema\n }\n\n get isTransaction() {\n return this.db.isTransaction\n }\n\n assertTransaction() {\n assert(this.isTransaction, 'Transaction required')\n }\n\n assertNotTransaction() {\n assert(!this.isTransaction, 'Cannot be in a transaction')\n }\n\n async transaction<T>(fn: (db: Database) => Promise<T>): Promise<T> {\n const leakyTxPlugin = new LeakyTxPlugin()\n const { dbTxn, txRes } = await this.db\n .withPlugin(leakyTxPlugin)\n .transaction()\n .execute(async (txn) => {\n const dbTxn = new Database(this.opts, {\n db: txn,\n pool: this.pool,\n })\n const txRes = await fn(dbTxn)\n .catch(async (err) => {\n leakyTxPlugin.endTx()\n // ensure that all in-flight queries are flushed & the connection is open\n await dbTxn.db.getExecutor().provideConnection(noopAsync)\n throw err\n })\n .finally(() => leakyTxPlugin.endTx())\n return { dbTxn, txRes }\n })\n dbTxn?.txEvt.emit('commit')\n return txRes\n }\n\n onCommit(fn: () => void) {\n this.assertTransaction()\n this.txEvt.once('commit', fn)\n }\n\n async close(): Promise<void> {\n if (this.destroyed) return\n await this.db.destroy()\n this.destroyed = true\n }\n\n async migrateToOrThrow(migration: string) {\n if (this.schema) {\n await this.db.schema.createSchema(this.schema).ifNotExists().execute()\n }\n const { error, results } = await this.migrator.migrateTo(migration)\n if (error) {\n throw error\n }\n if (!results) {\n throw new Error('An unknown failure occurred while migrating')\n }\n return results\n }\n\n async migrateToLatestOrThrow() {\n if (this.schema) {\n await this.db.schema.createSchema(this.schema).ifNotExists().execute()\n }\n const { error, results } = await this.migrator.migrateToLatest()\n if (error) {\n throw error\n }\n if (!results) {\n throw new Error('An unknown failure occurred while migrating')\n }\n return results\n }\n}\n\nexport default Database\n\nconst onPoolError = (err: Error) => dbLogger.error({ err }, 'db pool error')\nconst onClientError = (err: Error) => dbLogger.error({ err }, 'db client error')\n\n// utils\n// -------\n\nclass LeakyTxPlugin implements KyselyPlugin {\n private txOver = false\n\n endTx() {\n this.txOver = true\n }\n\n transformQuery(args: PluginTransformQueryArgs): RootOperationNode {\n if (this.txOver) {\n throw new Error('tx already failed')\n }\n return args.node\n }\n\n async transformResult(\n args: PluginTransformResultArgs,\n ): Promise<QueryResult<UnknownRow>> {\n return args.result\n }\n}\n\ntype TxnEmitter = TypedEmitter.default<TxnEvents>\n\ntype TxnEvents = {\n commit: () => void\n}\n\nconst noopAsync = async () => {}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/db/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,OAAO,EACL,MAAM,EAIN,eAAe,GAIhB,MAAM,QAAQ,CAAA;AACf,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,EAAE,MAAM,IAAI,CAAA;AACnB,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,CAAA;AAG3C,OAAO,EAAE,QAAQ,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B,CAAC,CAAA;AAEhF,QAAQ;AACR,UAAU;AAEV,MAAM,aAAa;IAAnB;QACU,WAAM,GAAG,KAAK,CAAA;IAkBxB,CAAC;IAhBC,KAAK;QACH,IAAI,CAAC,MAAM,GAAG,IAAI,CAAA;IACpB,CAAC;IAED,cAAc,CAAC,IAA8B;QAC3C,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAA;QACtC,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAA;IAClB,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,IAA+B;QAE/B,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;CACF;AAQD,MAAM,SAAS,GAAG,KAAK,IAAI,EAAE,GAAE,CAAC,CAAA","sourcesContent":["import assert from 'node:assert'\nimport { EventEmitter } from 'node:events'\nimport {\n Kysely,\n type KyselyPlugin,\n type PluginTransformQueryArgs,\n type PluginTransformResultArgs,\n PostgresDialect,\n type QueryResult,\n type RootOperationNode,\n type UnknownRow,\n} from 'kysely'\nimport { Migrator } from 'kysely/migration'\nimport pg from 'pg'\nconst { Pool: PgPool, types: pgTypes } = pg\ntype PgPool = InstanceType<typeof PgPool>\nimport type TypedEmitter from 'typed-emitter'\nimport { dbLogger } from '../logger.js'\nimport * as migrations from './migrations/index.js'\nimport { CtxMigrationProvider } from './migrations/provider.js'\nimport type { DatabaseSchema, DatabaseSchemaType } from './schema/index.js'\nimport type { PgOptions } from './types.js'\n\n// Stable pg advisory lock IDs used to coordinate daemon work across\n// instances. Centralized here so IDs can never silently collide.\nexport const STATS_COMPUTER_LOCK_ID = 7_239_401\nexport const MATERIALIZED_VIEW_REFRESH_LOCK_ID = 7_239_402\n\nexport class Database {\n pool: PgPool\n db: DatabaseSchema\n migrator: Migrator\n txEvt = new EventEmitter() as TxnEmitter\n destroyed = false\n isPrimary = false\n\n constructor(\n public opts: PgOptions,\n instances?: { db: DatabaseSchema; pool: PgPool },\n ) {\n // if instances are provided, use those\n if (instances) {\n this.db = instances.db\n this.pool = instances.pool\n } else {\n // else create a pool & connect\n const { schema, url } = opts\n const pool =\n opts.pool ??\n new PgPool({\n connectionString: url,\n max: opts.poolSize,\n maxUses: opts.poolMaxUses,\n idleTimeoutMillis: opts.poolIdleTimeoutMs,\n })\n\n // Select count(*) and other pg bigints as js integer\n pgTypes.setTypeParser(pgTypes.builtins.INT8, (n) => parseInt(n, 10))\n\n // Setup schema usage, primarily for test parallelism (each test suite runs in its own pg schema)\n if (schema && !/^[a-z_]+$/i.test(schema)) {\n throw new Error(\n `Postgres schema must only contain [A-Za-z_]: ${schema}`,\n )\n }\n\n pool.on('error', onPoolError)\n pool.on('connect', (client) => {\n client.on('error', onClientError)\n // Used for trigram indexes, e.g. on actor search\n client.query('SET pg_trgm.word_similarity_threshold TO .4;')\n if (schema) {\n // Shared objects such as extensions will go in the public schema\n client.query(`SET search_path TO \"${schema}\",public;`)\n }\n })\n\n this.pool = pool\n this.db = new Kysely<DatabaseSchemaType>({\n dialect: new PostgresDialect({ pool }),\n })\n }\n\n this.migrator = new Migrator({\n db: this.db,\n migrationTableSchema: opts.schema,\n provider: new CtxMigrationProvider(migrations, 'pg'),\n })\n }\n\n get schema(): string | undefined {\n return this.opts.schema\n }\n\n get isTransaction() {\n return this.db.isTransaction\n }\n\n assertTransaction() {\n assert(this.isTransaction, 'Transaction required')\n }\n\n assertNotTransaction() {\n assert(!this.isTransaction, 'Cannot be in a transaction')\n }\n\n async transaction<T>(fn: (db: Database) => Promise<T>): Promise<T> {\n const leakyTxPlugin = new LeakyTxPlugin()\n const { dbTxn, txRes } = await this.db\n .withPlugin(leakyTxPlugin)\n .transaction()\n .execute(async (txn) => {\n const dbTxn = new Database(this.opts, {\n db: txn,\n pool: this.pool,\n })\n const txRes = await fn(dbTxn)\n .catch(async (err) => {\n leakyTxPlugin.endTx()\n // ensure that all in-flight queries are flushed & the connection is open\n await dbTxn.db.getExecutor().provideConnection(noopAsync)\n throw err\n })\n .finally(() => leakyTxPlugin.endTx())\n return { dbTxn, txRes }\n })\n dbTxn?.txEvt.emit('commit')\n return txRes\n }\n\n onCommit(fn: () => void) {\n this.assertTransaction()\n this.txEvt.once('commit', fn)\n }\n\n async close(): Promise<void> {\n if (this.destroyed) return\n await this.db.destroy()\n this.destroyed = true\n }\n\n async migrateToOrThrow(migration: string) {\n if (this.schema) {\n await this.db.schema.createSchema(this.schema).ifNotExists().execute()\n }\n const { error, results } = await this.migrator.migrateTo(migration)\n if (error) {\n throw error\n }\n if (!results) {\n throw new Error('An unknown failure occurred while migrating')\n }\n return results\n }\n\n async migrateToLatestOrThrow() {\n if (this.schema) {\n await this.db.schema.createSchema(this.schema).ifNotExists().execute()\n }\n const { error, results } = await this.migrator.migrateToLatest()\n if (error) {\n throw error\n }\n if (!results) {\n throw new Error('An unknown failure occurred while migrating')\n }\n return results\n }\n}\n\nexport default Database\n\nconst onPoolError = (err: Error) => dbLogger.error({ err }, 'db pool error')\nconst onClientError = (err: Error) => dbLogger.error({ err }, 'db client error')\n\n// utils\n// -------\n\nclass LeakyTxPlugin implements KyselyPlugin {\n private txOver = false\n\n endTx() {\n this.txOver = true\n }\n\n transformQuery(args: PluginTransformQueryArgs): RootOperationNode {\n if (this.txOver) {\n throw new Error('tx already failed')\n }\n return args.node\n }\n\n async transformResult(\n args: PluginTransformResultArgs,\n ): Promise<QueryResult<UnknownRow>> {\n return args.result\n }\n}\n\ntype TxnEmitter = TypedEmitter.default<TxnEvents>\n\ntype TxnEvents = {\n commit: () => void\n}\n\nconst noopAsync = async () => {}\n"]}
|
package/dist/db/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/db/types.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK,kBAAkB,EAExB,MAAM,QAAQ,CAAA;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/db/types.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK,kBAAkB,EAExB,MAAM,QAAQ,CAAA;AACf,OAAO,KAAK,EAAE,MAAM,IAAI,CAAA;AACxB,KAAK,MAAM,GAAG,EAAE,CAAC,IAAI,CAAA;AAErB,MAAM,MAAM,KAAK,GACf,UAAU,CAAC,OAAO,CAAC,GAAG,UAAU,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAA;AAEjE,MAAM,MAAM,KAAK,GAAG,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;AAErD,MAAM,MAAM,SAAS,GAAG;IACtB,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAA;CAC3B,CAAA;AAED,eAAO,MAAM,KAAK,GAAI,CAAC,OAAO,CAAC,kBAG9B,CAAA"}
|
package/dist/db/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/db/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,GAAG,GACJ,MAAM,QAAQ,CAAA;
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/db/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,GAAG,GACJ,MAAM,QAAQ,CAAA;AAkBf,MAAM,CAAC,MAAM,KAAK,GAAG,CAAI,GAAM,EAAE,EAAE;IACjC,IAAI,GAAG,KAAK,IAAI;QAAE,OAAO,GAAG,CAAG,MAAM,CAAA;IACrC,OAAO,GAAG,CAAG,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAA;AAC9C,CAAC,CAAA","sourcesContent":["import {\n type DynamicModule,\n type RawBuilder,\n type SelectQueryBuilder,\n sql,\n} from 'kysely'\nimport type pg from 'pg'\ntype PgPool = pg.Pool\n\nexport type DbRef =\n RawBuilder<unknown> | ReturnType<DynamicModule<unknown>['ref']>\n\nexport type AnyQb = SelectQueryBuilder<any, any, any>\n\nexport type PgOptions = {\n url: string\n pool?: PgPool\n schema?: string\n poolSize?: number\n poolMaxUses?: number\n poolIdleTimeoutMs?: number\n}\n\nexport const jsonb = <T>(val: T) => {\n if (val === null) return sql<T>`null`\n return sql<T>`${JSON.stringify(val)}::jsonb`\n}\n"]}
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AAIjC,OAAO,OAAO,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAA;AAIjC,OAAO,OAAO,MAAM,SAAS,CAAA;AAI7B,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAClE,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAMjE,cAAc,mBAAmB,CAAA;AACjC,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAC9D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AACxC,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAC3E,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,qBAAa,YAAY;IAChB,GAAG,EAAE,UAAU,CAAA;IACf,GAAG,EAAE,OAAO,CAAC,WAAW,CAAA;IACxB,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,CAAA;IAC3B,OAAO,CAAC,UAAU,CAAC,CAAgB;IACnC,OAAO,CAAC,eAAe,CAAC,CAAgB;IAExC,YAAY,IAAI,EAAE;QAAE,GAAG,EAAE,UAAU,CAAC;QAAC,GAAG,EAAE,OAAO,CAAC,WAAW,CAAA;KAAE,EAG9D;IAED,OAAa,MAAM,CACjB,GAAG,EAAE,WAAW,EAChB,OAAO,EAAE,YAAY,EACrB,SAAS,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,GACrC,OAAO,CAAC,YAAY,CAAC,CA0BvB;IAEK,kBAAkB,kBA4BvB;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAgClC;IAEK,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAkB7B;CACF;eAEc,YAAY"}
|
package/dist/index.js
CHANGED
|
@@ -2,8 +2,7 @@ import events from 'node:events';
|
|
|
2
2
|
import compression from 'compression';
|
|
3
3
|
import cors from 'cors';
|
|
4
4
|
import express from 'express';
|
|
5
|
-
|
|
6
|
-
import httpTerminator from 'http-terminator';
|
|
5
|
+
import { createHttpTerminator } from 'http-terminator';
|
|
7
6
|
import { DAY, SECOND } from '@atproto/common';
|
|
8
7
|
import API, { health, wellKnown } from './api/index.js';
|
|
9
8
|
import { AppContext } from './context.js';
|
|
@@ -84,7 +83,7 @@ export class OzoneService {
|
|
|
84
83
|
const server = this.app.listen(this.ctx.cfg.service.port);
|
|
85
84
|
this.server = server;
|
|
86
85
|
server.keepAliveTimeout = 90000;
|
|
87
|
-
this.terminator =
|
|
86
|
+
this.terminator = createHttpTerminator({ server });
|
|
88
87
|
await events.once(server, 'listening');
|
|
89
88
|
const { port } = server.address();
|
|
90
89
|
this.ctx.assignPort(port);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAGhC,OAAO,WAAW,MAAM,aAAa,CAAA;AACrC,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,OAAO,MAAM,SAAS,CAAA;AAC7B,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAGhC,OAAO,WAAW,MAAM,aAAa,CAAA;AACrC,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,OAAO,MAAM,SAAS,CAAA;AAC7B,OAAO,EAAuB,oBAAoB,EAAE,MAAM,iBAAiB,CAAA;AAC3E,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAC7C,OAAO,GAAG,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAEvD,OAAO,EAAE,UAAU,EAA0B,MAAM,cAAc,CAAA;AAEjE,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAExD,cAAc,mBAAmB,CAAA;AACjC,OAAO,EAAyB,MAAM,wBAAwB,CAAA;AAC9D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AACxC,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAC3E,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,MAAM,OAAO,YAAY;IAOvB,YAAY,IAAmD;QAC7D,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,G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AE,SAAS,EAAE,CAAA;QACpC,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC;gBACH,MAAM,IAAI,CAAC,GAAG,CAAC,eAAe,CAAC,OAAO,EAAE,CAAA;YAC1C,CAAC;oBAAS,CAAC;gBACT,IAAI,CAAC;oBACH,MAAM,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,OAAO,EAAE,CAAA;gBACpC,CAAC;wBAAS,CAAC;oBACT,MAAM,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,CAAA;gBAC3B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAED,eAAe,YAAY,CAAA","sourcesContent":["import events from 'node:events'\nimport type http from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport compression from 'compression'\nimport cors from 'cors'\nimport express from 'express'\nimport { type HttpTerminator, createHttpTerminator } from 'http-terminator'\nimport { DAY, SECOND } from '@atproto/common'\nimport API, { health, wellKnown } from './api/index.js'\nimport type { OzoneConfig, OzoneSecrets } from './config/index.js'\nimport { AppContext, type AppContextOptions } from './context.js'\nimport type { Member } from './db/schema/member.js'\nimport * as error from './error.js'\nimport { createServer } from './lexicon/index.js'\nimport { dbLogger, loggerMiddleware } from './logger.js'\n\nexport * from './config/index.js'\nexport { type ImageInvalidator } from './image-invalidator.js'\nexport { Database } from './db/index.js'\nexport { EventPusher, EventReverser, OzoneDaemon } from './daemon/index.js'\nexport { AppContext } from './context.js'\nexport { httpLogger } from './logger.js'\n\nexport class OzoneService {\n public ctx: AppContext\n public app: express.Application\n public server?: http.Server\n private terminator?: HttpTerminator\n private dbStatsInterval?: NodeJS.Timeout\n\n constructor(opts: { ctx: AppContext; app: express.Application }) {\n this.ctx = opts.ctx\n this.app = opts.app\n }\n\n static async create(\n cfg: OzoneConfig,\n secrets: OzoneSecrets,\n overrides?: Partial<AppContextOptions>,\n ): Promise<OzoneService> {\n const app = express()\n app.set('trust proxy', true)\n app.use(cors({ maxAge: DAY / SECOND }))\n app.use(loggerMiddleware)\n app.use(compression())\n\n const ctx = await AppContext.fromConfig(cfg, secrets, overrides)\n\n let server = createServer({\n validateResponse: false,\n payload: {\n jsonLimit: 100 * 1024, // 100kb\n textLimit: 100 * 1024, // 100kb\n blobLimit: 5 * 1024 * 1024, // 5mb\n },\n })\n\n server = API(server, ctx)\n\n app.use(health.createRouter(ctx))\n app.use(wellKnown.createRouter(ctx))\n app.use(server.xrpc.router)\n app.use(error.handler)\n\n return new OzoneService({ ctx, app })\n }\n\n async seedInitialMembers() {\n const members: Array<{ role: Member['role']; did: string }> = []\n this.ctx.cfg.access.admins.forEach((did) =>\n members.push({\n role: 'tools.ozone.team.defs#roleAdmin',\n did,\n }),\n )\n this.ctx.cfg.access.triage.forEach((did) =>\n members.push({\n role: 'tools.ozone.team.defs#roleTriage',\n did,\n }),\n )\n this.ctx.cfg.access.moderators.forEach((did) =>\n members.push({\n role: 'tools.ozone.team.defs#roleModerator',\n did,\n }),\n )\n\n for (const member of members) {\n const service = this.ctx.teamService(this.ctx.db)\n await service.upsert({\n ...member,\n lastUpdatedBy: this.ctx.cfg.service.did,\n })\n }\n }\n\n async start(): Promise<http.Server> {\n if (this.dbStatsInterval) {\n throw new Error(`${this.constructor.name} already started`)\n }\n\n // Any moderator that are configured via env var may not exist in the database\n // so we need to sync them from env var to the database\n await this.seedInitialMembers()\n\n this.dbStatsInterval = setInterval(() => {\n dbLogger.info(\n {\n idleCount: this.ctx.db.pool.idleCount,\n totalCount: this.ctx.db.pool.totalCount,\n waitingCount: this.ctx.db.pool.waitingCount,\n },\n 'db pool stats',\n )\n dbLogger.info(\n this.ctx.backgroundQueue.getStats(),\n 'background queue stats',\n )\n }, 10000)\n await this.ctx.sequencer.start()\n const server = this.app.listen(this.ctx.cfg.service.port)\n this.server = server\n server.keepAliveTimeout = 90000\n this.terminator = createHttpTerminator({ server })\n await events.once(server, 'listening')\n const { port } = server.address() as AddressInfo\n this.ctx.assignPort(port)\n return server\n }\n\n async destroy(): Promise<void> {\n clearInterval(this.dbStatsInterval)\n this.dbStatsInterval = undefined\n\n // @TODO Use a disposable stack when Node24 becomes the min supported version\n try {\n await this.terminator?.terminate()\n } finally {\n try {\n await this.ctx.backgroundQueue.destroy()\n } finally {\n try {\n await this.ctx.sequencer.destroy()\n } finally {\n await this.ctx.db.close()\n }\n }\n }\n }\n}\n\nexport default OzoneService\n"]}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { WebSocketKeepAlive } from '@atproto/ws-client';
|
|
2
1
|
type JetstreamRecord = Record<string, unknown>;
|
|
3
2
|
type OnCreateCallback<T extends JetstreamRecord> = (e: CommitCreateEvent<T>) => Promise<void>;
|
|
4
3
|
export type JetstreamOptions = {
|
|
@@ -42,7 +41,7 @@ export interface CommitDeleteEvent extends EventBase {
|
|
|
42
41
|
} & CommitBase;
|
|
43
42
|
}
|
|
44
43
|
export declare class Jetstream {
|
|
45
|
-
|
|
44
|
+
#private;
|
|
46
45
|
url: URL;
|
|
47
46
|
/** The current cursor. */
|
|
48
47
|
cursor?: number;
|
|
@@ -52,7 +51,9 @@ export declare class Jetstream {
|
|
|
52
51
|
onDelete?: Record<string, (e: CommitDeleteEvent) => Promise<void>>;
|
|
53
52
|
}): Promise<void>;
|
|
54
53
|
/**
|
|
55
|
-
*
|
|
54
|
+
* Ends the stream and closes the connection, resolving once it has closed: the
|
|
55
|
+
* abort tears the socket down, and the stream's own unwind is what tells us
|
|
56
|
+
* that finished. A close() before start() is an inert no-op.
|
|
56
57
|
*/
|
|
57
58
|
close(): Promise<void>;
|
|
58
59
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/jetstream/service.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/jetstream/service.ts"],"names":[],"mappings":"AAEA,KAAK,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAC9C,KAA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ChD,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;KACnE,iBAQA;IAqCD;;;;OAIG;IACG,KAAK,kBAGV;CACF"}
|
|
@@ -1,5 +1,14 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CloseCode, CloseError, websocket } from '@atproto/ws-client';
|
|
2
|
+
// The abort reason close() uses. Any abort closes the socket politely; a
|
|
3
|
+
// `CloseError` rather than a bare sentinel because the reason picks the close
|
|
4
|
+
// code sent to the peer — a CloseError names its own (1000 here), anything else
|
|
5
|
+
// defaults to 1000 anyway, so this spells the intent out. Its identity is also
|
|
6
|
+
// how start() tells our own shutdown from a real failure.
|
|
7
|
+
const STOPPED = new CloseError(CloseCode.Normal, 'jetstream stopped', true);
|
|
2
8
|
export class Jetstream {
|
|
9
|
+
#abort = new AbortController();
|
|
10
|
+
/** The `start()` run in flight, so `close()` can await its unwind. */
|
|
11
|
+
#running;
|
|
3
12
|
constructor(opts) {
|
|
4
13
|
this.url = new URL(opts.endpoint);
|
|
5
14
|
opts.wantedCollections?.forEach((collection) => {
|
|
@@ -12,34 +21,49 @@ export class Jetstream {
|
|
|
12
21
|
this.cursor = opts.cursor;
|
|
13
22
|
}
|
|
14
23
|
async start(options) {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
24
|
+
// Retained so close() resolves only once the stream has unwound, and with it
|
|
25
|
+
// the connection. Swallows its own outcome: a caller awaiting close() is
|
|
26
|
+
// asking about shutdown, not about how the stream ended — that's what the
|
|
27
|
+
// promise start() returns is for.
|
|
28
|
+
const running = this.#consume(options);
|
|
29
|
+
this.#running = running.catch(() => { });
|
|
30
|
+
return running;
|
|
31
|
+
}
|
|
32
|
+
async #consume(options) {
|
|
33
|
+
const ws = websocket(() => {
|
|
34
|
+
if (this.cursor)
|
|
35
|
+
this.url.searchParams.set('cursor', this.cursor.toString());
|
|
36
|
+
return this.url.toString();
|
|
37
|
+
}, { dataMode: 'text', signal: this.#abort.signal });
|
|
38
|
+
try {
|
|
39
|
+
for await (const message of ws) {
|
|
40
|
+
const parsedMessage = JSON.parse(message);
|
|
41
|
+
if (parsedMessage.kind === 'commit') {
|
|
42
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- `record` is used via `typeof record` below
|
|
43
|
+
const { collection, operation, record } = parsedMessage.commit || {};
|
|
44
|
+
if (operation === 'create') {
|
|
45
|
+
options.onCreate?.[collection]?.(parsedMessage);
|
|
46
|
+
}
|
|
47
|
+
else if (operation === 'delete') {
|
|
48
|
+
options.onDelete?.[collection]?.(parsedMessage);
|
|
49
|
+
}
|
|
32
50
|
}
|
|
33
51
|
}
|
|
34
52
|
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
// Our own close() is not a failure; anything else is.
|
|
55
|
+
if (err !== STOPPED)
|
|
56
|
+
throw err;
|
|
57
|
+
}
|
|
35
58
|
}
|
|
36
59
|
/**
|
|
37
|
-
*
|
|
60
|
+
* Ends the stream and closes the connection, resolving once it has closed: the
|
|
61
|
+
* abort tears the socket down, and the stream's own unwind is what tells us
|
|
62
|
+
* that finished. A close() before start() is an inert no-op.
|
|
38
63
|
*/
|
|
39
64
|
async close() {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
this.ws?.ws?.close();
|
|
65
|
+
this.#abort.abort(STOPPED);
|
|
66
|
+
await this.#running;
|
|
43
67
|
}
|
|
44
68
|
}
|
|
45
69
|
//# sourceMappingURL=service.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/jetstream/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|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CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;QAC1B,MAAM,IAAI,CAAC,QAAQ,CAAA;IACrB,CAAC;CACF","sourcesContent":["import { CloseCode, CloseError, websocket } from '@atproto/ws-client'\n\ntype JetstreamRecord = Record<string, unknown>\ntype OnCreateCallback<T extends JetstreamRecord> = (\n e: CommitCreateEvent<T>,\n) => Promise<void>\n\nexport type JetstreamOptions = {\n endpoint: string\n /**\n * The record collections that you want to receive updates for.\n * Leave this empty to receive updates for all record collections.\n */\n wantedCollections?: string[]\n /**\n * The DIDs that you want to receive updates for.\n * Leave this empty to receive updates for all DIDs.\n */\n wantedDids?: string[]\n\n /**\n * The Unix timestamp in microseconds that you want to receive updates from.\n */\n cursor?: number\n}\nexport type EventBase = {\n did: string\n time_us: number\n // @TODO: Limited to just commit events for now\n kind: 'commit'\n}\nexport type CommitBase = {\n collection: string\n rkey: string\n cid: string\n}\nexport interface CommitCreateEvent<\n RecordType extends JetstreamRecord,\n> extends EventBase {\n kind: 'commit'\n commit: {\n operation: 'create'\n record: RecordType\n } & CommitBase\n}\n\nexport interface CommitDeleteEvent extends EventBase {\n kind: 'commit'\n commit: {\n operation: 'delete'\n } & CommitBase\n}\n\n// The abort reason close() uses. Any abort closes the socket politely; a\n// `CloseError` rather than a bare sentinel because the reason picks the close\n// code sent to the peer — a CloseError names its own (1000 here), anything else\n// defaults to 1000 anyway, so this spells the intent out. Its identity is also\n// how start() tells our own shutdown from a real failure.\nconst STOPPED = new CloseError(CloseCode.Normal, 'jetstream stopped', true)\n\nexport class Jetstream {\n public url: URL\n readonly #abort = new AbortController()\n /** The `start()` run in flight, so `close()` can await its unwind. */\n #running?: Promise<void>\n /** The current cursor. */\n public cursor?: number\n\n constructor(opts: JetstreamOptions) {\n this.url = new URL(opts.endpoint)\n opts.wantedCollections?.forEach((collection) => {\n this.url.searchParams.append('wantedCollections', collection)\n })\n opts.wantedDids?.forEach((did) => {\n this.url.searchParams.append('wantedDids', did)\n })\n if (opts.cursor) this.cursor = opts.cursor\n }\n\n async start(options: {\n onCreate?: Record<string, OnCreateCallback<any>>\n onDelete?: Record<string, (e: CommitDeleteEvent) => Promise<void>>\n }) {\n // Retained so close() resolves only once the stream has unwound, and with it\n // the connection. Swallows its own outcome: a caller awaiting close() is\n // asking about shutdown, not about how the stream ended — that's what the\n // promise start() returns is for.\n const running = this.#consume(options)\n this.#running = running.catch(() => {})\n return running\n }\n\n async #consume(options: {\n onCreate?: Record<string, OnCreateCallback<any>>\n onDelete?: Record<string, (e: CommitDeleteEvent) => Promise<void>>\n }) {\n const ws = websocket(\n () => {\n if (this.cursor)\n this.url.searchParams.set('cursor', this.cursor.toString())\n return this.url.toString()\n },\n { dataMode: 'text', signal: this.#abort.signal },\n )\n\n try {\n for await (const message of ws) {\n const parsedMessage = JSON.parse(message)\n if (parsedMessage.kind === 'commit') {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- `record` is used via `typeof record` below\n const { collection, operation, record } = parsedMessage.commit || {}\n\n if (operation === 'create') {\n options.onCreate?.[collection]?.(\n parsedMessage as CommitCreateEvent<typeof record>,\n )\n } else if (operation === 'delete') {\n options.onDelete?.[collection]?.(parsedMessage as CommitDeleteEvent)\n }\n }\n }\n } catch (err) {\n // Our own close() is not a failure; anything else is.\n if (err !== STOPPED) throw err\n }\n }\n\n /**\n * Ends the stream and closes the connection, resolving once it has closed: the\n * abort tears the socket down, and the stream's own unwind is what tells us\n * that finished. A close() before start() is an inert no-op.\n */\n async close() {\n this.#abort.abort(STOPPED)\n await this.#running\n }\n}\n"]}
|