All files / json-crdt-repo/src/local/level LevelLocalRepo.ts

81.57% Statements 549/673
71% Branches 213/300
90.42% Functions 85/94
85.83% Lines 515/600

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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 120613x 13x 13x 13x 13x 13x 13x   13x 13x 13x                                                                                   13x               13x                   13x                 13x                 13x                 13x                 13x                   13x           13x                                                                                                                           13x             135x   135x 135x 135x 135x 135x 135x 135x 135x 138x       135x 135x 135x   13x 13x 135x 135x 135x 135x 135x 135x       1x         185x 152x 152x                     923x             1054x       720x 720x 720x       1027x 1027x 1027x         810x       584x       203x 203x       9x                 9x                 252x       188x 188x 187x       286x   286x                 286x   286x                 286x 286x 286x       53x 53x                                                                                     789x 789x 733x 733x       327x 327x 290x 290x       327x 327x 290x 290x   33x 33x           293x 293x 293x   232x 232x         189x 189x 131x 131x   187x       79x 79x 79x 27x 52x       542x       3x 3x       4x 4x           148x 148x 148x 148x       165x 148x       148x 148x   70x 70x 23x         81x                 151x 151x 104x 104x 104x 104x 104x 101x 101x   102x 20x 20x 20x 1x 1x 1x       20x 20x   19x     82x 81x 81x 81x 188x 188x   81x 81x 78x 55x 55x     55x 55x 55x 55x 55x     55x 55x 55x 55x 55x 55x                     55x 55x 4x 4x 5x 5x 5x   4x                       55x 63x 63x 63x   55x 55x 55x                 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x   55x                                         96x 96x 96x       96x 96x 4x 4x         96x       4x 4x 3x           3x 3x 3x               96x 96x 3x 3x 3x 3x   4x 4x 4x 4x 4x 3x       95x     135x       96x 96x       96x         95x 88x       88x 1x 1x   88x 88x             178x 178x       178x 178x 178x 110x 124x 124x 124x 124x 124x         124x     178x 178x 176x 175x 95x   95x     10x     95x 95x       1x 1x         1x               105x 105x 71x 71x   33x 33x 33x 33x 33x 33x 33x             16x 16x 16x 15x 10x   15x 6x   6x 6x 4x 4x       15x               225x 225x 225x 225x 225x 225x 197x 110x 110x   45x 45x       87x 68x 68x   35x     35x       19x   28x       178x 95x 95x       73x 73x 73x 73x 52x 52x 52x 21x 21x 21x   73x 73x 73x 73x       73x 73x 73x 73x 73x 73x 73x 23x 23x   73x 73x 73x 73x 86x 86x 86x 86x 86x 8x 8x   79x 79x 13x 13x 13x   79x 79x 79x 79x 79x 79x 79x   73x 70x   73x 70x 70x   3x   73x 3x 3x   70x     13x     70x 11x 11x   59x       185x         150x 150x 150x       170x 135x                 159x 159x       9x 9x 9x 9x 9x 9x 9x       9x 9x                             9x             200x 200x 200x 40x   31x 16x 16x 9x   7x 2x 2x   5x   15x 15x 15x             17x 17x 12x 12x 12x 12x 9x 9x 9x         9x       9x 9x 9x 9x             202x 202x 186x 186x 186x 186x 186x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     185x 59x 58x 58x 43x 2x 2x 2x 126x 2x 2x 2x 2x   2x   41x 41x 41x 8x 8x 8x   41x 41x 39x 39x         87x 87x 87x     133x   62x 61x 62x 61x 61x     4x 4x 4x 4x     61x 57x 57x 51x 51x 27x   57x 26x 26x     6x 6x 6x       133x   87x             135x     87x 87x 87x 86x 86x     205x 205x   33x 28x   170x 46x   2x 2x         86x     86x       86x 86x       170x 170x 170x 170x 170x 170x 170x 146x 146x 145x 145x 125x 125x 123x       1x 1x 1x         2x 2x 1x 1x 1x 1x                             1x   1x        
import {BehaviorSubject, defer, type Observable, Subject, type Subscription} from 'rxjs';
import {catchError, filter, finalize, map, share, switchMap, takeUntil} from 'rxjs/operators';
import {Writer} from '@jsonjoy.com/buffers/lib/Writer';
import {CborJsonValueCodec} from '@jsonjoy.com/json-pack/lib/codecs/cbor';
import {Model, Patch} from 'json-joy/lib/json-crdt';
import {deepEqual} from '@jsonjoy.com/json-equal/lib/deepEqual';
import {RpcError} from '@jsonjoy.com/rpc-error';
import {SESSION} from 'json-joy/lib/json-crdt-patch/constants';
import {once} from 'thingies/lib/once';
import {timeout} from 'thingies/lib/timeout';
import {pubsub} from '../../pubsub';
import type {ServerBatch, ServerHistory, ServerPatch} from '../../remote/types';
import type {
  BlockId,
  LocalRepo,
  LocalRepoEvent,
  LocalRepoDeleteEvent,
  LocalRepoMergeEvent,
  LocalRepoRebaseEvent,
  LocalRepoResetEvent,
  LocalRepoSyncRequest,
  LocalRepoSyncResponse,
  LocalRepoGetResponse,
  LocalRepoGetRequest,
  LocalRepoCreateResponse,
  LocalRepoCreateRequest,
  LocalRepoGet0Response,
  LocalRepoGetIfResponse,
  LocalRepoGetIfRequest,
  LocalRepoPullResponse,
} from '../types';
import type {
  BinStrLevel,
  BinStrLevelOperation,
  BlockMeta,
  LocalBatch,
  SyncResult,
  LevelLocalRepoPubSub,
  LevelLocalRepoPubSubMessage,
  LevelLocalRepoCursor,
  BlockSyncRecord,
} from './types';
import type {CrudLocalRepoCipher} from './types';
import type {Locks} from 'thingies/lib/Locks';
import type {JsonValueCodec} from '@jsonjoy.com/json-pack/lib/codecs/types';
 
