WatchFunctionalTest.php 48.8 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Tests\Operation;

5
use MongoDB\ChangeStream;
6
use MongoDB\BSON\TimestampInterface;
7
use MongoDB\Driver\Cursor;
8 9
use MongoDB\Driver\Manager;
use MongoDB\Driver\ReadPreference;
10
use MongoDB\Driver\Server;
11
use MongoDB\Driver\WriteConcern;
12
use MongoDB\Driver\Exception\LogicException;
13
use MongoDB\Driver\Exception\ServerException;
14
use MongoDB\Exception\ResumeTokenException;
15
use MongoDB\Operation\CreateCollection;
16
use MongoDB\Operation\DatabaseCommand;
17 18
use MongoDB\Operation\InsertOne;
use MongoDB\Operation\Watch;
19 20
use MongoDB\Tests\CommandObserver;
use stdClass;
21
use ReflectionClass;
22

23
class WatchFunctionalTest extends FunctionalTestCase
24
{
25 26
    private static $wireVersionForStartAtOperationTime = 7;

27
    private $defaultOptions = ['maxAwaitTimeMS' => 500];
28

29 30 31
    public function setUp()
    {
        parent::setUp();
32

33
        $this->skipIfChangeStreamIsNotSupported();
34
        $this->createCollection();
Jeremy Mikola's avatar
Jeremy Mikola committed
35
    }
36

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    /**
     * Prose test: "ChangeStream must continuously track the last seen
     * resumeToken"
     */
    public function testGetResumeToken()
    {
        if ($this->isPostBatchResumeTokenSupported()) {
            $this->markTestSkipped('postBatchResumeToken is supported');
        }

        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $changeStream->rewind();
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->getResumeToken());

        $this->insertDocument(['x' => 1]);
        $this->insertDocument(['x' => 2]);

        $changeStream->next();
        $this->assertSameDocument($changeStream->current()->_id, $changeStream->getResumeToken());

        $changeStream->next();
        $this->assertSameDocument($changeStream->current()->_id, $changeStream->getResumeToken());

        $this->insertDocument(['x' => 3]);

        $changeStream->next();
        $this->assertSameDocument($changeStream->current()->_id, $changeStream->getResumeToken());
    }

    /**
     * Prose test: "ChangeStream must continuously track the last seen
     * resumeToken"
     */
    public function testGetResumeTokenWithPostBatchResumeToken()
    {
        if ( ! $this->isPostBatchResumeTokenSupported()) {
            $this->markTestSkipped('postBatchResumeToken is not supported');
        }

        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);

        $events = [];

        (new CommandObserver)->observe(
            function() use ($operation, &$changeStream) {
                $changeStream = $operation->execute($this->getPrimaryServer());
            },
            function (array $event) use (&$events) {
                $events[] = $event;
            }
        );

        $this->assertCount(1, $events);
        $this->assertSame('aggregate', $events[0]['started']->getCommandName());
        $postBatchResumeToken = $this->getPostBatchResumeTokenFromReply($events[0]['succeeded']->getReply());

        $changeStream->rewind();
        $this->assertFalse($changeStream->valid());
        $this->assertSameDocument($postBatchResumeToken, $changeStream->getResumeToken());

        $this->insertDocument(['x' => 1]);
        $this->insertDocument(['x' => 2]);

        $events = [];

        (new CommandObserver)->observe(
            function() use ($changeStream) {
                $changeStream->next();
            },
            function (array $event) use (&$events) {
                $events[] = $event;
            }
        );

        $this->assertCount(1, $events);
        $this->assertSame('getMore', $events[0]['started']->getCommandName());
        $postBatchResumeToken = $this->getPostBatchResumeTokenFromReply($events[0]['succeeded']->getReply());

        $changeStream->next();
        $this->assertSameDocument($changeStream->current()->_id, $changeStream->getResumeToken());

        $changeStream->next();
        $this->assertSameDocument($postBatchResumeToken, $changeStream->getResumeToken());
    }

    /**
     * Prose test: "ChangeStream will resume after a killCursors command is
     * issued for its child cursor."
     */
129
    public function testNextResumesAfterCursorNotFound()
130
    {
131
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
132
        $changeStream = $operation->execute($this->getPrimaryServer());
133

134
        $changeStream->rewind();
135
        $this->assertFalse($changeStream->valid());
136

137
        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
138

139
        $changeStream->next();
140
        $this->assertTrue($changeStream->valid());
141 142 143 144

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
145
            'fullDocument' => ['_id' => 1, 'x' => 'foo'],
146
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
147
            'documentKey' => ['_id' => 1],
148 149
        ];

150
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
151

152
        $this->killChangeStreamCursor($changeStream);
153

154
        $this->insertDocument(['_id' => 2, 'x' => 'bar']);
155

156
        $changeStream->next();
157
        $this->assertTrue($changeStream->valid());
158 159 160 161

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
162
            'fullDocument' => ['_id' => 2, 'x' => 'bar'],
163
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
164
            'documentKey' => ['_id' => 2]
165 166
        ];

167
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
Jeremy Mikola's avatar
Jeremy Mikola committed
168
    }
