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

namespace MongoDB\Tests\Operation;

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

18
class WatchFunctionalTest extends FunctionalTestCase
19
{
20
    private $defaultOptions = ['maxAwaitTimeMS' => 500];
21

22 23 24
    public function setUp()
    {
        parent::setUp();
25

26 27 28 29
        if ($this->getPrimaryServer()->getType() === Server::TYPE_STANDALONE) {
            $this->markTestSkipped('$changeStream is not supported on standalone servers');
        }

30 31 32
        if (version_compare($this->getFeatureCompatibilityVersion(), '3.6', '<')) {
            $this->markTestSkipped('$changeStream is only supported on FCV 3.6 or higher');
        }
Jeremy Mikola's avatar
Jeremy Mikola committed
33
    }
34

35
    public function testNextResumesAfterCursorNotFound()
36
    {
37
        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
38

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

42 43
        $changeStream->rewind();
        $this->assertNull($changeStream->current());
44

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

47
        $changeStream->next();
48
        $this->assertTrue($changeStream->valid());
49 50 51 52 53 54 55 56 57 58

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

        $this->assertSameDocument($expectedResult, $changeStream->current());
59

60
        $this->killChangeStreamCursor($changeStream);
61

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

64
        $changeStream->next();
65
        $this->assertTrue($changeStream->valid());
66 67 68 69 70 71 72 73 74 75

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

        $this->assertSameDocument($expectedResult, $changeStream->current());
Jeremy Mikola's avatar
Jeremy Mikola committed
76
    }
77

78 79 80 81 82 83 84 85
    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));

86
        $operation = new Watch($manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
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 129 130
        $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();
                },
                function(stdClass $command) use (&$commands) {
                    $commands[] = key((array) $command);
                }
            );
            $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);
    }

131 132 133 134 135 136 137 138
    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));

139
        $operation = new Watch($manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
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
        $changeStream = $operation->execute($primaryServer);

        $commands = [];

        try {
            (new CommandObserver)->observe(
                function() use ($changeStream) {
                    $changeStream->rewind();
                },
                function(stdClass $command) use (&$commands) {
                    $commands[] = key((array) $command);
                }
            );
            $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);
    }

181 182
    public function testNoChangeAfterResumeBeforeInsert()
    {
183
        $this->insertDocument(['_id' => 1, 'x' => 'foo']);
184

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

188 189
        $changeStream->rewind();
        $this->assertNull($changeStream->current());
190

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

193
        $changeStream->next();
194
        $this->assertTrue($changeStream->valid());
195 196 197 198 199 200 201 202 203 204

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

        $this->assertSameDocument($expectedResult, $changeStream->current());
205

206
        $this->killChangeStreamCursor($changeStream);
207

208
        $changeStream->next();
209
        $this->assertFalse($changeStream->valid());
210
        $this->assertNull($changeStream->current());
211

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

214
        $changeStream->next();
215
        $this->assertTrue($changeStream->valid());
216 217 218 219 220 221 222 223 224 225

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

        $this->assertSameDocument($expectedResult, $changeStream->current());
226 227 228 229
    }

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

233
        $this->assertFalse($changeStream->valid());
234
        $this->assertNull($changeStream->key());
235

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

238
        $changeStream->rewind();
239
        $this->assertTrue($changeStream->valid());
240
        $this->assertSame(0, $changeStream->key());
241

242
        $changeStream->next();
243
        $this->assertFalse($changeStream->valid());
244
        $this->assertNull($changeStream->key());
245

246
        $changeStream->next();
247
        $this->assertFalse($changeStream->valid());
248
        $this->assertNull($changeStream->key());
249

250
        $this->killChangeStreamCursor($changeStream);
251

252
        $changeStream->next();
253
        $this->assertFalse($changeStream->valid());
254
        $this->assertNull($changeStream->key());
255

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

258
        $changeStream->next();
259
        $this->assertTrue($changeStream->valid());
260
        $this->assertSame(1, $changeStream->key());
261 262 263 264 265 266
    }

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

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

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

272
        $changeStream->rewind();
273
        $this->assertTrue($changeStream->valid());
274 275 276 277 278 279 280

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

        $this->assertSameDocument($expectedResult, $changeStream->current());
281 282
    }

283
    public function testInitialCursorIsNotClosed()
284
    {
285
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), []);
286
        $changeStream = $operation->execute($this->getPrimaryServer());
287

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        /* 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());
308 309 310 311
    }

    /**
     * @expectedException MongoDB\Exception\ResumeTokenException
312
     * @expectedExceptionMessage Resume token not found in change document
313
     */
314
    public function testNextResumeTokenNotFound()
315 316 317
    {
        $pipeline =  [['$project' => ['_id' => 0 ]]];

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

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

325
        $changeStream->next();
326 327
    }

