{"t":{"$date":"2023-08-29T14:53:09.474Z"},"s":"I","c":"MONGOSH","id":1000000000,"ctx":"log","msg":"Starting log","attr":{"execPath":"/usr/bin/mongosh","envInfo":{"EDITOR":"vi","NODE_OPTIONS":null,"TERM":"linux"},"version":"1.10.6","distributionKind":"compiled","buildArch":"x64","buildPlatform":"linux","buildTarget":"linux-x64","buildTime":"2023-08-24T16:32:23.981Z","gitVersion":"6bcde16381f6258d9be713998c67c48a99cfd691","nodeVersion":"v16.20.2","opensslVersion":"1.1.1v+quic","sharedOpenssl":false,"runtimeArch":"x64","runtimePlatform":"linux","deps":{"nodeDriverVersion":"5.7.0","libmongocryptVersion":"1.9.0-20230511+gitc56c703400","libmongocryptNodeBindingsVersion":"2.8.0"}}} {"t":{"$date":"2023-08-29T14:53:09.488Z"},"s":"I","c":"MONGOSH","id":1000000005,"ctx":"config","msg":"User updated"} {"t":{"$date":"2023-08-29T14:53:09.490Z"},"s":"I","c":"MONGOSH","id":1000000048,"ctx":"config","msg":"Loading global configuration file","attr":{"filename":"/etc/mongosh.conf","found":false}} {"t":{"$date":"2023-08-29T14:53:09.520Z"},"s":"I","c":"MONGOSH","id":1000000052,"ctx":"startup","msg":"Fetching update metadata","attr":{"updateURL":"https://downloads.mongodb.com/compass/mongosh.json","localFilePath":"/home/zhangch/.mongodb/mongosh/update-metadata.json"}} {"t":{"$date":"2023-08-29T14:53:09.549Z"},"s":"I","c":"DEVTOOLS-CONNECT","id":1000000042,"ctx":"mongosh-connect","msg":"Initiating connection attempt","attr":{"uri":"mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.6","driver":{"name":"nodejs|mongosh","version":"5.7.0|1.10.6"},"devtoolsConnectVersion":"2.3.1","host":"127.0.0.1:27017"}} {"t":{"$date":"2023-08-29T14:53:09.552Z"},"s":"I","c":"DEVTOOLS-CONNECT","id":1000000035,"ctx":"mongosh-connect","msg":"Server heartbeat succeeded","attr":{"connectionId":"127.0.0.1:27017"}} {"t":{"$date":"2023-08-29T14:53:09.567Z"},"s":"I","c":"DEVTOOLS-CONNECT","id":1000000037,"ctx":"mongosh-connect","msg":"Connection attempt finished"} {"t":{"$date":"2023-08-29T14:53:09.598Z"},"s":"I","c":"MONGOSH","id":1000000004,"ctx":"connect","msg":"Connecting to server","attr":{"session_id":"64ee0655d03c62292610e01e","userId":null,"telemetryAnonymousId":"63e9b2714ee18e9850852641","connectionUri":"mongodb://:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.6","is_atlas":false,"is_localhost":true,"is_do":false,"server_version":"6.0.4","node_version":"v16.20.2","mongosh_version":"1.10.6","server_os":"linux","server_arch":"x86_64","is_enterprise":false,"auth_type":null,"is_data_federation":false,"dl_version":null,"atlas_version":null,"is_genuine":true,"non_genuine_server_name":"mongodb","fcv":"6.0","api_version":null,"api_strict":null,"api_deprecation_errors":null}} {"t":{"$date":"2023-08-29T14:53:09.604Z"},"s":"I","c":"MONGOSH","id":1000000011,"ctx":"shell-api","msg":"Performed API call","attr":{"method":"adminCommand","class":"Database","db":"test","arguments":{"cmd":{"ping":1}}}} {"t":{"$date":"2023-08-29T14:53:09.607Z"},"s":"I","c":"MONGOSH","id":1000000011,"ctx":"shell-api","msg":"Performed API call","attr":{"method":"getSiblingDB","class":"Database","db":"test","arguments":{"db":"admin"}}} {"t":{"$date":"2023-08-29T14:53:09.836Z"},"s":"I","c":"MONGOSH","id":1000000010,"ctx":"shell-api","msg":"Initialized context","attr":{"method":"setCtx","arguments":{}}} {"t":{"$date":"2023-08-29T14:53:09.842Z"},"s":"I","c":"MONGOSH","id":1000000009,"ctx":"shell-api","msg":"Used \"show\" command","attr":{"method":"show startupWarnings"}} {"t":{"$date":"2023-08-29T14:53:09.843Z"},"s":"I","c":"MONGOSH","id":1000000011,"ctx":"shell-api","msg":"Performed API call","attr":{"method":"adminCommand","class":"Database","db":"test","arguments":{"cmd":{"getLog":"startupWarnings"}}}} {"t":{"$date":"2023-08-29T14:53:09.844Z"},"s":"I","c":"MONGOSH","id":1000000011,"ctx":"shell-api","msg":"Performed API call","attr":{"method":"getSiblingDB","class":"Database","db":"test","arguments":{"db":"admin"}}} {"t":{"$date":"2023-08-29T14:53:09.845Z"},"s":"I","c":"MONGOSH","id":1000000009,"ctx":"shell-api","msg":"Used \"show\" command","attr":{"method":"show automationNotices"}} {"t":{"$date":"2023-08-29T14:53:09.847Z"},"s":"I","c":"MONGOSH","id":1000000011,"ctx":"shell-api","msg":"Performed API call","attr":{"method":"hello","class":"Database","db":"test","arguments":{}}} {"t":{"$date":"2023-08-29T14:53:09.851Z"},"s":"I","c":"MONGOSH","id":1000000009,"ctx":"shell-api","msg":"Used \"show\" command","attr":{"method":"show nonGenuineMongoDBCheck"}} {"t":{"$date":"2023-08-29T14:53:09.852Z"},"s":"I","c":"MONGOSH-SNIPPETS","id":1000000024,"ctx":"snippets","msg":"Fetching snippet index","attr":{"refreshMode":"allow-cached"}} {"t":{"$date":"2023-08-29T14:53:09.853Z"},"s":"I","c":"MONGOSH-SNIPPETS","id":1000000019,"ctx":"snippets","msg":"Loaded snippets","attr":{"installdir":"/home/zhangch/.mongodb/mongosh/snippets"}} {"t":{"$date":"2023-08-29T14:53:09.861Z"},"s":"I","c":"MONGOSH-SNIPPETS","id":1000000030,"ctx":"snippets","msg":"Loading snippet","attr":{"source":"load-all","name":"@mongosh/snippet-mongocompat"}} {"t":{"$date":"2023-08-29T14:53:09.867Z"},"s":"I","c":"MONGOSH","id":1000000012,"ctx":"shell-api","msg":"Loading file via load()","attr":{"nested":false,"filename":"/home/zhangch/.mongodb/mongosh/snippets/node_modules/@mongosh/snippet-mongocompat/index.js"}} {"t":{"$date":"2023-08-29T14:53:09.869Z"},"s":"I","c":"MONGOSH-SNIPPETS","id":1000000027,"ctx":"snippets","msg":"Fetching snippet index done"} {"t":{"$date":"2023-08-29T14:53:09.869Z"},"s":"I","c":"MONGOSH-SNIPPETS","id":1000000024,"ctx":"snippets","msg":"Fetching snippet index","attr":{"refreshMode":"force-refresh"}} {"t":{"$date":"2023-08-29T14:53:10.461Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"load(__dirname + '/mongonative.js');\nload(__dirname + '/mongoassert.js');\nload(__dirname + '/mongotypes.js');"}} {"t":{"$date":"2023-08-29T14:53:10.929Z"},"s":"I","c":"MONGOSH","id":1000000012,"ctx":"shell-api","msg":"Loading file via load()","attr":{"nested":true,"filename":"/home/zhangch/.mongodb/mongosh/snippets/node_modules/@mongosh/snippet-mongocompat/mongonative.js"}} {"t":{"$date":"2023-08-29T14:53:11.213Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"var cd = process.chdir;\nvar getHostName = os.hostname;\nvar hostname = os.hostname;\nvar pwd = process.cwd;\nvar _rand = Math.random;\nvar _isWindows = () => process.platform === 'win32';\n\nfunction cat(filename, useBinaryMode) {\n let contents = fs.readFileSync(filename, 'utf8');\n if (!useBinaryMode && _isWindows()) {\n contents = contents.replace(/(? !arg.startsWith('-'));\n if (argv.includes('--nodb')) {\n return loadedFiles.length === 0;\n } else {\n return loadedFiles.length <= 1;\n }\n}\n\nfunction listFiles(dir = '.') {\n const files = fs.readdirSync(dir, { withFileTypes: true });\n return files.map(dirent => {\n const obj = { baseName: dirent.name, name: path.join(dir, dirent.name) };\n obj.isDirectory = dirent.isDirectory();\n if (dirent.isFile()) {\n obj.size = fs.statSync(obj.name).size;\n }\n return obj;\n });\n}\n\nfunction ls(dir) {\n return listFiles(dir).map(file => file.name);\n}\n\nfunction md5sumFile(filename) {\n return crypto.createHash('md5').update(fs.readFileSync(filename)).digest('hex');\n}\n\nfunction mkdir(path) {\n const ret = fs.mkdirSync(path, { recursive: true });\n if (ret === undefined) {\n return { exists: true, created: false };\n } else {\n return { exists: true, created: true };\n }\n}\n\nfunction removeFile(path) {\n let existed = false;\n try {\n fs.statSync(path);\n existed = true;\n } catch {}\n fs.rmSync(path, { recursive: true, force: true });\n return existed;\n}"}} {"t":{"$date":"2023-08-29T14:53:11.264Z"},"s":"I","c":"MONGOSH","id":1000000012,"ctx":"shell-api","msg":"Loading file via load()","attr":{"nested":true,"filename":"/home/zhangch/.mongodb/mongosh/snippets/node_modules/@mongosh/snippet-mongocompat/mongoassert.js"}} {"t":{"$date":"2023-08-29T14:53:12.403Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"doassert = function(msg, obj) {\n // eval if msg is a function\n if (typeof (msg) == \"function\")\n msg = msg();\n\n if (typeof (msg) == \"object\")\n msg = tojson(msg);\n\n /*if (jsTest.options().traceExceptions) {\n if (typeof (msg) == \"string\" && msg.indexOf(\"assert\") == 0)\n print(msg);\n else\n print(\"assert: \" + msg);\n }*/\n\n var ex;\n if (obj) {\n ex = _getErrorWithCode(obj, msg);\n } else {\n ex = Error(msg);\n }\n /*if (jsTest.options().traceExceptions) {\n print(ex.stack);\n }*/\n throw ex;\n};\n\n// Sort doc/obj fields and return new sorted obj\nsortDoc = function(doc) {\n // Helper to sort the elements of the array\n var sortElementsOfArray = function(arr) {\n var newArr = [];\n if (!arr || arr.constructor != Array)\n return arr;\n for (var i = 0; i < arr.length; i++) {\n newArr.push(sortDoc(arr[i]));\n }\n return newArr;\n };\n\n // not a container we can sort\n if (!(doc instanceof Object))\n return doc;\n\n // if it an array, sort the elements\n if (doc.constructor == Array)\n return sortElementsOfArray(doc);\n\n var newDoc = {};\n var fields = Object.keys(doc);\n if (fields.length > 0) {\n fields.sort();\n for (var i = 0; i < fields.length; i++) {\n var field = fields[i];\n if (doc.hasOwnProperty(field)) {\n var tmp = doc[field];\n\n if (tmp) {\n // Sort recursively for Arrays and Objects (including bson ones)\n if (tmp.constructor == Array)\n tmp = sortElementsOfArray(tmp);\n else if (tmp._bson || tmp.constructor == Object)\n tmp = sortDoc(tmp);\n }\n newDoc[field] = tmp;\n }\n }\n } else {\n newDoc = doc;\n }\n\n return newDoc;\n};\n\n/*\n * This function transforms a given function, 'func', into a function 'safeFunc',\n * where 'safeFunc' matches the behavior of 'func', except that it returns false\n * in any instance where 'func' throws an exception. 'safeFunc' also prints\n * message 'excMsg' upon catching such a thrown exception.\n */\nfunction _convertExceptionToReturnStatus(func, excMsg) {\n var safeFunc = () => {\n try {\n return func();\n } catch (e) {\n print(excMsg + \", exception: \" + e);\n return false;\n }\n };\n return safeFunc;\n}\n\nassert = (function() {\n // Wrapping the helper function in an IIFE to avoid polluting the global namespace.\n\n function _processMsg(msg) {\n if (typeof msg === \"function\") {\n return msg();\n } else if (typeof msg === \"object\") {\n return tojson(msg);\n }\n\n return msg;\n }\n\n function _validateAssertionMessage(msg) {\n if (msg) {\n if (typeof msg === \"function\") {\n if (msg.length !== 0) {\n doassert(\"msg function cannot expect any parameters.\");\n }\n } else if (typeof msg !== \"string\" && typeof msg !== \"object\") {\n doassert(\"msg parameter must be a string, function or object.\");\n }\n\n if (msg && assert._debug) {\n print(\"in assert for: \" + _processMsg(msg));\n }\n }\n }\n\n function _buildAssertionMessage(msg, prefix) {\n var fullMessage = '';\n\n if (prefix) {\n fullMessage += prefix;\n }\n\n if (prefix && msg) {\n fullMessage += ' : ';\n }\n\n if (msg) {\n fullMessage += _processMsg(msg);\n }\n\n return fullMessage;\n }\n\n assert.automsg = function(b) {\n assert(eval(b), b);\n };\n\n assert._debug = false;\n\n function _isEq(a, b) {\n if (a == b) {\n return true;\n }\n\n if ((a != null && b != null) && friendlyEqual(a, b)) {\n return true;\n }\n\n return false;\n }\n\n assert.eq = function(a, b, msg) {\n _validateAssertionMessage(msg);\n\n if (_isEq(a, b)) {\n return;\n }\n\n doassert(_buildAssertionMessage(\n msg, \"[\" + tojson(a) + \"] != [\" + tojson(b) + \"] are not equal\"));\n };\n\n function _isDocEq(a, b) {\n if (a == b) {\n return true;\n }\n\n var aSorted = sortDoc(a);\n var bSorted = sortDoc(b);\n\n if ((aSorted != null && bSorted != null) && friendlyEqual(aSorted, bSorted)) {\n return true;\n }\n\n return false;\n }\n\n assert.docEq = function(a, b, msg) {\n _validateAssertionMessage(msg);\n\n if (_isDocEq(a, b)) {\n return;\n }\n\n doassert(_buildAssertionMessage(\n msg, \"[\" + tojson(a) + \"] != [\" + tojson(b) + \"] are not equal\"));\n };\n\n assert.setEq = function(aSet, bSet, msg) {\n const failAssertion = function() {\n doassert(_buildAssertionMessage(msg, tojson(aSet) + \" != \" + tojson(bSet)));\n };\n if (aSet.size !== bSet.size) {\n failAssertion();\n }\n for (let a of aSet) {\n if (!bSet.has(a)) {\n failAssertion();\n }\n }\n };\n\n /**\n * Throws if the two arrays do not have the same members, in any order. By default, nested\n * arrays must have the same order to be considered equal.\n *\n * Optionally accepts a compareFn to compare values instead of using docEq.\n */\n assert.sameMembers = function(aArr, bArr, msg, compareFn = _isDocEq) {\n _validateAssertionMessage(msg);\n\n const failAssertion = function() {\n doassert(_buildAssertionMessage(msg, tojson(aArr) + \" != \" + tojson(bArr)));\n };\n\n if (aArr.length !== bArr.length) {\n failAssertion();\n }\n\n // Keep a set of which indices we've already used to avoid double counting values.\n const matchedIndicesInRight = new Set();\n for (let a of aArr) {\n let foundMatch = false;\n for (let i = 0; i < bArr.length; ++i) {\n // Sort both inputs in case either is a document. Note: by default this does not\n // sort any nested arrays.\n if (!matchedIndicesInRight.has(i) && compareFn(a, bArr[i])) {\n matchedIndicesInRight.add(i);\n foundMatch = true;\n break;\n }\n }\n if (!foundMatch) {\n failAssertion();\n }\n }\n };\n\n assert.eq.automsg = function(a, b) {\n assert.eq(eval(a), eval(b), \"[\" + a + \"] != [\" + b + \"]\");\n };\n\n assert.neq = function(a, b, msg) {\n _validateAssertionMessage(msg);\n\n if (!_isEq(a, b)) {\n return;\n }\n\n doassert(_buildAssertionMessage(msg, \"[\" + a + \"] != [\" + b + \"] are equal\"));\n };\n\n assert.hasFields = function(result, arr, msg) {\n var count = 0;\n if (!Array.isArray(arr)) {\n throw new Error(\"The second argument to assert.hasFields must be an array.\");\n }\n\n for (var field in result) {\n if (arr.includes(field)) {\n count += 1;\n }\n }\n\n if (count != arr.length) {\n doassert(_buildAssertionMessage(\n msg, \"Not all of the values from \" + tojson(arr) + \" were in \" + tojson(result)));\n }\n };\n\n assert.contains = function(o, arr, msg) {\n var wasIn = false;\n if (!Array.isArray(arr)) {\n throw new Error(\"The second argument to assert.contains must be an array.\");\n }\n\n for (var i = 0; i < arr.length; i++) {\n wasIn = arr[i] == o || ((arr[i] != null && o != null) && friendlyEqual(arr[i], o));\n if (wasIn) {\n break;\n }\n }\n\n if (!wasIn) {\n doassert(_buildAssertionMessage(msg, tojson(o) + \" was not in \" + tojson(arr)));\n }\n };\n\n assert.containsPrefix = function(prefix, arr, msg) {\n var wasIn = false;\n if (typeof (prefix) !== \"string\") {\n throw new Error(\"The first argument to containsPrefix must be a string.\");\n }\n if (!Array.isArray(arr)) {\n throw new Error(\"The second argument to containsPrefix must be an array.\");\n }\n\n for (let i = 0; i < arr.length; i++) {\n if (typeof (arr[i]) !== \"string\") {\n continue;\n }\n\n wasIn = arr[i].startsWith(prefix);\n if (wasIn) {\n break;\n }\n }\n\n if (!wasIn) {\n doassert(_buildAssertionMessage(\n msg, tojson(prefix) + \" was not a prefix in \" + tojson(arr)));\n }\n };\n\n /*\n * Calls a function 'func' at repeated intervals until either func() returns true\n * or more than 'timeout' milliseconds have elapsed. Throws an exception with\n * message 'msg' after timing out.\n */\n assert.soon = function(func, msg, timeout, interval, {runHangAnalyzer = true} = {}) {\n _validateAssertionMessage(msg);\n\n var msgPrefix = \"assert.soon failed: \" + func;\n\n if (msg) {\n if (typeof (msg) != \"function\") {\n msgPrefix = \"assert.soon failed, msg\";\n }\n }\n\n var start = new Date();\n\n if (TestData && TestData.inEvergreen) {\n timeout = timeout || 10 * 60 * 1000;\n } else {\n timeout = timeout || 90 * 1000;\n }\n\n interval = interval || 200;\n\n while (1) {\n if (typeof (func) == \"string\") {\n if (eval(func))\n return;\n } else {\n if (func())\n return;\n }\n\n diff = (new Date()).getTime() - start.getTime();\n if (diff > timeout) {\n msg = _buildAssertionMessage(msg, msgPrefix);\n if (runHangAnalyzer) {\n msg = msg +\n \" The hang analyzer is automatically called in assert.soon functions.\" +\n \" If you are *expecting* assert.soon to possibly fail, call assert.soon\" +\n \" with {runHangAnalyzer: false} as the fifth argument\" +\n \" (you can fill unused arguments with `undefined`).\";\n print(msg + \" Running hang analyzer from assert.soon.\");\n MongoRunner.runHangAnalyzer();\n }\n doassert(msg);\n } else {\n sleep(interval);\n }\n }\n };\n\n /*\n * Calls a function 'func' at repeated intervals until either func() returns true without\n * throwing an exception or more than 'timeout' milliseconds have elapsed. Throws an exception\n * with message 'msg' after timing out.\n */\n assert.soonNoExcept = function(func, msg, timeout, interval) {\n var safeFunc =\n _convertExceptionToReturnStatus(func, \"assert.soonNoExcept caught exception\");\n var getFunc = () => {\n // No TestData means not running from resmoke. Non-resmoke tests usually don't trace\n // exceptions.\n if (typeof TestData === \"undefined\") {\n return safeFunc;\n }\n return () => {\n // Turns off printing the JavaScript stacktrace in doassert() to avoid\n // generating an overwhelming amount of log messages when handling transient\n // errors.\n const origTraceExceptions = TestData.traceExceptions;\n TestData.traceExceptions = false;\n\n const res = safeFunc();\n\n // Restore it's value to original value.\n TestData.traceExceptions = origTraceExceptions;\n return res;\n };\n };\n\n assert.soon(getFunc(), msg, timeout, interval);\n };\n\n /*\n * Calls the given function 'func' repeatedly at time intervals specified by\n * 'intervalMS' (milliseconds) until either func() returns true or the number of\n * attempted function calls is equal to 'num_attempts'. Throws an exception with\n * message 'msg' after all attempts are used up. If no 'intervalMS' argument is passed,\n * it defaults to 0.\n */\n assert.retry = function(func, msg, num_attempts, intervalMS, {runHangAnalyzer = true} = {}) {\n var intervalMS = intervalMS || 0;\n var attempts_made = 0;\n while (attempts_made < num_attempts) {\n if (func()) {\n return;\n } else {\n attempts_made += 1;\n print(\"assert.retry failed on attempt \" + attempts_made + \" of \" + num_attempts);\n sleep(intervalMS);\n }\n }\n // Used up all attempts\n msg = _buildAssertionMessage(msg);\n if (runHangAnalyzer) {\n msg = msg + \" The hang analyzer is automatically called in assert.retry functions. \" +\n \"If you are *expecting* assert.soon to possibly fail, call assert.retry \" +\n \"with {runHangAnalyzer: false} as the fifth argument \" +\n \"(you can fill unused arguments with `undefined`).\";\n print(msg + \" Running hang analyzer from assert.retry.\");\n MongoRunner.runHangAnalyzer();\n }\n doassert(msg);\n };\n\n /*\n * Calls the given function 'func' repeatedly at time intervals specified by\n * 'intervalMS' (milliseconds) until either func() returns true without throwing\n * an exception or the number of attempted function calls is equal to 'num_attempts'.\n * Throws an exception with message 'msg' after all attempts are used up. If no 'intervalMS'\n * argument is passed, it defaults to 0.\n */\n assert.retryNoExcept = function(func, msg, num_attempts, intervalMS) {\n var safeFunc =\n _convertExceptionToReturnStatus(func, \"assert.retryNoExcept caught exception\");\n assert.retry(safeFunc, msg, num_attempts, intervalMS);\n };\n\n /**\n * Runs the given command on the 'admin' database of the provided node. Asserts that the command\n * worked but allows network errors to occur.\n *\n * Returns the response if the command succeeded, or undefined if the command failed, *even* if\n * the failure was due to a network error.\n */\n assert.adminCommandWorkedAllowingNetworkError = function(node, commandObj) {\n let res;\n try {\n res = node.adminCommand(commandObj);\n assert.commandWorked(res);\n } catch (e) {\n // Ignore errors due to connection failures.\n if (!isNetworkError(e)) {\n throw e;\n }\n print(\"Caught network error: \" + tojson(e));\n }\n return res;\n };\n\n assert.time = function(f, msg, timeout /*ms*/, {runHangAnalyzer = true} = {}) {\n _validateAssertionMessage(msg);\n\n var start = new Date();\n timeout = timeout || 30000;\n if (typeof (f) == \"string\") {\n res = eval(f);\n } else {\n res = f();\n }\n\n diff = (new Date()).getTime() - start.getTime();\n if (diff > timeout) {\n const msgPrefix =\n \"assert.time failed timeout \" + timeout + \"ms took \" + diff + \"ms : \" + f + \", msg\";\n msg = _buildAssertionMessage(msg, msgPrefix);\n if (runHangAnalyzer) {\n msg = msg +\n \" The hang analyzer is automatically called in assert.time functions. \" +\n \"If you are *expecting* assert.soon to possibly fail, call assert.time \" +\n \"with {runHangAnalyzer: false} as the fourth argument \" +\n \"(you can fill unused arguments with `undefined`).\";\n print(msg + \" Running hang analyzer from assert.time.\");\n MongoRunner.runHangAnalyzer();\n }\n doassert(msg);\n }\n return res;\n };\n\n function assertThrowsHelper(func, params) {\n if (typeof func !== \"function\") {\n throw new Error('1st argument must be a function');\n }\n\n if (arguments.length >= 2 && !Array.isArray(params) &&\n Object.prototype.toString.call(params) !== \"[object Arguments]\") {\n throw new Error(\"2nd argument must be an Array or Arguments object\");\n }\n\n let thisKeywordWasUsed = false;\n\n const thisSpy = new Proxy({}, {\n has: () => {\n thisKeywordWasUsed = true;\n return false;\n },\n\n get: () => {\n thisKeywordWasUsed = true;\n return undefined;\n },\n\n set: () => {\n thisKeywordWasUsed = true;\n return false;\n },\n\n deleteProperty: () => {\n thisKeywordWasUsed = true;\n return false;\n }\n });\n\n let error = null;\n let res = null;\n try {\n res = func.apply(thisSpy, params);\n } catch (e) {\n error = e;\n }\n\n if (thisKeywordWasUsed) {\n doassert(\"Attempted to access 'this' during function call in\" +\n \" assert.throws/doesNotThrow. Instead, wrap the function argument in\" +\n \" another function.\");\n }\n\n return {error: error, res: res};\n }\n\n assert.throws = function(func, params, msg) {\n _validateAssertionMessage(msg);\n\n // Use .apply() instead of calling the function directly with explicit arguments to\n // preserve the length of the `arguments` object.\n const {error} = assertThrowsHelper.apply(null, arguments);\n\n if (!error) {\n doassert(_buildAssertionMessage(msg, \"did not throw exception\"));\n }\n\n return error;\n };\n\n assert.doesNotThrow = function(func, params, msg) {\n _validateAssertionMessage(msg);\n\n // Use .apply() instead of calling the function directly with explicit arguments to\n // preserve the length of the `arguments` object.\n const {error, res} = assertThrowsHelper.apply(null, arguments);\n\n if (error) {\n doassert(_buildAssertionMessage(msg, \"threw unexpected exception: \" + error));\n }\n\n return res;\n };\n\n assert.throws.automsg = function(func, params) {\n if (arguments.length === 1)\n params = [];\n assert.throws(func, params, func.toString());\n };\n\n assert.doesNotThrow.automsg = function(func, params) {\n if (arguments.length === 1)\n params = [];\n assert.doesNotThrow(func, params, func.toString());\n };\n\n function _rawReplyOkAndNoWriteErrors(raw, {ignoreWriteErrors, ignoreWriteConcernErrors} = {}) {\n if (raw.ok === 0) {\n return false;\n }\n\n // A write command response may have ok:1 but write errors.\n if (!ignoreWriteErrors && raw.hasOwnProperty(\"writeErrors\") && raw.writeErrors.length > 0) {\n return false;\n }\n\n if (!ignoreWriteConcernErrors && raw.hasOwnProperty(\"writeConcernError\")) {\n return false;\n }\n\n return true;\n }\n\n // Returns whether res is a type which may have write errors (not command errors).\n // These types imply that the write command succeeded.\n function _isWriteResultType(res) {\n return res instanceof WriteResult || res instanceof WriteError ||\n res instanceof BulkWriteResult || res instanceof BulkWriteError;\n }\n\n function _validateCommandResponse(res, assertionName) {\n if (typeof res !== \"object\") {\n doassert(\"unknown response type '\" + typeof res + \"' given to \" + assertionName +\n \", res='\" + res + \"'\");\n }\n }\n\n function _runHangAnalyzerIfWriteConcernTimedOut(res) {\n const timeoutMsg = \"waiting for replication timed out\";\n let isWriteConcernTimeout = false;\n if (_isWriteResultType(res)) {\n if (res.hasWriteConcernError() && res.getWriteConcernError().errmsg === timeoutMsg) {\n isWriteConcernTimeout = true;\n }\n } else if ((res.hasOwnProperty(\"errmsg\") && res.errmsg === timeoutMsg) ||\n (res.hasOwnProperty(\"writeConcernError\") &&\n res.writeConcernError.errmsg === timeoutMsg)) {\n isWriteConcernTimeout = true;\n }\n if (isWriteConcernTimeout) {\n print(\"Running hang analyzer for writeConcern timeout \" + tojson(res));\n MongoRunner.runHangAnalyzer();\n return true;\n }\n return false;\n }\n\n function _runHangAnalyzerIfNonTransientLockTimeoutError(res) {\n // Concurrency suites see a lot of LockTimeouts when running concurrent transactions.\n // However, they will also abort transactions and continue running rather than fail the\n // test, so we don't want to run the hang analyzer when the error has a\n // TransientTransactionError error label.\n const isTransientTxnError = res.hasOwnProperty(\"errorLabels\") &&\n res.errorLabels.includes(\"TransientTransactionError\");\n const isLockTimeout = res.hasOwnProperty(\"code\") && ErrorCodes.LockTimeout === res.code;\n if (isLockTimeout && !isTransientTxnError) {\n print(\"Running hang analyzer for lock timeout \" + tojson(res));\n MongoRunner.runHangAnalyzer();\n return true;\n }\n return false;\n }\n\n function _runHangAnalyzerForSpecificFailureTypes(res) {\n // If the hang analyzer is run, then we shouldn't try to run it again.\n if (_runHangAnalyzerIfWriteConcernTimedOut(res)) {\n return;\n }\n\n _runHangAnalyzerIfNonTransientLockTimeoutError(res);\n }\n\n function _assertCommandWorked(res, msg, {ignoreWriteErrors, ignoreWriteConcernErrors}) {\n _validateAssertionMessage(msg);\n _validateCommandResponse(res, \"commandWorked\");\n\n // Keep this as a function so we don't call tojson if not necessary.\n const makeFailMsg = () => {\n let prefix = \"command failed: \" + tojson(res);\n if (typeof res._commandObj === \"object\" && res._commandObj !== null) {\n prefix += \" with original command request: \" + tojson(res._commandObj);\n }\n if (typeof res._mongo === \"object\" && res._mongo !== null) {\n prefix += \" on connection: \" + res._mongo;\n }\n return _buildAssertionMessage(msg, prefix);\n };\n\n if (_isWriteResultType(res)) {\n // These can only contain write errors, not command errors.\n if (!ignoreWriteErrors) {\n assert.writeOK(res, msg, {ignoreWriteConcernErrors: ignoreWriteConcernErrors});\n }\n } else if (res instanceof WriteCommandError || res instanceof Error) {\n // A WriteCommandError implies ok:0.\n // Error objects may have a `code` property added (e.g.\n // DBCollection.prototype.mapReduce) without a `ok` property.\n doassert(makeFailMsg(), res);\n } else if (res.hasOwnProperty(\"ok\")) {\n // Handle raw command responses or cases like MapReduceResult which extend command\n // response.\n if (!_rawReplyOkAndNoWriteErrors(res, {\n ignoreWriteErrors: ignoreWriteErrors,\n ignoreWriteConcernErrors: ignoreWriteConcernErrors\n })) {\n _runHangAnalyzerForSpecificFailureTypes(res);\n doassert(makeFailMsg(), res);\n }\n } else if (res.hasOwnProperty(\"acknowledged\")) {\n // CRUD api functions return plain js objects with an acknowledged property.\n // no-op.\n } else {\n doassert(_buildAssertionMessage(\n msg, \"unknown type of result, cannot check ok: \" + tojson(res)),\n res);\n }\n return res;\n }\n\n assert._kAnyErrorCode = Object.create(null);\n\n function _assertCommandFailed(res, expectedCode, msg) {\n _validateAssertionMessage(msg);\n _validateCommandResponse(res, \"commandFailed\");\n\n if (expectedCode !== assert._kAnyErrorCode && !Array.isArray(expectedCode)) {\n expectedCode = [expectedCode];\n }\n\n // Keep this as a function so we don't call tojson if not necessary.\n const makeFailMsg = () => {\n return _buildAssertionMessage(\n msg, \"command worked when it should have failed: \" + tojson(res));\n };\n\n const makeFailCodeMsg = () => {\n return (expectedCode !== assert._kAnyErrorCode)\n ? _buildAssertionMessage(msg,\n \"command did not fail with any of the following codes \" +\n tojson(expectedCode) + \" \" + tojson(res))\n : \"\";\n };\n\n if (_isWriteResultType(res)) {\n // These can only contain write errors, not command errors.\n assert.writeErrorWithCode(res, expectedCode, msg);\n } else if (res instanceof WriteCommandError || res instanceof Error) {\n // A WriteCommandError implies ok:0.\n // Error objects may have a `code` property added (e.g.\n // DBCollection.prototype.mapReduce) without a `ok` property.\n if (expectedCode !== assert._kAnyErrorCode) {\n if (!res.hasOwnProperty(\"code\") || !expectedCode.includes(res.code)) {\n doassert(makeFailCodeMsg(), res);\n }\n }\n } else if (res.hasOwnProperty(\"ok\")) {\n // Handle raw command responses or cases like MapReduceResult which extend command\n // response.\n if (_rawReplyOkAndNoWriteErrors(res)) {\n doassert(makeFailMsg(), res);\n }\n\n if (expectedCode !== assert._kAnyErrorCode) {\n let foundCode = false;\n if (res.hasOwnProperty(\"code\") && expectedCode.includes(res.code)) {\n foundCode = true;\n } else if (res.hasOwnProperty(\"writeErrors\")) {\n foundCode = res.writeErrors.some((err) => expectedCode.includes(err.code));\n } else if (res.hasOwnProperty(\"writeConcernError\")) {\n foundCode = expectedCode.includes(res.writeConcernError.code);\n }\n\n if (!foundCode) {\n _runHangAnalyzerForSpecificFailureTypes(res);\n doassert(makeFailCodeMsg(), res);\n }\n }\n } else if (res.hasOwnProperty(\"acknowledged\")) {\n // CRUD api functions return plain js objects with an acknowledged property.\n doassert(makeFailMsg());\n } else {\n doassert(_buildAssertionMessage(\n msg, \"unknown type of result, cannot check error: \" + tojson(res)),\n res);\n }\n return res;\n }\n\n assert.commandWorkedOrFailedWithCode = function commandWorkedOrFailedWithCode(\n res, errorCodeSet, msg) {\n if (!res.ok) {\n return assert.commandFailedWithCode(res, errorCodeSet, msg);\n } else {\n return assert.commandWorked(res, msg);\n }\n };\n\n assert.commandWorked = function(res, msg) {\n return _assertCommandWorked(res, msg, {ignoreWriteErrors: false});\n };\n\n assert.commandWorkedIgnoringWriteErrors = function(res, msg) {\n return _assertCommandWorked(res, msg, {ignoreWriteErrors: true});\n };\n\n assert.commandWorkedIgnoringWriteConcernErrors = function(res, msg) {\n return _assertCommandWorked(res, msg, {ignoreWriteConcernErrors: true});\n };\n\n assert.commandWorkedIgnoringWriteErrorsAndWriteConcernErrors = function(res, msg) {\n return _assertCommandWorked(\n res, msg, {ignoreWriteConcernErrors: true, ignoreWriteErrors: true});\n };\n\n assert.commandFailed = function(res, msg) {\n return _assertCommandFailed(res, assert._kAnyErrorCode, msg);\n };\n\n // expectedCode can be an array of possible codes.\n assert.commandFailedWithCode = function(res, expectedCode, msg) {\n return _assertCommandFailed(res, expectedCode, msg);\n };\n\n assert.writeOK = function(res, msg, {ignoreWriteConcernErrors} = {}) {\n var errMsg = null;\n\n if (res instanceof WriteResult) {\n if (res.hasWriteError()) {\n errMsg = \"write failed with error: \" + tojson(res);\n } else if (!ignoreWriteConcernErrors && res.hasWriteConcernError()) {\n errMsg = \"write concern failed with errors: \" + tojson(res);\n }\n } else if (res instanceof BulkWriteResult) {\n // Can only happen with bulk inserts\n if (res.hasWriteErrors()) {\n errMsg = \"write failed with errors: \" + tojson(res);\n } else if (!ignoreWriteConcernErrors && res.hasWriteConcernError()) {\n errMsg = \"write concern failed with errors: \" + tojson(res);\n }\n } else if (res instanceof WriteCommandError || res instanceof WriteError ||\n res instanceof BulkWriteError) {\n errMsg = \"write command failed: \" + tojson(res);\n } else {\n if (!res || !res.ok) {\n errMsg = \"unknown type of write result, cannot check ok: \" + tojson(res);\n }\n }\n\n if (errMsg) {\n _runHangAnalyzerForSpecificFailureTypes(res);\n doassert(_buildAssertionMessage(msg, errMsg), res);\n }\n\n return res;\n };\n\n assert.writeError = function(res, msg) {\n return assert.writeErrorWithCode(res, assert._kAnyErrorCode, msg);\n };\n\n // If expectedCode is an array then this asserts that the found code is one of the codes in\n // the expectedCode array.\n assert.writeErrorWithCode = function(res, expectedCode, msg) {\n if (expectedCode === undefined) {\n doassert(\"assert.writeErrorWithCode called with undefined error code\");\n }\n\n var errMsg = null;\n var writeErrorCodes = new Set();\n\n if (res instanceof WriteResult) {\n if (res.hasWriteError()) {\n writeErrorCodes.add(res.getWriteError().code);\n } else if (res.hasWriteConcernError()) {\n writeErrorCodes.add(res.getWriteConcernError().code);\n } else {\n errMsg = \"no write error: \" + tojson(res);\n }\n } else if (res instanceof BulkWriteResult || res instanceof BulkWriteError) {\n // Can only happen with bulk inserts\n if (res.hasWriteErrors()) {\n // Save every write error code.\n res.getWriteErrors().forEach((we) => writeErrorCodes.add(we.code));\n } else if (res.hasWriteConcernError()) {\n writeErrorCodes.add(res.getWriteConcernError().code);\n } else {\n errMsg = \"no write errors: \" + tojson(res);\n }\n } else if (res instanceof WriteCommandError) {\n // Can only happen with bulk inserts\n // No-op since we're expecting an error\n } else if (res instanceof WriteError) {\n writeErrorCodes.add(res.code);\n } else {\n if (!res || res.ok) {\n errMsg = \"unknown type of write result, cannot check error: \" + tojson(res);\n }\n }\n\n if (!errMsg && expectedCode !== assert._kAnyErrorCode) {\n if (!Array.isArray(expectedCode)) {\n expectedCode = [expectedCode];\n }\n const found = expectedCode.some((ec) => writeErrorCodes.has(ec));\n if (!found) {\n errMsg = \"found code(s) \" + tojson(Array.from(writeErrorCodes)) +\n \" does not match any of the expected codes \" + tojson(expectedCode);\n }\n }\n\n if (errMsg) {\n _runHangAnalyzerForSpecificFailureTypes(res);\n doassert(_buildAssertionMessage(msg, errMsg));\n }\n\n return res;\n };\n\n assert.isnull = function(what, msg) {\n _validateAssertionMessage(msg);\n\n if (what == null) {\n return;\n }\n\n doassert(\"supposed to be null (\" + (_processMsg(msg) || \"\") + \") was: \" + tojson(what));\n };\n\n function _shouldUseBsonWoCompare(a, b) {\n const bsonTypes = [\n Timestamp,\n ];\n\n if (typeof a !== \"object\" || typeof b !== \"object\") {\n return false;\n }\n\n for (let t of bsonTypes) {\n if (a instanceof t && b instanceof t) {\n return true;\n }\n }\n\n return false;\n }\n\n function _compare(f, a, b) {\n if (_shouldUseBsonWoCompare(a, b)) {\n const result = bsonWoCompare({_: a}, {_: b});\n return f(result, 0);\n }\n\n return f(a, b);\n }\n\n function _assertCompare(f, a, b, description, msg) {\n _validateAssertionMessage(msg);\n\n if (_compare(f, a, b)) {\n return;\n }\n\n doassert(_buildAssertionMessage(msg, a + \" is not \" + description + \" \" + b));\n }\n\n assert.lt = function(a, b, msg) {\n _assertCompare((a, b) => {\n return a < b;\n }, a, b, \"less than\", msg);\n };\n\n assert.gt = function(a, b, msg) {\n _assertCompare((a, b) => {\n return a > b;\n }, a, b, \"greater than\", msg);\n };\n\n assert.lte = function(a, b, msg) {\n _assertCompare((a, b) => {\n return a <= b;\n }, a, b, \"less than or eq\", msg);\n };\n\n assert.gte = function(a, b, msg) {\n _assertCompare((a, b) => {\n return a >= b;\n }, a, b, \"greater than or eq\", msg);\n };\n\n assert.between = function(a, b, c, msg, inclusive) {\n _validateAssertionMessage(msg);\n\n let compareFn = (a, b) => {\n return a < b;\n };\n\n if ((inclusive == undefined || inclusive == true)) {\n compareFn = (a, b) => {\n return a <= b;\n };\n }\n\n if (_compare(compareFn, a, b) && _compare(compareFn, b, c)) {\n return;\n }\n\n doassert(_buildAssertionMessage(msg, b + \" is not between \" + a + \" and \" + c));\n };\n\n assert.betweenIn = function(a, b, c, msg) {\n assert.between(a, b, c, msg, true);\n };\n assert.betweenEx = function(a, b, c, msg) {\n assert.between(a, b, c, msg, false);\n };\n\n assert.close = function(a, b, msg, places = 4) {\n // This treats 'places' as digits past the decimal point.\n var absoluteError = Math.abs(a - b);\n if (Math.round(absoluteError * Math.pow(10, places)) === 0) {\n return;\n }\n\n // This treats 'places' as significant figures.\n var relativeError = Math.abs(absoluteError / b);\n if (Math.round(relativeError * Math.pow(10, places)) === 0) {\n return;\n }\n\n const msgPrefix = `${a} is not equal to ${b} within ${places} places, absolute error: ` +\n `${absoluteError}, relative error: ${relativeError}`;\n doassert(_buildAssertionMessage(msg, msgPrefix));\n };\n\n /**\n * Asserts if the times in millis are not withing delta milliseconds, in either direction.\n * Default Delta: 1 second\n */\n assert.closeWithinMS = function(a, b, msg, deltaMS) {\n \"use strict\";\n\n if (deltaMS === undefined) {\n deltaMS = 1000;\n }\n var aMS = a instanceof Date ? a.getTime() : a;\n var bMS = b instanceof Date ? b.getTime() : b;\n var actualDelta = Math.abs(Math.abs(aMS) - Math.abs(bMS));\n\n if (actualDelta <= deltaMS) {\n return;\n }\n\n const msgPrefix = \"\" + a + \" is not equal to \" + b + \" within \" + deltaMS + \" millis, \" +\n \"actual delta: \" + actualDelta + \" millis\";\n doassert(_buildAssertionMessage(msg, msgPrefix));\n };\n\n assert.gleOK = function(res, msg) {\n var errMsg = null;\n\n if (!res) {\n errMsg = \"missing first argument, no response to check\";\n } else if (!res.ok) {\n errMsg = \"getLastError failed: \" + tojson(res);\n } else if ('code' in res || 'errmsg' in res || ('err' in res && res['err'] != null)) {\n errMsg = \"write or write concern failed: \" + tojson(res);\n }\n\n if (errMsg) {\n doassert(_buildAssertionMessage(msg, errMsg), res);\n }\n\n return res;\n };\n\n assert.gleSuccess = function(dbOrGLEDoc, msg) {\n var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;\n if (gle.err) {\n if (typeof (msg) == \"function\")\n msg = msg(gle);\n doassert(_buildAssertionMessage(msg, \"getLastError not null: \" + tojson(gle)), gle);\n }\n return gle;\n };\n\n assert.gleError = function(dbOrGLEDoc, msg) {\n var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;\n if (!gle.err) {\n if (typeof (msg) == \"function\")\n msg = msg(gle);\n doassert(_buildAssertionMessage(msg, \"getLastError is null: \" + tojson(gle)));\n }\n };\n\n assert.gleErrorCode = function(dbOrGLEDoc, code, msg) {\n var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;\n if (!gle.err || gle.code != code) {\n if (typeof (msg) == \"function\")\n msg = msg(gle);\n doassert(_buildAssertionMessage(\n msg,\n \"getLastError is null or has code other than \\\"\" + code + \"\\\": \" + tojson(gle)));\n }\n };\n\n assert.gleErrorRegex = function(dbOrGLEDoc, regex, msg) {\n var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;\n if (!gle.err || !regex.test(gle.err)) {\n if (typeof (msg) == \"function\")\n msg = msg(gle);\n doassert(_buildAssertionMessage(\n msg,\n \"getLastError is null or doesn't match regex (\" + regex + \"): \" + tojson(gle)));\n }\n };\n\n assert.includes = function(haystack, needle, msg) {\n if (!haystack.includes(needle)) {\n var assertMsg = \"string [\" + haystack + \"] does not include [\" + needle + \"]\";\n if (msg) {\n assertMsg += \", \" + msg;\n }\n\n doassert(assertMsg);\n }\n };\n\n return assert;\n})();"}} {"t":{"$date":"2023-08-29T14:53:12.612Z"},"s":"I","c":"MONGOSH","id":1000000012,"ctx":"shell-api","msg":"Loading file via load()","attr":{"nested":true,"filename":"/home/zhangch/.mongodb/mongosh/snippets/node_modules/@mongosh/snippet-mongocompat/mongotypes.js"}} {"t":{"$date":"2023-08-29T14:53:13.171Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"// Date and time types\nif (typeof (Timestamp) != \"undefined\") {\n Timestamp.prototype.tojson = function() {\n return this.toStringIncomparable();\n };\n\n Timestamp.prototype.getTime = function() {\n return this.hasOwnProperty(\"t\") ? this.t : this.high;\n };\n\n Timestamp.prototype.getInc = function() {\n return this.hasOwnProperty(\"i\") ? this.i : this.low;\n };\n\n Timestamp.prototype.toString = function() {\n // Resmoke overrides `toString` to throw an error to prevent accidental operator\n // comparisons, e.g: >, -, etc...\n return this.toStringIncomparable();\n };\n\n Timestamp.prototype.toStringIncomparable = function() {\n var t = this.hasOwnProperty(\"t\") ? this.t : this.high;\n var i = this.hasOwnProperty(\"i\") ? this.i : this.low;\n return \"Timestamp(\" + t + \", \" + i + \")\";\n };\n} else {\n print(\"warning: no Timestamp class\");\n}\n\nDate.timeFunc = function(theFunc, numTimes) {\n var start = new Date();\n numTimes = numTimes || 1;\n for (var i = 0; i < numTimes; i++) {\n theFunc.apply(null, Array.from(arguments).slice(2));\n }\n\n return (new Date()).getTime() - start.getTime();\n};\n\nDate.prototype.tojson = function() {\n try {\n // If this === Date.prototype or this is a Date instance created from\n // Object.create(Date.prototype), then the [[DateValue]] internal slot won't be set and will\n // lead to a TypeError. We instead treat it as though the [[DateValue]] internal slot is NaN\n // in order to be consistent with the ES5 behavior in MongoDB 3.2 and earlier.\n this.getTime();\n } catch (e) {\n if (e instanceof TypeError &&\n e.message.includes(\"getTime method called on incompatible Object\")) {\n return new Date(NaN).tojson();\n }\n throw e;\n }\n\n var UTC = 'UTC';\n var year = this['get' + UTC + 'FullYear']().zeroPad(4);\n var month = (this['get' + UTC + 'Month']() + 1).zeroPad(2);\n var date = this['get' + UTC + 'Date']().zeroPad(2);\n var hour = this['get' + UTC + 'Hours']().zeroPad(2);\n var minute = this['get' + UTC + 'Minutes']().zeroPad(2);\n var sec = this['get' + UTC + 'Seconds']().zeroPad(2);\n\n if (this['get' + UTC + 'Milliseconds']())\n sec += '.' + this['get' + UTC + 'Milliseconds']().zeroPad(3);\n\n var ofs = 'Z';\n // // print a non-UTC time\n // var ofsmin = this.getTimezoneOffset();\n // if (ofsmin != 0){\n // ofs = ofsmin > 0 ? '-' : '+'; // This is correct\n // ofs += (ofsmin/60).zeroPad(2)\n // ofs += (ofsmin%60).zeroPad(2)\n // }\n return 'ISODate(\"' + year + '-' + month + '-' + date + 'T' + hour + ':' + minute + ':' + sec +\n ofs + '\")';\n};\n\nISODate = function(isoDateStr) {\n if (!isoDateStr)\n return new Date();\n\n var isoDateRegex =\n /^(\\d{4})-?(\\d{2})-?(\\d{2})([T ](\\d{2})(:?(\\d{2})(:?(\\d{2}(\\.\\d+)?))?)?(Z|([+-])(\\d{2}):?(\\d{2})?)?)?$/;\n var res = isoDateRegex.exec(isoDateStr);\n\n if (!res)\n throw Error(\"invalid ISO date: \" + isoDateStr);\n\n var year = parseInt(res[1], 10);\n var month = (parseInt(res[2], 10)) - 1;\n var date = parseInt(res[3], 10);\n var hour = parseInt(res[5], 10) || 0;\n var min = parseInt(res[7], 10) || 0;\n var sec = parseInt((res[9] && res[9].substr(0, 2)), 10) || 0;\n var ms = Math.round((parseFloat(res[10]) || 0) * 1000);\n\n var dateTime = new Date();\n\n dateTime.setUTCFullYear(year, month, date);\n dateTime.setUTCHours(hour);\n dateTime.setUTCMinutes(min);\n dateTime.setUTCSeconds(sec);\n var time = dateTime.setUTCMilliseconds(ms);\n\n if (res[11] && res[11] != 'Z') {\n var ofs = 0;\n ofs += (parseInt(res[13], 10) || 0) * 60 * 60 * 1000; // hours\n ofs += (parseInt(res[14], 10) || 0) * 60 * 1000; // mins\n if (res[12] == '+') // if ahead subtract\n ofs *= -1;\n\n time += ofs;\n }\n\n // If we are outside the range 0000-01-01T00:00:00.000Z - 9999-12-31T23:59:59.999Z, abort with\n // error.\n const DATE_RANGE_MIN_MICROSECONDS = -62167219200000;\n const DATE_RANGE_MAX_MICROSECONDS = 253402300799999;\n\n if (time < DATE_RANGE_MIN_MICROSECONDS || time > DATE_RANGE_MAX_MICROSECONDS)\n throw Error(\"invalid ISO date: \" + isoDateStr);\n\n return new Date(time);\n};\n\n// Regular Expression\nRegExp.escape = function(text) {\n return text.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, \"\\\\$&\");\n};\n\nRegExp.prototype.tojson = RegExp.prototype.toString;\n\n// Array\nArray.contains = function(a, x) {\n if (!Array.isArray(a)) {\n throw new Error(\"The first argument to Array.contains must be an array\");\n }\n\n for (var i = 0; i < a.length; i++) {\n if (a[i] == x)\n return true;\n }\n return false;\n};\n\nArray.unique = function(a) {\n if (!Array.isArray(a)) {\n throw new Error(\"The first argument to Array.unique must be an array\");\n }\n\n var u = [];\n for (var i = 0; i < a.length; i++) {\n var o = a[i];\n if (!Array.contains(u, o)) {\n u.push(o);\n }\n }\n return u;\n};\n\nArray.shuffle = function(arr) {\n if (!Array.isArray(arr)) {\n throw new Error(\"The first argument to Array.shuffle must be an array\");\n }\n\n for (var i = 0; i < arr.length - 1; i++) {\n var pos = i + Random.randInt(arr.length - i);\n var save = arr[i];\n arr[i] = arr[pos];\n arr[pos] = save;\n }\n return arr;\n};\n\nArray.tojson = function(a, indent, nolint, depth) {\n if (!Array.isArray(a)) {\n throw new Error(\"The first argument to Array.tojson must be an array\");\n }\n\n if (typeof depth !== 'number') {\n depth = 0;\n }\n if (depth > tojson.MAX_DEPTH) {\n return \"[Array]\";\n }\n\n var elementSeparator = nolint ? \" \" : \"\\n\";\n\n if (!indent)\n indent = \"\";\n if (nolint)\n indent = \"\";\n\n if (a.length == 0) {\n return \"[ ]\";\n }\n\n var s = \"[\" + elementSeparator;\n\n // add to indent if we are pretty\n if (!nolint)\n indent += \"\\t\";\n\n for (var i = 0; i < a.length; i++) {\n s += indent + tojson(a[i], indent, nolint, depth + 1);\n if (i < a.length - 1) {\n s += \",\" + elementSeparator;\n }\n }\n\n // remove from indent if we are pretty\n if (!nolint)\n indent = indent.substring(1);\n\n s += elementSeparator + indent + \"]\";\n return s;\n};\n\nArray.fetchRefs = function(arr, coll) {\n if (!Array.isArray(arr)) {\n throw new Error(\"The first argument to Array.fetchRefs must be an array\");\n }\n\n var n = [];\n for (var i = 0; i < arr.length; i++) {\n var z = arr[i];\n if (coll && coll != z.getCollection())\n continue;\n n.push(z.fetch());\n }\n return n;\n};\n\nArray.sum = function(arr) {\n if (!Array.isArray(arr)) {\n throw new Error(\"The first argument to Array.sum must be an array\");\n }\n\n if (arr.length == 0)\n return null;\n var s = arr[0];\n for (var i = 1; i < arr.length; i++)\n s += arr[i];\n return s;\n};\n\nArray.avg = function(arr) {\n if (!Array.isArray(arr)) {\n throw new Error(\"The first argument to Array.avg must be an array\");\n }\n\n if (arr.length == 0)\n return null;\n return Array.sum(arr) / arr.length;\n};\n\nArray.stdDev = function(arr) {\n if (!Array.isArray(arr)) {\n throw new Error(\"The first argument to Array.stdDev must be an array\");\n }\n\n var avg = Array.avg(arr);\n var sum = 0;\n\n for (var i = 0; i < arr.length; i++) {\n sum += Math.pow(arr[i] - avg, 2);\n }\n\n return Math.sqrt(sum / arr.length);\n};\n\n// Object\nObject.extend = function(dst, src, deep) {\n for (var k in src) {\n var v = src[k];\n if (deep && typeof (v) == \"object\" && v !== null) {\n if (v.constructor === ObjectId) { // convert ObjectId properly\n eval(\"v = \" + tojson(v));\n } else if (\"floatApprox\" in v) { // convert NumberLong properly\n eval(\"v = \" + tojson(v));\n } else {\n v = Object.extend(typeof (v.length) == \"number\" ? [] : {}, v, true);\n }\n }\n dst[k] = v;\n }\n return dst;\n};\n\nObject.merge = function(dst, src, deep) {\n var clone = Object.extend({}, dst, deep);\n return Object.extend(clone, src, deep);\n};\n\nObject.keySet = function(o) {\n var ret = new Array();\n for (var i in o) {\n if (!(i in o.__proto__ && o[i] === o.__proto__[i])) {\n ret.push(i);\n }\n }\n return ret;\n};\n\n// mongosh-specific addition\nObject.bsonsize = bsonsize;\n\n// String\nif (String.prototype.trim === undefined) {\n String.prototype.trim = function() {\n return this.replace(/^\\s+|\\s+$/g, \"\");\n };\n}\nif (String.prototype.trimLeft === undefined) {\n String.prototype.trimLeft = function() {\n return this.replace(/^\\s+/, \"\");\n };\n}\nif (String.prototype.trimRight === undefined) {\n String.prototype.trimRight = function() {\n return this.replace(/\\s+$/, \"\");\n };\n}\n\n// always provide ltrim and rtrim for backwards compatibility\nString.prototype.ltrim = String.prototype.trimLeft;\nString.prototype.rtrim = String.prototype.trimRight;\n\nString.prototype.startsWith = function(str) {\n return this.indexOf(str) == 0;\n};\n\nString.prototype.endsWith = function(str) {\n return this.indexOf(str, this.length - str.length) !== -1;\n};\n\n// Polyfill taken from\n// \nif (!String.prototype.includes) {\n String.prototype.includes = function() {\n 'use strict';\n return String.prototype.indexOf.apply(this, arguments) !== -1;\n };\n}\n\n// Returns a copy padded with the provided character _chr_ so it becomes (at least) _length_\n// characters long.\n// No truncation is performed if the string is already longer than _length_.\n// @param length minimum length of the returned string\n// @param right if falsy add leading whitespace, otherwise add trailing whitespace\n// @param chr character to be used for padding, defaults to whitespace\n// @return the padded string\nString.prototype.pad = function(length, right, chr) {\n if (typeof chr == 'undefined')\n chr = ' ';\n var str = this;\n for (var i = length - str.length; i > 0; i--) {\n if (right) {\n str = str + chr;\n } else {\n str = chr + str;\n }\n }\n return str;\n};\n\n// Number\nNumber.prototype.toPercentStr = function() {\n return (this * 100).toFixed(2) + \"%\";\n};\n\nNumber.prototype.zeroPad = function(width) {\n return ('' + this).pad(width, false, '0');\n};\n\n// NumberLong\nif (!NumberLong.prototype) {\n NumberLong.prototype = {};\n}\n\nNumberLong.prototype.tojson = function() {\n return this.toString();\n};\n\n// NumberInt\nif (!NumberInt.prototype) {\n NumberInt.prototype = {};\n}\n\nNumberInt.prototype.tojson = function() {\n return this.toString();\n};\n\n// NumberDecimal\nif (typeof NumberDecimal !== 'undefined') {\n if (!NumberDecimal.prototype) {\n NumberDecimal.prototype = {};\n }\n\n NumberDecimal.prototype.tojson = function() {\n return this.toString();\n };\n}\n\n// ObjectId\nif (!ObjectId.prototype)\n ObjectId.prototype = {};\n\nObjectId.prototype.toString = function() {\n return this.inspect();\n};\n\nObjectId.prototype.tojson = function() {\n return this.toString();\n};\n\nObject.defineProperty(ObjectId.prototype, 'str', {\n enumerable: true,\n get() {\n return this.toHexString();\n }\n});\n\nObjectId.prototype.valueOf = function() {\n return this.str;\n};\n\nObjectId.prototype.isObjectId = true;\n\nObjectId.prototype.getTimestamp = function() {\n return new Date(parseInt(this.valueOf().slice(0, 8), 16) * 1000);\n};\n\nObjectId.prototype.equals = function(other) {\n return this.str == other.str;\n};\n\n// Creates an ObjectId from a Date.\n// Based on solution discussed here:\n// \nObjectId.fromDate = function(source) {\n if (!source) {\n throw Error(\"date missing or undefined\");\n }\n\n var sourceDate;\n\n // Extract Date from input.\n // If input is a string, assume ISO date string and\n // create a Date from the string.\n if (source instanceof Date) {\n sourceDate = source;\n } else {\n throw Error(\"Cannot create ObjectId from \" + typeof (source) + \": \" + tojson(source));\n }\n\n // Convert date object to seconds since Unix epoch.\n var seconds = Math.floor(sourceDate.getTime() / 1000);\n\n // Generate hex timestamp with padding.\n var hexTimestamp = seconds.toString(16).pad(8, false, '0') + \"0000000000000000\";\n\n // Create an ObjectId with hex timestamp.\n var objectId = ObjectId(hexTimestamp);\n\n return objectId;\n};\n\n// DBPointer\nif (typeof (DBPointer) != \"undefined\") {\n DBPointer.prototype.fetch = function() {\n assert(this.ns, \"need a ns\");\n assert(this.id, \"need an id\");\n return db[this.ns].findOne({_id: this.id});\n };\n\n DBPointer.prototype.tojson = function(indent) {\n return this.toString();\n };\n\n DBPointer.prototype.getCollection = function() {\n return this.ns;\n };\n\n DBPointer.prototype.getId = function() {\n return this.id;\n };\n\n DBPointer.prototype.toString = function() {\n return \"DBPointer(\" + tojson(this.ns) + \", \" + tojson(this.id) + \")\";\n };\n} else {\n // print(\"warning: no DBPointer\");\n}\n\n// DBRef\nif (typeof (DBRef) != \"undefined\") {\n DBRef.prototype.fetch = function() {\n assert(this.$ref, \"need a ns\");\n assert(this.$id, \"need an id\");\n var coll = this.$db ? db.getSiblingDB(this.$db).getCollection(this.$ref) : db[this.$ref];\n return coll.findOne({_id: this.$id});\n };\n\n DBRef.prototype.tojson = function(indent) {\n return this.toString();\n };\n\n DBRef.prototype.getDb = function() {\n return this.$db || undefined;\n };\n\n DBRef.prototype.getCollection = function() {\n return this.$ref;\n };\n\n DBRef.prototype.getRef = function() {\n return this.$ref;\n };\n\n DBRef.prototype.getId = function() {\n return this.$id;\n };\n\n DBRef.prototype.toString = function() {\n return \"DBRef(\" + tojson(this.$ref) + \", \" + tojson(this.$id) +\n (this.$db ? \", \" + tojson(this.$db) : \"\") + \")\";\n };\n} else {\n print(\"warning: no DBRef\");\n}\n\n// BinData\nif (typeof (BinData) != \"undefined\") {\n BinData.prototype.tojson = function() {\n return this.toString();\n };\n\n BinData.prototype.subtype = function() {\n return this.type;\n };\n BinData.prototype.length = function() {\n return this.len;\n };\n} else {\n print(\"warning: no BinData class\");\n}\n\nif (typeof (gc) == \"undefined\") {\n gc = function() {\n print(\"warning: using noop gc()\");\n };\n}\n\n// Free Functions\ntojsononeline = function(x) {\n return tojson(x, \" \", true);\n};\n\ntojson = function(x, indent, nolint, depth) {\n if (x === null)\n return \"null\";\n\n if (x === undefined)\n return \"undefined\";\n\n if (!indent)\n indent = \"\";\n\n if (typeof depth !== 'number') {\n depth = 0;\n }\n\n switch (typeof x) {\n case \"string\":\n return JSON.stringify(x);\n case \"number\":\n case \"boolean\":\n return \"\" + x;\n case \"object\": {\n var s = tojsonObject(x, indent, nolint, depth);\n if ((nolint == null || nolint == true) && s.length < 80 &&\n (indent == null || indent.length == 0)) {\n s = s.replace(/[\\t\\r\\n]+/gm, \" \");\n }\n return s;\n }\n case \"function\":\n if (x === MinKey || x === MaxKey)\n return x.tojson();\n return x.toString();\n default:\n throw Error(\"tojson can't handle type \" + (typeof x));\n }\n};\ntojson.MAX_DEPTH = 100;\n\ntojsonObject = function(x, indent, nolint, depth) {\n if (typeof depth !== 'number') {\n depth = 0;\n }\n var lineEnding = nolint ? \" \" : \"\\n\";\n var tabSpace = nolint ? \"\" : \"\\t\";\n assert.eq((typeof x), \"object\", \"tojsonObject needs object, not [\" + (typeof x) + \"]\");\n\n if (!indent)\n indent = \"\";\n\n if (typeof (x.tojson) == \"function\" && x.tojson != tojson) {\n return x.tojson(indent, nolint, depth);\n }\n\n if (x.constructor && typeof (x.constructor.tojson) == \"function\" &&\n x.constructor.tojson != tojson) {\n return x.constructor.tojson(x, indent, nolint, depth);\n }\n\n if (x instanceof Error) {\n return x.toString();\n }\n\n try {\n x.toString();\n } catch (e) {\n // toString not callable\n return \"[Object]\";\n }\n\n if (depth > tojson.MAX_DEPTH) {\n return \"[Object]\";\n }\n\n var s = \"{\" + lineEnding;\n\n // push one level of indent\n indent += tabSpace;\n\n var keys = x;\n if (typeof (x._simpleKeys) == \"function\")\n keys = x._simpleKeys();\n var fieldStrings = [];\n for (var k in keys) {\n var val = x[k];\n\n // skip internal DB types to avoid issues with interceptors\n if (typeof DB != 'undefined' && val == DB.prototype)\n continue;\n if (typeof DBCollection != 'undefined' && val == DBCollection.prototype)\n continue;\n\n fieldStrings.push(indent + \"\\\"\" + k + \"\\\" : \" + tojson(val, indent, nolint, depth + 1));\n }\n\n if (fieldStrings.length > 0) {\n s += fieldStrings.join(\",\" + lineEnding);\n } else {\n s += indent;\n }\n s += lineEnding;\n\n // pop one level of indent\n indent = indent.substring(1);\n return s + indent + \"}\";\n};\n\nprintjson = function(x) {\n print(tojson(x));\n};\n\nprintjsononeline = function(x) {\n print(tojsononeline(x));\n};\n\nisString = function(x) {\n return typeof (x) == \"string\";\n};\n\nisNumber = function(x) {\n return typeof (x) == \"number\";\n};\n\n// This function returns true even if the argument is an array. See SERVER-14220.\nisObject = function(x) {\n return typeof (x) == \"object\";\n};"}} {"t":{"$date":"2023-08-29T14:53:13.252Z"},"s":"I","c":"MONGOSH","id":1000000053,"ctx":"startup","msg":"Fetching update metadata complete","attr":{"latest":"1.10.6"}} {"t":{"$date":"2023-08-29T14:53:13.265Z"},"s":"I","c":"MONGOSH","id":1000000002,"ctx":"repl","msg":"Started REPL","attr":{"version":"1.10.6"}} {"t":{"$date":"2023-08-29T14:53:14.126Z"},"s":"I","c":"MONGOSH-SNIPPETS","id":1000000027,"ctx":"snippets","msg":"Fetching snippet index done"} {"t":{"$date":"2023-08-29T14:53:20.814Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"b = 'lt'"}} {"t":{"$date":"2023-08-29T14:53:27.107Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"switch (b) { case 'gt': print('gt'); break; case 'lt': print('lt'); break; case 'le': print('le'); break;}"}} {"t":{"$date":"2023-08-29T14:53:38.135Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"b = 'gt'"}} {"t":{"$date":"2023-08-29T14:53:39.513Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"switch (b) { case 'gt': print('gt'); break; case 'lt': print('lt'); break; case 'le': print('le'); break;}"}} {"t":{"$date":"2023-08-29T14:53:46.618Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"b = 'le'"}} {"t":{"$date":"2023-08-29T14:53:48.114Z"},"s":"I","c":"MONGOSH","id":1000000007,"ctx":"repl","msg":"Evaluating input","attr":{"input":"switch (b) { case 'gt': print('gt'); break; case 'lt': print('lt'); break; case 'le': print('le'); break;}"}}