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

83.33% Statements 165/198
79.54% Branches 70/88
83.87% Functions 26/31
87.87% Lines 145/165

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 2879x 9x 9x 9x   9x 9x                     9x   80x 80x   80x     80x           465x       80x 80x 80x 80x 80x   80x 80x 80x 105x   80x 17x 17x 17x 17x 17x     80x 79x 79x   80x         34x       120x 113x 79x 79x 79x       13x 13x 13x 13x 13x     80x           9x 163x 154x 154x 154x 154x 154x 154x 154x 90x   154x   154x 147x 147x             143x   124x 72x 72x 72x 72x   124x 34x 34x   90x 1x 1x     124x 124x 105x 46x 9x       9x 9x       105x   124x   7x 6x 5x       5x     149x 149x         122x 122x 106x   94x                 7x 7x 7x             2x 1x                   37x 37x 37x 37x 37x 37x       16x 16x 16x 16x 16x 16x 16x                                     40x 39x 39x 39x 39x 39x 40x 40x 40x 40x 40x 12x 12x 12x           80x   80x 91x 91x 25x 25x 25x     91x 58x   49x 49x       198x 161x 161x 161x 161x 47x 47x 47x 45x 29x 6x 6x 6x             161x        
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/concurrencyDecorator';
import {createRace} from 'thingies/lib/createRace';
import {SESSION} from 'json-joy/lib/json-crdt-patch/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();
 
  /** Reference count — `dispose()` only tears the session down at zero. */
  protected _refs = 1;
 
  /** Invoked exactly once on final teardown (after the last `dispose`). */
  public onTeardown?: () => void;
 
  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);
  }
 
  /** Increment the reference count — for a new caller sharing this session. */
  public acquire(): void {
    this._refs++;
  }
 
  public dispose(): void {
    if (this._stopped) return;
    if (--this._refs > 0) return;
    this._stopped = true;
    this._stop$.next();
    this.onTeardown?.();
  }
 
  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;
 
  /**
   * Push (persist) any in-memory changes and pull (load) the latest state
   * from the local repo.
   */
  @concurrency(1) public 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 () => {
            if (this._stopped) return;
            const get = await this.repo.getIf({
              id: this.id,
              cursor: this.cursor,
            });
            Iif (this._stopped) return;
            Eif (!get) return;
            this.reset(<any>get.model);
            this.cursor = get.cursor;
          }, 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((error) => {
          Iif (error instanceof Error) this.onsyncerror?.(error);
        })
        .catch((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;
    Iif (end.api.builder.patch.ops.length) end.api.flush();
    end.reset(model);
    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);
    log.end.reset(newEnd);
  }
 
  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 = [];
    });
  }
}