Skip to content

Commit

Permalink
fix: hashgraph merge hook (#456)
Browse files Browse the repository at this point in the history
  • Loading branch information
magnified103 authored Feb 11, 2025
1 parent a78078f commit a3e7e6d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/object/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ export class DRPObject implements ObjectPb.DRPObjectBase {
*/
private _mergeWithDrp(vertices: Vertex[]): [merged: boolean, missing: string[]] {
const missing: Hash[] = [];
const newVertices: Vertex[] = this.vertices;
const newVertices: Vertex[] = [];
for (const vertex of vertices) {
// Check to avoid manually crafted `undefined` operations
if (!vertex.operation || this.hashGraph.vertices.has(vertex.hash)) {
Expand Down Expand Up @@ -289,6 +289,7 @@ export class DRPObject implements ObjectPb.DRPObjectBase {
}
}

this.vertices = this.hashGraph.getAllVertices();
this._updateObjectACLState();
this._updateDRPState();
this._notify("merge", newVertices);
Expand Down
45 changes: 45 additions & 0 deletions packages/object/tests/hashgraph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { SetDRP } from "@ts-drp/blueprints/src/Set/index.js";
import { beforeAll, beforeEach, describe, expect, test } from "vitest";

import { ObjectACL } from "../src/acl/index.js";
import { Vertex } from "../src/hashgraph/index.js";
import {
ACLGroup,
DRP,
Expand Down Expand Up @@ -995,3 +996,47 @@ describe("Hash validation tests", () => {
);
});
});

describe("HashGraph hook tests", () => {
let obj1: DRPObject;
let obj2: DRPObject;
beforeEach(async () => {
obj1 = new DRPObject({ peerId: "peer1", acl, drp: new SetDRP<number>() });
obj2 = new DRPObject({ peerId: "peer1", acl, drp: new SetDRP<number>() });
});

test("New operations are hooked from callFn", () => {
const drp1 = obj1.drp as SetDRP<number>;
const newVertices: Vertex[] = [];

obj1.subscribe((object, origin, vertices) => {
if (origin === "callFn") {
newVertices.push(...vertices);
}
});
for (let i = 1; i < 100; i++) {
drp1.add(i);
expect(newVertices.length).toBe(i);
expect(newVertices[i - 1].operation?.opType).toBe("add");
expect(newVertices[i - 1].operation?.value[0]).toBe(i);
}
});

test("Merged operations are hooked from merge", () => {
const drp1 = obj1.drp as SetDRP<number>;
const newVertices: Vertex[] = [];

obj2.subscribe((object, origin, vertices) => {
if (origin === "merge") {
newVertices.push(...vertices);
}
});
for (let i = 1; i < 100; i++) {
drp1.add(i);
obj2.merge(obj1.hashGraph.getAllVertices());
expect(newVertices.length).toBe(i);
expect(newVertices[i - 1].operation?.opType).toBe("add");
expect(newVertices[i - 1].operation?.value[0]).toBe(i);
}
});
});

0 comments on commit a3e7e6d

Please sign in to comment.