328 329
    /**
     * @expectedException MongoDB\Exception\ResumeTokenException
330
     * @expectedExceptionMessage Resume token not found in change document
331
     */
332
    public function testRewindResumeTokenNotFound()
333 334 335
    {
        $pipeline =  [['$project' => ['_id' => 0 ]]];

336
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
        $changeStream = $operation->execute($this->getPrimaryServer());

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

        $changeStream->rewind();
    }

    /**
     * @expectedException MongoDB\Exception\ResumeTokenException
     * @expectedExceptionMessage Expected resume token to have type "array or object" but found "string"
     */
    public function testNextResumeTokenInvalidType()
    {
        $pipeline =  [['$project' => ['_id' => ['$literal' => 'foo']]]];

352
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
        $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]);

        $changeStream->next();
    }

    /**
     * @expectedException MongoDB\Exception\ResumeTokenException
     * @expectedExceptionMessage Expected resume token to have type "array or object" but found "string"
     */
    public function testRewindResumeTokenInvalidType()
    {
        $pipeline =  [['$project' => ['_id' => ['$literal' => 'foo']]]];

370
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $pipeline, $this->defaultOptions);
371 372 373 374 375 376 377
        $changeStream = $operation->execute($this->getPrimaryServer());

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

        $changeStream->rewind();
    }

378 379
    public function testMaxAwaitTimeMS()
    {
380 381 382
        /* 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. */
383
        $maxAwaitTimeMS = 500;
384

385 386 387 388 389
        /* 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;

390 391 392 393 394
        /* 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;

395 396
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], ['maxAwaitTimeMS' => $maxAwaitTimeMS]);
        $changeStream = $operation->execute($this->getPrimaryServer());
397

398 399 400 401 402
        /* 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). */
403
        $startTime = microtime(true);
404
        $changeStream->rewind();
405
        $duration = microtime(true) - $startTime;
406
        $this->assertGreaterThan($pivot, $duration);
407
        $this->assertLessThan($upperBound, $duration);
408

409
        $this->assertFalse($changeStream->valid());
410 411 412 413

        /* Advancing again on a change stream will issue a getMore, so we should
         * expect a delay again. */
        $startTime = microtime(true);
414
        $changeStream->next();
415
        $duration = microtime(true) - $startTime;
416
        $this->assertGreaterThan($pivot, $duration);
417
        $this->assertLessThan($upperBound, $duration);
418

419
        $this->assertFalse($changeStream->valid());
420

421 422
        /* After inserting a document, the change stream will not issue a
         * getMore so we should not expect a delay. */
423
        $this->insertDocument(['_id' => 1]);
424 425

        $startTime = microtime(true);
426
        $changeStream->next();
427
        $duration = microtime(true) - $startTime;
428
        $this->assertLessThan($pivot, $duration);
429
        $this->assertTrue($changeStream->valid());
430
    }
431

Katherine Walker's avatar
Katherine Walker committed
432
    public function testRewindResumesAfterCursorNotFound()
433
    {
434
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
435 436 437 438 439 440 441 442 443
        $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
444
    public function testRewindExtractsResumeTokenAndNextResumes()
445
    {
446
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], $this->defaultOptions);
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        $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],
        ];
        $this->assertSameDocument($expectedResult, $changeStream->current());

        $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],
        ];
        $this->assertSameDocument($expectedResult, $changeStream->current());
    }

478 479 480 481 482
    /**
     * @dataProvider provideTypeMapOptionsAndExpectedChangeDocument
     */
    public function testTypeMapOption(array $typeMap, $expectedChangeDocument)
    {
483
        $operation = new Watch($this->manager, $this->getDatabaseName(), $this->getCollectionName(), [], ['typeMap' => $typeMap] + $this->defaultOptions);
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        $changeStream = $operation->execute($this->getPrimaryServer());

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

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

        $changeStream->next();
        $this->assertTrue($changeStream->valid());
        $changeDocument = $changeStream->current();

        // Unset the resume token and namespace, which are intentionally omitted
        if (is_array($changeDocument)) {
            unset($changeDocument['_id'], $changeDocument['ns']);
        } else {
            unset($changeDocument->_id, $changeDocument->ns);
        }

        $this->assertEquals($expectedChangeDocument, $changeDocument);
    }

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

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    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());
    }

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    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());
    }

591 592 593 594 595 596
    private function insertDocument($document)
    {
        $insertOne = new InsertOne($this->getDatabaseName(), $this->getCollectionName(), $document);
        $writeResult = $insertOne->execute($this->getPrimaryServer());
        $this->assertEquals(1, $writeResult->getInsertedCount());
    }
597 598 599 600 601 602 603 604 605 606 607

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

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