chatTranscriptApi.ts 5.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import Router from '@koa/router'
  2. import type Koa from 'koa'
  3. import type { ChatCacheCoordinator } from './chatCache.js'
  4. import type { LocalAuthStore } from './localAuth.js'
  5. import { HttpError } from './errors.js'
  6. import { CHAT_TRANSCRIPT_FEATURE } from '../shared/chatTranscript.js'
  7. export function chatTranscriptRouter(cache:ChatCacheCoordinator,auth:LocalAuthStore):Router {
  8. const router=new Router(),store=cache.store,transcripts=store.transcripts
  9. const scope=(ctx:Koa.Context)=>{
  10. const owner=auth.require(ctx).id,profile=String(ctx.query.profile??'default'),requested=ctx.params.id
  11. if(!profile||profile.length>256||!requested||requested.length>256)throw new HttpError(400,'会话标识无效','invalid_session')
  12. const id=store.canonicalSessionID(owner,profile,requested)
  13. store.requireOwned(owner,profile,id)
  14. if(!auth.canUseSource(owner,'local',profile))throw new HttpError(403,'没有此 Profile 的权限','profile_forbidden')
  15. ctx.set('Cache-Control','no-store')
  16. return {owner,profile,id}
  17. }
  18. router.get('/api/app/chat/capabilities',ctx=>{auth.require(ctx);ctx.set('Cache-Control','no-store');ctx.body={features:transcripts.enabled?[CHAT_TRANSCRIPT_FEATURE]:[],epoch:transcripts.epoch}})
  19. router.get('/api/app/chat/sessions/:id/snapshot',ctx=>{
  20. const {owner,profile,id}=scope(ctx)
  21. const before=ctx.query.before===undefined?Number.MAX_SAFE_INTEGER:Number(ctx.query.before),limit=ctx.query.limit===undefined?150:Number(ctx.query.limit)
  22. if(!Number.isSafeInteger(before)||before<1||!Number.isSafeInteger(limit)||limit<1||limit>500)throw new HttpError(400,'历史分页参数无效','invalid_page')
  23. const coverage=store.db.prepare('SELECT complete FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,id)
  24. if(!coverage?.complete||store.needsListMetadata(owner,profile)||store.localDetail(owner,profile,id)?.state==='gap')cache.schedule(owner,profile,id)
  25. store.db.exec('SAVEPOINT transcript_snapshot')
  26. try{
  27. transcripts.seed(owner,profile,id)
  28. const detail=store.localDetail(owner,profile,id)!
  29. ctx.body=transcripts.snapshot(owner,profile,id,JSON.parse(detail.response.body.toString()),detail.state,before,limit)
  30. store.db.exec('RELEASE transcript_snapshot')
  31. }catch(error){store.db.exec('ROLLBACK TO transcript_snapshot; RELEASE transcript_snapshot');throw error}
  32. })
  33. router.get('/api/app/chat/sessions/:id/events',ctx=>{
  34. const {owner,profile,id}=scope(ctx),version=auth.pushAuthorizationVersion(owner)
  35. const raw=ctx.get('last-event-id')||String(ctx.query.after??''),parts=raw.split(':')
  36. let cursor=Number(parts.at(-1)),closed=false,lastFlush=0,ready=false
  37. transcripts.seed(owner,profile,id)
  38. const epoch=transcripts.epochFor(owner,profile,id)
  39. if(parts.length!==2||parts[0]!==epoch||!Number.isSafeInteger(cursor)||cursor<0||cursor>transcripts.cursor(owner,profile,id))throw new HttpError(409,'聊天事件需要重新同步','transcript_reset')
  40. const res=ctx.res
  41. let timer:ReturnType<typeof setTimeout>|undefined,heartbeat:ReturnType<typeof setInterval>|undefined,off=()=>{}
  42. const valid=()=>!store.isClosed&&auth.isUserActive(owner)&&auth.pushAuthorizationVersion(owner)===version&&auth.current(ctx)?.id===owner&&store.ownsSession(owner,profile,id)&&auth.canUseSource(owner,'local',profile)
  43. const close=()=>{if(closed)return;closed=true;clearTimeout(timer);clearInterval(heartbeat);off();if(!res.writableEnded)res.end()}
  44. const write=(value:string)=>{
  45. if(closed||res.destroyed||!valid()){close();return false}
  46. if(res.writableLength+Buffer.byteLength(value)>4*1024*1024){res.write('event: reset\ndata: {}\n\n');close();return false}
  47. res.write(value);return true
  48. }
  49. const control=()=>({epoch,cursor,...transcripts.control(owner,profile,id)})
  50. const flush=()=>{
  51. clearTimeout(timer);timer=undefined
  52. if(closed)return
  53. if(!valid()){close();return}
  54. if(transcripts.epochFor(owner,profile,id)!==epoch){write('event: reset\ndata: {}\n\n');close();return}
  55. const events=transcripts.events(owner,profile,id,cursor)
  56. for(const event of events){if(event.epoch!==epoch){write('event: reset\ndata: {}\n\n');close();return}if(!write(`id: ${epoch}:${event.cursor}\nevent: transcript\ndata: ${JSON.stringify(event)}\n\n`))return;cursor=event.cursor}
  57. if(events.length)lastFlush=Date.now()
  58. if(events.length===250){timer=setTimeout(flush,0);return}
  59. // A control frame must never acknowledge events still waiting in another page.
  60. if(cursor!==transcripts.cursor(owner,profile,id)){write('event: reset\ndata: {}\n\n');close();return}
  61. if(!ready){ready=true;write(`event: ready\ndata: ${JSON.stringify(control())}\n\n`)}
  62. }
  63. const changed=()=>{
  64. if(closed)return
  65. const events=transcripts.events(owner,profile,id,cursor)
  66. if(!events.length)return
  67. if(events.some(event=>event.type!=='message.patch')||Date.now()-lastFlush>=33)flush()
  68. else if(timer===undefined)timer=setTimeout(flush,Math.max(0,33-(Date.now()-lastFlush)))
  69. }
  70. ctx.respond=false
  71. res.writeHead(200,{'Content-Type':'text/event-stream; charset=utf-8','Cache-Control':'no-store','X-Accel-Buffering':'no'})
  72. res.flushHeaders();res.once('close',close);res.once('error',close)
  73. off=transcripts.subscribe(changed)
  74. flush()
  75. if(closed)return
  76. heartbeat=setInterval(()=>{
  77. if(!valid()){close();return}
  78. if(transcripts.epochFor(owner,profile,id)!==epoch){write('event: reset\ndata: {}\n\n');close();return}
  79. flush()
  80. if(!closed&&ready&&timer===undefined)write(`event: state\ndata: ${JSON.stringify(control())}\n\n`)
  81. },5_000);heartbeat.unref()
  82. })
  83. return router
  84. }