refactor (backend): port publishBroadcastStream to backend-rs

This commit is contained in:
naskya 2024-04-26 13:30:13 +09:00
parent 0caba566e6
commit d40db1ee7e
No known key found for this signature in database
GPG key ID: 712D413B3A9FED5C
7 changed files with 71 additions and 25 deletions

View file

@ -1162,6 +1162,18 @@ export enum ChatIndexEvent {
Read = 'read' Read = 'read'
} }
export function publishToChatIndexStream(userId: string, kind: ChatIndexEvent, object: any): void export function publishToChatIndexStream(userId: string, kind: ChatIndexEvent, object: any): void
export interface PackedEmoji {
id: string
aliases: Array<string>
name: string
category: string | null
host: string | null
url: string
license: string | null
width: number | null
height: number | null
}
export function publishToBroadcastStream(emoji: PackedEmoji): void
export interface AbuseUserReportLike { export interface AbuseUserReportLike {
id: string id: string
targetUserId: string targetUserId: string

View file

@ -310,7 +310,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`) throw new Error(`Failed to load native binding`)
} }
const { SECOND, MINUTE, HOUR, DAY, USER_ONLINE_THRESHOLD, USER_ACTIVE_THRESHOLD, FILE_TYPE_BROWSERSAFE, loadEnv, loadConfig, stringToAcct, acctToString, addNoteToAntenna, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getImageSizeFromUrl, getNoteSummary, toMastodonId, fromMastodonId, fetchMeta, metaToPugArgs, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, AntennaSrcEnum, DriveFileUsageHintEnum, MutedNoteReasonEnum, NoteVisibilityEnum, NotificationTypeEnum, PageVisibilityEnum, PollNotevisibilityEnum, RelayStatusEnum, UserEmojimodpermEnum, UserProfileFfvisibilityEnum, UserProfileMutingnotificationtypesEnum, initializeRustLogger, watchNote, unwatchNote, publishToChannelStream, ChatEvent, publishToChatStream, ChatIndexEvent, publishToChatIndexStream, publishToModerationStream, getTimestamp, genId, genIdAt, secureRndstr } = nativeBinding const { SECOND, MINUTE, HOUR, DAY, USER_ONLINE_THRESHOLD, USER_ACTIVE_THRESHOLD, FILE_TYPE_BROWSERSAFE, loadEnv, loadConfig, stringToAcct, acctToString, addNoteToAntenna, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getImageSizeFromUrl, getNoteSummary, toMastodonId, fromMastodonId, fetchMeta, metaToPugArgs, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, AntennaSrcEnum, DriveFileUsageHintEnum, MutedNoteReasonEnum, NoteVisibilityEnum, NotificationTypeEnum, PageVisibilityEnum, PollNotevisibilityEnum, RelayStatusEnum, UserEmojimodpermEnum, UserProfileFfvisibilityEnum, UserProfileMutingnotificationtypesEnum, initializeRustLogger, watchNote, unwatchNote, publishToChannelStream, ChatEvent, publishToChatStream, ChatIndexEvent, publishToChatIndexStream, publishToBroadcastStream, publishToModerationStream, getTimestamp, genId, genIdAt, secureRndstr } = nativeBinding
module.exports.SECOND = SECOND module.exports.SECOND = SECOND
module.exports.MINUTE = MINUTE module.exports.MINUTE = MINUTE
@ -370,6 +370,7 @@ module.exports.ChatEvent = ChatEvent
module.exports.publishToChatStream = publishToChatStream module.exports.publishToChatStream = publishToChatStream
module.exports.ChatIndexEvent = ChatIndexEvent module.exports.ChatIndexEvent = ChatIndexEvent
module.exports.publishToChatIndexStream = publishToChatIndexStream module.exports.publishToChatIndexStream = publishToChatIndexStream
module.exports.publishToBroadcastStream = publishToBroadcastStream
module.exports.publishToModerationStream = publishToModerationStream module.exports.publishToModerationStream = publishToModerationStream
module.exports.getTimestamp = getTimestamp module.exports.getTimestamp = getTimestamp
module.exports.genId = genId module.exports.genId = genId

View file

@ -2,6 +2,7 @@ pub mod antenna;
pub mod channel; pub mod channel;
pub mod chat; pub mod chat;
pub mod chat_index; pub mod chat_index;
pub mod custom_emoji;
pub mod moderation; pub mod moderation;
use crate::config::CONFIG; use crate::config::CONFIG;
@ -13,7 +14,7 @@ pub enum Stream {
#[strum(serialize = "internal")] #[strum(serialize = "internal")]
Internal, Internal,
#[strum(serialize = "broadcast")] #[strum(serialize = "broadcast")]
Broadcast, CustomEmoji,
#[strum(to_string = "adminStream:{moderator_id}")] #[strum(to_string = "adminStream:{moderator_id}")]
Moderation { moderator_id: String }, Moderation { moderator_id: String },
#[strum(to_string = "user:{user_id}")] #[strum(to_string = "user:{user_id}")]
@ -84,7 +85,7 @@ mod unit_test {
#[test] #[test]
fn channel_to_string() { fn channel_to_string() {
assert_eq!(Stream::Internal.to_string(), "internal"); assert_eq!(Stream::Internal.to_string(), "internal");
assert_eq!(Stream::Broadcast.to_string(), "broadcast"); assert_eq!(Stream::CustomEmoji.to_string(), "broadcast");
assert_eq!( assert_eq!(
Stream::Moderation { Stream::Moderation {
moderator_id: "9tb42br63g5apjcq".to_string() moderator_id: "9tb42br63g5apjcq".to_string()

View file

@ -0,0 +1,27 @@
use crate::service::stream::{publish_to_stream, Error, Stream};
use serde::{Deserialize, Serialize};
// TODO: define schema type in other place
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[crate::export(object)]
pub struct PackedEmoji {
pub id: String,
pub aliases: Vec<String>,
pub name: String,
pub category: Option<String>,
pub host: Option<String>,
pub url: String,
pub license: Option<String>,
pub width: Option<i32>,
pub height: Option<i32>,
}
#[crate::export(js_name = "publishToBroadcastStream")]
pub fn publish(emoji: &PackedEmoji) -> Result<(), Error> {
publish_to_stream(
&Stream::CustomEmoji,
Some("emojiAdded".to_string()),
Some(format!("{{\"emoji\":{}}}", serde_json::to_string(emoji)?)),
)
}

View file

@ -1,10 +1,14 @@
import define from "@/server/api/define.js"; import define from "@/server/api/define.js";
import { Emojis, DriveFiles } from "@/models/index.js"; import { Emojis, DriveFiles } from "@/models/index.js";
import { type ImageSize, genId, getImageSizeFromUrl } from "backend-rs"; import {
type ImageSize,
genId,
getImageSizeFromUrl,
publishToBroadcastStream,
} from "backend-rs";
import { insertModerationLog } from "@/services/insert-moderation-log.js"; import { insertModerationLog } from "@/services/insert-moderation-log.js";
import { ApiError } from "@/server/api/error.js"; import { ApiError } from "@/server/api/error.js";
import rndstr from "rndstr"; import rndstr from "rndstr";
import { publishBroadcastStream } from "@/services/stream.js";
import { db } from "@/db/postgre.js"; import { db } from "@/db/postgre.js";
import { apiLogger } from "@/server/api/logger.js"; import { apiLogger } from "@/server/api/logger.js";
import { inspect } from "node:util"; import { inspect } from "node:util";
@ -75,9 +79,7 @@ export default define(meta, paramDef, async (ps, me) => {
await db.queryResultCache!.remove(["meta_emojis"]); await db.queryResultCache!.remove(["meta_emojis"]);
publishBroadcastStream("emojiAdded", { publishToBroadcastStream(await Emojis.pack(emoji));
emoji: await Emojis.pack(emoji.id),
});
insertModerationLog(me, "addEmoji", { insertModerationLog(me, "addEmoji", {
emojiId: emoji.id, emojiId: emoji.id,

View file

@ -1,10 +1,14 @@
import define from "@/server/api/define.js"; import define from "@/server/api/define.js";
import { Emojis } from "@/models/index.js"; import { Emojis } from "@/models/index.js";
import { type ImageSize, genId, getImageSizeFromUrl } from "backend-rs"; import {
type ImageSize,
genId,
getImageSizeFromUrl,
publishToBroadcastStream,
} from "backend-rs";
import { ApiError } from "@/server/api/error.js"; import { ApiError } from "@/server/api/error.js";
import type { DriveFile } from "@/models/entities/drive-file.js"; import type { DriveFile } from "@/models/entities/drive-file.js";
import { uploadFromUrl } from "@/services/drive/upload-from-url.js"; import { uploadFromUrl } from "@/services/drive/upload-from-url.js";
import { publishBroadcastStream } from "@/services/stream.js";
import { db } from "@/db/postgre.js"; import { db } from "@/db/postgre.js";
import { apiLogger } from "@/server/api/logger.js"; import { apiLogger } from "@/server/api/logger.js";
import { inspect } from "node:util"; import { inspect } from "node:util";
@ -102,9 +106,7 @@ export default define(meta, paramDef, async (ps, me) => {
await db.queryResultCache!.remove(["meta_emojis"]); await db.queryResultCache!.remove(["meta_emojis"]);
publishBroadcastStream("emojiAdded", { publishToBroadcastStream(await Emojis.pack(copied));
emoji: await Emojis.pack(copied.id),
});
return { return {
id: copied.id, id: copied.id,

View file

@ -10,7 +10,7 @@ import type {
StreamChannels, StreamChannels,
// AdminStreamTypes, // AdminStreamTypes,
// AntennaStreamTypes, // AntennaStreamTypes,
BroadcastTypes, // BroadcastTypes,
// ChannelStreamTypes, // ChannelStreamTypes,
DriveStreamTypes, DriveStreamTypes,
GroupMessagingStreamTypes, GroupMessagingStreamTypes,
@ -64,16 +64,17 @@ class Publisher {
); );
}; };
public publishBroadcastStream = <K extends keyof BroadcastTypes>( /* ported to backend-rs */
type: K, // public publishBroadcastStream = <K extends keyof BroadcastTypes>(
value?: BroadcastTypes[K], // type: K,
): void => { // value?: BroadcastTypes[K],
this.publish( // ): void => {
"broadcast", // this.publish(
type, // "broadcast",
typeof value === "undefined" ? null : value, // type,
); // typeof value === "undefined" ? null : value,
}; // );
// };
public publishMainStream = <K extends keyof MainStreamTypes>( public publishMainStream = <K extends keyof MainStreamTypes>(
userId: User["id"], userId: User["id"],
@ -215,7 +216,7 @@ export default publisher;
export const publishInternalEvent = publisher.publishInternalEvent; export const publishInternalEvent = publisher.publishInternalEvent;
export const publishUserEvent = publisher.publishUserEvent; export const publishUserEvent = publisher.publishUserEvent;
export const publishBroadcastStream = publisher.publishBroadcastStream; // export const publishBroadcastStream = publisher.publishBroadcastStream;
export const publishMainStream = publisher.publishMainStream; export const publishMainStream = publisher.publishMainStream;
export const publishDriveStream = publisher.publishDriveStream; export const publishDriveStream = publisher.publishDriveStream;
export const publishNoteStream = publisher.publishNoteStream; export const publishNoteStream = publisher.publishNoteStream;