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

namespace MongoDB\Tests\Operation;

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

21
class WatchFunctionalTest extends FunctionalTestCase
22
{
23
    private $defaultOptions = ['maxAwaitTimeMS' => 500];
24

25 26 27
    public function setUp()
    {
        parent::setUp();
28

29
        $this->skipIfChangeStreamIsNotSupported();
Jeremy Mikola's avatar
Jeremy Mikola committed
30
    }
31

32
    public function testNextResumesAfterCursorNotFound()
33
    {
34
        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
35

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

39 40
        $changeStream->rewind();
        $this->assertNull($changeStream->current());
41

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

44
        $changeStream->next();
45
        $this->assertTrue($changeStream->valid());
46 47 48 49 50 51 52 53 54

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

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

57
        $this->killChangeStreamCursor($changeStream);
58

59
        $this->insertDocument(['_id' => 3, 'x' => 'baz']);
60

61
        $changeStream->next();
62
        $this->assertTrue($changeStream->valid());
63 64 65 66 67 68 69 70 71

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

72
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
Jeremy Mikola's avatar
Jeremy Mikola committed
73
    }
74

75 76 77 78 79 80 81 82
    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. */
        $manager = new Manager($this->getUri(), ['socketTimeoutMS' => 50]);
        $primaryServer = $manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));

83
        $operation = new Watch($manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
84 85 86 87 88 89 90 91 92 93 94 95
        $changeStream = $operation->execute($primaryServer);

        /* Note: we intentionally do not start iteration with rewind() to ensure
         * that we test resume functionality within next(). */

        $commands = [];

        try {
            (new CommandObserver)->observe(
                function() use ($changeStream) {
                    $changeStream->next();
                },
96 97
                function(array $event) use (&$commands) {
                    $commands[] = $event['started']->getCommandName();
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
                }
            );
            $this->fail('ConnectionTimeoutException was not thrown');
        } catch (ConnectionTimeoutException $e) {}

        $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
             * stream (with either rewind() or next()). */
            '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',
            /* Finally, ChangeStream will rewind the new cursor as the last step
             * of the resume process. This results in one last getMore. */
            'getMore',
        ];

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

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    public function testResumeBeforeReceivingAnyResultsIncludesStartAtOperationTime()
    {
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);

        $operationTime = null;
        $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());
        $operationTime = $events[0]['succeeded']->getReply()->operationTime;
        $this->assertInstanceOf(TimestampInterface::class, $operationTime);

        $this->assertNull($changeStream->current());
        $this->killChangeStreamCursor($changeStream);

        $events = [];

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

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

        $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]);

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

        $this->assertNull($changeStream->current());
        $this->killChangeStreamCursor($changeStream);

        $events = [];

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

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

        $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]);

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

        $this->assertNull($changeStream->current());
    }

    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);
    }

222 223 224 225 226 227 228 229
    public function testRewindResumesAfterConnectionException()
    {
        /* 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. */
        $manager = new Manager($this->getUri(), ['socketTimeoutMS' => 50]);
        $primaryServer = $manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));

230
        $operation = new Watch($manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
231 232 233 234 235 236 237 238 239
        $changeStream = $operation->execute($primaryServer);

        $commands = [];

        try {
            (new CommandObserver)->observe(
                function() use ($changeStream) {
                    $changeStream->rewind();
                },
240 241
                function(array $event) use (&$commands) {
                    $commands[] = $event['started']->getCommandName();
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
                }
            );
            $this->fail('ConnectionTimeoutException was not thrown');
        } catch (ConnectionTimeoutException $e) {}

        $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
             * stream (with either rewind() or next()). */
            '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',
            /* Finally, ChangeStream will rewind the new cursor as the last step
             * of the resume process. This results in one last getMore. */
            'getMore',
        ];

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

272 273
    public function testNoChangeAfterResumeBeforeInsert()
    {
274
        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
275

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

279 280
        $changeStream->rewind();
        $this->assertNull($changeStream->current());
281

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

284
        $changeStream->next();
285
        $this->assertTrue($changeStream->valid());
286 287 288 289 290 291 292 293 294

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

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

297
        $this->killChangeStreamCursor($changeStream);
298

299
        $changeStream->next();
300
        $this->assertFalse($changeStream->valid());
301
        $this->assertNull($changeStream->current());
302

303
        $this->insertDocument(['_id' => 3, 'x' => 'baz']);
304

305
        $changeStream->next();
306
        $this->assertTrue($changeStream->valid());
307 308 309 310 311 312 313 314 315

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

316
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
317 318 319 320
    }

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

324
        $this->assertFalse($changeStream->valid());
325
        $this->assertNull($changeStream->key());
326

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

329
        $changeStream->rewind();
330
        $this->assertTrue($changeStream->valid());
331
        $this->assertSame(0, $changeStream->key());
332

333
        $changeStream->next();
334
        $this->assertFalse($changeStream->valid());
