Skip to content

Commit

Permalink
feat(NODE-6325): implement document sequence support
Browse files Browse the repository at this point in the history
  • Loading branch information
durran committed Aug 18, 2024
1 parent b70c885 commit f37adc6
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion src/cmap/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,17 @@ export interface OpMsgOptions {
readPreference: ReadPreference;
}

/** @internal */
export class DocumentSequence {
field: string;
documents: Document[];

constructor(field: string, documents: Document[]) {
this.field = field;
this.documents = documents;
}
}

/** @internal */
export class OpMsgRequest {
requestId: number;
Expand Down Expand Up @@ -491,14 +502,48 @@ export class OpMsgRequest {
}

makeDocumentSegment(buffers: Uint8Array[], document: Document): number {
const sequencesBuffer = this.extractDocumentSequences(document);
const payloadTypeBuffer = Buffer.alloc(1);
payloadTypeBuffer[0] = 0;

const documentBuffer = this.serializeBson(document);
buffers.push(payloadTypeBuffer);
buffers.push(documentBuffer);
buffers.push(sequencesBuffer);

return payloadTypeBuffer.length + documentBuffer.length;
return payloadTypeBuffer.length + documentBuffer.length + sequencesBuffer.length;
}

extractDocumentSequences(document: Document): Uint8Array {
// Pull out any field in the command document that's value is a document sequence.
const chunks = [];
for (const [key, value] of Object.entries(document)) {
if (value instanceof DocumentSequence) {
// Document sequences starts with type 1 at the first byte.
const payloadTypeBuffer = Buffer.alloc(1);
payloadTypeBuffer[0] = 1;
chunks.push(payloadTypeBuffer);
// Second part of the sequence is the length;
const lengthBuffer = Buffer.alloc(4);
chunks.push(lengthBuffer);
// Third part is the field name.
const fieldBuffer = Buffer.from(key);
chunks.push(fieldBuffer);
// Fourth part are the documents' bytes.
let docsLength = 0;
for (const doc of value.documents) {
const docBson = this.serializeBson(doc);
docsLength += docBson.length;
chunks.push(docBson);
}
lengthBuffer.writeInt32LE(fieldBuffer.length + docsLength);
delete document[key];
}
}
if (chunks.length > 0) {
return Buffer.concat(chunks);
}
return Buffer.alloc(0);
}

serializeBson(document: Document): Uint8Array {
Expand Down

0 comments on commit f37adc6

Please sign in to comment.