/**
 * @todo
 *
 * 1. Implement pull loop, when WebSocket subscription cannot be established.
 */
 
enum Defaults {
  /**
   * The root of the block repository.
   *
   * ```
   * b!<collection>!<id>!
   * ```
   */
  BlockRepoRoot = 'b',
 
  /**
   * The root of the key-space where items are marked as "dirty" and need sync.
   *
   * ```
   * s!b!<collection>!<id>
   * ```
   */
  // eslint-disable-next-line
  SyncRoot = 's',
 
  /**
   * The metadata of the block.
   *
   * ```
   * b!<collection>!<id>!k!x
   * ```
   */
  Metadata = 'k!x',
 
  /**
   * The state of the latest known server-side model.
   *
   * ```
   * b!<collection>!<id>!k!m
   * ```
   */
  Model = 'k!m',
 
  /**
   * List of frontier patches.
   *
   * ```
   * b!<collection>!<id>!f!<time>
   * ```
   */
  Frontier = 'f',
 
  /**
   * List of batches verified by the server.
   *
   * ```
   * b!<collection>!<id>!h!<seq>
   * ```
   */
  Batches = 'h',
 
  /**
   * List of snapshots.
   *
   * ```
   * b!<collection>!<id>!s!<seq>
   * ```
   */
  // eslint-disable-next-line
  Snapshots = 's',
 
  /**
   * The default length of the history, if `hist` metadata property not
   * specified.
   */
  HistoryLength = 100,
}
 
export interface LevelLocalRepoOpts {
  /**
   * Session ID of the user on this device. The same session ID is reused across
   * all tabs.
   */
  readonly sid: number;
 
  /**
   * Local persistance LevelDB API.
   */
  readonly kv: BinStrLevel;
 
  /**
   * Optional content encryption/decryption API.
   */
  readonly cipher?: CrudLocalRepoCipher;
 
  /**
   * Cross-tab locking API.
   */
  readonly locks: Locks;
 
  /**
   * Optional observable that emits `true` when the device is connected to the
   * server and `false` when it's not.
   */
  readonly connected$?: BehaviorSubject<boolean>;
 
  /**
   * RPC API for communication with the server.
   */
  readonly rpc: ServerHistory;
 
  /**
   * Event bus.
   */
  readonly pubsub?: LevelLocalRepoPubSub;
 
  /**
   * Number of milliseconds after which remote calls are considered timed out.
   */
  readonly remoteTimeout?: number;
 
  /**
   * Minimum backoff time in milliseconds for the sync loop.
   */
  readonly syncLoopMinBackoff?: number;
 
  /**
   * Maximum backoff time in milliseconds for the sync loop.
   */
  readonly syncLoopMaxBackoff?: number;
 
  /**
   * If specified, background sync errors will be emitted here.
   */
  readonly onSyncError?: (error: Error | unknown) => void;
}
 
export class LevelLocalRepo implements LocalRepo {
  readonly kv: BinStrLevel;
  public readonly locks: Locks;
  public readonly sid: number;
  public readonly connected$: BehaviorSubject<boolean>;
  protected readonly pubsub: LevelLocalRepoPubSub;
  protected readonly cipher?: CrudLocalRepoCipher;
  protected readonly codec: JsonValueCodec = new CborJsonValueCodec(new Writer(1024 * 16) as any);
 
  constructor(protected readonly opts: LevelLocalRepoOpts) {
    this.kv = opts.kv;
    this.locks = opts.locks;
    this.sid = opts.sid;
    this.connected$ = opts.connected$ ?? new BehaviorSubject(true);
    this.pubsub = opts.pubsub ?? pubsub('level-local-repo');
    this.cipher = opts.cipher;
    this._conSub = this.connected$.subscribe((connected) => {
      if (connected && !this._remoteSyncLoopActive) this.runRemoteSyncLoop();
    });
  }
 
  private _conSub: Subscription | undefined = undefined;
  private _stopped = false;
  private readonly _stop$ = new Subject<void>();
 
  @once
  public stop(): void {
    this._remoteSyncLoopActive = false;
    clearTimeout(this._remoteSyncDelayTimer as any);
    this._stopped = true;
    this._stop$.next();
    this._stop$.complete();
    this._conSub?.unsubscribe();
  }
 
  protected emitSyncError(error: Error | unknown): void {
    Eif (this._stopped) return;
    this.opts.onSyncError?.(error);
  }
 
  protected emitPubSub(message: LevelLocalRepoPubSubMessage): void {
    if (this._stopped) return;
    try {
      this.pubsub.pub(message);
    } catch (error) {
      if (this._stopped) return;
      this.emitSyncError(error);
    }
  }
 
  // eslint-disable-next-line
  protected async encrypt(blob: Uint8Array, zip: boolean): Promise<Uint8Array> {
    // if (zip) blob = await gzip(blob);
    // if (this.cipher) blob = await this.cipher.encrypt(blob);
    return blob;
  }
 
  // eslint-disable-next-line
  protected async decrypt(blob: Uint8Array, zip: boolean): Promise<Uint8Array> {
    // if (this.cipher) blob = await this.cipher.decrypt(blob);
    // if (zip) blob = await ungzip(blob);
    return blob;
  }
 
  protected async encode(value: unknown, zip: boolean): Promise<Uint8Array> {
    const encoded = this.codec.encoder.encode(value);
    const encrypted = await this.encrypt(encoded, zip);
    return encrypted;
  }
 