335
        $this->assertNull($changeStream->key());
336

337
        $changeStream->next();
338
        $this->assertFalse($changeStream->valid());
339
        $this->assertNull($changeStream->key());
340

341
        $this->killChangeStreamCursor($changeStream);
342

343
        $changeStream->next();
344
        $this->assertFalse($changeStream->valid());
345
        $this->assertNull($changeStream->key());
346

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

349
        $changeStream->next();
350
        $this->assertTrue($changeStream->valid());
351
        $this->assertSame(1, $changeStream->key());
352 353 354 355 356 357
    }

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

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

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

363
        $changeStream->rewind();
364
        $this->assertTrue($changeStream->valid());
365 366 367 368 369 370 371

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

        $this->assertSameDocument($expectedResult, $changeStream->current());
372 373
    }

374
    public function testInitialCursorIsNotClosed()
375
    {
376
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), []);
377
        $changeStream = $operation->execute($this->getPrimaryServer());
378

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
        /* 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());

        $rc = new ReflectionClass('MongoDB\ChangeStream');
        $rp = $rc->getProperty('csIt');
        $rp->setAccessible(true);

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

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

        $cursor = $iterator->getInnerIterator();

        $this->assertInstanceOf('MongoDB\Driver\Cursor', $cursor);
        $this->assertFalse($cursor->isDead());
399 400
    }

401
    public function testNextResumeTokenNotFound()
402 403 404
    {
        $pipeline =  [['$project' => ['_id' => 0 ]]];

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

Katherine Walker's avatar
Katherine Walker committed
408 409
        /* Note: we intentionally do not start iteration with rewind() to ensure
         * that we test extraction functionality within next(). */
410
        $this->insertDocument(['x' => 1]);
411

412 413
        $this->expectException(ResumeTokenException::class);
        $this->expectExceptionMessage('Resume token not found in change document');
414
        $changeStream->next();
415 416
    }

417
    public function testRewindResumeTokenNotFound()
418 419 420
    {
        $pipeline =  [['$project' => ['_id' => 0 ]]];

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

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

426 427
        $this->expectException(ResumeTokenException::class);
        $this->expectExceptionMessage('Resume token not found in change document');
428 429 430 431 432 433 434
        $changeStream->rewind();
    }

    public function testNextResumeTokenInvalidType()
    {
        $pipeline =  [['$project' => ['_id' => ['$literal' => 'foo']]]];

435
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
436 437 438 439 440 441
        $changeStream = $operation->execute($this->getPrimaryServer());

        /* Note: we intentionally do not start iteration with rewind() to ensure
         * that we test extraction functionality within next(). */
        $this->insertDocument(['x' => 1]);

442 443
        $this->expectException(ResumeTokenException::class);
        $this->expectExceptionMessage('Expected resume token to have type "array or object" but found "string"');
444 445 446 447 448 449 450
        $changeStream->next();
    }

    public function testRewindResumeTokenInvalidType()
    {
        $pipeline =  [['$project' => ['_id' => ['$literal' => 'foo']]]];

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

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

456 457
        $this->expectException(ResumeTokenException::class);
        $this->expectExceptionMessage('Expected resume token to have type "array or object" but found "string"');
458 459 460
        $changeStream->rewind();
    }

461 462
    public function testMaxAwaitTimeMS()
    {
463 464 465
        /* 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. */
466
        $maxAwaitTimeMS = 500;
467

468 469 470 471 472
        /* 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;

473 474 475 476 477
        /* 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;

478 479
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], ['maxAwaitTimeMS' => $maxAwaitTimeMS]);
        $changeStream = $operation->execute($this->getPrimaryServer());
480

481 482 483 484 485
        /* The initial change stream is empty so we should expect a delay when
         * we call rewind, since it issues a getMore. Expect to wait at least
         * maxAwaitTimeMS, since no new documents should be inserted to wake up
         * the server's query thread. Also ensure we don't wait too long (server
         * default is one second). */
486
        $startTime = microtime(true);
487
        $changeStream->rewind();
488
        $duration = microtime(true) - $startTime;
489
        $this->assertGreaterThan($pivot, $duration);
490
        $this->assertLessThan($upperBound, $duration);
491

492
        $this->assertFalse($changeStream->valid());
493 494 495 496

        /* Advancing again on a change stream will issue a getMore, so we should
         * expect a delay again. */
        $startTime = microtime(true);
497
        $changeStream->next();
498
        $duration = microtime(true) - $startTime;
499
        $this->assertGreaterThan($pivot, $duration);
500
        $this->assertLessThan($upperBound, $duration);
501

502
        $this->assertFalse($changeStream->valid());
503

504 505
        /* After inserting a document, the change stream will not issue a
         * getMore so we should not expect a delay. */
506
        $this->insertDocument(['_id' => 1]);
507 508

        $startTime = microtime(true);
509
        $changeStream->next();
510
        $duration = microtime(true) - $startTime;
511
        $this->assertLessThan($pivot, $duration);
512
        $this->assertTrue($changeStream->valid());
513
    }
