All files / json-crdt-repo/src/session EditSession.ts

83.91% Statements 167/199
80.23% Branches 69/86
87.09% Functions 27/31
87.05% Lines 148/170

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 29410x 10x 10x 10x 10x 10x 10x                     10x   116x 116x   116x     715x       116x 116x 116x 116x 116x   116x 116x 116x 128x   116x 70x 70x 70x 70x 70x     116x 115x 115x   116x       123x 115x 115x       15x 15x 15x 15x 15x     116x 116x             246x       244x 240x 240x 240x 240x 240x 240x 240x 129x   240x   240x 229x 229x             227x   215x 120x 120x 120x 120x   215x 90x 90x   125x 10x 10x     215x 215x 175x 122x 122x 27x       23x 23x 1x 1x                 175x   215x   11x 9x 8x       8x     236x 236x         198x     198x 129x   127x                   8x 8x 8x             2x 1x                   94x 94x 94x 94x 94x 94x 94x 94x       82x 82x 82x 82x 82x 82x 82x                                         168x 160x 160x 160x 160x 160x 195x 195x 195x 195x 195x 65x 65x 65x           116x   116x 245x 245x 77x 77x 77x     245x 159x   168x 168x       404x 326x 326x 326x 326x 167x 167x 167x 165x 83x 7x 7x 7x             326x        
import {Log} from 'json-joy/lib/json-crdt/log/Log';
import {type JsonNode, Model, type Patch} from 'json-joy/lib/json-crdt';
import {concurrency} from 'thingies/lib/concurrency';
import {createRace} from 'thingies/lib/createRace';
import {SESSION_GLOBAL} from '../constants';
import {Subject} from 'rxjs';
import {first, takeUntil} from 'rxjs/operators';
import type {
  BlockId,
  LocalRepo,
  LocalRepoDeleteEvent,
  LocalRepoEvent,
  LocalRepoMergeEvent,
  LocalRepoRebaseEvent,
  LocalRepoResetEvent,
} from '../local/types';
 
export class EditSession<N extends JsonNode = JsonNode<any>> {
  public log: Log<N>;
  protected _stopped = false;
  protected _stop$ = new Subject<void>();
  public onsyncerror?: (error: Error | unknown) => void;
  private _syncRace = createRace();
 
  public get model(): Model<N> {
    return this.log.end;
  }
 
  constructor(
    public readonly repo: LocalRepo,
    public readonly id: BlockId,
    protected start: Model<N>,
    public cursor: undefined | unknown = undefined,
    protected readonly session: number = Math.floor(Math.random() * 0x7fffffff),
  ) {
    this.log = new Log<N>(() => this.start.clone());
    const api = this.log.end.api;
    const flushUnsubscribe = api.onFlush.listen(() => {
      this.syncLog();
    });
    const patchUnsubscribe = api.onPatch.listen((patch) => {
      const id = patch.getId();
      Iif (!id) return;
      const clock = this.model.clock;
      Eif (id.sid === clock.sid && clock.time >= id.time) {
        this.syncLog();
      }
    });
    this._stop$.pipe(first()).subscribe(() => {
      flushUnsubscribe();
      patchUnsubscribe();
    });
    this.repo.change$(this.id).pipe(takeUntil(this._stop$)).subscribe(this.onEvent);
  }
 
  public dispose(): void {
    if (this._stopped) return;
    this._stopped = true;
    this._stop$.next();
  }
 
  protected clear(): void {
    const {start, log} = this;
    const empty = Model.create(undefined, start.clock.sid);
    start.reset(<any>empty);
    log.patches.clear();
    log.end.reset(<any>empty);
  }
 
  private saveInProgress = false;
  private readonly _syncQueue = concurrency(1);
 
  /**
   * Push (persist) any in-memory changes and pull (load) the latest state
   * from the local repo.
   */
  public sync(): Promise<null | {remote?: Promise<void>}> {
    return this._syncQueue(() => this._sync());
  }
 
  private async _sync(): Promise<null | {remote?: Promise<void>}> {
    if (this._stopped) return null;
    const log = this.log;
    const api = log.end.api;
    api.flush();
    this.saveInProgress = true;
    try {
      const patches: Patch[] = [];
      log.patches.forEach((patch) => {
        patches.push(patch.v);
      });
      const length = patches.length;
      // TODO: After async call check that sync state is still valid. New patches, might have been added.
      if (length || this.cursor === undefined) {
        const time = this.start.clock.time - 1;
        const res = await this.repo.sync({
          id: this.id,
          patches,
          time,
          cursor: this.cursor,
          session: this.session,
        });
        if (this._stopped) return null;
        // TODO: After sync call succeeds, remove the patches from the log.
        if (length) {
          const last = patches[length - 1];
          const lastId = last.getId();
          Eif (lastId) this.log.advanceTo(lastId);
          this.start.applyBatch(patches);
        }
        if (res.model) {
          this._syncRace(() => {
            this.reset(<any>res.model!);
          });
        } else if (res.merge && res.merge) {
          this._syncRace(() => {
            this.merge(<any>res.merge!);
          });
        }
        const cursorBehind = this.cursor !== res.cursor;
        if (cursorBehind) {
          const timer = setTimeout(async () => {
            try {
              if (this._stopped) return;
              const get = await this.repo.getIf({
                id: this.id,
                cursor: this.cursor,
              });
              Iif (this._stopped) return;
              if (!get) return;
              this.reset(<any>get.model);
              this.cursor = get.cursor;
            } catch {
              // Best-effort catch-up in a detached timer. The block may have
              // been deleted (getIf throws "NotFound") or the repo stopped
              // between scheduling and firing. Deletion is handled via the
              // change$/onEvent delete flow, so swallow the error here instead
              // of letting it surface as an unhandled promise rejection.
            }
          }, 50);
          (timer as {unref?: () => void}).unref?.();
        }
        return {remote: res.remote};
      } else {
        const res = await this.repo.getIf({id: this.id, time: this.model.clock.time - 1, cursor: this.cursor});
        if (this._stopped) return null;
        Iif (res) {
          this.reset(<any>res.model);
          this.cursor = res.cursor;
        }
        return null;
      }
    } finally {
      this.saveInProgress = false;
      this.drainEvents();
    }
  }
 