169

170 171 172 173 174
    public function testNextResumesAfterConnectionException()
    {
        /* In order to trigger a dropped connection, we'll use a new client with
         * a socket timeout that is less than the change stream's maxAwaitTimeMS
         * option. */
175
        $manager = new Manager(static::getUri(), ['socketTimeoutMS' => 50]);
176 177
        $primaryServer = $manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));

178
        $operation = new Watch($manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
179
        $changeStream = $operation->execute($primaryServer);
180
        $changeStream->rewind();
181 182 183

        $commands = [];

184 185 186 187 188 189 190 191
        (new CommandObserver)->observe(
            function() use ($changeStream) {
                $changeStream->next();
            },
            function(array $event) use (&$commands) {
                $commands[] = $event['started']->getCommandName();
            }
        );
192 193 194 195 196 197

        $expectedCommands = [
            /* The initial aggregate command for change streams returns a cursor
             * envelope with an empty initial batch, since there are no changes
             * to report at the moment the change stream is created. Therefore,
             * we expect a getMore to be issued when we first advance the change
198
             * stream with next(). */
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
            'getMore',
            /* Since socketTimeoutMS is less than maxAwaitTimeMS, the previous
             * getMore command encounters a client socket timeout and leaves the
             * cursor open on the server. ChangeStream should catch this error
             * and resume by issuing a new aggregate command. */
            'aggregate',
            /* When ChangeStream resumes, it overwrites its original cursor with
             * the new cursor resulting from the last aggregate command. This
             * removes the last reference to the old cursor, which causes the
             * driver to kill it (via mongoc_cursor_destroy()). */
            'killCursors',
        ];

        $this->assertSame($expectedCommands, $commands);
    }

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    public function testResumeBeforeReceivingAnyResultsIncludesPostBatchResumeToken()
    {
        if ( ! $this->isPostBatchResumeTokenSupported()) {
            $this->markTestSkipped('postBatchResumeToken is not supported');
        }

        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);

        $events = [];

        (new CommandObserver)->observe(
            function() use ($operation, &$changeStream) {
                $changeStream = $operation->execute($this->getPrimaryServer());
            },
            function (array $event) use (&$events) {
                $events[] = $event;
            }
        );

        $this->assertCount(1, $events);
        $this->assertSame('aggregate', $events[0]['started']->getCommandName());
236
        $postBatchResumeToken = $this->getPostBatchResumeTokenFromReply($events[0]['succeeded']->getReply());
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

        $this->assertFalse($changeStream->valid());
        $this->killChangeStreamCursor($changeStream);

        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });

        $events = [];

        (new CommandObserver)->observe(
            function() use ($changeStream) {
                $changeStream->next();
            },
            function (array $event) use (&$events) {
                $events[] = $event;
            }
        );

        $this->assertCount(3, $events);

        $this->assertSame('getMore', $events[0]['started']->getCommandName());
        $this->arrayHasKey('failed', $events[0]);

        $this->assertSame('aggregate', $events[1]['started']->getCommandName());
        $this->assertResumeAfter($postBatchResumeToken, $events[1]['started']->getCommand());
        $this->arrayHasKey('succeeded', $events[1]);

        // Original cursor is freed immediately after the change stream resumes
        $this->assertSame('killCursors', $events[2]['started']->getCommandName());
        $this->arrayHasKey('succeeded', $events[2]);

        $this->assertFalse($changeStream->valid());
    }

    private function assertResumeAfter($expectedResumeToken, stdClass $command)
    {
        $this->assertObjectHasAttribute('pipeline', $command);
        $this->assertInternalType('array', $command->pipeline);
        $this->assertArrayHasKey(0, $command->pipeline);
        $this->assertObjectHasAttribute('$changeStream', $command->pipeline[0]);
        $this->assertObjectHasAttribute('resumeAfter', $command->pipeline[0]->{'$changeStream'});
        $this->assertEquals($expectedResumeToken, $command->pipeline[0]->{'$changeStream'}->resumeAfter);
    }

280 281 282 283 284
    /**
     * Prose test: "$changeStream stage for ChangeStream against a server >=4.0
     * and <4.0.7 that has not received any results yet MUST include a
     * startAtOperationTime option when resuming a changestream."
     */
285 286
    public function testResumeBeforeReceivingAnyResultsIncludesStartAtOperationTime()
    {
287 288 289 290 291 292 293
        if ( ! $this->isStartAtOperationTimeSupported()) {
            $this->markTestSkipped('startAtOperationTime is not supported');
        }

        if ($this->isPostBatchResumeTokenSupported()) {
            $this->markTestSkipped('postBatchResumeToken takes precedence over startAtOperationTime');
        }
294

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);

        $events = [];

        (new CommandObserver)->observe(
            function() use ($operation, &$changeStream) {
                $changeStream = $operation->execute($this->getPrimaryServer());
            },
            function (array $event) use (&$events) {
                $events[] = $event;
            }
        );

        $this->assertCount(1, $events);
        $this->assertSame('aggregate', $events[0]['started']->getCommandName());
