Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions infrastructure/evault-core/src/core/db/db.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,90 @@ export class DbService {
};
}

/**
* Store a meta-envelope with a specific ID (for migrations)
* Similar to storeMetaEnvelope but allows preserving the original ID
* @param meta - The meta-envelope data (without id)
* @param acl - Access control list
* @param eName - The eName identifier for multi-tenant isolation
* @param id - Optional ID to use (if not provided, generates new one)
* @returns The stored meta-envelope with its envelopes
*/
async storeMetaEnvelopeWithId<
T extends Record<string, any> = Record<string, any>,
>(
meta: Omit<MetaEnvelope<T>, "id">,
acl: string[],
eName: string,
id?: string,
): Promise<StoreMetaEnvelopeResult<T>> {
if (!eName) {
throw new Error("eName is required for storing meta-envelopes");
}

// Use provided ID or generate new one
const metaId = id || (await new W3IDBuilder().build()).id;

const cypher: string[] = [
`CREATE (m:MetaEnvelope { id: $metaId, ontology: $ontology, acl: $acl, eName: $eName })`,
];

const envelopeParams: Record<string, any> = {
metaId: metaId,
ontology: meta.ontology,
acl: acl,
eName: eName,
};

const createdEnvelopes: Envelope<T[keyof T]>[] = [];
let counter = 0;

for (const [key, value] of Object.entries(meta.payload)) {
const envW3id = await new W3IDBuilder().build();
const envelopeId = envW3id.id;
const alias = `e${counter}`;

const { value: storedValue, type: valueType } =
serializeValue(value);

cypher.push(`
CREATE (${alias}:Envelope {
id: $${alias}_id,
ontology: $${alias}_ontology,
value: $${alias}_value,
valueType: $${alias}_type
})
WITH m, ${alias}
MERGE (m)-[:LINKS_TO]->(${alias})
`);

envelopeParams[`${alias}_id`] = envelopeId;
envelopeParams[`${alias}_ontology`] = key;
envelopeParams[`${alias}_value`] = storedValue;
envelopeParams[`${alias}_type`] = valueType;

createdEnvelopes.push({
id: envelopeId,
ontology: key,
value: value as T[keyof T],
valueType,
});

counter++;
}

await this.runQueryInternal(cypher.join("\n"), envelopeParams);

return {
metaEnvelope: {
id: metaId,
ontology: meta.ontology,
acl: acl,
},
envelopes: createdEnvelopes,
};
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
* Finds meta-envelopes containing the search term in any of their envelopes.
* Returns all envelopes from the matched meta-envelopes.
Expand Down
231 changes: 0 additions & 231 deletions infrastructure/evault-core/src/core/http/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -718,235 +718,4 @@ export async function registerHttpRoutes(
},
);
}