  protected async decode(blob: Uint8Array, zip: boolean): Promise<unknown> {
    const decrypted = await this.decrypt(blob, zip);
    const decoded = this.codec.decoder.decode(decrypted);
    return decoded;
  }
 
  /** @todo Encrypt collection and key. */
  public async blockKeyBase(id: BlockId): Promise<string> {
    return Defaults.BlockRepoRoot + '!' + id.join('!') + '!';
  }
 
  public frontierKeyBase(blockKeyBase: string): string {
    return blockKeyBase + Defaults.Frontier + '!';
  }
 
  public frontierKey(blockKeyBase: string, time: number): string {
    const timeFormatted = time.toString(36).padStart(8, '0');
    return this.frontierKeyBase(blockKeyBase) + timeFormatted;
  }
 
  public batchKeyBase(blockKeyBase: string): string {
    return blockKeyBase + Defaults.Batches + '!';
  }
 
  public batchKey(blockKeyBase: string, seq: number): string {
    const seqFormatted = seq.toString(36).padStart(8, '0');
    return this.batchKeyBase(blockKeyBase) + seqFormatted;
  }
 
  public snapshotKeyBase(blockKeyBase: string): string {
    return blockKeyBase + Defaults.Snapshots + '!';
  }
 
  public snapshotKey(blockKeyBase: string, seq: number): string {
    const seqFormatted = seq.toString(36).padStart(8, '0');
    return this.snapshotKeyBase(blockKeyBase) + seqFormatted;
  }
 
  protected syncKey(keyBase: string): string {
    return Defaults.SyncRoot + '!' + keyBase;
  }
 
  protected async _exists(keyBase: string): Promise<boolean> {
    const metaKey = keyBase + Defaults.Metadata;
    const exists = (await this.kv.keys({gte: metaKey, lte: metaKey, limit: 1}).all()).length > 0;
    return exists;
  }
 
  protected _modelWrOp(keyBase: string, model: Uint8Array): Promise<BinStrLevelOperation> {
    return this.encode(model, true).then(
      (value) =>
        ({
          type: 'put',
          key: keyBase + Defaults.Model,
          value,
        }) as BinStrLevelOperation,
    );
  }
 
  protected _metaWrOp(keyBase: string, meta?: BlockMeta): Promise<BinStrLevelOperation> {
    return this.encode(meta, false).then(
      (value) =>
        ({
          type: 'put',
          key: keyBase + Defaults.Metadata,
          value,
        }) as BinStrLevelOperation,
    );
  }
 
  protected async _modelWrOps(keyBase: string, model: Uint8Array, meta?: BlockMeta): Promise<BinStrLevelOperation[]> {
    const ops: Promise<BinStrLevelOperation>[] = [this._modelWrOp(keyBase, model)];
    Eif (meta) ops.push(this._metaWrOp(keyBase, meta));
    return Promise.all(ops);
  }
 
  protected async _wrModel(keyBase: string, model: Uint8Array, meta?: BlockMeta): Promise<void> {
    const ops = await this._modelWrOps(keyBase, model, meta);
    await this.kv.batch(ops);
  }
 
  protected async load(id: BlockId): Promise<{model: Model; cursor: number}> {
    const blockId = id.join('/');
    const res = await this.opts.rpc.read(blockId);
    const block = res.block;
    const snapshot = block.snapshot;
    const seq = snapshot.seq;
    const sid = this.sid;
    const model = Model.load(snapshot.blob, sid);
    for (const batch of block.tip) for (const patch of batch.patches) model.applyPatch(Patch.fromBinary(patch.blob));
    const keyBase = await this.blockKeyBase(id);
    const metaKey = keyBase + Defaults.Metadata;
    const meta: BlockMeta = {
      time: 0,
      seq,
    };
    const modelBlob = model.toBinary();
    const [metaBlob, modelTupleBlob] = await Promise.all([this.encode(meta, false), this.encode(modelBlob, true)]);
    const ops: BinStrLevelOperation[] = [
      {
        type: 'put',
        key: metaKey,
        value: metaBlob,
      },
      {
        type: 'put',
        key: keyBase + Defaults.Model,
        value: modelTupleBlob,
      },
    ];
    await this.lockBlock(keyBase, async () => {
      const exists = await this._exists(keyBase);
      if (exists) throw new Error('EXISTS');
      await this.kv.batch(ops);
    });
    // TODO: Emit something here...
    // this.pubsub.pub(['pull', {id, batches: [], snapshot: {seq, blob: modelBlob}}])
    return {model, cursor: seq};
  }
 
  protected async readMeta(keyBase: string): Promise<BlockMeta> {
    const metaKey = keyBase + Defaults.Metadata;
    const blob = await this.kv.get(metaKey);
    const meta = (await this.decode(blob as any, false)) as BlockMeta;
    return meta;
  }
 
  public async readModel0(keyBase: string): Promise<Uint8Array> {
    const modelKey = keyBase + Defaults.Model;
    const blob = await this.kv.get(modelKey);
    const decoded = (await this.decode(blob as any, true)) as Uint8Array;
    return decoded;
  }
 
  public async readModel(keyBase: string): Promise<Model> {
    try {
      const blob = await this.readModel0(keyBase);
      const model = Model.load(blob, this.sid);
      return model;
    } catch (error) {
      Eif (!!error && typeof error === 'object' && (error as any).code === 'LEVEL_NOT_FOUND')
        throw new Error('NOT_FOUND');
      throw error;
    }
  }
 
  public async *readFrontierBlobs0(keyBase: string) {
    const gt = this.frontierKeyBase(keyBase);
    const lt = gt + '~';
    for await (const [key, buf] of this.kv.iterator({gt, lt})) {
      /** @todo Remove this conversion once json-pack supports Buffers. */
      const uint8 = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
      yield [key, uint8] as const;
    }
  }
 
