File: changestreams.t

package info (click to toggle)
libmongodb-perl 2.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 10,264 kB
  • sloc: perl: 14,419; python: 299; makefile: 20; sh: 11
file content (413 lines) | stat: -rw-r--r-- 14,148 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#  Copyright 2018 - present MongoDB, Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

use strict;
use warnings;
use utf8;
use Test::More 0.96;
use Test::Deep;
use Storable qw( dclone );
use Safe::Isa;

use MongoDB;
use MongoDB::Error;

use lib "t/lib";
use MongoDBTest qw/
    skip_unless_mongod
    skip_unless_sessions
    uuid_to_string
    build_client
    get_test_db
    server_version
    server_type
    check_min_server_version
    skip_unless_min_version
/;

skip_unless_mongod();

my @events;

sub clear_events { @events = () }

sub event_cb { push @events, dclone $_[0] }

my $conn = build_client(monitoring_callback => \&event_cb);
my $testdb = get_test_db($conn);
my $server_version = server_version($conn);
my $server_type = server_type($conn);
my $coll = $testdb->get_collection('test_collection');

plan skip_all => 'MongoDB replica set required'
    unless $server_type eq 'RSPrimary';

subtest 'client' => sub {
    skip_unless_min_version($conn, 'v4.0.0');
    run_tests_for($conn);
};

subtest 'database' => sub {
    skip_unless_min_version($conn, 'v4.0.0');
    run_tests_for($testdb);
};

subtest 'collection' => sub {
    skip_unless_min_version($conn, 'v3.6.0');
    run_tests_for($coll);
    run_collection_tests($coll);
};

done_testing;

sub insert_and_check {
    my ($coll, $change_stream, $doc) = @_;
    $coll->insert_one($doc);
    ok(my $change = $change_stream->next, 'got next doc');
    is($change->{'operationType'}, 'insert', 'correct insert op');
    cmp_deeply($change->{'ns'}, {
        'db' => $coll->database->name,
        'coll' => $coll->name,
    });
    ok($change->{'fullDocument'}, 'got full doc');
    return $change;
}

