@@ -290,38 +290,49 @@ export class MongoServer {
290290 this . dbPath = undefined ;
291291 }
292292
293+ private async _ensureMatchingMetadataColl (
294+ client : MongoClient ,
295+ mode : 'insert-new' | 'restore-check' ,
296+ ) : Promise < void > {
297+ const hello = await client . db ( 'admin' ) . command ( { hello : 1 } ) ;
298+ const isMongoS = hello . msg === 'isdbgrid' ;
299+ const insertedInfo = pick ( this . serialize ( ) , [
300+ '_id' ,
301+ 'pid' ,
302+ 'port' ,
303+ 'dbPath' ,
304+ 'startTime' ,
305+ ] ) ;
306+ const runnerColl = client
307+ . db ( isMongoS ? 'config' : 'local' )
308+ . collection < SerializedServerProperties > ( 'mongodbrunner' ) ;
309+ if ( mode === 'insert-new' ) {
310+ await runnerColl . insertOne ( insertedInfo ) ;
311+ } else {
312+ const match = await runnerColl . findOne ( ) ;
313+ if ( ! match ) {
314+ throw new Error (
315+ 'Cannot find mongodbrunner entry, assuming that this instance was not started by mongodb-runner' ,
316+ ) ;
317+ }
318+ if ( match . _id !== insertedInfo . _id ) {
319+ throw new Error (
320+ `Mismatched mongodbrunner entry: ${ JSON . stringify ( match ) } !== ${ JSON . stringify ( insertedInfo ) } ` ,
321+ ) ;
322+ }
323+ }
324+ }
325+
293326 private async _populateBuildInfo (
294327 mode : 'insert-new' | 'restore-check' ,
295328 ) : Promise < Error | null > {
296329 if ( this . buildInfo ?. version ) return null ;
297330 try {
298331 this . buildInfo = await this . withClient ( async ( client ) => {
299- const admin = client . db ( 'admin' ) ;
300- const coll =
301- admin . collection < SerializedServerProperties > ( 'mongodbrunner' ) ;
302- const insertedInfo = pick ( this . serialize ( ) , [
303- '_id' ,
304- 'pid' ,
305- 'port' ,
306- 'dbPath' ,
307- 'startTime' ,
308- ] ) ;
309- if ( mode === 'insert-new' ) {
310- await coll . insertOne ( insertedInfo ) ;
311- } else {
312- const match = await coll . findOne ( ) ;
313- if ( ! match ) {
314- throw new Error (
315- 'Cannot find mongodbrunner entry, assuming that this instance was not started by mongodb-runner' ,
316- ) ;
317- }
318- if ( match . _id !== insertedInfo . _id ) {
319- throw new Error (
320- `Mismatched mongodbrunner entry: ${ JSON . stringify ( match ) } !== ${ JSON . stringify ( insertedInfo ) } ` ,
321- ) ;
322- }
323- }
324- return await admin . command ( { buildInfo : 1 } ) ;
332+ // Insert the metadata entry, except if we're a freshly started mongos
333+ // (which does not have its own storage to persist)
334+ await this . _ensureMatchingMetadataColl ( client , mode ) ;
335+ return await client . db ( 'admin' ) . command ( { buildInfo : 1 } ) ;
325336 } ) ;
326337 } catch ( err ) {
327338 debug ( 'failed to get buildInfo, treating as closed server' , err ) ;
0 commit comments