  public async readFrontier0(keyBase: string): Promise<Patch[]> {
    const patches: Patch[] = [];
    for await (const [, blob] of this.readFrontierBlobs0(keyBase)) {
      const patch = Patch.fromBinary(blob);
      patches.push(patch);
    }
    return patches;
  }
 
  public async readFrontierTip(keyBase: string): Promise<Patch | undefined> {
    const frontierBase = this.frontierKeyBase(keyBase);
    const lte = frontierBase + '~';
    for await (const blob of this.kv.values({lte, limit: 1, reverse: true}))
      return Patch.fromBinary(await this.decrypt(blob, false));
    return;
  }
 
  protected async lockBlock<T>(keyBase: string, fn: () => Promise<T>): Promise<T> {
    return await this.locks.lock(keyBase, 500, 500)<T>(fn);
  }
 
  protected async lockBlockForSync<T>(keyBase: string, fn: () => Promise<T>): Promise<T> {
    const key = 's!' + keyBase;
    return await this.locks.lock(key, 2000, 3000)<T>(fn);
  }
 
  protected isBlockLockedForSync(keyBase: string): boolean {
    const key = 's!' + keyBase;
    return this.locks.isLocked(key);
  }
 
  // --------------------------------------------------- Remote synchronization
 
  protected async markDirty(keyBase: string, id: BlockId): Promise<void> {
    const key = this.syncKey(keyBase);
    const record: BlockSyncRecord = [id, Date.now()];
    const blob = await this.encode(record, false);
    await this.kv.put(key, blob);
  }
 
  protected async markDirtyAndSync(keyBase: string, id: BlockId): Promise<boolean> {
    if (this._stopped) return false;
    this.markDirty(keyBase, id).catch((error) => {
      if (this._stopped) return;
      this.emitSyncError(error);
    });
    try {
      return await this.push(keyBase, id, true);
    } catch (error) {
      Iif (typeof error === 'object' && error && (error as any).message === 'Not Found') return false;
      else if (error instanceof Error && error.message === 'DISCONNECTED') return false;
      throw error;
    }
  }
 
  protected remoteTimeout(): number {
    return this.opts.remoteTimeout ?? 5000;
  }
 
  /**
   * Pushes to remote.
   * @param id Block ID.
   * @param pull Whether to pull if there are no patches to push.
   */
  protected async push(keyBase: string, id: BlockId, doPull = false): Promise<boolean> {
    Iif (this._stopped) return false;
    if (!this.connected$.getValue()) throw new Error('DISCONNECTED');
    const remote = this.opts.rpc;
    const remoteId = id.join('/');
    const patches: ServerPatch[] = [];
    const ops: BinStrLevelOperation[] = [{type: 'del', key: this.syncKey(keyBase)}];
    for await (const [key, blob] of this.readFrontierBlobs0(keyBase)) {
      ops.push({type: 'del', key});
      patches.push({blob});
    }
    if (!patches.length) {
      const meta = await this.readMeta(keyBase);
      Eif (meta.seq === -1) {
        remote.create(remoteId).catch((error) => {
          const code = !!error && typeof error === 'object' ? (error as any).code : undefined;
          const message = error instanceof Error ? error.message : undefined;
          Eif (code === 'CONFLICT' || message === 'CONFLICT') return;
          this.emitSyncError(error);
        });
      }
      Eif (doPull) {
        await this.pull(id);
      }
      return false;
    }
    // TODO: handle case when this times out, but actually succeeds, so on re-sync it handles the case when the block is already synced.
    return await this.lockBlock(keyBase, async () => {
      const TIMEOUT = this.remoteTimeout();
      const startTime = Date.now();
      const assertTimeout = () => {
        Iif (Date.now() - startTime > TIMEOUT) throw new Error('TIMEOUT');
        if (this._stopped) throw new Error('STOPPED');
      };
      return await timeout(TIMEOUT, async () => {
        const read = await Promise.all([this.readModel(keyBase), this.readMeta(keyBase)]);
        assertTimeout();
        let model = read[0];
        const meta = read[1];
        // TODO: Track some meta to avoid unnecessary syncs.
        // if (Date.now() - meta.ts < 1000) return false;
        const hist = !!meta.hist;
        const lastKnownSeq = meta.seq;
        try {
          const response = await remote.update(remoteId, {patches}, lastKnownSeq);
          assertTimeout();
          // TODO: handle case when block is deleted on the server.
          // Process pull
          const merge: Uint8Array[] = []; // List of merge patches to emit over pubsub.
          const pull = response.pull;
          Eif (pull) {
            const snapshot = pull.snapshot;
            const batches = pull.batches;
            Iif (snapshot) {
              model = Model.load(snapshot.blob, this.sid);
              if (hist) {
                ops.push({
                  type: 'put',
                  key: this.snapshotKey(keyBase, snapshot.seq),
                  value: await this.encode(snapshot, true),
                });
                assertTimeout();
              }
            }
            Eif (batches) {
              for (const b of batches) {
                const patches = b.patches;
                for (const patch of patches) {
                  const blob = patch.blob;
                  merge.push(blob);
                  model.applyPatch(Patch.fromBinary(blob));
                }
                Iif (hist) {
                  ops.push({
                    type: 'put',
                    key: this.batchKey(keyBase, b.seq),
                    value: await this.encode(b, false),
                  });
                  assertTimeout();
                }
              }
            }
          }
          // Process the latest batch
          for (const patch of patches) {
            const blob = patch.blob;
            merge.push(blob);
            model.applyPatch(Patch.fromBinary(blob));
          }
          const batch: LocalBatch = {...response.batch, patches};
          const seq = batch.seq;
          Iif (hist) {
            ops.push({
              type: 'put',
              key: this.batchKey(keyBase, seq),
              value: await this.encode(batch, false),
            });
            assertTimeout();
          }
          // Process the model and metadata
          delete meta.syncFailures;
          meta.syncTs = Date.now();
          meta.time = model.clock.time - 1;
          meta.seq = seq;
          const modelOps = await this._modelWrOps(keyBase, model.toBinary(), meta);
          assertTimeout();
          ops.push(...modelOps);
          await this.kv.batch(ops);
          Eif (merge.length) {
            this.emitPubSub({type: 'merge', id, patches: merge, seq: seq});
          }
          return true;
        } catch (error) {
          // Store fails and time.
          meta.syncTs = Date.now();
          meta.syncFailures = (meta.syncFailures ?? 0) + 1;
          try {
            const op = await this._metaWrOp(keyBase, meta);
            await this.kv.batch([op]);
          } catch (err) {
            this.emitSyncError(err);
          }
          throw error;
        }
      });
    });
  }
 