// Emover endpoint - Copy metaEnvelopes to new evault instance
server.post<{
Body: {
eName: string;
targetNeo4jUri: string;
targetNeo4jUser: string;
targetNeo4jPassword: string;
};
}>(
"/emover",
{
schema: {
tags: ["migration"],
description:
"Copy all metaEnvelopes for an eName to a new evault instance",
body: {
type: "object",
required: [
"eName",
"targetNeo4jUri",
"targetNeo4jUser",
"targetNeo4jPassword",
],
properties: {
eName: { type: "string" },
targetNeo4jUri: { type: "string" },
targetNeo4jUser: { type: "string" },
targetNeo4jPassword: { type: "string" },
},
},
response: {
200: {
type: "object",
properties: {
success: { type: "boolean" },
count: { type: "number" },
message: { type: "string" },
},
},
400: {
type: "object",
properties: {
error: { type: "string" },
},
},
500: {
type: "object",
properties: {
error: { type: "string" },
},
},
},
},
},
async (
request: TypedRequest<{
eName: string;
targetNeo4jUri: string;
targetNeo4jUser: string;
targetNeo4jPassword: string;
}>,
reply: TypedReply,
) => {
const {
eName,
targetNeo4jUri,
targetNeo4jUser,
targetNeo4jPassword,
} = request.body;

if (!dbService) {
return reply.status(500).send({
error: "Database service not available",
});
}

try {
console.log(
`[MIGRATION] Starting migration for eName: ${eName} to target evault`,
);

// Step 1: Validate eName exists in current evault
const existingMetaEnvelopes =
await dbService.findAllMetaEnvelopesByEName(eName);
if (existingMetaEnvelopes.length === 0) {
console.log(
`[MIGRATION] No metaEnvelopes found for eName: ${eName}`,
);
return reply.status(200).send({
success: true,
count: 0,
message: "No metaEnvelopes to copy",
});
}

console.log(
`[MIGRATION] Found ${existingMetaEnvelopes.length} metaEnvelopes for eName: ${eName}`,
);

// Step 2: Create connection to target evault's Neo4j
console.log(
`[MIGRATION] Connecting to target Neo4j at: ${targetNeo4jUri}`,
);
const targetDriver = await connectWithRetry(
targetNeo4jUri,
targetNeo4jUser,
targetNeo4jPassword,
);
const targetDbService = new DbService(targetDriver);

try {
// Step 3: Copy all metaEnvelopes to target evault
console.log(
`[MIGRATION] Copying ${existingMetaEnvelopes.length} metaEnvelopes to target evault`,
);
const copiedCount =
await dbService.copyMetaEnvelopesToNewEvaultInstance(
eName,
targetDbService,
);

// Step 4: Verify copy
console.log(
`[MIGRATION] Verifying copy: checking ${copiedCount} metaEnvelopes in target evault`,
);
const targetMetaEnvelopes =
await targetDbService.findAllMetaEnvelopesByEName(
eName,
);

if (
targetMetaEnvelopes.length !==
existingMetaEnvelopes.length
) {
const error = `Copy verification failed: expected ${existingMetaEnvelopes.length} metaEnvelopes, found ${targetMetaEnvelopes.length}`;
console.error(`[MIGRATION ERROR] ${error}`);
return reply.status(500).send({ error });
}

// Verify IDs match
const sourceIds = new Set(
existingMetaEnvelopes.map((m) => m.id),
);
const targetIds = new Set(
targetMetaEnvelopes.map((m) => m.id),
);

if (sourceIds.size !== targetIds.size) {
const error =
"Copy verification failed: ID count mismatch";
console.error(`[MIGRATION ERROR] ${error}`);
return reply.status(500).send({ error });
}

for (const id of sourceIds) {
if (!targetIds.has(id)) {
const error = `Copy verification failed: missing metaEnvelope ID: ${id}`;
console.error(`[MIGRATION ERROR] ${error}`);
return reply.status(500).send({ error });
}
}

// Verify envelope relationships for each metaEnvelope
console.log(
`[MIGRATION] Verifying envelope relationships for each metaEnvelope`,
);
for (const sourceMeta of existingMetaEnvelopes) {
const sourceEnvelopeIds = new Set(
sourceMeta.envelopes.map((e) => e.id),
);

const targetMeta = targetMetaEnvelopes.find(
(m) => m.id === sourceMeta.id,
);
if (!targetMeta) {
const error = `Copy verification failed: missing metaEnvelope ID: ${sourceMeta.id}`;
console.error(`[MIGRATION ERROR] ${error}`);
return reply.status(500).send({ error });
}

const targetEnvelopeIds = new Set(
targetMeta.envelopes.map((e) => e.id),
);

if (sourceEnvelopeIds.size !== targetEnvelopeIds.size) {
const error = `Copy verification failed: envelope count mismatch for metaEnvelope ${sourceMeta.id} - expected ${sourceEnvelopeIds.size}, got ${targetEnvelopeIds.size}`;
console.error(`[MIGRATION ERROR] ${error}`);
return reply.status(500).send({ error });
}

for (const envelopeId of sourceEnvelopeIds) {
if (!targetEnvelopeIds.has(envelopeId)) {
const error = `Copy verification failed: missing envelope ID ${envelopeId} for metaEnvelope ${sourceMeta.id}`;
console.error(`[MIGRATION ERROR] ${error}`);
return reply.status(500).send({ error });
}
}

console.log(
`[MIGRATION] Verified ${sourceEnvelopeIds.size} envelopes for metaEnvelope ${sourceMeta.id}`,
);
}

console.log(
`[MIGRATION] Verification successful: ${copiedCount} metaEnvelopes with all envelopes copied and verified`,
);

// Close target connection
await targetDriver.close();

return {
success: true,
count: copiedCount,
message: `Successfully copied ${copiedCount} metaEnvelopes to target evault`,
};
} catch (copyError) {
await targetDriver.close();
throw copyError;
}
} catch (error) {
console.error(`[MIGRATION ERROR] Migration failed:`, error);
return reply.status(500).send({
error:
error instanceof Error
? error.message
: "Failed to migrate metaEnvelopes",
});
}
},
);
}
Loading