A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(api): keep operators' wall revision history
Hampus8eea43ee0cda
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallHistory.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallHistory.tsnew file mode 100644index 000000000..19ade2621--- /dev/null+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallHistory.ts@@ -0,0 +1,155 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {UserID} from '@app/api/BrandedTypes';+import type {+ OperatorPassWallDecisionRow,+ OperatorPassWallEventRow,+ OperatorPassWallRevisionRow,+ OperatorPassWallRevisionStatus,+} from '@app/api/database/types/OperatorPassTypes';+import {getOperatorPassWallTier} from '@app/api/operator_pass/OperatorPassPrices';+import {OPERATOR_PASS_WALL_FALLBACK_NAME} from '@app/api/operator_pass/OperatorPassWallConstants';+import {compareSnowflakes} from '@fluxer/snowflake/src/SnowflakeComparison';++type WallHistoryItem =+ | {kind: 'revision'; at: bigint; revision: OperatorPassWallRevisionRow}+ | {kind: 'decision'; at: bigint; decision: OperatorPassWallDecisionRow};++export function revisionStatuses(+ revisions: ReadonlyArray<OperatorPassWallRevisionRow>,+ decisions: ReadonlyArray<OperatorPassWallDecisionRow>,+): Map<bigint, {status: OperatorPassWallRevisionStatus; decision: OperatorPassWallDecisionRow | null}> {+ const result = new Map<+ bigint,+ {status: OperatorPassWallRevisionStatus; decision: OperatorPassWallDecisionRow | null}+ >(revisions.map((revision) => [revision.revision_id, {status: 'pending', decision: null}]));+ let live: bigint | null = null;+ const timeline = [+ ...revisions.map((revision): WallHistoryItem => ({kind: 'revision', at: revision.revision_id, revision})),+ ...decisions.map((decision): WallHistoryItem => ({kind: 'decision', at: decision.decision_id, decision})),+ ].sort((left, right) => compareSnowflakes(left.at, right.at));+ for (const item of timeline) {+ if (item.kind === 'revision') {+ for (const [id, value] of result) {+ if (value.status === 'pending' && id < item.revision.revision_id) {+ result.set(id, {status: 'superseded', decision: null});+ }+ }+ continue;+ }+ const decision = item.decision;+ const target = decision.revision_id ?? null;+ if (decision.kind === 'force_fallback') {+ if (live != null) {+ result.set(live, {status: 'reverted', decision});+ live = null;+ }+ continue;+ }+ if (target == null) continue;+ switch (decision.kind) {+ case 'approve':+ result.set(target, {status: 'approved', decision});+ live = target;+ break;+ case 'decline':+ result.set(target, {status: 'declined', decision});+ break;+ case 'revert':+ if (live != null && live !== target) {+ result.set(live, {status: 'reverted', decision});+ }+ live = target;+ break;+ }+ }+ return result;+}++export interface OperatorPassWallAsOfEntry {+ userId: UserID;+ name: string;+ avatar: string | null;+ count: number;+ tier: number;+ firstPassAt: Date;+ deleted: boolean;+}++export function reconstructOperatorPassWallEntry(params: {+ userId: UserID;+ at: Date;+ username: string | null;+ revisions: ReadonlyArray<OperatorPassWallRevisionRow>;+ decisions: ReadonlyArray<OperatorPassWallDecisionRow>;+ events: ReadonlyArray<OperatorPassWallEventRow>;+ tierMinimums: ReadonlyArray<number>;+ userDeleted?: boolean;+}): OperatorPassWallAsOfEntry | null {+ const atMs = params.at.getTime();+ const events = params.events.filter((event) => event.occurred_at.getTime() <= atMs);+ let count = 0;+ let firstPassAt: Date | null = null;+ for (const event of events.filter((event) => event.kind === 'count_changed')) {+ const next = event.pass_count ?? 0;+ if (count === 0 && next > 0) firstPassAt = event.occurred_at;+ if (next === 0) firstPassAt = null;+ count = next;+ }+ const listing = events.findLast(+ (event) => event.kind === 'listed' || event.kind === 'changed' || event.kind === 'opted_out',+ );+ if (count === 0 || listing == null || listing.kind === 'opted_out' || !firstPassAt) {+ return null;+ }+ const deleted =+ params.userDeleted === true ||+ params.events.some((event) => event.kind === 'taken_down' && event.cause === 'deletion');+ const revisions = params.revisions.filter((revision) => revision.created_at.getTime() <= atMs);+ const decisions = params.decisions.filter((decision) => decision.decided_at.getTime() <= atMs);+ let liveId: bigint | null = null;+ let hidden = false;+ let usernameDeclined = false;+ for (const decision of decisions) {+ switch (decision.kind) {+ case 'approve':+ liveId = decision.revision_id ?? liveId;+ usernameDeclined = false;+ break;+ case 'revert':+ liveId = decision.revision_id ?? liveId;+ break;+ case 'force_fallback':+ liveId = null;+ break;+ case 'hide':+ hidden = true;+ break;+ case 'unhide':+ hidden = false;+ break;+ }+ usernameDeclined = decision.username_declined === true || usernameDeclined;+ }+ if (hidden) {+ return null;+ }+ const live = liveId != null ? revisions.find((revision) => revision.revision_id === liveId) : undefined;+ const tier = getOperatorPassWallTier(count, params.tierMinimums);+ if (deleted || live?.name === '') {+ return {+ userId: params.userId,+ name: OPERATOR_PASS_WALL_FALLBACK_NAME,+ avatar: null,+ count,+ tier,+ firstPassAt,+ deleted: true,+ };+ }+ let name = live?.name;+ if (name == null) {+ name = usernameDeclined || !params.username ? OPERATOR_PASS_WALL_FALLBACK_NAME : params.username;+ }+ return {userId: params.userId, name, avatar: live?.avatar ?? null, count, tier, firstPassAt, deleted: false};+}diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallHistoryService.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallHistoryService.tsnew file mode 100644index 000000000..fb4dd4c74--- /dev/null+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallHistoryService.ts@@ -0,0 +1,115 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {UserID} from '@app/api/BrandedTypes';+import {Config} from '@app/api/Config';+import type {+ OperatorPassWallDecisionRow,+ OperatorPassWallEntryRow,+ OperatorPassWallEventRow,+ OperatorPassWallRevisionRow,+ OperatorPassWallRevisionStatus,+} from '@app/api/database/types/OperatorPassTypes';+import type {OperatorPassRepository} from '@app/api/operator_pass/OperatorPassRepository';+import {OPERATOR_PASS_WALL_FALLBACK_NAME} from '@app/api/operator_pass/OperatorPassWallConstants';+import type {OperatorPassWallEntryStore} from '@app/api/operator_pass/OperatorPassWallEntryStore';+import {+ type OperatorPassWallAsOfEntry,+ reconstructOperatorPassWallEntry,+ revisionStatuses,+} from '@app/api/operator_pass/OperatorPassWallHistory';+import type {UserRepository} from '@app/api/user/repositories/UserRepository';+import {UserFlags} from '@fluxer/constants/src/UserConstants';+import {compareSnowflakes} from '@fluxer/snowflake/src/SnowflakeComparison';++const AS_OF_BATCH_SIZE = 25;++interface OperatorPassWallTimelineRevision {+ revision: OperatorPassWallRevisionRow;+ status: OperatorPassWallRevisionStatus;+ decision: OperatorPassWallDecisionRow | null;+}++interface OperatorPassWallTimeline {+ entry: OperatorPassWallEntryRow | null;+ revisions: Array<OperatorPassWallTimelineRevision>;+ decisions: Array<OperatorPassWallDecisionRow>;+ events: Array<OperatorPassWallEventRow>;+}++export class OperatorPassWallHistoryService {+ constructor(+ private readonly repository: OperatorPassRepository,+ private readonly userRepository: UserRepository,+ private readonly entries: OperatorPassWallEntryStore,+ ) {}++ async timeline(userId: UserID): Promise<OperatorPassWallTimeline> {+ const [entry, revisions, decisions, events] = await Promise.all([+ this.repository.findWallEntry(userId),+ this.repository.listWallRevisions(userId),+ this.repository.listWallDecisions(userId),+ this.repository.listWallEvents(userId),+ ]);+ const statuses = revisionStatuses(revisions, decisions);+ return {+ entry,+ revisions: revisions.map((revision) => ({+ revision,+ status: statuses.get(revision.revision_id)?.status ?? 'pending',+ decision: statuses.get(revision.revision_id)?.decision ?? null,+ })),+ decisions,+ events,+ };+ }++ async wallAsOf(at: Date): Promise<Array<OperatorPassWallAsOfEntry>> {+ const result: Array<OperatorPassWallAsOfEntry> = [];+ const entries = await this.entries.scanAll();+ for (let index = 0; index < entries.length; index += AS_OF_BATCH_SIZE) {+ const items = await Promise.all(+ entries.slice(index, index + AS_OF_BATCH_SIZE).map(async (entry) => {+ const [revisions, decisions, events, user] = await Promise.all([+ this.repository.listWallRevisions(entry.user_id),+ this.repository.listWallDecisions(entry.user_id),+ this.repository.listWallEvents(entry.user_id),+ this.userRepository.findUnique(entry.user_id),+ ]);+ return reconstructOperatorPassWallEntry({+ userId: entry.user_id,+ at,+ username: user?.username ?? null,+ revisions,+ decisions,+ events,+ tierMinimums: Config.operatorPass.wallTierMinimums,+ userDeleted: !user || (user.flags & UserFlags.DELETED) !== 0n,+ });+ }),+ );+ for (const item of items) {+ if (item) result.push(item);+ }+ }+ for (const tombstone of await this.repository.listWallTombstones()) {+ const tokenId = tombstone.token_ as UserID;+ const item = reconstructOperatorPassWallEntry({+ userId: tokenId,+ at,+ username: null,+ revisions: [],+ decisions: [],+ events: await this.repository.listWallEvents(tokenId),+ tierMinimums: Config.operatorPass.wallTierMinimums,+ });+ if (item) result.push({...item, name: OPERATOR_PASS_WALL_FALLBACK_NAME, avatar: null, deleted: true});+ }+ result.sort(+ (left, right) =>+ right.tier - left.tier ||+ left.firstPassAt.getTime() - right.firstPassAt.getTime() ||+ compareSnowflakes(left.userId, right.userId),+ );+ return result;+ }+}