  /**
   * Iterates over all blocks marked as dirty.
   */
  protected async *listDirty(): AsyncIterableIterator<BlockSyncRecord> {
    const gt: string = Defaults.SyncRoot;
    const lt: string = Defaults.SyncRoot + '~';
    for await (const blob of this.kv.values({gt, lt})) yield (await this.decode(blob, false)) as BlockSyncRecord;
  }
 
  protected async *listDirtyBatch(batchSize: number = 3): AsyncIterableIterator<BlockSyncRecord[]> {
    let batch: BlockSyncRecord[] = [];
    for await (const record of this.listDirty()) {
      batch.push(record);
      Iif (batch.length >= batchSize) {
        yield batch;
        batch = [];
      }
    }
    if (batch.length) yield batch;
  }
 
  public async syncItem(keyBase: string, id: BlockId): Promise<SyncResult> {
    try {
      const meta = await this.readMeta(keyBase);
      Iif (meta.syncFailures && meta.syncTs) {
        const timeout = Math.min(1000 * Math.pow(2, meta.syncFailures), 30000);
        const now = Date.now();
        const shouldSkip = now - timeout < meta.syncTs;
        if (shouldSkip) return [id, false];
      }
      return await this.lockBlockForSync(keyBase, async () => {
        const success = await this.push(keyBase, id, true);
        return [id, success];
      });
    } catch (error) {
      return [id, false, error];
    }
  }
 
  public async remoteSyncAll(): Promise<SyncResult[]> {
    const resultList: SyncResult[] = [];
    for await (const batch of this.listDirtyBatch()) {
      Iif (this._stopped) return resultList;
      Iif (!this._remoteSyncLoopActive) return resultList;
      Iif (!this.connected$.getValue()) return resultList;
      await Promise.all(
        batch.map(async (record) => {
          const [id] = record;
          const keyBase = await this.blockKeyBase(id);
          const isLocked = this.isBlockLockedForSync(keyBase);
          Iif (isLocked) return;
          const result = await this.syncItem(keyBase, id);
          resultList.push(result);
        }),
      );
    }
    return resultList;
  }
 
  protected _remoteSyncLoopActive = false;
  protected _remoteSyncDelayTimer: unknown;
 
  protected runRemoteSyncLoop(): void {
    this._remoteSyncLoopActive = true;
    Iif (!this.connected$.getValue()) {
      this._remoteSyncLoopActive = false;
      return;
    }
    this.remoteSyncAll()
      .catch((error) => {
        this.emitSyncError(error);
      })
      .finally(() => {
        if (!this._remoteSyncLoopActive) return;
        Iif (!this.connected$.getValue()) {
          this._remoteSyncLoopActive = false;
          return;
        }
        const timer = setTimeout(() => {
          Iif (!this._remoteSyncLoopActive) return;
          this.runRemoteSyncLoop();
        }, 2000);
        (timer as {unref?: () => void}).unref?.();
        this._remoteSyncDelayTimer = timer;
      });
  }
 
  /** ----------------------------------------------------- {@link LocalRepo} */
 
  public async create({id, patches}: LocalRepoCreateRequest): Promise<LocalRepoCreateResponse> {
    const keyBase = await this.blockKeyBase(id);
    const meta: BlockMeta = {
      time: 0,
      seq: -1,
    };
    const ops: BinStrLevelOperation[] = [];
    const model = Model.create(void 0, this.sid);
    if (patches && patches.length) {
      for (const patch of patches) {
        const patchId = patch.getId();
        Iif (!patchId) throw new Error('PATCH_ID_MISSING');
        model.applyPatch(patch);
        const patchKey = this.frontierKey(keyBase, patchId.time);
        const op: BinStrLevelOperation = {
          type: 'put',
          key: patchKey,
          value: await this.encrypt(patch.toBinary(), false),
        };
        ops.push(op);
      }
    }
    ops.push(...(await this._modelWrOps(keyBase, model.toBinary(), meta)));
    await this.lockBlock(keyBase, async () => {
      const exists = await this._exists(keyBase);
      if (exists) throw new Error('EXISTS');
      await this.kv.batch(ops);
    });
    const remote = this.markDirtyAndSync(keyBase, id)
      .then(() => {})
      .catch((error) => {
        Eif (this._stopped) return;
        this.emitSyncError(error);
      });
    remote.catch(() => {});
    return {model, remote};
  }
 
  public async get0(id: BlockId): Promise<LocalRepoGet0Response> {
    const keyBase = await this.blockKeyBase(id);
    const [model, meta, frontier] = await Promise.all([
      this.readModel(keyBase),
      this.readMeta(keyBase),
      this.readFrontier0(keyBase),
    ]);
    return {
      model,
      frontier,
      meta,
    };
  }
 
