yjs-connection-manager.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import type { Server } from 'socket.io';
  2. import { MongodbPersistence } from 'y-mongodb-provider';
  3. import { YSocketIO, type Document as Ydoc } from 'y-socket.io/dist/server';
  4. import * as Y from 'yjs';
  5. import { getMongoUri } from '../util/mongoose-utils';
  6. const MONGODB_PERSISTENCE_COLLECTION_NAME = 'yjs-writings';
  7. const MONGODB_PERSISTENCE_FLUSH_SIZE = 100;
  8. export const extractPageIdFromYdocId = (ydocId: string): string | undefined => {
  9. const result = ydocId.match(/yjs\/(.*)/);
  10. return result?.[1];
  11. };
  12. class YjsConnectionManager {
  13. private static instance: YjsConnectionManager;
  14. private ysocketio: YSocketIO;
  15. private mdb: MongodbPersistence;
  16. get ysocketioInstance(): YSocketIO {
  17. return this.ysocketio;
  18. }
  19. private constructor(io: Server) {
  20. this.ysocketio = new YSocketIO(io);
  21. this.ysocketio.initialize();
  22. this.mdb = new MongodbPersistence(getMongoUri(), {
  23. collectionName: MONGODB_PERSISTENCE_COLLECTION_NAME,
  24. flushSize: MONGODB_PERSISTENCE_FLUSH_SIZE,
  25. });
  26. }
  27. public static getInstance(io?: Server) {
  28. if (this.instance != null) {
  29. return this.instance;
  30. }
  31. if (io == null) {
  32. throw new Error("'io' is required if initialize YjsConnectionManager");
  33. }
  34. this.instance = new YjsConnectionManager(io);
  35. return this.instance;
  36. }
  37. public async handleYDocSync(pageId: string, initialValue: string): Promise<void> {
  38. const currentYdoc = this.getCurrentYdoc(pageId);
  39. if (currentYdoc == null) {
  40. return;
  41. }
  42. const persistedYdoc = await this.getPersistedYdoc(pageId);
  43. const persistedStateVector = Y.encodeStateVector(persistedYdoc);
  44. await this.mdb.flushDocument(pageId);
  45. // If no write operation has been performed, insert initial value
  46. const clientsSize = persistedYdoc.store.clients.size;
  47. if (clientsSize === 0) {
  48. currentYdoc.getText('codemirror').insert(0, initialValue);
  49. }
  50. const diff = Y.encodeStateAsUpdate(currentYdoc, persistedStateVector);
  51. if (diff.reduce((prev, curr) => prev + curr, 0) > 0) {
  52. this.mdb.storeUpdate(pageId, diff);
  53. }
  54. Y.applyUpdate(currentYdoc, Y.encodeStateAsUpdate(persistedYdoc));
  55. currentYdoc.on('update', async(update) => {
  56. await this.mdb.storeUpdate(pageId, update);
  57. });
  58. currentYdoc.on('destroy', async() => {
  59. await this.mdb.flushDocument(pageId);
  60. });
  61. persistedYdoc.destroy();
  62. }
  63. public async handleYDocUpdate(pageId: string, newValue: string): Promise<void> {
  64. // TODO: https://redmine.weseek.co.jp/issues/132775
  65. // It's necessary to confirm that the user is not editing the target page in the Editor
  66. const currentYdoc = this.getCurrentYdoc(pageId);
  67. if (currentYdoc == null) {
  68. return;
  69. }
  70. const currentMarkdownLength = currentYdoc.getText('codemirror').length;
  71. currentYdoc.getText('codemirror').delete(0, currentMarkdownLength);
  72. currentYdoc.getText('codemirror').insert(0, newValue);
  73. Y.encodeStateAsUpdate(currentYdoc);
  74. }
  75. public getCurrentYdoc(pageId: string): Ydoc | undefined {
  76. const currentYdoc = this.ysocketio.documents.get(`yjs/${pageId}`);
  77. return currentYdoc;
  78. }
  79. public async getPersistedYdoc(pageId: string): Promise<Y.Doc> {
  80. const persistedYdoc = await this.mdb.getYDoc(pageId);
  81. return persistedYdoc;
  82. }
  83. }
  84. export const instantiateYjsConnectionManager = (io: Server): YjsConnectionManager => {
  85. return YjsConnectionManager.getInstance(io);
  86. };
  87. // export the singleton instance
  88. export const getYjsConnectionManager = (): YjsConnectionManager => {
  89. return YjsConnectionManager.getInstance();
  90. };