  public syncLog(): void {
    Iif (!this.log.patches.size()) {
      return;
    }
    this._syncRace(() => {
      this.sync()
        .then((result) => {
          Iif (result instanceof Error) this.onsyncerror?.(result);
        })
        .catch((error) => {
          console.error('syncLog: sync error', error);
          this.onsyncerror?.(error);
        });
    });
  }
 
  public async del(): Promise<void> {
    this.clear();
    this.dispose();
    await this.repo.del(this.id);
  }
 
  /**
   * Load latest state from the local repo.
   */
  public async load(): Promise<void> {
    const {model} = await this.repo.get({id: this.id});
    Eif (model.clock.time > this.start.clock.time) this.reset(<any>model);
  }
 
  public loadSilent(): void {
    this.load().catch(() => {});
  }
 
  // ------------------------------------------------------- change integration
 
  protected reset(model: Model<N>): void {
    this.start = model.clone();
    const log = this.log;
    const end = log.end;
    const ext = end.ext;
    Iif (end.api.builder.patch.ops.length) end.api.flush();
    end.reset(model);
    end.ext = ext;
    log.patches.forEach((patch) => end.applyPatch(patch.v));
  }
 
  protected rebase(patches: Patch[]): void {
    Iif (patches.length === 0) return;
    const log = this.log;
    const end = log.end;
    Iif (end.api.builder.patch.ops.length) end.api.flush();
    Eif (log.patches.size() === 0) {
      this.merge(patches);
      return;
    }
    this.start.applyBatch(patches);
    const newEnd = this.start.clone();
    const lastPatch = patches[patches.length - 1];
    let nextTick = lastPatch.getId()!.time + lastPatch.span();
    const rebased: Patch[] = [];
    log.patches.forEach(({v}) => {
      const patch = v.rebase(nextTick);
      rebased.push(patch);
      newEnd.applyPatch(patch);
      nextTick += patch.span();
    });
    log.patches.clear();
    for (const patch of rebased) log.patches.set(patch.getId()!, patch);
    const ext = log.end.ext;
    log.end.reset(newEnd);
    log.end.ext = ext;
  }
 
  protected merge(patches: Patch[]): void {
    if (!patches.length) return;
    const start = this.start;
    const log = this.log;
    const end = log.end;
    const sid = end.clock.sid;
    for (const patch of patches) {
      const patchId = patch.getId();
      Iif (!patchId) continue;
      const patchSid = patchId.sid;
      Iif (patchSid === SESSION_GLOBAL) continue;
      if (patchSid === sid && patchId.time < end.clock.time) continue;
      end.applyPatch(patch);
      start.applyPatch(patch);
      log.patches.del(patchId);
    }
  }
 
  // ------------------------------------------------ reactive event processing
 
  private events: LocalRepoEvent[] = [];
 
  private onEvent = (event: LocalRepoEvent): void => {
    Iif (this._stopped) return;
    if ((event as LocalRepoMergeEvent).merge) {
      const cursor = (event as LocalRepoMergeEvent).cursor;
      Eif (cursor !== undefined) {
        this.cursor = cursor;
      }
    }
    if ((event as LocalRepoRebaseEvent).rebase) {
      if ((event as LocalRepoRebaseEvent).session === this.session) return;
    }
    this.events.push(event);
    this.drainEvents();
  };
 
  private drainEvents(): void {
    if (this.saveInProgress || this._stopped) return;
    this._syncRace(() => {
      const events = this.events;
      const length = events.length;
      for (let i = 0; i < length; i++) {
        const event = events[i];
        try {
          if ((event as LocalRepoResetEvent).reset) this.reset(<any>(event as LocalRepoResetEvent).reset);
          else if ((event as LocalRepoRebaseEvent).rebase) this.rebase((event as LocalRepoRebaseEvent).rebase);
          else if ((event as LocalRepoMergeEvent).merge) this.merge((event as LocalRepoMergeEvent).merge);
          else Eif ((event as LocalRepoDeleteEvent).del) {
            this.clear();
            break;
          }
        } catch (error) {
          // tslint:disable-next-line no-console
          console.error('Failed to apply event', event, error);
        }
      }
      this.events = [];
    });
  }
}