  public async get({id, remote}: LocalRepoGetRequest): Promise<LocalRepoGetResponse> {
    try {
      const {model, cursor} = await this._syncRead(id);
      Iif (!model) throw RpcError.notFound();
      return {model, cursor};
    } catch (error) {
      const code = !!error && typeof error === 'object' ? (error as any).code : undefined;
      const message = error instanceof Error ? error.message : undefined;
      const notFound = code === 'NOT_FOUND' || message === 'NOT_FOUND' || message === 'Not Found';
      Iif (remote && notFound) return await this.load(id);
      Eif (notFound) {
        Iif (RpcError.isRpcError(error)) throw error;
        throw RpcError.notFound('Not Found', undefined, error);
      }
      throw error;
    }
  }
 
  public async getIf(request: LocalRepoGetIfRequest): Promise<null | LocalRepoGetIfResponse> {
    let get = false;
    const keyBase = await this.blockKeyBase(request.id);
    const meta = await this.readMeta(keyBase);
    if (typeof request.cursor === 'number') {
      Iif (request.cursor < meta.seq) get = true;
    }
    if (!get && typeof request.time === 'number') {
      Iif (request.time < meta.time) get = true;
      else {
        const tip = await this.readFrontierTip(keyBase);
        if (tip) {
          const tipTime = tip.getId()?.time ?? 0;
          Iif (request.time < tipTime + tip.span() - 1) get = true;
        }
      }
    }
    Eif (!get) return null;
    const [model, frontier] = await Promise.all([this.readModel(keyBase), this.readFrontier0(keyBase)]);
    model.applyBatch(frontier);
    const cursor: LevelLocalRepoCursor = meta.seq;
    return {model, cursor};
  }
 
  public async sync(req: LocalRepoSyncRequest): Promise<LocalRepoSyncResponse> {
    const cursor = req.cursor as LevelLocalRepoCursor | undefined;
    const {id, patches} = req;
    const isNewSession = cursor === undefined;
    const isCreate = !!patches;
    const isWrite = !!patches && patches.length !== 0;
    if (isNewSession) {
      if (isWrite) {
        try {
          return await this._syncCreate(req);
        } catch (error) {
          Eif (error instanceof Error && error.message === 'EXISTS') {
            return await this._syncMerge(req);
          }
          throw error;
        }
      } else if (isCreate) {
        try {
          return await this._syncCreate(req);
        } catch (error) {
          Eif (error instanceof Error && error.message === 'EXISTS')
            // TODO: make sure reset does not happen, if models are the same.
            // TODO: Check for `req.time` in `_syncRead`.
            return await this._syncRead(id);
          throw error;
        }
      } else {
        return await this._syncRead(id);
      }
    } else return await this._syncMerge(req);
  }
 
  private async _syncCreate(req: LocalRepoSyncRequest): Promise<LocalRepoSyncResponse> {
    const {remote} = await this.create(req);
    const cursor: LevelLocalRepoCursor = -1;
    return {cursor, remote};
  }
 
  private async _syncMerge(req: LocalRepoSyncRequest): Promise<LocalRepoSyncResponse> {
    const {id, patches} = req;
    let lastKnownTime = 0;
    const reqTime = req.time;
    if (typeof reqTime === 'number') {
      lastKnownTime = reqTime;
      const firstPatch = patches?.[0];
      if (firstPatch?.getId()?.sid === SESSION.GLOBAL) lastKnownTime = firstPatch.getId()!.time + firstPatch.span() - 1;
    } else Eif (patches?.length) {
      const firstPatchTime = patches?.[0]?.getId()?.time;
      Eif (typeof firstPatchTime === 'number') lastKnownTime = firstPatchTime - 1;
    }
    const keyBase = await this.blockKeyBase(id);
    Iif (!patches || !patches.length) throw new Error('EMPTY_BATCH');
    const writtenPatches: Uint8Array[] = [];
    let cursor: LevelLocalRepoCursor = -1;
    // TODO: Check if `patches` need rebasing, if not, just merge.
    // TODO: Return correct response.
    // TODO: Check that remote state is in sync, too.
    let needsReset = false;
    const didPush = await this.lockBlock(keyBase, async () => {
      const [tip, meta] = await Promise.all([this.readFrontierTip(keyBase), this.readMeta(keyBase)]);
      let nextTick = meta.time + 1;
      if (lastKnownTime < meta.time) needsReset = true;
      cursor = meta.seq;
      if (tip) {
        const tipTime = tip.getId()?.time ?? 0;
        nextTick = tipTime + tip.span();
      }
      const ops: BinStrLevelOperation[] = [];
      const sid = this.sid;
      const length = patches.length;
      for (let i = 0; i < length; i++) {
        const patch = patches[i];
        const patchId = patch.getId();
        Iif (!patchId) throw new Error('PATCH_ID_MISSING');
        const isSchemaPatch = patchId.sid === SESSION.GLOBAL && patchId.time === 1;
        if (isSchemaPatch) {
          const patchAheadOfTip = patchId.time >= nextTick;
          if (!patchAheadOfTip) continue;
        }
        let rebased = patch;
        if (patchId.sid === sid && nextTick > patchId.time) {
          needsReset = true;
          rebased = patch.rebase(nextTick);
          nextTick = rebased.getId()!.time + rebased.span();
        }
        const id = rebased.getId()!;
        const time = id.time;
        const patchKey = this.frontierKey(keyBase, time);
        const uint8 = await this.encrypt(rebased.toBinary(), false);
        writtenPatches.push(uint8);
        const op: BinStrLevelOperation = {type: 'put', key: patchKey, value: uint8};
        ops.push(op);
      }
      if (writtenPatches.length) {
        this.emitPubSub({type: 'rebase', id, patches: writtenPatches, session: req.session});
      }
      if (ops.length) {
        await this.kv.batch(ops);
        return true;
      }
      return false;
    });
    if (!didPush && !needsReset) {
      const merge = await this.readFrontier0(keyBase);
      return {cursor, merge};
    }
    const remote = this.markDirtyAndSync(keyBase, id)
      .then(() => {})
      .catch((error) => {
        Eif (this._stopped) return;
        this.emitSyncError(error);
      });
    if (needsReset) {
      const {cursor, model} = await this._syncRead0(keyBase);
      return {cursor, model, remote};
    }
    return {cursor, remote};
  }
 
