#!/usr/bin/env node import { randomBytes } from 'node:crypto'; const APP_ID = process.env.XIAOSHU_PARSE_APP_ID || '7pIbDBJmKx_main'; const MASTER_KEY = process.env.XIAOSHU_MASTER_KEY || ''; const PARSE_URL = (process.env.XIAOSHU_PARSE_URL || 'https://server.xiaoshu.pro/parse').replace(/\/$/, ''); const FUNCTION_URL = PARSE_URL.replace(/\/parse$/, '/api/functions'); if (!MASTER_KEY) throw new Error('缺少 XIAOSHU_MASTER_KEY'); const headers = { 'X-Parse-Application-Id': APP_ID, 'X-Parse-Master-Key': MASTER_KEY, 'Content-Type': 'application/json' }; async function parse(path, init = {}) { const response = await fetch(`${PARSE_URL}${path}`, { ...init, headers: { ...headers, ...(init.headers || {}) } }); const payload = await response.json().catch(() => ({})); if (!response.ok || payload.error) throw new Error(typeof payload.error === 'string' ? payload.error : JSON.stringify(payload.error || { status: response.status })); return payload; } const company = (await parse('/classes/Company?limit=1&keys=objectId')).results?.[0]; if (!company?.objectId) throw new Error('生产 Parse 未找到 Company'); const suffix = `${Date.now()}_${randomBytes(4).toString('hex')}`; const username = `index_maintainer_${suffix}`; const password = `${randomBytes(24).toString('base64url')}Aa9!`; const path = `xiaoshu/system/ensure-app-indexes-${suffix}`; let userId = ''; let functionId = ''; const statements = [ 'CREATE INDEX IF NOT EXISTS "idx_cm_company_model_item" ON "CommonModel" ("company","modelId","itemId")', 'CREATE INDEX IF NOT EXISTS "idx_cm_company_model_general" ON "CommonModel" ("company","modelId","generalId")', 'CREATE INDEX IF NOT EXISTS "idx_cm_company_model_node" ON "CommonModel" ("company","modelId","nodeId")', 'CREATE INDEX IF NOT EXISTS "idx_cm_company_model_node_order" ON "CommonModel" ("company","modelId","nodeId","orderId","generalId")', 'CREATE INDEX IF NOT EXISTS "idx_daily_company_user_date" ON "DailyStudyRecord" ("company","userId","dqrq")', 'CREATE INDEX IF NOT EXISTS "idx_daily_company_user_updated" ON "DailyStudyRecord" ("company","userId","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_daily_company_date_user" ON "DailyStudyRecord" ("company","dqrq","userId")', 'CREATE INDEX IF NOT EXISTS "idx_daily_company_coach_date" ON "DailyStudyRecord" ("company","pl","dqrq")', 'CREATE INDEX IF NOT EXISTS "idx_daily_company_appointment" ON "DailyStudyRecord" ("company","dsid")', 'CREATE INDEX IF NOT EXISTS "idx_daily_company_id" ON "DailyStudyRecord" ("company","id")', 'CREATE INDEX IF NOT EXISTS "idx_appt_company_student_time" ON "CourseAppointment" ("company","szyh","yysj")', 'CREATE INDEX IF NOT EXISTS "idx_appt_company_student_updated" ON "CourseAppointment" ("company","szyh","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_appt_company_coach_updated" ON "CourseAppointment" ("company","pl","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_appt_company_assistant_updated" ON "CourseAppointment" ("company","fxpl","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_appt_company_coach_time" ON "CourseAppointment" ("company","pl","yysj")', 'CREATE INDEX IF NOT EXISTS "idx_appt_company_student_effective_date" ON "CourseAppointment" ("company","szyh",(REPLACE(LEFT(COALESCE(NULLIF("bxrq",\'\'),"yysj"),10),\'-\',\'\')))', 'CREATE INDEX IF NOT EXISTS "idx_appt_company_coach_effective_date" ON "CourseAppointment" ("company","pl",(REPLACE(LEFT(COALESCE(NULLIF("bxrq",\'\'),"yysj"),10),\'-\',\'\')))', 'CREATE INDEX IF NOT EXISTS "idx_appt_company_id" ON "CourseAppointment" ("company","id")', 'CREATE INDEX IF NOT EXISTS "idx_binding_company_user_id" ON "CourseBinding" ("company","yhid","id")', 'CREATE INDEX IF NOT EXISTS "idx_binding_company_user_updated" ON "CourseBinding" ("company","yhid","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_memory_company_user_time" ON "MemoryPracticeRecord" ("company","yhid","kywsj")', 'CREATE INDEX IF NOT EXISTS "idx_memory_company_user_updated" ON "MemoryPracticeRecord" ("company","yhid","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_memory_company_coach_updated" ON "MemoryPracticeRecord" ("company","plid","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_memory_company_coach_status" ON "MemoryPracticeRecord" ("company","plid","fxzt")', 'CREATE INDEX IF NOT EXISTS "idx_memory_company_id" ON "MemoryPracticeRecord" ("company","id")', 'CREATE INDEX IF NOT EXISTS "idx_practice_company_user_word_updated" ON "PracticeRecord" ("company",(CAST("yhid" AS text)),(CAST("scid" AS text)),"updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_lesson_company_coach_time" ON "LessonRecord" ("company","jsmz","lessonAt")', 'CREATE INDEX IF NOT EXISTS "idx_lesson_company_student_updated" ON "LessonRecord" ("company","xymz","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_lesson_company_coach_updated" ON "LessonRecord" ("company","jsmz","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_reservation_company_student_updated" ON "CourseCreditReservation" ("company","studentId","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_reading_item_user_updated" ON "SurveyItem" ("user","type","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_reading_log_user_updated" ON "SurveyLog" ("user","updatedAt" DESC)', 'CREATE INDEX IF NOT EXISTS "idx_node_company_node" ON "Node" ("company","nodeId")', 'CREATE INDEX IF NOT EXISTS "idx_vocab_company_id" ON "VocabularyWord" ("company","id")', ]; const indexNames = statements.map((statement) => statement.match(/"([^"]+)"/)?.[1] || ''); const code = String.raw` async function handler(request, response) { try { const current = request.user || (typeof user !== 'undefined' ? user : null); if (!current) return response.status(401).json({ success:false, message:'需要超级管理员会话' }); await current.fetch({ useMasterKey:true }); const roles = Array.isArray(current.get('roles')) ? current.get('roles').map(String) : []; if (current.get('adminRoleKey') !== 'super-admin' && !roles.includes('super-admin')) return response.status(403).json({ success:false, message:'仅超级管理员可执行' }); const statements = ${JSON.stringify(statements)}; const applied = [], skipped = []; for (const statement of statements) { try { await Psql.none(statement); applied.push(statement.match(/"([^"]+)"/)?.[1] || statement); } catch (error) { skipped.push({ index: statement.match(/"([^"]+)"/)?.[1] || statement, reason: String(error.message || error) }); } } const indexes = await Psql.query('SELECT indexname FROM pg_indexes WHERE schemaname=current_schema() AND indexname=ANY($1::text[]) ORDER BY indexname', [${JSON.stringify(indexNames)}]); response.json({ success:true, data:{ applied, skipped, indexes:indexes.map((row) => row.indexname) } }); } catch (error) { response.status(Number(error.status)||500).json({ success:false, message:String(error.message||error) }); } }`; try { const createdUser = await parse('/users', { method: 'POST', body: JSON.stringify({ username, password, isAdmin: true, role: 'admin', roles: ['admin', 'super-admin'], adminRoleKey: 'super-admin', company: { __type: 'Pointer', className: 'Company', objectId: company.objectId }, realName: '应用查询索引临时管理员', testCreatedBy: 'ensure-app-performance-indexes' }), }); userId = createdUser.objectId; let token = createdUser.sessionToken || ''; if (!token) token = (await parse('/login', { method: 'POST', body: JSON.stringify({ username, password }) })).sessionToken; if (!token) throw new Error('临时超级管理员没有会话'); const createdFunction = await parse('/classes/Function', { method: 'POST', body: JSON.stringify({ name: path, desc: '一次性补齐用户端高频查询索引', type: 'standalone', path, code, params: [], paramList: [], respType: 'json', respJson: { success: true }, enabled: true }) }); functionId = createdFunction.objectId; const response = await fetch(`${FUNCTION_URL}/${path}`, { method: 'POST', headers: { 'X-Parse-Application-Id': APP_ID, 'Content-Type': 'application/json' }, body: JSON.stringify({ token, params: {} }) }); const payload = await response.json().catch(() => ({})); if (!response.ok || payload.success !== true) throw new Error(payload.message || payload.error || `索引维护失败:${response.status}`); console.log(JSON.stringify({ ensured: true, applied: payload.data?.applied || [], skipped: payload.data?.skipped || [], indexes: payload.data?.indexes || [] }, null, 2)); } finally { if (functionId) await parse(`/classes/Function/${functionId}`, { method: 'DELETE' }).catch(() => undefined); if (userId) { const where = encodeURIComponent(JSON.stringify({ user: { __type: 'Pointer', className: '_User', objectId: userId } })); const sessions = await parse(`/classes/_Session?where=${where}&limit=1000&keys=objectId`).catch(() => ({ results: [] })); for (const session of sessions.results || []) await parse(`/classes/_Session/${session.objectId}`, { method: 'DELETE' }).catch(() => undefined); await parse(`/users/${userId}`, { method: 'DELETE' }).catch(() => undefined); } }