310 311 312
        $reply = $events[0]['succeeded']->getReply();
        $this->assertObjectHasAttribute('operationTime', $reply);
        $operationTime = $reply->operationTime;
313 314
        $this->assertInstanceOf(TimestampInterface::class, $operationTime);

315
        $this->assertFalse($changeStream->valid());
316 317
        $this->killChangeStreamCursor($changeStream);

318
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
319 320 321 322 323 324 325 326 327 328 329 330

        $events = [];

        (new CommandObserver)->observe(
            function() use ($changeStream) {
                $changeStream->next();
            },
            function (array $event) use (&$events) {
                $events[] = $event;
            }
        );

331
        $this->assertCount(3, $events);
332 333 334 335 336 337 338 339 340 341 342 343

        $this->assertSame('getMore', $events[0]['started']->getCommandName());
        $this->arrayHasKey('failed', $events[0]);

        $this->assertSame('aggregate', $events[1]['started']->getCommandName());
        $this->assertStartAtOperationTime($operationTime, $events[1]['started']->getCommand());
        $this->arrayHasKey('succeeded', $events[1]);

        // Original cursor is freed immediately after the change stream resumes
        $this->assertSame('killCursors', $events[2]['started']->getCommandName());
        $this->arrayHasKey('succeeded', $events[2]);

344
        $this->assertFalse($changeStream->valid());
345 346 347 348 349 350 351 352 353 354 355 356
    }

    private function assertStartAtOperationTime(TimestampInterface $expectedOperationTime, stdClass $command)
    {
        $this->assertObjectHasAttribute('pipeline', $command);
        $this->assertInternalType('array', $command->pipeline);
        $this->assertArrayHasKey(0, $command->pipeline);
        $this->assertObjectHasAttribute('$changeStream', $command->pipeline[0]);
        $this->assertObjectHasAttribute('startAtOperationTime', $command->pipeline[0]->{'$changeStream'});
        $this->assertEquals($expectedOperationTime, $command->pipeline[0]->{'$changeStream'}->startAtOperationTime);
    }

357 358 359 360 361 362 363 364
    public function testRewindMultipleTimesWithResults()
    {
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $this->insertDocument(['x' => 1]);
        $this->insertDocument(['x' => 2]);

365 366 367 368 369 370 371 372 373 374 375 376
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());
        $this->assertNull($changeStream->current());

        // Subsequent rewind does not change iterator state
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());
        $this->assertNull($changeStream->current());

        $changeStream->next();
377 378 379 380
        $this->assertTrue($changeStream->valid());
        $this->assertSame(0, $changeStream->key());
        $this->assertNotNull($changeStream->current());

381 382 383
        /* Rewinding when the iterator is still at its first element is a NOP.
         * Note: PHPLIB-448 may see rewind() throw after any call to next() */
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
        $this->assertTrue($changeStream->valid());
        $this->assertSame(0, $changeStream->key());
        $this->assertNotNull($changeStream->current());

        $changeStream->next();
        $this->assertTrue($changeStream->valid());
        $this->assertSame(1, $changeStream->key());
        $this->assertNotNull($changeStream->current());

        // Rewinding after advancing the iterator is an error
        $this->expectException(LogicException::class);
        $changeStream->rewind();
    }

    public function testRewindMultipleTimesWithNoResults()
    {
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

403
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
404 405 406 407 408
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());
        $this->assertNull($changeStream->current());

        // Subsequent rewind does not change iterator state
409
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
410 411 412 413 414 415 416 417 418
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());
        $this->assertNull($changeStream->current());

        $changeStream->next();
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());
        $this->assertNull($changeStream->current());

419 420 421 422 423 424
        /* Rewinding when the iterator hasn't advanced to an element is a NOP.
         * Note: PHPLIB-448 may see rewind() throw after any call to next() */
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());
        $this->assertNull($changeStream->current());
425 426
    }

427 428
    public function testNoChangeAfterResumeBeforeInsert()
    {
429
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
430
        $changeStream = $operation->execute($this->getPrimaryServer());
431

432 433
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
        $this->assertFalse($changeStream->valid());
434

435
        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
436

437
        $changeStream->next();
438
        $this->assertTrue($changeStream->valid());
439 440 441 442

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
443
            'fullDocument' => ['_id' => 1, 'x' => 'foo'],
444
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
445
            'documentKey' => ['_id' => 1],
446 447
        ];

448
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
449

450
        $this->killChangeStreamCursor($changeStream);
451

452
        $changeStream->next();
453
        $this->assertFalse($changeStream->valid());
454

455
        $this->insertDocument(['_id' => 2, 'x' => 'bar']);
456

457
        $changeStream->next();
458
        $this->assertTrue($changeStream->valid());
459 460 461 462

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
463
            'fullDocument' => ['_id' => 2, 'x' => 'bar'],
464
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
465
            'documentKey' => ['_id' => 2],
466 467
        ];

468
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
469 470
    }

471
    public function testResumeMultipleTimesInSuccession()