  protected async readLocal0(keyBase: string): Promise<[model: Model, cursor: LevelLocalRepoCursor]> {
    const [model, meta, frontier] = await Promise.all([
      this.readModel(keyBase),
      this.readMeta(keyBase),
      this.readFrontier0(keyBase),
    ]);
    model.applyBatch(frontier);
    const cursor: LevelLocalRepoCursor = meta.seq;
    return [model, cursor];
  }
 
  private async _syncRead0(keyBase: string): Promise<LocalRepoSyncResponse> {
    const [model, cursor] = await this.readLocal0(keyBase);
    return {
      model,
      cursor,
      // TODO: `remote` should load the block from the server.
      remote: Promise.resolve(),
    };
  }
 
  private async _syncRead(id: BlockId): Promise<LocalRepoSyncResponse> {
    const keyBase = await this.blockKeyBase(id);
    return this._syncRead0(keyBase);
  }
 
  public async del(id: BlockId): Promise<void> {
    const keyBase = await this.blockKeyBase(id);
    const frontierKeyBase = this.frontierKeyBase(keyBase);
    const batchKeyBase = this.batchKeyBase(keyBase);
    const snapshotKeyBase = this.snapshotKeyBase(keyBase);
    const kv = this.kv;
    await this.lockBlock(keyBase, async () => {
      await kv.batch([
        {type: 'del', key: keyBase + Defaults.Metadata},
        {type: 'del', key: keyBase + Defaults.Model},
      ]);
      this.emitPubSub({id, type: 'del'});
      await Promise.all([
        kv.clear({
          gt: frontierKeyBase,
          lt: frontierKeyBase + '~',
        }),
        kv.clear({
          gt: batchKeyBase,
          lt: batchKeyBase + '~',
        }),
        kv.clear({
          gt: snapshotKeyBase,
          lt: snapshotKeyBase + '~',
        }),
      ]);
    });
    await this.opts.rpc.delete?.(id.join('/'));
  }
 
  /**
   * Pull from remote.
   */
  public async pull(id: BlockId): Promise<LocalRepoPullResponse> {
    const keyBase = await this.blockKeyBase(id);
    try {
      const {model, meta} = await this.pullExisting(id, keyBase);
      return {model, cursor: meta.seq};
    } catch (error) {
      if (!!error && typeof error === 'object' && (error as any).code === 'LEVEL_NOT_FOUND') {
        try {
          const {model, meta} = await this.pullNew(id, keyBase);
          return {model, cursor: meta.seq};
        } catch (error) {
          if (error instanceof Error && error.message === 'EXISTS') {
            const {model, meta} = await this.pullExisting(id, keyBase);
            return {model, cursor: meta.seq};
          }
          throw error;
        }
      } else Eif (error instanceof Error && error.message === 'CONCURRENCY') {
        const [model, cursor] = await this.readLocal0(keyBase);
        return {model, cursor};
      }
      throw error;
    }
  }
 
  protected async pullNew(id: BlockId, keyBase: string): Promise<{model: Model; meta: BlockMeta}> {
    const blockId = id.join('/');
    const {block} = await this.opts.rpc.read(blockId);
    const _pubsub = this.pubsub;
    return this.lockBlock(keyBase, async () => {
      const exists = await this._exists(keyBase);
      if (exists) throw new Error('EXISTS');
      const model = Model.load(block.snapshot.blob, this.sid);
      let seq = block.snapshot.seq;
      for (const batch of block.tip) {
        if (batch.seq <= seq) continue;
        seq = batch.seq;
        for (const patch of batch.patches) model.applyPatch(Patch.fromBinary(patch.blob));
      }
      const meta: BlockMeta = {
        time: 0,
        seq,
      };
      const blob = model.toBinary();
      await this._wrModel(keyBase, blob, meta);
      this.emitPubSub({type: 'reset', id, model: blob});
      return {model, meta};
    });
  }
 
