@@ -237,4 +237,49 @@ public function testConnectionException()
237237 ]);
238238 $ this ->assertEquals ($ changeStreamResult ->current (), $ expectedResult );
239239 }
240+
241+ public function testMaxAwaitTimeMS ()
242+ {
243+ $ this ->collection = new Collection ($ this ->manager , $ this ->getDatabaseName (), $ this ->getCollectionName ());
244+ /* On average, an acknowledged write takes about 20 ms to appear in a
245+ * change stream on the server so we'll use a higher maxAwaitTimeMS to
246+ * ensure we see the write. */
247+ $ maxAwaitTimeMS = 100 ;
248+ $ changeStreamResult = $ this ->collection ->watch ([], ['maxAwaitTimeMS ' => $ maxAwaitTimeMS ]);
249+
250+ /* The initial change stream is empty so we should expect a delay when
251+ * we call rewind, since it issues a getMore. Expect to wait at least
252+ * maxAwaitTimeMS, since no new documents should be inserted to wake up
253+ * the server's query thread. Also ensure we don't wait too long (server
254+ * default is one second). */
255+ $ startTime = microtime (true );
256+ $ changeStreamResult ->rewind ();
257+ $ duration = microtime (true ) - $ startTime ;
258+ $ this ->assertGreaterThanOrEqual ($ maxAwaitTimeMS * 0.001 , $ duration );
259+ $ this ->assertLessThan (0.5 , $ duration );
260+
261+ $ this ->assertFalse ($ changeStreamResult ->valid ());
262+
263+ /* Advancing again on a change stream will issue a getMore, so we should
264+ * expect a delay again. */
265+ $ startTime = microtime (true );
266+ $ changeStreamResult ->next ();
267+ $ duration = microtime (true ) - $ startTime ;
268+ $ this ->assertGreaterThanOrEqual ($ maxAwaitTimeMS * 0.001 , $ duration );
269+ $ this ->assertLessThan (0.5 , $ duration );
270+
271+ $ this ->assertFalse ($ changeStreamResult ->valid ());
272+
273+ /* After inserting a document, the change stream will not issue a
274+ * getMore so we should not expect a delay. */
275+ $ result = $ this ->collection ->insertOne (['_id ' => 1 ]);
276+ $ this ->assertInstanceOf ('MongoDB\InsertOneResult ' , $ result );
277+ $ this ->assertSame (1 , $ result ->getInsertedCount ());
278+
279+ $ startTime = microtime (true );
280+ $ changeStreamResult ->next ();
281+ $ duration = microtime (true ) - $ startTime ;
282+ $ this ->assertLessThan ($ maxAwaitTimeMS * 0.001 , $ duration );
283+ $ this ->assertTrue ($ changeStreamResult ->valid ());
284+ }
240285}
0 commit comments