472 473 474 475
    {
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

476
        /* Killing the cursor when there are no results will test that neither
477 478
         * the initial rewind() nor a resume attempt via next() increment the
         * key. */
479 480
        $this->killChangeStreamCursor($changeStream);

481
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
482 483
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());
484 485
        $this->assertNull($changeStream->current());

486 487 488 489 490 491 492 493 494 495 496 497
        $changeStream->next();
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());
        $this->assertNull($changeStream->current());

        // A consecutive resume attempt should still not increment the key
        $this->killChangeStreamCursor($changeStream);

        $changeStream->next();
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());
        $this->assertNull($changeStream->current());
498

499 500 501
        /* Insert a document and advance the change stream to ensure we capture
         * a resume token. This is necessary when startAtOperationTime is not
         * supported (i.e. 3.6 server version). */
502
        $this->insertDocument(['_id' => 1]);
503

504
        $changeStream->next();
505
        $this->assertTrue($changeStream->valid());
506
        $this->assertSame(0, $changeStream->key());
507 508 509 510

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
511
            'fullDocument' => ['_id' => 1],
512
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
513
            'documentKey' => ['_id' => 1],
514 515 516 517
        ];

        $this->assertMatchesDocument($expectedResult, $changeStream->current());

518 519 520
        /* Insert another document and kill the cursor. ChangeStream::next()
         * should resume and pick up the last insert. */
        $this->insertDocument(['_id' => 2]);
521 522
        $this->killChangeStreamCursor($changeStream);

523
        $changeStream->next();
524
        $this->assertTrue($changeStream->valid());
525
        $this->assertSame(1, $changeStream->key());
526 527 528 529

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
530
            'fullDocument' => ['_id' => 2],
531
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
532
            'documentKey' => ['_id' => 2],
533 534 535 536
        ];

        $this->assertMatchesDocument($expectedResult, $changeStream->current());

537 538 539 540 541 542 543
        /* Insert another document and kill the cursor. It is technically
         * permissable to call ChangeStream::rewind() since the previous call to
         * next() will have left the cursor positioned at its first and only
         * result. Assert that rewind() does not execute a getMore nor does it
         * modify the iterator's state.
         *
         * Note: PHPLIB-448 may require rewind() to throw an exception here. */
544
        $this->insertDocument(['_id' => 3]);
545
        $this->killChangeStreamCursor($changeStream);
546

547 548 549 550 551 552
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
        $this->assertTrue($changeStream->valid());
        $this->assertSame(1, $changeStream->key());
        $this->assertMatchesDocument($expectedResult, $changeStream->current());

        // ChangeStream::next() should resume and pick up the last insert
553 554
        $changeStream->next();
        $this->assertTrue($changeStream->valid());
555
        $this->assertSame(2, $changeStream->key());
556 557 558 559

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
560
            'fullDocument' => ['_id' => 3],
561
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
562
            'documentKey' => ['_id' => 3],
563 564 565 566
        ];

        $this->assertMatchesDocument($expectedResult, $changeStream->current());

567
        // Test one final, consecutive resume via ChangeStream::next()
568
        $this->insertDocument(['_id' => 4]);
569
        $this->killChangeStreamCursor($changeStream);
570 571 572

        $changeStream->next();
        $this->assertTrue($changeStream->valid());
573
        $this->assertSame(3, $changeStream->key());
574 575 576 577

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
578
            'fullDocument' => ['_id' => 4],
579
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
580
            'documentKey' => ['_id' => 4],
581 582 583 584 585
        ];

        $this->assertMatchesDocument($expectedResult, $changeStream->current());
    }

586 587
    public function testKey()
    {
588
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
589
        $changeStream = $operation->execute($this->getPrimaryServer());
590

591
        $this->assertFalse($changeStream->valid());
592
        $this->assertNull($changeStream->key());
593

594 595 596 597
        $this->assertNoCommandExecuted(function() use ($changeStream) { $changeStream->rewind(); });
        $this->assertFalse($changeStream->valid());
        $this->assertNull($changeStream->key());

598
        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
599

600
        $changeStream->next();
601
        $this->assertTrue($changeStream->valid());
602
        $this->assertSame(0, $changeStream->key());
603

604
        $changeStream->next();
605
        $this->assertFalse($changeStream->valid());
606
        $this->assertNull($changeStream->key());
607

608
        $changeStream->next();
609
        $this->assertFalse($changeStream->valid());
610
        $this->assertNull($changeStream->key());
611

612
        $this->killChangeStreamCursor($changeStream);
613

614
        $changeStream->next();
615
        $this->assertFalse($changeStream->valid());
616
        $this->assertNull($changeStream->key());
617

618
        $this->insertDocument(['_id' => 2, 'x' => 'bar']);
619

620
        $changeStream->next();
621
        $this->assertTrue($changeStream->valid());
622
        $this->assertSame(1, $changeStream->key());
623 624 625 626 627 628
    }

    public function testNonEmptyPipeline()
    {
        $pipeline = [['$project' => ['foo' => [0]]]];

629
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
630 631 632
        $changeStream = $operation->execute($this->getPrimaryServer());

        $this->insertDocument(['_id' => 1]);
633

634
        $changeStream->rewind();
635 636 637
        $this->assertFalse($changeStream->valid());

        $changeStream->next();
638
        $this->assertTrue($changeStream->valid());
639 640 641 642 643 644 645

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'foo' => [0],
        ];

        $this->assertSameDocument($expectedResult, $changeStream->current());