sub run_tests_for {
    my ($watchable) = @_;

    subtest 'basic' => sub {
        $coll->drop;
        $coll->insert_one({ value => 1 });
        $coll->insert_one({ value => 2 });

        my $change_stream = $watchable->watch();
        is $change_stream->next, undef, 'next without changes';

        for my $index (1..10) {
            $coll->insert_one({ value => 100 + $index });
        }
        my %changed;
        while (my $change = $change_stream->next) {
            is $changed{ $change->{fullDocument}{value} }++, 0,
                'first seen '.$change->{fullDocument}{value};
            cmp_deeply($change_stream->get_resume_token, $change->{'_id'},
                'track resumeToken');
        }
        is scalar(keys %changed), 10, 'seen all changes';
    };

    subtest 'change streams w/ maxAwaitTimeMS' => sub {
        $coll->drop;
        my $change_stream = $watchable->watch([], { maxAwaitTimeMS => 3000 });
        my $start = time;
        is $change_stream->next, undef, 'next without changes';
        ok(!$change_stream->get_resume_token, 'track resumeToken');
        my $elapsed = time - $start;
        my $min_elapsed = 2;
        ok $elapsed > $min_elapsed, "waited for at least $min_elapsed secs";
    };

    subtest 'change streams w/ fullDocument' => sub {
        $coll->drop;
        $coll->insert_one({ value => 1 });
        my $change_stream = $watchable->watch(
            [],
            { fullDocument => 'updateLookup' },
        );
        $coll->update_one(
            { value => 1 },
            { '$set' => { updated => 3 }},
        );
        my $change = $change_stream->next;
        is $change->{operationType}, 'update', 'change is an update';
        ok exists($change->{fullDocument}), 'delta contains full document';
        cmp_deeply($change_stream->get_resume_token, $change->{'_id'},
            'track resumeToken');
    };

    subtest 'change streams w/ resumeAfter' => sub {
        $coll->drop;
        my $id = do {
            my $change_stream = $watchable->watch();
            $coll->insert_one({ value => 200 });
            $coll->insert_one({ value => 201 });
            my $change = $change_stream->next;
            ok $change, 'change exists';
            is $change->{fullDocument}{value}, 200,
                'correct change';
            $change_stream->get_resume_token
        };
        do {
            my $change_stream = $watchable->watch(
                [],
                { resumeAfter => $id },
            );
            cmp_deeply($id, $change_stream->get_resume_token,
                'getResumeToken must return resumeAfter from the initial
                 aggregate if the option was specified.');
            my $change = $change_stream->next;
            ok $change, 'change exists after resume';
            is $change->{fullDocument}{value}, 201,
                'correct change after resume';
            is $change_stream->next, undef, 'no more changes';
        };
    };

    subtest 'change streams w/ CursorNotFound reconnection' => sub {
        $coll->drop;

        my $change_stream = $watchable->watch;

        my $change = insert_and_check($coll, $change_stream, { value => 301 });
        ok $change, 'change received';
        is $change->{fullDocument}{value}, 301, 'correct change';

        $testdb->run_command([
            killCursors => $coll->name,
            cursors => [$change_stream->_result->_cursor_id],
        ]);

        $change = insert_and_check($coll, $change_stream, { value => 302 });
        ok $change, 'change received after reconnect';
        is $change->{fullDocument}{value}, 302, 'correct change';
    };

    subtest 'startAtOperationTime' => sub {
	skip_unless_min_version($conn, 'v4.0.0');
        $coll->drop;

        my $change_stream = $watchable->watch([], {
            startAtOperationTime => scalar(time + 3),
        });
        $coll->insert_one({ value => 401 });
        sleep 4;
        $coll->insert_one({ value => 402 });

        my $change = $change_stream->next;
        ok $change, 'change received';
        is $change->{fullDocument}{value}, 402, 'correct change';

        ok !defined($change_stream->next), 'no more changes';
        cmp_deeply($change_stream->get_resume_token, $change->{'_id'},
            'track resumeToken');
    };

    subtest 'sessions' => sub {
        skip_unless_sessions();
        clear_events();

        my $session = $conn->start_session;

        my $change_stream = $watchable->watch([], {
            session => $session,
        });

        my ($event) = grep {
            $_->{commandName} eq 'aggregate' and
            $_->{type} eq 'command_started'
        } @events;

        ok(defined($event), 'found event')
            or return;

        my $lsid = uuid_to_string(
            $session->_server_session->session_id->{id}->data,
        );

        my $command = $event->{command};
        my $command_sid = uuid_to_string($command->{lsid}{id}->data);

        is $command_sid, $lsid, 'command has correct session id';
    };

    subtest 'PERL-1090' => sub {
        $coll->drop;
        my $change_stream = $watchable->watch([
            { '$project' => { '_id' => 0 } }
        ]);
        is $change_stream->next, undef, 'next without changes';

        $coll->insert_one({});

        my $change = eval { $change_stream->next };
        my $err = $@;
        ok($err, 'ChangeStream must raise an exception');
        ok(
            $err->$_isa('MongoDB::InvalidOperationError')
            || $err->$_isa('MongoDB::DatabaseError'), 'correct exp error');
    };

    subtest 'batchSize is honored' => sub {
        $coll->drop;
        clear_events();

        my $batch_size = { batchSize => 3 };
        my $change_stream = $watchable->watch([], dclone($batch_size));
        is $change_stream->next, undef, 'next without changes';
        ok(!$change_stream->get_resume_token, 'no resume token yet');

        insert_and_check($coll, $change_stream, { '_id' => 1 });
        ok(!$change_stream->next, 'no more changes');

        my $got_event = (
            grep {
                $_->{commandName} eq 'aggregate'
                and $_->{type} eq 'command_started'
            } @events
        )[0];
        cmp_deeply($got_event->{'command'}{'cursor'}, $batch_size);
    };

    subtest 'initial empty batch' => sub {
        $coll->drop;
        my $change_stream = $watchable->watch;
        my $result = $change_stream->_result;
        ok(!$result->has_next, 'The first batch should be empty');
        ok(my $cursor_id = $result->_cursor_id, 'active cursor');

        insert_and_check($coll, $change_stream, {});
        is($cursor_id, $change_stream->_result->_cursor_id,
           'still using same cursor');
    };

    subtest 'postBatchResumeToken' => sub {
	skip_unless_min_version($conn, 'v4.0.7');
        $coll->drop;
        my $id = do {
            my $change_stream = $watchable->watch();
            $coll->insert_one({ value => 200 });
            $coll->insert_one({ value => 201 });
            my $change = $change_stream->next;
            ok $change, 'change exists';
            is $change->{fullDocument}{value}, 200,
                'correct change';
            $change_stream->get_resume_token
        };
        do {
            my $change_stream = $watchable->watch(
                [],
                { resumeAfter => $id },
            );
            my $change = $change_stream->next;
            ok $change, 'change exists after resume';
            is $change->{fullDocument}{value}, 201,
                'correct change after resume';
            my $resume_token = $change_stream->get_resume_token;
            cmp_deeply($resume_token, $change->{'postBatchResumeToken'},
                'track resumeToken');
            is $change_stream->next, undef, 'no more changes';
            cmp_deeply($change_stream->get_resume_token, $resume_token,
                'track resumeToken');
        };
    };

    subtest 'postBatchResumeToken beyond previous batch' => sub {
	skip_unless_min_version($conn, 'v4.0.7');
        $coll->drop;
        my $change_stream = $watchable->watch();
        $coll->insert_one({ value => 200 });
        my $change = $change_stream->next;
        ok $change, 'change exists';
        is $change->{fullDocument}{value}, 200,
            'correct change';
        my $resume_token = $change_stream->get_resume_token;
        ok(!$change_stream->next, 'no more changes');
        # next batch
        $change_stream = $watchable->watch(
            [],
            { resumeAfter => $resume_token },
        );
        $coll->insert_one({ value => 201 });
        $coll->insert_one({ value => 202 });
        cmp_deeply($change_stream->get_resume_token, $resume_token,
            'getResumeToken must return the resume token from
             the previous command response.');
        $change = $change_stream->next;
        isnt($change_stream->get_resume_token->{_data}, $resume_token->{_data});
        isnt($change->{postBatchResumeToken}{_data}, $resume_token->{_data});
    };
}

sub run_collection_tests {
    my ($watchable) = @_;
    my $invalidate_resume_token = sub {
        my $change_stream = $watchable->watch(
            [{ '$match' => { 'operationType' => 'invalidate' } }]
        );
        $coll->insert_one({ '_id' => 1 });
        $coll->drop;
        my $change = $change_stream->next;
        ok $change, 'change exists';
        is($change->{'operationType'}, 'invalidate',
           'correct invalidate op');
        $change_stream->get_resume_token
    };

    subtest 'test startAfter' => sub {
	skip_unless_min_version($conn, 'v4.2.0');
        my $id = $invalidate_resume_token->();
        eval { $watchable->watch([], { resumeAfter => $id }) };
        ok(my $err = $@, 'resume_after cannot resume after invalidate');
        ok($err->$_isa('MongoDB::DatabaseError'), 'got error');
        my $change_stream = $watchable->watch(
            [],
            { startAfter => $id },
        );
        $coll->insert_one({ '_id' => 2});
        cmp_deeply($id, $change_stream->get_resume_token,
            'getResumeToken must return startAfter from the initial
             aggregate if the option was specified.');
        my $change = $change_stream->next;
        ok $change, 'change exists';
        is($change->{'operationType'}, 'insert', 'correct insert op');
    };
    subtest 'test startAfter resume process with changes' => sub {
	skip_unless_min_version($conn, 'v4.2.0');
        my $id = $invalidate_resume_token->();
        my $change_stream = $watchable->watch(
            [],
            { startAfter => $id, maxAwaitTimeMS => 250 },
        );
        $coll->insert_one({ '_id' => 2 });
        my $change = $change_stream->next;
        ok $change, 'change exists';
        is($change->{'operationType'}, 'insert', 'correct insert op');
        cmp_deeply($change->{'fullDocument'}, { '_id' => 2 }, 'correct full doc');

        ok(!$change_stream->next, 'no more changes');

        $coll->insert_one({ '_id' => 3 });
        $change = $change_stream->next;
        ok $change, 'change exists';
        is($change->{'operationType'}, 'insert', 'correct insert op');
        cmp_deeply($change->{'fullDocument'}, { '_id' => 3 }, 'correct full doc');
    };
    subtest 'test startAfter resume process without changes' => sub {
	skip_unless_min_version($conn, 'v4.2.0');
        my $id = $invalidate_resume_token->();
        my $change_stream = $watchable->watch(
            [],
            { startAfter => $id, maxAwaitTimeMS => 250 },
        );

        ok(!$change_stream->next, 'no more changes');

        $coll->insert_one({ '_id' => 2 });
        my $change = $change_stream->next;
        ok $change, 'change exists';
        is($change->{'operationType'}, 'insert', 'correct insert op');
        cmp_deeply($change->{'fullDocument'}, { '_id' => 2 }, 'correct full doc');
    };
}