  protected async pullExisting(id: BlockId, keyBase: string): Promise<{model: Model; meta: BlockMeta}> {
    // TODO: try catching up using batches, if not possible, reset
    // TODO: load batches to catch up with remote
    const blockId = id.join('/');
    const meta = await this.readMeta(keyBase);
    const {seq} = meta;
    const pull = await this.opts.rpc.pull(blockId, seq);
    const nextSeq = pull.batches.length ? pull.batches[pull.batches.length - 1].seq : (pull.snapshot?.seq ?? seq);
    const _pubsub = this.pubsub;
    if (nextSeq < seq) {
      return this.lockBlock(keyBase, async () => {
        const seq2 = (await this.readMeta(keyBase)).seq;
        Iif (seq2 !== seq) throw new Error('CONCURRENCY');
        Iif (!pull.snapshot) throw new Error('missing snapshot');
        const model = Model.load(pull.snapshot.blob, this.sid);
        for (const batch of pull.batches)
          for (const patch of batch.patches) model.applyPatch(Patch.fromBinary(patch.blob));
        const modelBlob = model.toBinary();
        meta.time = model.clock.time - 1;
        meta.seq = nextSeq;
        meta.syncTs = Date.now();
        delete meta.syncFailures;
        await this._wrModel(keyBase, modelBlob, meta);
        this.emitPubSub({type: 'reset', id, model: modelBlob});
        return {model, meta};
      });
    }
    return this.lockBlock(keyBase, async () => {
      const [model, meta] = await Promise.all([this.readModel(keyBase), this.readMeta(keyBase)]);
      const seq2 = meta.seq;
      if (seq2 !== seq) throw new Error('CONCURRENCY');
      if (pull.snapshot) {
        Eif (nextSeq > seq2) {
          const model = Model.load(pull.snapshot.blob, this.sid);
          for (const batch of pull.batches)
            for (const patch of batch.patches) model.applyPatch(Patch.fromBinary(patch.blob));
          const modelBlob = model.toBinary();
          meta.seq = nextSeq;
          await this._wrModel(keyBase, modelBlob, meta);
          this.emitPubSub({type: 'reset', id, model: modelBlob});
        }
        return {model, meta};
      }
      Iif (!model) throw new Error('NO_MODEL');
      const patches: Uint8Array[] = [];
      for (const batch of pull.batches)
        for (const patch of batch.patches) {
          model.applyPatch(Patch.fromBinary(patch.blob));
          patches.push(patch.blob);
        }
      meta.seq = nextSeq;
      await this._wrModel(keyBase, model.toBinary(), meta);
      this.emitPubSub({type: 'merge', id, patches, seq: meta.seq});
      return {model, meta};
    });
  }
 
  public change$(id: BlockId): Observable<LocalRepoEvent> {
    return defer(() => {
      const remoteSubscription = this._subRemote(id).subscribe(() => {});
      return this.pubsub.bus$.pipe(
        takeUntil(this._stop$),
        map((msg) => {
          switch (msg.type) {
            case 'rebase': {
              if (!deepEqual(id, msg.id)) return;
              const rebase: Patch[] = [];
              for (const blob of msg.patches) rebase.push(Patch.fromBinary(blob));
              const event: LocalRepoRebaseEvent = {rebase, session: msg.session};
              return event;
            }
            case 'reset': {
              Iif (!deepEqual(id, msg.id)) return;
              const reset = Model.load(msg.model, this.sid);
              const event: LocalRepoResetEvent = {reset};
              return event;
            }
            case 'merge': {
              if (!deepEqual(id, msg.id)) return;
              const merge: Patch[] = [];
              for (const blob of msg.patches) {
                const patch = Patch.fromBinary(blob);
                if (patch.getId()?.sid === SESSION.GLOBAL) continue;
                merge.push(patch);
              }
              if (!merge.length) return;
              const event: LocalRepoMergeEvent = {merge, cursor: msg.seq};
              return event;
            }
            case 'del': {
              Iif (!deepEqual(id, msg.id)) return;
              const event: LocalRepoDeleteEvent = {del: true};
              return event;
            }
          }
        }),
        filter((event): event is LocalRepoEvent => !!event),
        finalize(() => {
          remoteSubscription.unsubscribe();
        }),
        share(),
      );
    });
  }
 
  private _subs: Record<string, Observable<void>> = {};
 
  protected _subRemote(id: BlockId): Observable<void> {
    const blockId = id.join('/');
    let sub = this._subs[blockId];
    if (sub) return sub;
    const source = defer(() =>
      this.opts.rpc.listen(blockId).pipe(
        takeUntil(this._stop$),
        switchMap(async ({event}) => {
          Iif (this._stopped) return;
          switch (event[0]) {
            case 'new':
              await this.pull(id);
              break;
            case 'upd':
              await this._onUpd(id, event[1].batch);
              break;
            case 'del':
              await this.del(id);
              break;
          }
        }),
      ),
    );
    sub = source.pipe(
      catchError(() => source),
      finalize<void>(() => {
        delete this._subs[blockId];
      }),
      share(),
    );
    this._subs[blockId] = sub;
    return sub;
  }
 
  protected async _onUpd(id: BlockId, batch: ServerBatch): Promise<void> {
    try {
      Iif (this._stopped) return;
      const keyBase = await this.blockKeyBase(id);
      const firstPatch = batch.patches[0];
      Iif (!firstPatch) return;
      const firstPatchSid = Patch.fromBinary(firstPatch.blob).getId()?.sid;
      if (firstPatchSid === this.sid) return;
      try {
        const meta = await this.readMeta(keyBase);
        const alreadySynced = meta.seq >= batch.seq;
        if (alreadySynced) return;
        const needsPull = meta.seq + 1 < batch.seq;
        if (needsPull) {
          await this.pull(id);
          return;
        }
      } catch (error) {
        Eif (!!error && typeof error === 'object' && (error as any).code === 'LEVEL_NOT_FOUND') {
          Iif (this._stopped) return;
          await this.pullNew(id, keyBase);
          return;
        }
        throw error;
      }
      let needsPull = false;
      await this.lockBlock(keyBase, async () => {
        Iif (this._stopped) return;
        const [model, meta] = await Promise.all([this.readModel(keyBase), this.readMeta(keyBase)]);
        Iif (this._stopped) return;
        Eif (meta.seq >= batch.seq) return;
        if (meta.seq + 1 < batch.seq) {
          needsPull = true;
          return;
        }
        const patches: Uint8Array[] = [];
        for (const serverPatch of batch.patches) {
          const patch = Patch.fromBinary(serverPatch.blob);
          model.applyPatch(patch);
          patches.push(serverPatch.blob);
        }
        meta.seq = batch.seq;
        await this._wrModel(keyBase, model.toBinary(), meta);
        this.emitPubSub({type: 'merge', id, patches, seq: meta.seq});
      });
      Iif (needsPull && !this._stopped) await this.pull(id);
    } catch (error) {
      this.emitSyncError(error);
    }
  }
}