|
| 1 | +import type { BSONSerializeOptions, Document, Long } from '../bson'; |
| 2 | +import type { Db } from '../db'; |
| 3 | +import { |
| 4 | + MongoCursorExhaustedError, |
| 5 | + MongoRuntimeError, |
| 6 | + MongoUnexpectedServerResponseError |
| 7 | +} from '../error'; |
| 8 | +import type { MongoClient } from '../mongo_client'; |
| 9 | +import { executeOperation } from '../operations/execute_operation'; |
| 10 | +import { GetMoreOperation } from '../operations/get_more'; |
| 11 | +import { KillCursorsOperation } from '../operations/kill_cursors'; |
| 12 | +import { RunCommandOperation } from '../operations/run_command'; |
| 13 | +import { ReadPreference, ReadPreferenceLike } from '../read_preference'; |
| 14 | +import type { Server } from '../sdam/server'; |
| 15 | +import type { ClientSession } from '../sessions'; |
| 16 | +import { List, MongoDBNamespace, ns } from '../utils'; |
| 17 | + |
| 18 | +/** @public */ |
| 19 | +export type RunCommandCursorOptions = { |
| 20 | + readPreference?: ReadPreferenceLike; |
| 21 | + session?: ClientSession; |
| 22 | +} & BSONSerializeOptions; |
| 23 | + |
| 24 | +/** @internal */ |
| 25 | +type RunCursorCommandResponse = { |
| 26 | + cursor: { id: bigint | Long | number; ns: string; firstBatch: Document[] }; |
| 27 | + ok: 1; |
| 28 | +}; |
| 29 | + |
| 30 | +/** @public */ |
| 31 | +export class RunCommandCursor { |
| 32 | + /** @internal */ |
| 33 | + client: MongoClient; |
| 34 | + /** @internal */ |
| 35 | + db: Db; |
| 36 | + /** @internal */ |
| 37 | + options: RunCommandCursorOptions; |
| 38 | + /** @internal */ |
| 39 | + documents: List<Document>; |
| 40 | + /** @internal */ |
| 41 | + storedIterator: AsyncGenerator<Document> | null = null; |
| 42 | + /** @internal */ |
| 43 | + getMoreOptions: { comment?: any; maxAwaitTimeMS?: number; batchSize?: number } = {}; |
| 44 | + /** @internal */ |
| 45 | + id: bigint | null = null; |
| 46 | + /** @internal */ |
| 47 | + ns: MongoDBNamespace | null = null; |
| 48 | + /** @internal */ |
| 49 | + server: Server | null = null; |
| 50 | + /** @internal */ |
| 51 | + readPreference: ReadPreference; |
| 52 | + /** @internal */ |
| 53 | + session: ClientSession; |
| 54 | + /** @internal */ |
| 55 | + done = false; |
| 56 | + |
| 57 | + readonly command: Readonly<Record<string, any>>; |
| 58 | + |
| 59 | + set comment(comment: any) { |
| 60 | + this.getMoreOptions.comment = comment; |
| 61 | + } |
| 62 | + |
| 63 | + get comment() { |
| 64 | + return this.getMoreOptions.comment; |
| 65 | + } |
| 66 | + |
| 67 | + set maxTimeMS(maxAwaitTimeMS: number) { |
| 68 | + this.getMoreOptions.maxAwaitTimeMS = maxAwaitTimeMS; |
| 69 | + } |
| 70 | + |
| 71 | + get maxTimeMS() { |
| 72 | + return this.getMoreOptions.maxAwaitTimeMS ?? 0; |
| 73 | + } |
| 74 | + |
| 75 | + set batchSize(batchSize: number) { |
| 76 | + this.getMoreOptions.batchSize = batchSize; |
| 77 | + } |
| 78 | + |
| 79 | + get batchSize() { |
| 80 | + return this.getMoreOptions.batchSize ?? 0; |
| 81 | + } |
| 82 | + |
| 83 | + /** @internal */ |
| 84 | + constructor( |
| 85 | + client: MongoClient, |
| 86 | + db: Db, |
| 87 | + command: Document | Map<string, any>, |
| 88 | + options: RunCommandCursorOptions = {} |
| 89 | + ) { |
| 90 | + this.client = client; |
| 91 | + this.db = db; |
| 92 | + this.command = |
| 93 | + Symbol.toStringTag in command && command[Symbol.toStringTag] === 'Map' |
| 94 | + ? Object.freeze(Object.fromEntries(command.entries())) |
| 95 | + : Object.freeze({ ...command }); |
| 96 | + this.options = options; |
| 97 | + this.documents = new List(); |
| 98 | + this.readPreference = ReadPreference.fromOptions(options) ?? ReadPreference.primary; |
| 99 | + this.session = options.session == null ? client.startSession({ owner: this }) : options.session; |
| 100 | + } |
| 101 | + |
| 102 | + /** @internal */ |
| 103 | + private static getIdFromResponse(response: { cursor: { id: number | Long | bigint } }): bigint { |
| 104 | + return typeof response.cursor.id === 'number' |
| 105 | + ? BigInt(response.cursor.id) |
| 106 | + : typeof response.cursor.id === 'object' |
| 107 | + ? response.cursor.id.toBigInt() |
| 108 | + : response.cursor.id; |
| 109 | + } |
| 110 | + |
| 111 | + /** @internal */ |
| 112 | + private async *iterator(): AsyncGenerator<Document> { |
| 113 | + if (this.done) { |
| 114 | + throw new MongoCursorExhaustedError('This cursor needs a nap'); |
| 115 | + } |
| 116 | + |
| 117 | + try { |
| 118 | + await this.runCommand(); |
| 119 | + while (this.documents.length) { |
| 120 | + const doc = this.documents.shift(); |
| 121 | + if (doc != null) { |
| 122 | + yield doc; |
| 123 | + } |
| 124 | + if (this.documents.length === 0 && this.id !== 0n) { |
| 125 | + await this.getMore(); |
| 126 | + } |
| 127 | + } |
| 128 | + } finally { |
| 129 | + await this.close().catch(() => null); |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + /** @internal */ |
| 134 | + private get asyncIterator(): AsyncGenerator<Document> { |
| 135 | + if (this.storedIterator == null) { |
| 136 | + this.storedIterator = this.iterator(); |
| 137 | + } |
| 138 | + return this.storedIterator; |
| 139 | + } |
| 140 | + |
| 141 | + /** @internal */ |
| 142 | + private async runCommand() { |
| 143 | + const operation = new RunCommandOperation<RunCursorCommandResponse>(this.db, this.command, { |
| 144 | + ...this.options, |
| 145 | + session: this.session, |
| 146 | + readPreference: this.readPreference |
| 147 | + }); |
| 148 | + |
| 149 | + const commandResponse = await executeOperation(this.client, operation); |
| 150 | + |
| 151 | + if (commandResponse.cursor == null) { |
| 152 | + throw new MongoUnexpectedServerResponseError('command must return a cursor document'); |
| 153 | + } |
| 154 | + |
| 155 | + this.id = RunCommandCursor.getIdFromResponse(commandResponse); |
| 156 | + this.ns = ns(commandResponse.cursor.ns); |
| 157 | + this.documents.pushMany(commandResponse.cursor.firstBatch); |
| 158 | + this.server = operation.server; |
| 159 | + } |
| 160 | + |
| 161 | + /** @internal */ |
| 162 | + private async getMore() { |
| 163 | + if (this.ns == null || this.id == null || this.server == null) { |
| 164 | + throw new MongoRuntimeError('getMore cannot be invoked with null namespace, id, nor server'); |
| 165 | + } |
| 166 | + |
| 167 | + const getMoreResponse = await executeOperation( |
| 168 | + this.client, |
| 169 | + new GetMoreOperation(this.ns, this.id, this.server, { |
| 170 | + ...this.options, |
| 171 | + session: this.session, |
| 172 | + readPreference: this.readPreference, |
| 173 | + ...this.getMoreOptions |
| 174 | + }) |
| 175 | + ); |
| 176 | + |
| 177 | + this.documents.pushMany(getMoreResponse.cursor.nextBatch); |
| 178 | + this.id = RunCommandCursor.getIdFromResponse(getMoreResponse); |
| 179 | + } |
| 180 | + |
| 181 | + /** @internal */ |
| 182 | + async start(): Promise<void> { |
| 183 | + const result = await this.asyncIterator.next(); |
| 184 | + if (!result.done) this.documents.unshift(result.value); |
| 185 | + } |
| 186 | + |
| 187 | + async *[Symbol.asyncIterator](): AsyncGenerator<Document> { |
| 188 | + if (this.done) { |
| 189 | + throw new MongoCursorExhaustedError('This cursor needs a nap'); |
| 190 | + } |
| 191 | + yield* this.asyncIterator; |
| 192 | + } |
| 193 | + |
| 194 | + async next(): Promise<Document | null> { |
| 195 | + if (this.done) { |
| 196 | + throw new MongoCursorExhaustedError('This cursor needs a nap'); |
| 197 | + } |
| 198 | + |
| 199 | + const result = await this.asyncIterator.next(); |
| 200 | + |
| 201 | + if (result.done) { |
| 202 | + return null; |
| 203 | + } |
| 204 | + |
| 205 | + return result.value; |
| 206 | + } |
| 207 | + |
| 208 | + async toArray() { |
| 209 | + const documents = new List(); |
| 210 | + for await (const doc of this) { |
| 211 | + documents.push(doc); |
| 212 | + } |
| 213 | + return documents.toArray(); |
| 214 | + } |
| 215 | + |
| 216 | + async close() { |
| 217 | + if (this.done) { |
| 218 | + return; |
| 219 | + } |
| 220 | + if (this.id != null && this.id !== 0n && this.ns != null && this.server != null) { |
| 221 | + const options = this.session.hasEnded ? {} : { session: this.session }; |
| 222 | + const killCursorsOperation = new KillCursorsOperation(this.id, this.ns, this.server, options); |
| 223 | + await executeOperation(this.client, killCursorsOperation).catch(() => null); |
| 224 | + } |
| 225 | + if (this.session.owner === this) { |
| 226 | + await this.session.endSession().catch(() => null); |
| 227 | + } |
| 228 | + this.done = true; |
| 229 | + } |
| 230 | +} |
0 commit comments