646 647
    }

648 649 650 651
    /**
     * Prose test: "Ensure that a cursor returned from an aggregate command with
     * a cursor id and an initial empty batch is not closed on the driver side."
     */
652
    public function testInitialCursorIsNotClosed()
653
    {
654
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), []);
655
        $changeStream = $operation->execute($this->getPrimaryServer());
656

657 658 659 660 661 662 663 664
        /* The spec requests that we assert that the cursor returned from the
         * aggregate command is not closed on the driver side. We will verify
         * this by checking that the cursor ID is non-zero and that libmongoc
         * reports the cursor as alive. While the cursor ID is easily accessed
         * through ChangeStream, we'll need to use reflection to access the
         * internal Cursor and call isDead(). */
        $this->assertNotEquals('0', (string) $changeStream->getCursorId());

665
        $rc = new ReflectionClass(ChangeStream::class);
666
        $rp = $rc->getProperty('iterator');
667 668 669 670 671 672 673 674
        $rp->setAccessible(true);

        $iterator = $rp->getValue($changeStream);

        $this->assertInstanceOf('IteratorIterator', $iterator);

        $cursor = $iterator->getInnerIterator();

675
        $this->assertInstanceOf(Cursor::class, $cursor);
676
        $this->assertFalse($cursor->isDead());
677 678
    }

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
    /**
     * Prose test: "ChangeStream will not attempt to resume after encountering
     * error code 11601 (Interrupted), 136 (CappedPositionLost), or 237
     * (CursorKilled) while executing a getMore command."
     *
     * @dataProvider provideNonResumableErrorCodes
     */
    public function testNonResumableErrorCodes($errorCode)
    {
        if (version_compare($this->getServerVersion(), '4.0.0', '<')) {
            $this->markTestSkipped('failCommand is not supported');
        }

        $this->configureFailPoint([
            'configureFailPoint' => 'failCommand',
            'mode' => ['times' => 1],
            'data' => ['failCommands' => ['getMore'], 'errorCode' => $errorCode],
        ]);

        $this->insertDocument(['x' => 1]);

        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), []);
        $changeStream = $operation->execute($this->getPrimaryServer());
        $changeStream->rewind();

        $this->expectException(ServerException::class);
        $this->expectExceptionCode($errorCode);
        $changeStream->next();
    }

    public function provideNonResumableErrorCodes()
    {
        return [
            [136], // CappedPositionLost
            [237], // CursorKilled
            [11601], // Interrupted
        ];
    }

718 719 720 721 722 723
    /**
     * Prose test: "ChangeStream will throw an exception if the server response
     * is missing the resume token (if wire version is < 8, this is a driver-
     * side error; for 8+, this is a server-side error)"
     */
    public function testResumeTokenNotFoundClientSideError()
724
    {
725 726 727 728
        if (version_compare($this->getServerVersion(), '4.1.8', '>=')) {
            $this->markTestSkipped('Server rejects change streams that modify resume token (SERVER-37786)');
        }

729 730
        $pipeline =  [['$project' => ['_id' => 0 ]]];

731
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
732 733
        $changeStream = $operation->execute($this->getPrimaryServer());

734 735 736 737
        $changeStream->rewind();

        /* Insert two documents to ensure the client does not ignore the first
         * document's resume token in favor of a postBatchResumeToken */
738
        $this->insertDocument(['x' => 1]);
739
        $this->insertDocument(['x' => 2]);
740

741 742
        $this->expectException(ResumeTokenException::class);
        $this->expectExceptionMessage('Resume token not found in change document');
743
        $changeStream->next();
744 745
    }

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    /**
     * Prose test: "ChangeStream will throw an exception if the server response
     * is missing the resume token (if wire version is < 8, this is a driver-
     * side error; for 8+, this is a server-side error)"
     */
    public function testResumeTokenNotFoundServerSideError()
    {
        if (version_compare($this->getServerVersion(), '4.1.8', '<')) {
            $this->markTestSkipped('Server does not reject change streams that modify resume token');
        }

        $pipeline =  [['$project' => ['_id' => 0 ]]];

        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $changeStream->rewind();
        $this->insertDocument(['x' => 1]);

        $this->expectException(ServerException::class);
        $changeStream->next();
    }

    /**
     * Prose test: "ChangeStream will throw an exception if the server response
     * is missing the resume token (if wire version is < 8, this is a driver-
     * side error; for 8+, this is a server-side error)"
     */
    public function testResumeTokenInvalidTypeClientSideError()
