From 934a11e5852887bb6b45f70dbfbe17bc142c520c Mon Sep 17 00:00:00 2001 From: Nguyen Viet Dung <29406816+magnified103@users.noreply.github.com> Date: Tue, 17 Dec 2024 14:03:02 +0700 Subject: [PATCH] add timestamp check to the UPDATE handler --- packages/node/src/handlers.ts | 30 +++++++++++++++++------------- packages/object/src/index.ts | 3 +++ 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/packages/node/src/handlers.ts b/packages/node/src/handlers.ts index f1b3d6b9..6cdf8a3d 100644 --- a/packages/node/src/handlers.ts +++ b/packages/node/src/handlers.ts @@ -62,20 +62,11 @@ async function updateHandler(node: DRPNode, data: Uint8Array, sender: string) { return false; } - const [merged, _] = object.merge( - updateMessage.vertices.map((v) => { - return { - hash: v.hash, - nodeId: v.nodeId, - operation: { - type: v.operation?.type ?? "", - value: v.operation?.value, - }, - dependencies: v.dependencies, - timestamp: v.timestamp, - }; - }), + const verifiedVertices = verifyIncomingVertices( + object, + updateMessage.vertices, ); + const [merged, _] = object.merge(verifiedVertices); if (!merged) { await node.syncObject(updateMessage.objectId, sender); @@ -220,3 +211,16 @@ export function drpObjectChangesHandler( log.error("::createObject: Invalid origin function"); } } + +export function verifyIncomingVertices( + object: DRPObject, + incomingVertices: ObjectPb.Vertex[], +): Vertex[] { + const currentTimestamp = Date.now(); + + return incomingVertices.filter( + (vertex) => + vertex.timestamp <= currentTimestamp && + currentTimestamp - vertex.timestamp < object.vertexExpirationPeriod, + ); +} diff --git a/packages/object/src/index.ts b/packages/object/src/index.ts index 56887b69..95582591 100644 --- a/packages/object/src/index.ts +++ b/packages/object/src/index.ts @@ -42,6 +42,7 @@ export interface IDRPObject extends ObjectPb.DRPObjectBase { // snake_casing to match the JSON config export interface DRPObjectConfig { log_config?: LoggerOptions; + vertex_expiration_period?: number; } export let log: Logger; @@ -58,6 +59,7 @@ export class DRPObject implements IDRPObject { states: Map; originalDRP: DRP; subscriptions: DRPObjectCallback[]; + vertexExpirationPeriod: number; constructor( nodeId: string, @@ -92,6 +94,7 @@ export class DRPObject implements IDRPObject { Object.getOwnPropertyDescriptors(structuredClone(drp)), ); this.vertices = this.hashGraph.getAllVertices(); + this.vertexExpirationPeriod = config?.vertex_expiration_period ?? Number.POSITIVE_INFINITY; } // This function is black magic, it allows us to intercept calls to the DRP object