controller.ts 914 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // To store message streaming controller
  2. export const ChatControllerPool = {
  3. controllers: {} as Record<string, AbortController>,
  4. addController(
  5. sessionId: string,
  6. messageId: string,
  7. controller: AbortController,
  8. ) {
  9. const key = this.key(sessionId, messageId);
  10. this.controllers[key] = controller;
  11. return key;
  12. },
  13. stop(sessionId: string, messageId: string) {
  14. const key = this.key(sessionId, messageId);
  15. const controller = this.controllers[key];
  16. controller?.abort();
  17. },
  18. stopAll() {
  19. Object.values(this.controllers).forEach((v) => v.abort());
  20. },
  21. hasPending() {
  22. return Object.values(this.controllers).length > 0;
  23. },
  24. remove(sessionId: string, messageId: string) {
  25. const key = this.key(sessionId, messageId);
  26. delete this.controllers[key];
  27. },
  28. key(sessionId: string, messageIndex: string) {
  29. return `${sessionId},${messageIndex}`;
  30. },
  31. };