Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sessions.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. 'use strict';
  2. const retrieveBSON = require('./connection/utils').retrieveBSON;
  3. const EventEmitter = require('events');
  4. const BSON = retrieveBSON();
  5. const Binary = BSON.Binary;
  6. const uuidV4 = require('./utils').uuidV4;
  7. const MongoError = require('./error').MongoError;
  8. const isRetryableError = require('././error').isRetryableError;
  9. const MongoNetworkError = require('./error').MongoNetworkError;
  10. const MongoWriteConcernError = require('./error').MongoWriteConcernError;
  11. const Transaction = require('./transactions').Transaction;
  12. const TxnState = require('./transactions').TxnState;
  13. function assertAlive(session, callback) {
  14. if (session.serverSession == null) {
  15. const error = new MongoError('Cannot use a session that has ended');
  16. if (typeof callback === 'function') {
  17. callback(error, null);
  18. return false;
  19. }
  20. throw error;
  21. }
  22. return true;
  23. }
  24. /**
  25. * Options to pass when creating a Client Session
  26. * @typedef {Object} SessionOptions
  27. * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session
  28. * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session.
  29. */
  30. /**
  31. * A BSON document reflecting the lsid of a {@link ClientSession}
  32. * @typedef {Object} SessionId
  33. */
  34. /**
  35. * A class representing a client session on the server
  36. * WARNING: not meant to be instantiated directly.
  37. * @class
  38. * @hideconstructor
  39. */
  40. class ClientSession extends EventEmitter {
  41. /**
  42. * Create a client session.
  43. * WARNING: not meant to be instantiated directly
  44. *
  45. * @param {Topology} topology The current client's topology (Internal Class)
  46. * @param {ServerSessionPool} sessionPool The server session pool (Internal Class)
  47. * @param {SessionOptions} [options] Optional settings
  48. * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver
  49. */
  50. constructor(topology, sessionPool, options, clientOptions) {
  51. super();
  52. if (topology == null) {
  53. throw new Error('ClientSession requires a topology');
  54. }
  55. if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) {
  56. throw new Error('ClientSession requires a ServerSessionPool');
  57. }
  58. options = options || {};
  59. this.topology = topology;
  60. this.sessionPool = sessionPool;
  61. this.hasEnded = false;
  62. this.serverSession = sessionPool.acquire();
  63. this.clientOptions = clientOptions;
  64. this.supports = {
  65. causalConsistency:
  66. typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true
  67. };
  68. options = options || {};
  69. if (typeof options.initialClusterTime !== 'undefined') {
  70. this.clusterTime = options.initialClusterTime;
  71. } else {
  72. this.clusterTime = null;
  73. }
  74. this.operationTime = null;
  75. this.explicit = !!options.explicit;
  76. this.owner = options.owner;
  77. this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions);
  78. this.transaction = new Transaction();
  79. }
  80. /**
  81. * The server id associated with this session
  82. * @type {SessionId}
  83. */
  84. get id() {
  85. return this.serverSession.id;
  86. }
  87. /**
  88. * Ends this session on the server
  89. *
  90. * @param {Object} [options] Optional settings. Currently reserved for future use
  91. * @param {Function} [callback] Optional callback for completion of this operation
  92. */
  93. endSession(options, callback) {
  94. if (typeof options === 'function') (callback = options), (options = {});
  95. options = options || {};
  96. if (this.hasEnded) {
  97. if (typeof callback === 'function') callback(null, null);
  98. return;
  99. }
  100. if (this.serverSession && this.inTransaction()) {
  101. this.abortTransaction(); // pass in callback?
  102. }
  103. // mark the session as ended, and emit a signal
  104. this.hasEnded = true;
  105. this.emit('ended', this);
  106. // release the server session back to the pool
  107. this.sessionPool.release(this.serverSession);
  108. // spec indicates that we should ignore all errors for `endSessions`
  109. if (typeof callback === 'function') callback(null, null);
  110. }
  111. /**
  112. * Advances the operationTime for a ClientSession.
  113. *
  114. * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to
  115. */
  116. advanceOperationTime(operationTime) {
  117. if (this.operationTime == null) {
  118. this.operationTime = operationTime;
  119. return;
  120. }
  121. if (operationTime.greaterThan(this.operationTime)) {
  122. this.operationTime = operationTime;
  123. }
  124. }
  125. /**
  126. * Used to determine if this session equals another
  127. * @param {ClientSession} session
  128. * @return {boolean} true if the sessions are equal
  129. */
  130. equals(session) {
  131. if (!(session instanceof ClientSession)) {
  132. return false;
  133. }
  134. return this.id.id.buffer.equals(session.id.id.buffer);
  135. }
  136. /**
  137. * Increment the transaction number on the internal ServerSession
  138. */
  139. incrementTransactionNumber() {
  140. this.serverSession.txnNumber++;
  141. }
  142. /**
  143. * @returns {boolean} whether this session is currently in a transaction or not
  144. */
  145. inTransaction() {
  146. return this.transaction.isActive;
  147. }
  148. /**
  149. * Starts a new transaction with the given options.
  150. *
  151. * @param {TransactionOptions} options Options for the transaction
  152. */
  153. startTransaction(options) {
  154. assertAlive(this);
  155. if (this.inTransaction()) {
  156. throw new MongoError('Transaction already in progress');
  157. }
  158. // increment txnNumber
  159. this.incrementTransactionNumber();
  160. // create transaction state
  161. this.transaction = new Transaction(
  162. Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions)
  163. );
  164. this.transaction.transition(TxnState.STARTING_TRANSACTION);
  165. }
  166. /**
  167. * Commits the currently active transaction in this session.
  168. *
  169. * @param {Function} [callback] optional callback for completion of this operation
  170. * @return {Promise} A promise is returned if no callback is provided
  171. */
  172. commitTransaction(callback) {
  173. if (typeof callback === 'function') {
  174. endTransaction(this, 'commitTransaction', callback);
  175. return;
  176. }
  177. return new Promise((resolve, reject) => {
  178. endTransaction(
  179. this,
  180. 'commitTransaction',
  181. (err, reply) => (err ? reject(err) : resolve(reply))
  182. );
  183. });
  184. }
  185. /**
  186. * Aborts the currently active transaction in this session.
  187. *
  188. * @param {Function} [callback] optional callback for completion of this operation
  189. * @return {Promise} A promise is returned if no callback is provided
  190. */
  191. abortTransaction(callback) {
  192. if (typeof callback === 'function') {
  193. endTransaction(this, 'abortTransaction', callback);
  194. return;
  195. }
  196. return new Promise((resolve, reject) => {
  197. endTransaction(
  198. this,
  199. 'abortTransaction',
  200. (err, reply) => (err ? reject(err) : resolve(reply))
  201. );
  202. });
  203. }
  204. /**
  205. * This is here to ensure that ClientSession is never serialized to BSON.
  206. * @ignore
  207. */
  208. toBSON() {
  209. throw new Error('ClientSession cannot be serialized to BSON.');
  210. }
  211. }
  212. function endTransaction(session, commandName, callback) {
  213. if (!assertAlive(session, callback)) {
  214. // checking result in case callback was called
  215. return;
  216. }
  217. // handle any initial problematic cases
  218. let txnState = session.transaction.state;
  219. if (txnState === TxnState.NO_TRANSACTION) {
  220. callback(new MongoError('No transaction started'));
  221. return;
  222. }
  223. if (commandName === 'commitTransaction') {
  224. if (
  225. txnState === TxnState.STARTING_TRANSACTION ||
  226. txnState === TxnState.TRANSACTION_COMMITTED_EMPTY
  227. ) {
  228. // the transaction was never started, we can safely exit here
  229. session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY);
  230. callback(null, null);
  231. return;
  232. }
  233. if (txnState === TxnState.TRANSACTION_ABORTED) {
  234. callback(new MongoError('Cannot call commitTransaction after calling abortTransaction'));
  235. return;
  236. }
  237. } else {
  238. if (txnState === TxnState.STARTING_TRANSACTION) {
  239. // the transaction was never started, we can safely exit here
  240. session.transaction.transition(TxnState.TRANSACTION_ABORTED);
  241. callback(null, null);
  242. return;
  243. }
  244. if (txnState === TxnState.TRANSACTION_ABORTED) {
  245. callback(new MongoError('Cannot call abortTransaction twice'));
  246. return;
  247. }
  248. if (
  249. txnState === TxnState.TRANSACTION_COMMITTED ||
  250. txnState === TxnState.TRANSACTION_COMMITTED_EMPTY
  251. ) {
  252. callback(new MongoError('Cannot call abortTransaction after calling commitTransaction'));
  253. return;
  254. }
  255. }
  256. // construct and send the command
  257. const command = { [commandName]: 1 };
  258. // apply a writeConcern if specified
  259. if (session.transaction.options.writeConcern) {
  260. Object.assign(command, { writeConcern: session.transaction.options.writeConcern });
  261. } else if (session.clientOptions && session.clientOptions.w) {
  262. Object.assign(command, { writeConcern: { w: session.clientOptions.w } });
  263. }
  264. function commandHandler(e, r) {
  265. if (commandName === 'commitTransaction') {
  266. session.transaction.transition(TxnState.TRANSACTION_COMMITTED);
  267. if (
  268. e &&
  269. (e instanceof MongoNetworkError ||
  270. e instanceof MongoWriteConcernError ||
  271. isRetryableError(e))
  272. ) {
  273. if (e.errorLabels) {
  274. const idx = e.errorLabels.indexOf('TransientTransactionError');
  275. if (idx !== -1) {
  276. e.errorLabels.splice(idx, 1);
  277. }
  278. } else {
  279. e.errorLabels = [];
  280. }
  281. e.errorLabels.push('UnknownTransactionCommitResult');
  282. }
  283. } else {
  284. session.transaction.transition(TxnState.TRANSACTION_ABORTED);
  285. }
  286. callback(e, r);
  287. }
  288. // The spec indicates that we should ignore all errors on `abortTransaction`
  289. function transactionError(err) {
  290. return commandName === 'commitTransaction' ? err : null;
  291. }
  292. // send the command
  293. session.topology.command('admin.$cmd', command, { session }, (err, reply) => {
  294. if (err && isRetryableError(err)) {
  295. return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) =>
  296. commandHandler(transactionError(_err), _reply)
  297. );
  298. }
  299. commandHandler(transactionError(err), reply);
  300. });
  301. }
  302. /**
  303. * Reflects the existence of a session on the server. Can be reused by the session pool.
  304. * WARNING: not meant to be instantiated directly. For internal use only.
  305. * @ignore
  306. */
  307. class ServerSession {
  308. constructor() {
  309. this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) };
  310. this.lastUse = Date.now();
  311. this.txnNumber = 0;
  312. }
  313. /**
  314. * Determines if the server session has timed out.
  315. * @ignore
  316. * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes"
  317. * @return {boolean} true if the session has timed out.
  318. */
  319. hasTimedOut(sessionTimeoutMinutes) {
  320. // Take the difference of the lastUse timestamp and now, which will result in a value in
  321. // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes`
  322. const idleTimeMinutes = Math.round(
  323. (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000
  324. );
  325. return idleTimeMinutes > sessionTimeoutMinutes - 1;
  326. }
  327. }
  328. /**
  329. * Maintains a pool of Server Sessions.
  330. * For internal use only
  331. * @ignore
  332. */
  333. class ServerSessionPool {
  334. constructor(topology) {
  335. if (topology == null) {
  336. throw new Error('ServerSessionPool requires a topology');
  337. }
  338. this.topology = topology;
  339. this.sessions = [];
  340. }
  341. /**
  342. * Ends all sessions in the session pool.
  343. * @ignore
  344. */
  345. endAllPooledSessions() {
  346. if (this.sessions.length) {
  347. this.topology.endSessions(this.sessions.map(session => session.id));
  348. this.sessions = [];
  349. }
  350. }
  351. /**
  352. * Acquire a Server Session from the pool.
  353. * Iterates through each session in the pool, removing any stale sessions
  354. * along the way. The first non-stale session found is removed from the
  355. * pool and returned. If no non-stale session is found, a new ServerSession
  356. * is created.
  357. * @ignore
  358. * @returns {ServerSession}
  359. */
  360. acquire() {
  361. const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes;
  362. while (this.sessions.length) {
  363. const session = this.sessions.shift();
  364. if (!session.hasTimedOut(sessionTimeoutMinutes)) {
  365. return session;
  366. }
  367. }
  368. return new ServerSession();
  369. }
  370. /**
  371. * Release a session to the session pool
  372. * Adds the session back to the session pool if the session has not timed out yet.
  373. * This method also removes any stale sessions from the pool.
  374. * @ignore
  375. * @param {ServerSession} session The session to release to the pool
  376. */
  377. release(session) {
  378. const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes;
  379. while (this.sessions.length) {
  380. const session = this.sessions[this.sessions.length - 1];
  381. if (session.hasTimedOut(sessionTimeoutMinutes)) {
  382. this.sessions.pop();
  383. } else {
  384. break;
  385. }
  386. }
  387. if (!session.hasTimedOut(sessionTimeoutMinutes)) {
  388. this.sessions.unshift(session);
  389. }
  390. }
  391. }
  392. module.exports = {
  393. ClientSession,
  394. ServerSession,
  395. ServerSessionPool,
  396. TxnState
  397. };