775
    {
776 777 778 779
        if (version_compare($this->getServerVersion(), '4.1.8', '>=')) {
            $this->markTestSkipped('Server rejects change streams that modify resume token (SERVER-37786)');
        }

780 781
        $pipeline =  [['$project' => ['_id' => ['$literal' => 'foo']]]];

782
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
783 784
        $changeStream = $operation->execute($this->getPrimaryServer());

785 786 787 788
        $changeStream->rewind();

        /* Insert two documents to ensure the client does not ignore the first
         * document's resume token in favor of a postBatchResumeToken */
789
        $this->insertDocument(['x' => 1]);
790
        $this->insertDocument(['x' => 2]);
791

792 793
        $this->expectException(ResumeTokenException::class);
        $this->expectExceptionMessage('Expected resume token to have type "array or object" but found "string"');
794 795 796
        $changeStream->next();
    }

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    /**
     * Prose test: "ChangeStream will throw an exception if the server response
     * is missing the resume token (if wire version is < 8, this is a driver-
     * side error; for 8+, this is a server-side error)"
     */
    public function testResumeTokenInvalidTypeServerSideError()
    {
        if (version_compare($this->getServerVersion(), '4.1.8', '<')) {
            $this->markTestSkipped('Server does not reject change streams that modify resume token');
        }

        $pipeline =  [['$project' => ['_id' => ['$literal' => 'foo']]]];

        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $changeStream->rewind();
        $this->insertDocument(['x' => 1]);

        $this->expectException(ServerException::class);
        $changeStream->next();
    }

820 821
    public function testMaxAwaitTimeMS()
    {
822 823 824
        /* On average, an acknowledged write takes about 20 ms to appear in a
         * change stream on the server so we'll use a higher maxAwaitTimeMS to
         * ensure we see the write. */
825
        $maxAwaitTimeMS = 500;
826

827 828 829 830 831
        /* Calculate an approximate pivot to use for time assertions. We will
         * assert that the duration of blocking responses is greater than this
         * value, and vice versa. */
        $pivot = ($maxAwaitTimeMS * 0.001) * 0.9;

832 833 834 835 836
        /* Calculate an approximate upper bound to use for time assertions. We
         * will assert that the duration of blocking responses is less than this
         * value. */
        $upperBound = ($maxAwaitTimeMS * 0.001) * 1.5;

837 838
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], ['maxAwaitTimeMS' => $maxAwaitTimeMS]);
        $changeStream = $operation->execute($this->getPrimaryServer());
839

840
        // Rewinding does not issue a getMore, so we should not expect a delay.
841
        $startTime = microtime(true);
842
        $changeStream->rewind();
843
        $duration = microtime(true) - $startTime;
844
        $this->assertLessThan($pivot, $duration);
845

846
        $this->assertFalse($changeStream->valid());
847 848

        /* Advancing again on a change stream will issue a getMore, so we should
849 850 851
         * expect a delay. Expect to wait at least maxAwaitTimeMS, since no new
         * documents will be inserted to wake up the server's query thread. Also
         * ensure we don't wait too long (server default is one second). */
852
        $startTime = microtime(true);
853
        $changeStream->next();
854
        $duration = microtime(true) - $startTime;
855
        $this->assertGreaterThan($pivot, $duration);
856
        $this->assertLessThan($upperBound, $duration);
857

858
        $this->assertFalse($changeStream->valid());
859

860
        $this->insertDocument(['_id' => 1]);
861

862 863
        /* Advancing the change stream again will issue a getMore, but the
         * server should not block since a document has been inserted. */
864
        $startTime = microtime(true);
865
        $changeStream->next();
866
        $duration = microtime(true) - $startTime;
867
        $this->assertLessThan($pivot, $duration);
868
        $this->assertTrue($changeStream->valid());
869
    }
870

871
    public function testRewindExtractsResumeTokenAndNextResumes()
872
    {
873
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
874 875
        $changeStream = $operation->execute($this->getPrimaryServer());

876 877 878
        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
        $this->insertDocument(['_id' => 2, 'x' => 'bar']);
        $this->insertDocument(['_id' => 3, 'x' => 'baz']);
879

880 881 882 883
        /* Obtain a resume token for the first insert. This will allow us to
         * start a change stream from that point and ensure aggregate returns
         * the second insert in its first batch, which in turn will serve as a
         * resume token for rewind() to extract. */
884 885 886
        $changeStream->rewind();
        $this->assertFalse($changeStream->valid());

887 888
        $changeStream->next();
        $this->assertTrue($changeStream->valid());
889

890 891 892
        $options = ['resumeAfter' => $changeStream->current()->_id] + $this->defaultOptions;
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $options);
        $changeStream = $operation->execute($this->getPrimaryServer());
893 894 895

        $changeStream->rewind();
        $this->assertTrue($changeStream->valid());
896
        $this->assertSame(0, $changeStream->key());
897 898 899
        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
900
            'fullDocument' => ['_id' => 2, 'x' => 'bar'],
901
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
902
            'documentKey' => ['_id' => 2],
903
        ];
904
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
905 906 907 908 909

        $this->killChangeStreamCursor($changeStream);

        $changeStream->next();
        $this->assertTrue($changeStream->valid());
910
        $this->assertSame(1, $changeStream->key());
911 912 913 914

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
915
            'fullDocument' => ['_id' => 3, 'x' => 'baz'],
916
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
917
            'documentKey' => ['_id' => 3],
918
        ];
