ensure-app-performance-indexes.mjs 6.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/env node
  2. import { randomBytes } from 'node:crypto';
  3. const APP_ID = process.env.XIAOSHU_PARSE_APP_ID || '7pIbDBJmKx_main';
  4. const MASTER_KEY = process.env.XIAOSHU_MASTER_KEY || '';
  5. const PARSE_URL = (process.env.XIAOSHU_PARSE_URL || 'https://server.xiaoshu.pro/parse').replace(/\/$/, '');
  6. const FUNCTION_URL = PARSE_URL.replace(/\/parse$/, '/api/functions');
  7. if (!MASTER_KEY) throw new Error('缺少 XIAOSHU_MASTER_KEY');
  8. const headers = { 'X-Parse-Application-Id': APP_ID, 'X-Parse-Master-Key': MASTER_KEY, 'Content-Type': 'application/json' };
  9. async function parse(path, init = {}) {
  10. const response = await fetch(`${PARSE_URL}${path}`, { ...init, headers: { ...headers, ...(init.headers || {}) } });
  11. const payload = await response.json().catch(() => ({}));
  12. if (!response.ok || payload.error) throw new Error(typeof payload.error === 'string' ? payload.error : JSON.stringify(payload.error || { status: response.status }));
  13. return payload;
  14. }
  15. const company = (await parse('/classes/Company?limit=1&keys=objectId')).results?.[0];
  16. if (!company?.objectId) throw new Error('生产 Parse 未找到 Company');
  17. const suffix = `${Date.now()}_${randomBytes(4).toString('hex')}`;
  18. const username = `index_maintainer_${suffix}`;
  19. const password = `${randomBytes(24).toString('base64url')}Aa9!`;
  20. const path = `xiaoshu/system/ensure-app-indexes-${suffix}`;
  21. let userId = '';
  22. let functionId = '';
  23. const statements = [
  24. 'CREATE INDEX IF NOT EXISTS "idx_cm_company_model_item" ON "CommonModel" ("company","modelId","itemId")',
  25. 'CREATE INDEX IF NOT EXISTS "idx_cm_company_model_general" ON "CommonModel" ("company","modelId","generalId")',
  26. 'CREATE INDEX IF NOT EXISTS "idx_cm_company_model_node" ON "CommonModel" ("company","modelId","nodeId")',
  27. 'CREATE INDEX IF NOT EXISTS "idx_daily_company_user_date" ON "DailyStudyRecord" ("company","userId","dqrq")',
  28. 'CREATE INDEX IF NOT EXISTS "idx_daily_company_id" ON "DailyStudyRecord" ("company","id")',
  29. 'CREATE INDEX IF NOT EXISTS "idx_appt_company_student_time" ON "CourseAppointment" ("company","szyh","yysj")',
  30. 'CREATE INDEX IF NOT EXISTS "idx_appt_company_coach_time" ON "CourseAppointment" ("company","pl","yysj")',
  31. 'CREATE INDEX IF NOT EXISTS "idx_appt_company_id" ON "CourseAppointment" ("company","id")',
  32. 'CREATE INDEX IF NOT EXISTS "idx_binding_company_user_id" ON "CourseBinding" ("company","yhid","id")',
  33. 'CREATE INDEX IF NOT EXISTS "idx_memory_company_user_time" ON "MemoryPracticeRecord" ("company","yhid","kywsj")',
  34. 'CREATE INDEX IF NOT EXISTS "idx_memory_company_coach_status" ON "MemoryPracticeRecord" ("company","plid","fxzt")',
  35. 'CREATE INDEX IF NOT EXISTS "idx_memory_company_id" ON "MemoryPracticeRecord" ("company","id")',
  36. 'CREATE INDEX IF NOT EXISTS "idx_lesson_company_coach_time" ON "LessonRecord" ("company","jsmz","lessonAt")',
  37. 'CREATE INDEX IF NOT EXISTS "idx_node_company_node" ON "Node" ("company","nodeId")',
  38. ];
  39. const indexNames = statements.map((statement) => statement.match(/"([^"]+)"/)?.[1] || '');
  40. const code = String.raw`
  41. async function handler(request, response) {
  42. try {
  43. const current = request.user || (typeof user !== 'undefined' ? user : null);
  44. if (!current) return response.status(401).json({ success:false, message:'需要超级管理员会话' });
  45. await current.fetch({ useMasterKey:true });
  46. const roles = Array.isArray(current.get('roles')) ? current.get('roles').map(String) : [];
  47. if (current.get('adminRoleKey') !== 'super-admin' && !roles.includes('super-admin')) return response.status(403).json({ success:false, message:'仅超级管理员可执行' });
  48. const statements = ${JSON.stringify(statements)};
  49. for (const statement of statements) await Psql.none(statement);
  50. 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)}]);
  51. response.json({ success:true, data:{ applied:statements.length, indexes:indexes.map((row) => row.indexname) } });
  52. } catch (error) {
  53. response.status(Number(error.status)||500).json({ success:false, message:String(error.message||error) });
  54. }
  55. }`;
  56. try {
  57. const createdUser = await parse('/users', {
  58. method: 'POST',
  59. 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' }),
  60. });
  61. userId = createdUser.objectId;
  62. let token = createdUser.sessionToken || '';
  63. if (!token) token = (await parse('/login', { method: 'POST', body: JSON.stringify({ username, password }) })).sessionToken;
  64. if (!token) throw new Error('临时超级管理员没有会话');
  65. 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 }) });
  66. functionId = createdFunction.objectId;
  67. 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: {} }) });
  68. const payload = await response.json().catch(() => ({}));
  69. if (!response.ok || payload.success !== true) throw new Error(payload.message || payload.error || `索引维护失败:${response.status}`);
  70. console.log(JSON.stringify({ ensured: true, applied: payload.data?.applied || 0, indexes: payload.data?.indexes || [] }, null, 2));
  71. } finally {
  72. if (functionId) await parse(`/classes/Function/${functionId}`, { method: 'DELETE' }).catch(() => undefined);
  73. if (userId) {
  74. const where = encodeURIComponent(JSON.stringify({ user: { __type: 'Pointer', className: '_User', objectId: userId } }));
  75. const sessions = await parse(`/classes/_Session?where=${where}&limit=1000&keys=objectId`).catch(() => ({ results: [] }));
  76. for (const session of sessions.results || []) await parse(`/classes/_Session/${session.objectId}`, { method: 'DELETE' }).catch(() => undefined);
  77. await parse(`/users/${userId}`, { method: 'DELETE' }).catch(() => undefined);
  78. }
  79. }