import { beforeEach, describe, expect, test } from "vitest"; import { expectStream } from "../coValue.js"; import { BinaryStreamItem, RawBinaryCoStream, } from "../coValues/binaryCoStream.js"; import { CoStreamItem, RawCoStreamView } from "../coValues/coStream.js"; import { TRANSACTION_CONFIG } from "../config.js"; import { WasmCrypto } from "../crypto/WasmCrypto.js"; import { SessionID } from "../ids.js"; import { loadCoValueOrFail, nodeWithRandomAgentAndSessionID, setupTestNode, waitFor, } from "./testUtils.js"; const Crypto = await WasmCrypto.create(); beforeEach(async () => { setupTestNode({ isSyncServer: true }); }); test("Empty CoStream works", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: null, ...Crypto.createdNowUnique(), }); const content = expectStream(coValue.getCurrentContent()); expect(content.type).toEqual("costream"); expect(content.toJSON()).toEqual({}); expect(content.getSingleStream()).toEqual(undefined); }); test("Can push into CoStream", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: null, ...Crypto.createdNowUnique(), }); const content = expectStream(coValue.getCurrentContent()); content.push({ hello: "world" }, "trusting"); expect(content.toJSON()).toEqual({ [node.currentSessionID]: [{ hello: "world" }], }); content.push({ foo: "bar" }, "trusting"); expect(content.toJSON()).toEqual({ [node.currentSessionID]: [{ hello: "world" }, { foo: "bar" }], }); expect(content.getSingleStream()).toEqual([ { hello: "world" }, { foo: "bar" }, ]); }); test("Empty RawBinaryCoStream works", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: { type: "binary" }, ...Crypto.createdNowUnique(), }); const content = coValue.getCurrentContent(); if ( content.type !== "costream" || content.headerMeta?.type !== "binary" || !(content instanceof RawBinaryCoStream) ) { throw new Error("Expected binary stream"); } expect(content.type).toEqual("costream"); expect(content.headerMeta.type).toEqual("binary"); expect(content.toJSON()).toEqual({}); expect(content.getBinaryChunks()).toEqual(undefined); }); test("Can push into RawBinaryCoStream", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: { type: "binary" }, ...Crypto.createdNowUnique(), }); const content = coValue.getCurrentContent(); if ( content.type !== "costream" || content.headerMeta?.type !== "binary" || !(content instanceof RawBinaryCoStream) ) { throw new Error("Expected binary stream"); } content.startBinaryStream( { mimeType: "text/plain", fileName: "test.txt" }, "trusting", ); content.pushBinaryStreamChunk(new Uint8Array([1, 2, 3]), "trusting"); content.pushBinaryStreamChunk(new Uint8Array([4, 5, 6]), "trusting"); content.endBinaryStream("trusting"); expect(content.getBinaryChunks()).toEqual({ mimeType: "text/plain", fileName: "test.txt", chunks: [new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])], finished: true, }); }); test("Should ignore meta transactions on RawBinaryCoStream", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: { type: "binary" }, ...Crypto.createdNowUnique(), }); coValue.makeTransaction([], "trusting", { unknownMeta: 1 }); const content = coValue.getCurrentContent(); if ( content.type !== "costream" || content.headerMeta?.type !== "binary" || !(content instanceof RawBinaryCoStream) ) { throw new Error("Expected binary stream"); } content.startBinaryStream( { mimeType: "text/plain", fileName: "test.txt" }, "trusting", ); content.pushBinaryStreamChunk(new Uint8Array([1, 2, 3]), "trusting"); content.endBinaryStream("trusting"); expect(content.getBinaryChunks()).toEqual({ mimeType: "text/plain", fileName: "test.txt", chunks: [new Uint8Array([1, 2, 3])], finished: true, }); }); test("When adding large transactions (small fraction of MAX_RECOMMENDED_TX_SIZE), we store an inbetween signature every time we reach MAX_RECOMMENDED_TX_SIZE and split up newContentSince accordingly", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: { type: "binary" }, ...Crypto.createdNowUnique(), }); const content = coValue.getCurrentContent(); if ( content.type !== "costream" || content.headerMeta?.type !== "binary" || !(content instanceof RawBinaryCoStream) ) { throw new Error("Expected binary stream"); } content.startBinaryStream( { mimeType: "text/plain", fileName: "test.txt" }, "trusting", ); for (let i = 0; i < 10; i++) { const chunk = new Uint8Array( TRANSACTION_CONFIG.MAX_RECOMMENDED_TX_SIZE / 3 + 100, ); content.pushBinaryStreamChunk(chunk, "trusting"); } content.endBinaryStream("trusting"); if (!coValue.isAvailable()) { throw new Error("CoValue is not available"); } const sessionEntry = coValue.verified.getSession(node.currentSessionID)!; expect(sessionEntry.transactions.length).toEqual(12); expect(sessionEntry.signatureAfter[0]).not.toBeDefined(); expect(sessionEntry.signatureAfter[1]).not.toBeDefined(); expect(sessionEntry.signatureAfter[2]).not.toBeDefined(); expect(sessionEntry.signatureAfter[3]).toBeDefined(); expect(sessionEntry.signatureAfter[4]).not.toBeDefined(); expect(sessionEntry.signatureAfter[5]).not.toBeDefined(); expect(sessionEntry.signatureAfter[6]).toBeDefined(); expect(sessionEntry.signatureAfter[7]).not.toBeDefined(); expect(sessionEntry.signatureAfter[8]).not.toBeDefined(); expect(sessionEntry.signatureAfter[9]).toBeDefined(); expect(sessionEntry.signatureAfter[10]).not.toBeDefined(); expect(sessionEntry.signatureAfter[11]).not.toBeDefined(); const newContent = coValue.newContentSince({ id: coValue.id, header: false, sessions: {}, })!; expect(newContent.length).toEqual(4); expect(newContent[0]!.header).toBeDefined(); expect(newContent[0]!.new[node.currentSessionID]!.lastSignature).toEqual( sessionEntry.signatureAfter[3], ); expect(newContent[1]!.new[node.currentSessionID]!.lastSignature).toEqual( sessionEntry.signatureAfter[6], ); expect(newContent[2]!.new[node.currentSessionID]!.lastSignature).toEqual( sessionEntry.signatureAfter[9], ); expect(newContent[3]!.new[node.currentSessionID]!.lastSignature).toEqual( sessionEntry.lastSignature, ); }); test("When adding large transactions (bigger than MAX_RECOMMENDED_TX_SIZE), we store an inbetween signature after every large transaction and split up newContentSince accordingly", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: { type: "binary" }, ...Crypto.createdNowUnique(), }); const content = coValue.getCurrentContent(); if ( content.type !== "costream" || content.headerMeta?.type !== "binary" || !(content instanceof RawBinaryCoStream) ) { throw new Error("Expected binary stream"); } content.startBinaryStream( { mimeType: "text/plain", fileName: "test.txt" }, "trusting", ); const chunk = new Uint8Array( TRANSACTION_CONFIG.MAX_RECOMMENDED_TX_SIZE + 100, ); for (let i = 0; i < 3; i++) { content.pushBinaryStreamChunk(chunk, "trusting"); } content.endBinaryStream("trusting"); if (!coValue.isAvailable()) { throw new Error("CoValue is not available"); } const sessionEntry = coValue.verified.getSession(node.currentSessionID)!; expect(sessionEntry.transactions.length).toEqual(5); expect(sessionEntry.signatureAfter[0]).not.toBeDefined(); expect(sessionEntry.signatureAfter[1]).toBeDefined(); expect(sessionEntry.signatureAfter[2]).toBeDefined(); expect(sessionEntry.signatureAfter[3]).toBeDefined(); expect(sessionEntry.signatureAfter[4]).not.toBeDefined(); const newContent = coValue.newContentSince({ id: coValue.id, header: false, sessions: {}, })!; expect(newContent.length).toEqual(4); expect(newContent[0]!.header).toBeDefined(); expect(newContent[0]!.new[node.currentSessionID]!.lastSignature).toEqual( sessionEntry.signatureAfter[1], ); expect(newContent[1]!.new[node.currentSessionID]!.lastSignature).toEqual( sessionEntry.signatureAfter[2], ); expect(newContent[2]!.new[node.currentSessionID]!.lastSignature).toEqual( sessionEntry.signatureAfter[3], ); expect(newContent[3]!.new[node.currentSessionID]!.lastSignature).toEqual( sessionEntry.lastSignature, ); }); test("totalValidTransactions should return the number of valid transactions processed", async () => { const client = setupTestNode({ connected: true, }); const otherClient = setupTestNode({}); const otherClientConnection = otherClient.connectToSyncServer(); const group = client.node.createGroup(); group.addMember("everyone", "reader"); const stream = group.createStream(); stream.push(1, "trusting"); const streamOnOtherClient = await loadCoValueOrFail( otherClient.node, stream.id, ); otherClientConnection.peerState.gracefulShutdown(); group.addMember("everyone", "writer"); await new Promise((resolve) => setTimeout(resolve, 50)); streamOnOtherClient.push(2, "trusting"); expect(streamOnOtherClient.totalValidTransactions).toEqual(1); expect(Object.keys(streamOnOtherClient.toJSON()).length).toEqual(1); otherClient.connectToSyncServer(); await waitFor(() => { expect( Object.keys( streamOnOtherClient.core.getCurrentContent().toJSON() as object, ).length, ).toEqual(2); }); expect( streamOnOtherClient.core.getCurrentContent().totalValidTransactions, ).toEqual(2); }); describe("isBinaryStreamEnded", () => { function setup() { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: { type: "binary" }, ...Crypto.createdNowUnique(), }); const content = coValue.getCurrentContent(); if ( content.type !== "costream" || content.headerMeta?.type !== "binary" || !(content instanceof RawBinaryCoStream) ) { throw new Error("Expected binary stream"); } return content; } test("returns true when the last item is end", () => { const stream = setup(); stream.startBinaryStream( { mimeType: "text/plain", fileName: "test.txt" }, "trusting", ); stream.endBinaryStream("trusting"); expect(stream.isBinaryStreamEnded()).toBe(true); }); test("returns false if the stream isn't ended", () => { const stream = setup(); stream.startBinaryStream( { mimeType: "text/plain", fileName: "test.txt" }, "trusting", ); expect(stream.isBinaryStreamEnded()).toBe(false); }); test("returns false if the stream isn't started", () => { const stream = setup(); expect(stream.isBinaryStreamEnded()).toBe(false); }); }); describe("Binary stream order", () => { class TestStreamView extends RawCoStreamView { public testCompareItems( a: CoStreamItem, b: CoStreamItem, ): number { return this.compareStreamItems(a, b); } } test("sorts by madeAt timestamp first", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: { type: "binary" }, ...Crypto.createdNowUnique(), }); const content = coValue.getCurrentContent(); if (!(content instanceof RawBinaryCoStream)) { throw new Error("Expected binary stream"); } const testView = new TestStreamView(content.core); const itemA: CoStreamItem = { value: { type: "start", mimeType: "text/plain" }, madeAt: 100, tx: { sessionID: node.currentSessionID, txIndex: 0 }, }; const itemB: CoStreamItem = { value: { type: "chunk", chunk: "binary_UAwECAQ" }, madeAt: 200, tx: { sessionID: node.currentSessionID, txIndex: 1 }, }; expect(testView.testCompareItems(itemA, itemB)).toBeLessThan(0); expect(testView.testCompareItems(itemB, itemA)).toBeGreaterThan(0); }); test("sorts by sessionID when timestamps are equal", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: { type: "binary" }, ...Crypto.createdNowUnique(), }); const content = coValue.getCurrentContent(); if (!(content instanceof RawBinaryCoStream)) { throw new Error("Expected binary stream"); } const testView = new TestStreamView(content.core); const timestamp = Date.now(); const itemA: CoStreamItem = { value: { type: "start", mimeType: "text/plain" }, madeAt: timestamp, tx: { sessionID: "a" as SessionID, txIndex: 0 }, }; const itemB: CoStreamItem = { value: { type: "chunk", chunk: "binary_UAwECAQ" }, madeAt: timestamp, tx: { sessionID: "b" as SessionID, txIndex: 0 }, }; expect(testView.testCompareItems(itemA, itemB)).toBeLessThan(0); expect(testView.testCompareItems(itemB, itemA)).toBeGreaterThan(0); }); test("sorts by txIndex when timestamps and sessionIDs are equal", () => { const node = nodeWithRandomAgentAndSessionID(); const coValue = node.createCoValue({ type: "costream", ruleset: { type: "unsafeAllowAll" }, meta: { type: "binary" }, ...Crypto.createdNowUnique(), }); const content = coValue.getCurrentContent(); if (!(content instanceof RawBinaryCoStream)) { throw new Error("Expected binary stream"); } const testView = new TestStreamView(content.core); const timestamp = Date.now(); const sessionID = node.currentSessionID; const itemA: CoStreamItem = { value: { type: "start", mimeType: "text/plain" }, madeAt: timestamp, tx: { sessionID, txIndex: 0 }, }; const itemB: CoStreamItem = { value: { type: "chunk", chunk: "binary_UAwECAQ" }, madeAt: timestamp, tx: { sessionID, txIndex: 1 }, }; // Expect itemA to be before itemB expect(testView.testCompareItems(itemA, itemB)).toBeLessThan(0); expect(testView.testCompareItems(itemB, itemA)).toBeGreaterThan(0); }); }); test("the stream should rebuild when the group permissions change", async () => { const alice = setupTestNode({ connected: true, }); const group = alice.node.createGroup(); const stream = group.createStream(); stream.push("fromAdmin"); const bob = setupTestNode({ connected: true, }); const streamOnBob = await loadCoValueOrFail(bob.node, stream.id); expect(Object.keys(streamOnBob.toJSON()).length).toEqual(0); expect(streamOnBob.totalValidTransactions).toEqual(0); group.addMember("everyone", "reader"); await waitFor(() => { expect(streamOnBob.getSingleStream()).toEqual(["fromAdmin"]); }); expect(streamOnBob.version).toEqual(1); expect(streamOnBob.totalValidTransactions).toEqual(1); });