514

Katherine Walker's avatar
Katherine Walker committed
515
    public function testRewindResumesAfterCursorNotFound()
516
    {
517
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
518 519 520 521 522 523 524 525 526
        $changeStream = $operation->execute($this->getPrimaryServer());

        $this->killChangeStreamCursor($changeStream);

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

Katherine Walker's avatar
Katherine Walker committed
527
    public function testRewindExtractsResumeTokenAndNextResumes()
528
    {
529
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
530 531 532 533 534 535 536 537 538 539 540 541 542 543
        $changeStream = $operation->execute($this->getPrimaryServer());

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

        $changeStream->rewind();
        $this->assertTrue($changeStream->valid());
        $expectedResult = [
            '_id' => $changeStream->current()->_id,
            'operationType' => 'insert',
            'fullDocument' => ['_id' => 1, 'x' => 'foo'],
            'ns' => ['db' => $this->getDatabaseName(), 'coll' => $this->getCollectionName()],
            'documentKey' => ['_id' => 1],
        ];
544
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
545 546 547 548 549 550 551 552 553 554 555 556 557

        $this->killChangeStreamCursor($changeStream);

        $changeStream->next();
        $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],
        ];
558
        $this->assertMatchesDocument($expectedResult, $changeStream->current());
559 560
    }

561 562 563 564 565
    /**
     * @dataProvider provideTypeMapOptionsAndExpectedChangeDocument
     */
    public function testTypeMapOption(array $typeMap, $expectedChangeDocument)
    {
566
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], ['typeMap' => $typeMap] + $this->defaultOptions);
567 568 569 570 571 572 573 574 575 576
        $changeStream = $operation->execute($this->getPrimaryServer());

        $changeStream->rewind();
        $this->assertNull($changeStream->current());

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

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

577
        $this->assertMatchesDocument($expectedChangeDocument, $changeStream->current());
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    }

    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],
                ],
            ],
        ];
    }

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    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]);

        $changeStream->next();

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

        $changeStream->next();

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

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    public function testResumeTokenNotFoundAdvancesKey()
    {
        $pipeline =  [['$project' => ['_id' => 0 ]]];

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

        /* Note: we intentionally do not start iteration with rewind() to ensure
         * that we test extraction functionality within next(). */
        $this->insertDocument(['x' => 1]);
        $this->insertDocument(['x' => 2]);
        $this->insertDocument(['x' => 3]);

        try {
            $changeStream->rewind();
            $this->fail('ResumeTokenException was not thrown');
        } catch (ResumeTokenException $e) {}

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

        try {
            $changeStream->next();
            $this->fail('ResumeTokenException was not thrown');
        } catch (ResumeTokenException $e) {}

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

        try {
            $changeStream->next();
            $this->fail('ResumeTokenException was not thrown');
        } catch (ResumeTokenException $e) {}

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

666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    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());
            },
684 685 686 687
            function(array $event) use (&$originalSession) {
                $command = $event['started']->getCommand();
                if (isset($command->aggregate)) {
                    $originalSession = bin2hex((string) $command->lsid->id);
688 689 690 691 692 693 694 695 696 697 698
                }
            }
        );

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

        (new CommandObserver)->observe(
            function() use (&$changeStream) {
                $changeStream->next();
            },
699 700 701
            function (array $event) use (&$sessionAfterResume, &$commands) {
                $commands[] = $event['started']->getCommandName();
                $sessionAfterResume[] = bin2hex((string) $event['started']->getCommand()->lsid->id);
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
            }
        );

        $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',
            /* Finally, ChangeStream will rewind the new cursor as the last step
             * of the resume process. This results in one last getMore. */
            'getMore',
        ];

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

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

    public function testSessionFreed()
    {
        $operation = new CreateCollection($this->getDatabaseName(), $this->getCollectionName());
        $operation->execute($this->getPrimaryServer());

        $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);

        $this->assertNotNull($rp->getValue($changeStream));

        // Invalidate the cursor to verify that resumeCallable is unset when the cursor is exhausted.
        $operation = new DropCollection($this->getDatabaseName(), $this->getCollectionName());
        $operation->execute($this->getPrimaryServer());

        $changeStream->next();

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

751 752 753 754 755 756
    private function insertDocument($document)
    {
        $insertOne = new InsertOne($this->getDatabaseName(), $this->getCollectionName(), $document);
        $writeResult = $insertOne->execute($this->getPrimaryServer());
        $this->assertEquals(1, $writeResult->getInsertedCount());
    }
757 758 759 760 761 762 763 764 765 766 767

    private function killChangeStreamCursor(ChangeStream $changeStream)
    {
        $command = [
            'killCursors' => $this->getCollectionName(),
            'cursors' => [ $changeStream->getCursorId() ],
        ];

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