From 28f03dbcbddb2b8abe8048041adcc397e56d3dde Mon Sep 17 00:00:00 2001 From: undefined Date: Fri, 23 Sep 2022 01:36:12 +0800 Subject: [PATCH] core: add provideModule and injectUI API --- packages/fps-importer/handler.ts | 7 +- packages/hydrooj/src/handler/import.ts | 6 +- packages/hydrooj/src/handler/user.ts | 8 +-- packages/hydrooj/src/init.ts | 6 ++ packages/hydrooj/src/interface.ts | 41 +++++++---- packages/hydrooj/src/lib/hash.hydro.ts | 5 +- packages/hydrooj/src/lib/ui.ts | 7 +- packages/hydrooj/src/model/user.ts | 2 +- packages/hydrooj/src/service/module.ts | 12 ++++ packages/hydrooj/src/service/server.ts | 9 ++- packages/hydrooj/src/service/watcher.ts | 3 +- packages/import-qduoj/handler.ts | 7 +- packages/login-with-github/lib.ts | 18 +++-- packages/login-with-google/lib.ts | 18 +++-- packages/migrate/index.ts | 31 ++++++++ packages/migrate/lib.ts | 25 ------- packages/migrate/script.ts | 9 --- packages/sonic/index.ts | 94 +++++++++++++++++++++++++ 18 files changed, 211 insertions(+), 97 deletions(-) create mode 100644 packages/migrate/index.ts delete mode 100644 packages/migrate/lib.ts delete mode 100644 packages/migrate/script.ts create mode 100644 packages/sonic/index.ts diff --git a/packages/fps-importer/handler.ts b/packages/fps-importer/handler.ts index 3396d653e..001e4aa96 100644 --- a/packages/fps-importer/handler.ts +++ b/packages/fps-importer/handler.ts @@ -4,10 +4,9 @@ import decodeHTML from 'decode-html'; import fs from 'fs-extra'; import { filter } from 'lodash'; import xml2js from 'xml2js'; -import type { ContentNode, ProblemConfigFile } from 'hydrooj'; +import type { ContentNode, PluginContext, ProblemConfigFile } from 'hydrooj'; import { FileTooLargeError, ValidationError } from 'hydrooj/src/error'; import { buildContent } from 'hydrooj/src/lib/content'; -import { ProblemAdd } from 'hydrooj/src/lib/ui'; import { PERM } from 'hydrooj/src/model/builtin'; import problem from 'hydrooj/src/model/problem'; import solution from 'hydrooj/src/model/solution'; @@ -130,7 +129,7 @@ class FpsProblemImportHandler extends Handler { } export const sideEffect = true; -export async function apply(ctx) { +export async function apply(ctx: PluginContext) { ctx.Route('problem_import_fps', '/problem/import/fps', FpsProblemImportHandler, PERM.PERM_CREATE_PROBLEM); - ProblemAdd('problem_import_fps', {}, 'copy', 'From FPS File'); + ctx.inject('ProblemAdd', 'problem_import_fps', { icon: 'copy', text: 'From FPS File' }); } diff --git a/packages/hydrooj/src/handler/import.ts b/packages/hydrooj/src/handler/import.ts index 26e809436..92ede7ba4 100644 --- a/packages/hydrooj/src/handler/import.ts +++ b/packages/hydrooj/src/handler/import.ts @@ -5,7 +5,7 @@ import AdmZip from 'adm-zip'; import fs from 'fs-extra'; import yaml from 'js-yaml'; import { ValidationError } from '../error'; -import { ProblemAdd } from '../lib/ui'; +import { PluginContext } from '../loader'; import { PERM, PRIV } from '../model/builtin'; import problem, { ProblemDoc } from '../model/problem'; import { Handler } from '../service/server'; @@ -93,7 +93,7 @@ class ProblemImportHydroHandler extends Handler { } } -export async function apply(ctx) { - ProblemAdd('problem_import_hydro', {}, 'copy', 'Import From Hydro'); +export async function apply(ctx: PluginContext) { ctx.Route('problem_import_hydro', '/problem/import/hydro', ProblemImportHydroHandler, PERM.PERM_CREATE_PROBLEM); + ctx.inject('ProblemAdd', 'problem_import_hydro', { icon: 'copy', text: 'Import From Hydro' }); } diff --git a/packages/hydrooj/src/handler/user.ts b/packages/hydrooj/src/handler/user.ts index 65101ada9..e629ea262 100644 --- a/packages/hydrooj/src/handler/user.ts +++ b/packages/hydrooj/src/handler/user.ts @@ -6,7 +6,7 @@ import { SystemError, UserAlreadyExistError, UserFacingError, UserNotFoundError, ValidationError, VerifyPasswordError, } from '../error'; -import { OAuthUserResponse, Udoc, User } from '../interface'; +import { Udoc, User } from '../interface'; import avatar from '../lib/avatar'; import { sendMail } from '../lib/mail'; import { isEmail, isPassword } from '../lib/validator'; @@ -359,7 +359,7 @@ class OauthHandler extends Handler { @param('type', Types.String) async get(domainId: string, type: string) { - await global.Hydro.lib[`oauth_${type}`]?.get?.call(this); + await global.Hydro.module.oauth[type]?.get.call(this); } } @@ -367,8 +367,8 @@ class OauthCallbackHandler extends Handler { noCheckPermView = true; async get(args: any) { - if (!global.Hydro.lib[`oauth_${args.type}`]) throw new UserFacingError('Oauth type'); - const r = await global.Hydro.lib[`oauth_${args.type}`].callback.call(this, args) as OAuthUserResponse; + if (!global.Hydro.module.oauth[args.type]) throw new UserFacingError('Oauth type'); + const r = await global.Hydro.module.oauth[args.type].callback.call(this, args); const uid = await oauth.get(r._id); if (uid) { await user.setById(uid, { loginat: new Date(), loginip: this.request.ip }); diff --git a/packages/hydrooj/src/init.ts b/packages/hydrooj/src/init.ts index afa54e15f..0f4750b5a 100644 --- a/packages/hydrooj/src/init.ts +++ b/packages/hydrooj/src/init.ts @@ -19,6 +19,12 @@ if (!global.Hydro) { script: {}, // @ts-ignore lib: {}, + module: new Proxy({} as any, { + get(self, key) { + if (!self[key]) self[key] = {}; + return self[key]; + }, + }), // @ts-ignore ui: { template: {}, diff --git a/packages/hydrooj/src/interface.ts b/packages/hydrooj/src/interface.ts index 9203cc290..537e11646 100644 --- a/packages/hydrooj/src/interface.ts +++ b/packages/hydrooj/src/interface.ts @@ -3,6 +3,7 @@ import type { Dictionary, NumericDictionary } from 'lodash'; import type { ItemBucketMetadata } from 'minio'; import type { Cursor, ObjectID } from 'mongodb'; import type { ProblemDoc } from './model/problem'; +import type { Handler } from './service/server'; type document = typeof import('./model/document'); @@ -686,10 +687,11 @@ export interface ProblemSearchOptions { export type ProblemSearch = (domainId: string, q: string, options?: ProblemSearchOptions) => Promise; +export { Context as PluginContext } from './service/module'; + export interface Lib extends Record { difficulty: typeof import('./lib/difficulty'), buildContent: typeof import('./lib/content').buildContent, - 'hash.hydro': typeof import('./lib/hash.hydro'), i18n: typeof import('./lib/i18n'), mail: typeof import('./lib/mail'), paginate: typeof import('./lib/paginate'), @@ -705,27 +707,36 @@ export interface Lib extends Record { export type UIInjectableFields = 'ProblemAdd' | 'Nav' | 'UserDropdown'; export interface UI { - template: Dictionary, + template: Record, nodes: Record, getNodes: typeof import('./lib/ui').getNodes, - Nav: typeof import('./lib/ui').Nav, - ProblemAdd: typeof import('./lib/ui').ProblemAdd, inject: typeof import('./lib/ui').inject, } +export interface ModuleInterfaces { + oauth: { + text: string; + icon?: string; + get: (this: Handler) => Promise; + callback: (this: Handler, args: Record) => Promise; + }; + hash: (password: string, salt: string, user: User) => boolean | string; +} + export interface HydroGlobal { - version: Record, - model: Model, + version: Record; + model: Model; /** @deprecated */ - handler: Record, - script: Record, - service: Service, - lib: Lib, - ui: UI, - error: typeof import('./error'), - Logger: typeof import('./logger').Logger, - logger: typeof import('./logger').logger, - locales: Record>, + handler: Record; + script: Record; + service: Service; + lib: Lib; + module: { [K in keyof ModuleInterfaces]: Record }; + ui: UI; + error: typeof import('./error'); + Logger: typeof import('./logger').Logger; + logger: typeof import('./logger').logger; + locales: Record>; } declare global { diff --git a/packages/hydrooj/src/lib/hash.hydro.ts b/packages/hydrooj/src/lib/hash.hydro.ts index 8014cc6b7..c37127584 100644 --- a/packages/hydrooj/src/lib/hash.hydro.ts +++ b/packages/hydrooj/src/lib/hash.hydro.ts @@ -1,9 +1,8 @@ import crypto from 'crypto'; function hash(password: string, salt: string) { - return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha256').toString('hex').substr(0, 64); + return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha256').toString('hex').substring(0, 64); } export = hash; - -global.Hydro.lib['hash.hydro'] = hash; +global.Hydro.module.hash.hydro = hash; diff --git a/packages/hydrooj/src/lib/ui.ts b/packages/hydrooj/src/lib/ui.ts index 30cd4f72f..c2f6277cc 100644 --- a/packages/hydrooj/src/lib/ui.ts +++ b/packages/hydrooj/src/lib/ui.ts @@ -31,7 +31,9 @@ export const nodes = new Proxy({}, { }, }); export function inject(node: UIInjectableFields, name: string, args: Record = {}, ...permPrivChecker: PermPrivChecker) { - nodes[node].push({ name, args: args || {}, checker: buildChecker(...permPrivChecker) }); + const obj = { name, args: args || {}, checker: buildChecker(...permPrivChecker) }; + nodes[node].push(obj); + return () => { nodes[node] = nodes[node].filter((i) => i !== obj); }; } export function getNodes(name: UIInjectableFields) { return nodes[name]; @@ -65,5 +67,4 @@ inject('ProblemAdd', 'problem_create', { icon: 'add', text: 'Create Problem' }); global.Hydro.ui.inject = inject; global.Hydro.ui.nodes = nodes as any; global.Hydro.ui.getNodes = getNodes; -global.Hydro.ui.Nav = Nav; -global.Hydro.ui.ProblemAdd = ProblemAdd; +Object.assign(global.Hydro.ui, { ProblemAdd, Nav }); diff --git a/packages/hydrooj/src/model/user.ts b/packages/hydrooj/src/model/user.ts index 6042af0c4..df4ac1565 100644 --- a/packages/hydrooj/src/model/user.ts +++ b/packages/hydrooj/src/model/user.ts @@ -132,7 +132,7 @@ export class User { } checkPassword(password: string) { - const h = global.Hydro.lib[`hash.${this.hashType}`]; + const h = global.Hydro.module.hash[this.hashType]; if (!h) throw new Error('Unknown hash method'); const result = h(password, this._salt, this); if (result !== true && result !== this._hash) { diff --git a/packages/hydrooj/src/service/module.ts b/packages/hydrooj/src/service/module.ts index b0be91c7b..60ac661fa 100644 --- a/packages/hydrooj/src/service/module.ts +++ b/packages/hydrooj/src/service/module.ts @@ -1,4 +1,6 @@ import Schema from 'schemastery'; +import { inject } from '../lib/ui'; +import { ModuleInterfaces } from '../loader'; import * as bus from './bus'; export const runtimes: Record = Object.create(null); @@ -9,6 +11,12 @@ function addScript(name: string, description: string, validate: Schema, ru return () => delete global.Hydro.script[name]; } +function provideModule(type: T, id: string, module: ModuleInterfaces[T]) { + if (global.Hydro.module[type][id]) throw new Error(`duplicate script ${type}/${id} registered.`); + global.Hydro.module[type as any][id] = module; + return () => delete global.Hydro.module[type][id]; +} + export interface Context { Route: typeof import('./server').Route; Connection: typeof import('./server').Connection; @@ -16,6 +24,8 @@ export interface Context { once: typeof bus['once']; off: typeof bus['off']; addScript: typeof addScript; + provideModule: typeof provideModule; + inject: typeof inject; } export class Runtime { @@ -46,6 +56,8 @@ export class Runtime { setInterval: T(setInterval, clearInterval), setTimeout: T(setTimeout, clearTimeout), setImmediate: T(setImmediate, clearImmediate), + provideModule: T(provideModule), + inject: T(inject), } as Context); if (module.sideEffect) this.sideEffect = true; this.loaded = true; diff --git a/packages/hydrooj/src/service/server.ts b/packages/hydrooj/src/service/server.ts index f4ce22588..75e7fb638 100644 --- a/packages/hydrooj/src/service/server.ts +++ b/packages/hydrooj/src/service/server.ts @@ -7,7 +7,6 @@ import Body from 'koa-body'; import Compress from 'koa-compress'; import proxy from 'koa-proxies'; import cache from 'koa-static-cache'; -import { filter } from 'lodash'; import WebSocket from 'ws'; import { parseMemoryMB } from '@hydrooj/utils/lib/utils'; import { @@ -176,11 +175,11 @@ export class Handler extends HandlerCommon { async init() { if (!argv.options.benchmark) await this.limitRate('global', 5, 88); if (!this.noCheckPermView && !this.user.hasPriv(PRIV.PRIV_VIEW_ALL_DOMAIN)) this.checkPerm(PERM.PERM_VIEW); - this.loginMethods = filter(Object.keys(global.Hydro.lib), (str) => str.startsWith('oauth_')) + this.loginMethods = Object.keys(global.Hydro.module.oauth) .map((key) => ({ - id: key.split('_')[1], - icon: global.Hydro.lib[key].icon, - text: global.Hydro.lib[key].text, + id: key, + icon: global.Hydro.module.oauth[key].icon, + text: global.Hydro.module.oauth[key].text, })); } diff --git a/packages/hydrooj/src/service/watcher.ts b/packages/hydrooj/src/service/watcher.ts index 4f4ad4b0f..5d6a9c304 100644 --- a/packages/hydrooj/src/service/watcher.ts +++ b/packages/hydrooj/src/service/watcher.ts @@ -52,7 +52,8 @@ class Watcher { if (process.env.WATCH_ROOT) roots.push(process.env.WATCH_ROOT); this.watcher = watch(roots, { ...this.config, - ignored: ['**/node_modules/**', '**/.git/**', '**/logs/**', '**/.cache/**'], + ignored: ['node_modules', '.git', 'logs', '.cache'] + .map((i) => `**/${i}/**`).concat('**/tsconfig.tsbuildinfo'), }); logger.info(`Start watching changes in ${this.root}`); diff --git a/packages/import-qduoj/handler.ts b/packages/import-qduoj/handler.ts index 83fc735c6..770614cd0 100644 --- a/packages/import-qduoj/handler.ts +++ b/packages/import-qduoj/handler.ts @@ -4,10 +4,9 @@ import path from 'path'; import AdmZip from 'adm-zip'; import fs from 'fs-extra'; import yaml from 'js-yaml'; -import type { ContentNode, ProblemConfigFile } from 'hydrooj'; +import type { ContentNode, PluginContext, ProblemConfigFile } from 'hydrooj'; import { ValidationError } from 'hydrooj/src/error'; import { buildContent } from 'hydrooj/src/lib/content'; -import { ProblemAdd } from 'hydrooj/src/lib/ui'; import { PERM } from 'hydrooj/src/model/builtin'; import problem from 'hydrooj/src/model/problem'; import { Handler } from 'hydrooj/src/service/server'; @@ -126,7 +125,7 @@ class ImportQduojHandler extends Handler { } } -export async function apply(ctx) { +export async function apply(ctx: PluginContext) { ctx.Route('problem_import_qduoj', '/problem/import/qduoj', ImportQduojHandler, PERM.PERM_CREATE_PROBLEM); - ProblemAdd('problem_import_qduoj', {}, 'copy', 'From QDUOJ Export'); + ctx.inject('ProblemAdd', 'problem_import_qduoj', { icon: 'copy', text: 'From QDUOJ Export' }); } diff --git a/packages/login-with-github/lib.ts b/packages/login-with-github/lib.ts index 47ad41646..0797260b6 100644 --- a/packages/login-with-github/lib.ts +++ b/packages/login-with-github/lib.ts @@ -1,6 +1,5 @@ -import 'hydrooj'; - import superagent from 'superagent'; +import { PluginContext } from 'hydrooj'; import { ForbiddenError } from 'hydrooj/src/error'; declare module 'hydrooj' { @@ -9,9 +8,6 @@ declare module 'hydrooj' { 'login-with-github.secret': string; 'login-with-github.endpoint': string; } - interface Lib { - oauth_github: typeof import('./lib'); - } } async function get() { @@ -75,8 +71,10 @@ async function callback({ state, code }) { return ret; } -global.Hydro.lib.oauth_github = { - text: 'Login with Github', - callback, - get, -}; +export function apply(ctx:PluginContext) { + ctx.provideModule('oauth', 'github', { + text: 'Login with Github', + callback, + get, + }); +} diff --git a/packages/login-with-google/lib.ts b/packages/login-with-google/lib.ts index 525573789..16080969f 100644 --- a/packages/login-with-google/lib.ts +++ b/packages/login-with-google/lib.ts @@ -1,15 +1,11 @@ -import 'hydrooj'; - import * as superagent from 'superagent'; +import { PluginContext } from 'hydrooj'; declare module 'hydrooj' { interface SystemKeys { 'login-with-google.id': string, 'login-with-google.secret': string, } - interface Lib { - oauth_google: typeof import('./lib'), - } } async function get() { @@ -81,8 +77,10 @@ async function callback({ }; } -global.Hydro.lib.oauth_google = { - text: 'Login with Google', - callback, - get, -}; +export function apply(ctx: PluginContext) { + ctx.provideModule('oauth', 'google', { + text: 'Login with Google', + callback, + get, + }); +} diff --git a/packages/migrate/index.ts b/packages/migrate/index.ts new file mode 100644 index 000000000..35608a942 --- /dev/null +++ b/packages/migrate/index.ts @@ -0,0 +1,31 @@ +import { md5, sha1 } from '@hydrooj/utils/lib/utils'; +import { PluginContext } from 'hydrooj'; +import { apply as hustoj } from './scripts/hustoj'; +import { apply as syzoj } from './scripts/syzoj'; +import { apply as vijos } from './scripts/vijos'; + +const RE_MD5 = /^[\da-f]{32}$/; + +export function apply(ctx: PluginContext) { + hustoj(ctx); + vijos(ctx); + syzoj(ctx); + ctx.provideModule('hash', 'hust', ($password, $saved) => { + $password = md5($password); + if (RE_MD5.test($saved)) return $password === $saved; + const $svd = Buffer.from($saved, 'base64').toString('hex'); + const $salt = Buffer.from($svd.substr(40), 'hex').toString(); + const $hash = Buffer.concat([ + Buffer.from(sha1($password + $salt), 'hex'), + Buffer.from($salt), + ]).toString('base64'); + if ($hash.trim() === $saved.trim()) return true; + return false; + }); + ctx.provideModule('hash', 'vj2', (password, salt, { uname }) => { + const pmd5 = md5(password); + const mixedSha1 = sha1(md5(uname.toLowerCase() + pmd5) + salt + sha1(pmd5 + salt)); + return `${Buffer.from(uname).toString('base64')}|${mixedSha1}`; + }); + ctx.provideModule('hash', 'syzoj', (password: string) => md5(`${password}syzoj2_xxx`)); +} diff --git a/packages/migrate/lib.ts b/packages/migrate/lib.ts deleted file mode 100644 index a5ff941ac..000000000 --- a/packages/migrate/lib.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { md5, sha1 } from '@hydrooj/utils/lib/utils'; - -const RE_MD5 = /^[\da-f]{32}$/; - -global.Hydro.lib['hash.hust'] = ($password: string, $saved: string) => { - $password = md5($password); - if (RE_MD5.test($saved)) return $password === $saved; - const $svd = Buffer.from($saved, 'base64').toString('hex'); - const $salt = Buffer.from($svd.substr(40), 'hex').toString(); - const $hash = Buffer.concat([ - Buffer.from(sha1($password + $salt), 'hex'), - Buffer.from($salt), - ]).toString('base64'); - if ($hash.trim() === $saved.trim()) return true; - return false; -}; - -global.Hydro.lib['hash.vj2'] = (password: string, salt: string, udoc: { uname: string; unameLower: string }) => { - const { uname, unameLower } = udoc; - const pmd5 = md5(password); - const mixedSha1 = sha1(md5(unameLower + pmd5) + salt + sha1(pmd5 + salt)); - return `${Buffer.from(uname).toString('base64')}|${mixedSha1}`; -}; - -global.Hydro.lib['hash.syzoj'] = (password: string) => md5(`${password}syzoj2_xxx`); diff --git a/packages/migrate/script.ts b/packages/migrate/script.ts deleted file mode 100644 index e3920f0ac..000000000 --- a/packages/migrate/script.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { apply as hustoj } from './scripts/hustoj'; -import { apply as syzoj } from './scripts/syzoj'; -import { apply as vijos } from './scripts/vijos'; - -export function apply(ctx) { - hustoj(ctx); - vijos(ctx); - syzoj(ctx); -} diff --git a/packages/sonic/index.ts b/packages/sonic/index.ts new file mode 100644 index 000000000..a0815a1ff --- /dev/null +++ b/packages/sonic/index.ts @@ -0,0 +1,94 @@ +import { Schema } from 'hydrooj'; +import { Logger } from 'hydrooj/src/logger'; +import DomainModel from 'hydrooj/src/model/domain'; +import * as system from 'hydrooj/src/model/system'; +import { iterateAllProblem, iterateAllProblemInDomain } from 'hydrooj/src/pipelineUtils'; +import sonic from './service'; + +const logger = new Logger('sonic'); + +global.Hydro.lib.problemSearch = async (domainId, query, opts) => { + const limit = opts?.limit || system.get('pagination.problem'); + const ids = await sonic.query('problem', `${domainId}@title`, query, { limit }); + if (limit - ids.length > 0) ids.push(...await sonic.query('problem', `${domainId}@content`, query, { limit: limit - ids.length })); + return { + countRelation: ids.length >= limit ? 'gte' : 'eq', + total: ids.length, + hits: ids, + }; +}; + +async function run({ domainId }, report) { + if (domainId) await sonic.flushb('problem', domainId); + else await sonic.flushc('problem'); + let i = 0; + const cb = async (pdoc) => { + i++; + if (!(i % 1000)) report({ message: `${i} problems indexed` }); + const union = await DomainModel.searchUnion({ union: pdoc.domainId, problem: true }); + const tasks = []; + for (const did of [pdoc.domainId, ...union.map((j) => j._id)]) { + tasks.push( + pdoc.title && sonic.push( + 'problem', `${did}@title`, `${pdoc.domainId}/${pdoc.docId}`, + `${pdoc.pid || ''} ${pdoc.title} ${pdoc.tag.join(' ')}`, + ), + pdoc.content.toString() && sonic.push('problem', `${did}@content`, `${pdoc.domainId}/${pdoc.docId}`, pdoc.content.toString()), + ); + } + await Promise.all(tasks).catch((e) => console.log(`${pdoc.domainId}/${pdoc.docId}`, e)); + }; + if (domainId) await iterateAllProblemInDomain(domainId, ['title', 'content'], cb); + else await iterateAllProblem(['title', 'content', 'tag'], cb); + return true; +} + +export function apply(ctx) { + ctx.on('problem/add', async (doc, docId) => { + const union = await DomainModel.searchUnion({ union: doc.domainId, problem: true }); + const tasks = []; + for (const domainId of [doc.domainId, ...union.map((i) => i._id)]) { + tasks.push( + sonic.push('problem', `${domainId}@title`, `${doc.domainId}/${docId}`, `${doc.pid || ''} ${doc.title} ${doc.tag?.join(' ')}`), + sonic.push('problem', `${domainId}@content`, `${doc.domainId}/${docId}`, doc.content.toString()), + ); + } + Promise.all(tasks).catch((e) => logger.error(e)); + }); + + ctx.on('problem/edit', async (pdoc) => { + const union = await DomainModel.searchUnion({ union: pdoc.domainId, problem: true }); + const tasks = []; + const id = `${pdoc.domainId}/${pdoc.docId}`; + for (const domainId of [pdoc.domainId, ...union.map((i) => i._id)]) { + tasks.push( + sonic.flusho('problem', `${domainId}@title`, id) + .then(() => sonic.push('problem', `${domainId}@title`, id, `${pdoc.pid || ''} ${pdoc.title} ${pdoc.tag?.join(' ')}`)), + sonic.flusho('problem', `${domainId}@content`, id) + .then(() => sonic.push('problem', `${domainId}@content`, id, pdoc.content.toString())), + ); + } + Promise.all(tasks).catch((e) => logger.error(e)); + }); + + ctx.on('problem/del', async (domainId, docId) => { + const union = await DomainModel.searchUnion({ union: domainId, problem: true }); + const tasks = []; + const id = `${domainId}/${docId}`; + for (const domain of [domainId, ...union.map((i) => i._id)]) { + tasks.push( + sonic.flusho('problem', `${domain}@title`, id), + sonic.flusho('problem', `${domain}@content`, id), + ); + } + await Promise.all(tasks); + }); + + ctx.addScript( + 'ensureSonicSearch', 'Sonic problem search re-index', + Schema.object({ + domainId: Schema.string(), + }), + run, + ); +}