919
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
920 921
    }

922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    public function testResumeAfterOption()
    {
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $changeStream->rewind();
        $this->assertFalse($changeStream->valid());

        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
        $this->insertDocument(['_id' => 2, 'x' => 'bar']);

        $changeStream->next();
        $this->assertTrue($changeStream->valid());

        $resumeToken = $changeStream->current()->_id;

        $options = $this->defaultOptions + ['resumeAfter' => $resumeToken];
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $options);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $changeStream->rewind();
        $this->assertTrue($changeStream->valid());

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
            'fullDocument' => ['_id' => 2, 'x' => 'bar'],
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
            'documentKey' => ['_id' => 2],
        ];

        $this->assertMatchesDocument($expectedResult, $changeStream->current());
    }

    public function testStartAfterOption()
    {
        if (version_compare($this->getServerVersion(), '4.1.1', '<')) {
            $this->markTestSkipped('startAfter is not supported');
        }

        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $changeStream->rewind();
        $this->assertFalse($changeStream->valid());

        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
        $this->insertDocument(['_id' => 2, 'x' => 'bar']);

        $changeStream->next();
        $this->assertTrue($changeStream->valid());

        $resumeToken = $changeStream->current()->_id;

        $options = $this->defaultOptions + ['startAfter' => $resumeToken];
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $options);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $changeStream->rewind();
        $this->assertTrue($changeStream->valid());

        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
            'fullDocument' => ['_id' => 2, 'x' => 'bar'],
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
            'documentKey' => ['_id' => 2],
        ];

        $this->assertMatchesDocument($expectedResult, $changeStream->current());
    }

994 995 996 997 998
    /**
     * @dataProvider provideTypeMapOptionsAndExpectedChangeDocument
     */
    public function testTypeMapOption(array $typeMap, $expectedChangeDocument)
    {
999
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], ['typeMap' => $typeMap] + $this->defaultOptions);
1000 1001 1002
        $changeStream = $operation->execute($this->getPrimaryServer());

        $changeStream->rewind();
1003
        $this->assertFalse($changeStream->valid());
1004 1005 1006 1007 1008 1009

        $this->insertDocument(['_id' => 1, 'x' => 'foo']);

        $changeStream->next();
        $this->assertTrue($changeStream->valid());

1010
        $this->assertMatchesDocument($expectedChangeDocument, $changeStream->current());
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    }

    public function provideTypeMapOptionsAndExpectedChangeDocument()
    {
        /* Note: the "_id" and "ns" fields are purposefully omitted because the
         * resume token's value cannot be anticipated and the collection name,
         * which is generated from the test name, is not available in the data
         * provider, respectively. */
        return [
            [
                ['root' => 'array', 'document' => 'array'],
                [
                    'operationType' => 'insert',
                    'fullDocument' => ['_id' => 1, 'x' => 'foo'],
                    'documentKey' => ['_id' => 1],
                ],
            ],
            [
                ['root' => 'object', 'document' => 'array'],
                (object) [
                    'operationType' => 'insert',
                    'fullDocument' => ['_id' => 1, 'x' => 'foo'],
                    'documentKey' => ['_id' => 1],
                ],
            ],
            [
                ['root' => 'array', 'document' => 'stdClass'],
                [
                    'operationType' => 'insert',
                    'fullDocument' => (object) ['_id' => 1, 'x' => 'foo'],
                    'documentKey' => (object) ['_id' => 1],
                ],
            ],
        ];
    }

1047 1048 1049 1050 1051 1052 1053 1054
    public function testNextAdvancesKey()
    {
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $this->insertDocument(['x' => 1]);
        $this->insertDocument(['x' => 2]);

1055 1056
        /* Note: we intentionally do not start iteration with rewind() to ensure
         * that next() behaves identically when called without rewind(). */
1057 1058 1059 1060 1061 1062 1063 1064 1065
        $changeStream->next();

        $this->assertSame(0, $changeStream->key());

        $changeStream->next();

        $this->assertSame(1, $changeStream->key());
    }

