All files / src collection-abstract.ts

81.81% Statements 54/66
55.55% Branches 15/27
73.33% Functions 11/15
88.13% Lines 52/59

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 2012x 2x 2x 2x         2x   2x     3x       3x               3x   3x     3x       6x 6x     3x   3x                             2x 2x   2x 2x 2x           2x     2x   4x   4x 4x                                 2x   2x                           2x 4x               2x                                   3x 3x 3x 3x                     2x     2x       2x       2x             2x 2x 4x       2x 2x     6x   6x 6x     6x     6x             2x   2x 2x 2x        
import Debug from 'debug';
import {randomUUID} from "node:crypto";
import EventEmitter from "node:events";
import {Delta} from "./delta";
import {Entity, EntityProperties} from "./entity";
import {ResolvedViewOne} from './last-write-wins';
import {RhizomeNode} from "./node";
import {DomainEntityID} from "./types";
const debug = Debug('rz:abstract-collection');
 
export abstract class Collection<View> {
  rhizomeNode?: RhizomeNode;
  name: string;
  eventStream = new EventEmitter();
  lossy?: View;
 
  constructor(name: string) {
    this.name = name;
  }
 
  abstract initializeView(): void;
 
  abstract resolve(id: DomainEntityID): ResolvedViewOne | undefined;
 
  rhizomeConnect(rhizomeNode: RhizomeNode) {
    this.rhizomeNode = rhizomeNode;
 
    this.initializeView();
 
    // Listen for completed transactions, and emit updates to event stream
    this.rhizomeNode.lossless.eventStream.on("updated", (id) => {
      // TODO: Filter so we only get members of our collection
 
      // TODO: Reslover / Delta Filter?
      const res = this.resolve(id);
      this.eventStream.emit("update", res);
    });
 
    rhizomeNode.httpServer.httpApi.serveCollection<View>(this);
 
    debug(`[${this.rhizomeNode.config.peerId}]`, `Connected ${this.name} to rhizome`);
  }
 
  // This function is here instead of Entity so that it can:
  // - read the current state in order to build its delta
  // - include the collection name in the delta it produces
  generateDeltas(
    entityId: DomainEntityID,
    newProperties: EntityProperties,
    creator: string,
    host: string,
  ): {
    transactionDelta: Delta | undefined,
    deltas: Delta[]
  } {
    const deltas: Delta[] = [];
    let oldProperties: EntityProperties = {};
 
    if (entityId) {
      const entity = this.resolve(entityId);
      Iif (entity) {
        oldProperties = entity.properties;
      }
    }
 
    // Generate a transaction ID
    const transactionId = `transaction-${randomUUID()}`;
 
    // Generate a delta for each changed property
    Object.entries(newProperties).forEach(([key, value]) => {
      // Disallow property named "id" 
      Iif (key === 'id') return;
 
      if (oldProperties[key] !== value && host && creator) {
        deltas.push(new Delta({
          creator,
          host,
          pointers: [{
            localContext: this.name,
            target: entityId,
            targetContext: key
          }, {
            localContext: key,
            target: value
          }]
        }));
      }
    });
 
    let transactionDelta: Delta | undefined;
 
    if (deltas.length > 1) {
      // We can generate a separate delta describing this transaction
      transactionDelta = new Delta({
        creator,
        host,
        pointers: [{
          localContext: "_transaction",
          target: transactionId,
          targetContext: "size"
        }, {
          localContext: "size",
          target: deltas.length
        }]
      });
 
      // Also need to annotate the deltas with the transactionId
      for (const delta of deltas) {
        delta.pointers.unshift({
          localContext: "_transaction",
          target: transactionId,
          targetContext: "deltas"
        });
      }
    }
 
    return {transactionDelta, deltas};
  }
 
  onCreate(cb: (entity: Entity) => void) {
    // TODO: Trigger for changes received from peers
    this.eventStream.on('create', (entity: Entity) => {
      cb(entity);
    });
  }
 
  onUpdate(cb: (entity: Entity) => void) {
    // TODO: Trigger for changes received from peers
    this.eventStream.on('update', (entity: Entity) => {
      cb(entity);
    });
  }
 
  getIds(): string[] {
    Iif (!this.rhizomeNode) return [];
    const set = this.rhizomeNode.lossless.referencedAs.get(this.name);
    Iif (!set) return [];
    return Array.from(set.values());
  }
 
  // THIS PUT SHOULD CORRESOND TO A PARTICULAR MATERIALIZED VIEW...
  // How can we encode that?
  // Well, we have a way to do that, we just need the same particular inputs.
  // We take a resolver as an optional argument.
  async put(
    entityId: DomainEntityID | undefined,
    properties: EntityProperties,
  ): Promise<ResolvedViewOne> {
    Iif (!this.rhizomeNode) throw new Error('collection not connecte to rhizome');
 
    // For convenience, we allow setting id via properties.id
    Iif (!entityId && !!properties.id && typeof properties.id === 'string') {
      entityId = properties.id;
    }
    // Generate an ID if none is provided
    Iif (!entityId) {
      entityId = randomUUID();
    }
 
    const {transactionDelta, deltas} = this.generateDeltas(
      entityId,
      properties,
      this.rhizomeNode?.config.creator,
      this.rhizomeNode?.config.peerId,
    );
 
    const ingested = new Promise<boolean>((resolve) => {
      this.rhizomeNode!.lossless.eventStream.on("updated", (id: DomainEntityID) => {
        if (id === entityId) resolve(true);
      })
    });
 
    if (transactionDelta) {
      deltas.unshift(transactionDelta);
    }
 
    deltas.forEach(async (delta: Delta) => {
      // record this delta just as if we had received it from a peer
      delta.receivedFrom = this.rhizomeNode!.myRequestAddr;
      this.rhizomeNode!.deltaStream.deltasAccepted.push(delta);
 
      // publish the delta to our subscribed peers
      await this.rhizomeNode!.deltaStream.publishDelta(delta);
 
      // ingest the delta as though we had received it from a peer
      this.rhizomeNode!.lossless.ingestDelta(delta);
    });
 
    // Return updated view of this entity
    // Let's wait for an event notifying us that the entity has been updated.
    // This means all of our deltas have been applied.
 
    await ingested;
 
    const res = this.resolve(entityId);
    Iif (!res) throw new Error("could not get what we just put!");
    return res;
  }
 
}