1066
    public function testResumeTokenNotFoundDoesNotAdvanceKey()
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    {
        $pipeline =  [['$project' => ['_id' => 0 ]]];

        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $this->insertDocument(['x' => 1]);
        $this->insertDocument(['x' => 2]);
        $this->insertDocument(['x' => 3]);

1077 1078
        $changeStream->rewind();
        $this->assertFalse($changeStream->valid());
1079
        $this->assertNull($changeStream->key());
1080 1081 1082

        try {
            $changeStream->next();
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
            $this->fail('Exception for missing resume token was not thrown');
        } catch (ResumeTokenException $e) {
            /* If a client-side error is thrown (server < 4.1.8), the tailable
             * cursor's position is still valid. This may change once PHPLIB-456
             * is implemented. */
            $expectedValid = true;
            $expectedKey = 0;
        } catch (ServerException $e) {
            /* If a server-side error is thrown (server >= 4.1.8), the tailable
             * cursor's position is not valid. */
            $expectedValid = false;
            $expectedKey = null;
        }
1096

1097 1098
        $this->assertSame($expectedValid, $changeStream->valid());
        $this->assertSame($expectedKey, $changeStream->key());
1099 1100 1101

        try {
            $changeStream->next();
1102 1103 1104 1105 1106 1107 1108 1109
            $this->fail('Exception for missing resume token was not thrown');
        } catch (ResumeTokenException $e) {
            $expectedValid = true;
            $expectedKey = 0;
        } catch (ServerException $e) {
            $expectedValid = false;
            $expectedKey = null;
        }
1110

1111 1112
        $this->assertSame($expectedValid, $changeStream->valid());
        $this->assertSame($expectedKey, $changeStream->key());
1113 1114
    }

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
    public function testSessionPersistsAfterResume()
    {
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);

        $changeStream = null;
        $originalSession = null;
        $sessionAfterResume = [];
        $commands = [];

        /* We want to ensure that the lsid of the initial aggregate matches the
         * lsid of any aggregates after the change stream resumes. After
         * PHPC-1152 is complete, we will ensure that the lsid of the initial
         * aggregate matches the lsid of any subsequent aggregates and getMores.
         */
        (new CommandObserver)->observe(
            function() use ($operation, &$changeStream) {
                $changeStream = $operation->execute($this->getPrimaryServer());
            },
1133 1134 1135 1136
            function(array $event) use (&$originalSession) {
                $command = $event['started']->getCommand();
                if (isset($command->aggregate)) {
                    $originalSession = bin2hex((string) $command->lsid->id);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
                }
            }
        );

        $changeStream->rewind();
        $this->killChangeStreamCursor($changeStream);

        (new CommandObserver)->observe(
            function() use (&$changeStream) {
                $changeStream->next();
            },
1148 1149 1150
            function (array $event) use (&$sessionAfterResume, &$commands) {
                $commands[] = $event['started']->getCommandName();
                $sessionAfterResume[] = bin2hex((string) $event['started']->getCommand()->lsid->id);
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
            }
        );

        $expectedCommands = [
            /* We expect a getMore to be issued because we are calling next(). */
            'getMore',
            /* Since we have killed the cursor, ChangeStream will resume by
             * issuing a new aggregate commmand. */
            'aggregate',
            /* When ChangeStream resumes, it overwrites its original cursor with
             * the new cursor resulting from the last aggregate command. This
             * removes the last reference to the old cursor, which causes the
             * driver to kill it (via mongoc_cursor_destroy()). */
            'killCursors',
        ];

        $this->assertSame($expectedCommands, $commands);

        foreach ($sessionAfterResume as $session) {
            $this->assertEquals($session, $originalSession);
        }
    }

    public function testSessionFreed()
    {
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
        $changeStream = $operation->execute($this->getPrimaryServer());

        $rc = new ReflectionClass($changeStream);
        $rp = $rc->getProperty('resumeCallable');
        $rp->setAccessible(true);

1183
        $this->assertInternalType('callable', $rp->getValue($changeStream));
1184 1185

        // Invalidate the cursor to verify that resumeCallable is unset when the cursor is exhausted.
1186
        $this->dropCollection();
1187 1188 1189 1190 1191 1192

        $changeStream->next();

        $this->assertNull($rp->getValue($changeStream));
    }

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    private function assertNoCommandExecuted(callable $callable)
    {
        $commands = [];

        (new CommandObserver)->observe(
            $callable,
            function(array $event) use (&$commands) {
                $this->fail(sprintf('"%s" command was executed', $event['started']->getCommandName()));
            }
        );

        $this->assertEmpty($commands);
    }

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    private function getPostBatchResumeTokenFromReply(stdClass $reply)
    {
        $this->assertObjectHasAttribute('cursor', $reply);
        $this->assertInternalType('object', $reply->cursor);
        $this->assertObjectHasAttribute('postBatchResumeToken', $reply->cursor);
        $this->assertInternalType('object', $reply->cursor->postBatchResumeToken);

        return $reply->cursor->postBatchResumeToken;
    }

1217 1218
    private function insertDocument($document)
    {
1219 1220 1221 1222 1223 1224
        $insertOne = new InsertOne(
            $this->getDatabaseName(),
            $this->getCollectionName(),
            $document,
            ['writeConcern' => new WriteConcern(WriteConcern::MAJORITY)]
        );
1225 1226 1227
        $writeResult = $insertOne->execute($this->getPrimaryServer());
        $this->assertEquals(1, $writeResult->getInsertedCount());
    }
1228

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
    private function isPostBatchResumeTokenSupported()
    {
        return version_compare($this->getServerVersion(), '4.0.7', '>=');
    }

    private function isStartAtOperationTimeSupported()
    {
        return \MongoDB\server_supports_feature($this->getPrimaryServer(), self::$wireVersionForStartAtOperationTime);
    }

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    private function killChangeStreamCursor(ChangeStream $changeStream)
    {
        $command = [
            'killCursors' => $this->getCollectionName(),
            'cursors' => [ $changeStream->getCursorId() ],
        ];

        $operation = new DatabaseCommand($this->getDatabaseName(), $command);
        $operation->execute($this->getPrimaryServer());
    }
1249
}