-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
TestCommunication.java
659 lines (567 loc) · 22.7 KB
/
TestCommunication.java
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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
478
479
480
481
482
483
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
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
/*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.com;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.IOException;
import org.neo4j.com.storecopy.ResponseUnpacker;
import org.neo4j.helpers.collection.Visitor;
import org.neo4j.kernel.impl.store.MismatchingStoreIdException;
import org.neo4j.kernel.impl.store.StoreId;
import org.neo4j.kernel.impl.transaction.CommittedTransactionRepresentation;
import org.neo4j.kernel.impl.transaction.log.TransactionIdStore;
import org.neo4j.kernel.lifecycle.LifeSupport;
import static java.lang.System.currentTimeMillis;
import static java.lang.Thread.yield;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.neo4j.com.MadeUpServer.FRAME_LENGTH;
import static org.neo4j.com.TxChecksumVerifier.ALWAYS_MATCH;
import static org.neo4j.com.storecopy.ResponseUnpacker.NO_OP_TX_HANDLER;
import static org.neo4j.kernel.impl.store.StoreIdTestFactory.newStoreIdForCurrentVersion;
public class TestCommunication
{
private static final byte INTERNAL_PROTOCOL_VERSION = 0;
private static final byte APPLICATION_PROTOCOL_VERSION = 0;
private static final int PORT = 1234;
private final LifeSupport life = new LifeSupport();
private StoreId storeIdToUse;
private Builder builder;
@Before
public void doBefore()
{
storeIdToUse = newStoreIdForCurrentVersion();
builder = new Builder();
}
@After
public void shutdownLife()
{
life.shutdown();
}
@Test
public void clientGetResponseFromServerViaComLayer() throws Throwable
{
MadeUpServerImplementation serverImplementation = new MadeUpServerImplementation( storeIdToUse );
MadeUpServer server = builder.server( serverImplementation );
MadeUpClient client = builder.client();
addToLifeAndStart( server, client );
int value1 = 10;
int value2 = 5;
Response<Integer> response = client.multiply( 10, 5 );
waitUntilResponseHasBeenWritten( server, 1000 );
assertEquals( (Integer) (value1 * value2), response.response() );
assertTrue( serverImplementation.gotCalled() );
assertTrue( server.responseHasBeenWritten() );
}
private void waitUntilResponseHasBeenWritten( MadeUpServer server, int maxTime ) throws Exception
{
long time = currentTimeMillis();
while ( !server.responseHasBeenWritten() && currentTimeMillis() - time < maxTime )
{
Thread.sleep( 50 );
}
}
@Test(expected = MismatchingStoreIdException.class)
public void makeSureClientStoreIdsMustMatch() throws Throwable
{
MadeUpServer server = builder.server();
MadeUpClient client = builder.storeId( newStoreIdForCurrentVersion( 10, 10, 10, 10 ) ).client();
addToLifeAndStart( server, client );
client.multiply( 1, 2 );
}
@Test(expected = MismatchingStoreIdException.class)
public void makeSureServerStoreIdsMustMatch() throws Throwable
{
MadeUpServer server = builder.storeId( newStoreIdForCurrentVersion( 10, 10, 10, 10 ) ).server();
MadeUpClient client = builder.client();
addToLifeAndStart( server, client );
client.multiply( 1, 2 );
}
@Test
public void makeSureClientCanStreamBigData() throws Throwable
{
MadeUpServer server = builder.server();
MadeUpClient client = builder.client();
addToLifeAndStart( server, client );
client.fetchDataStream( new ToAssertionWriter(), FRAME_LENGTH * 3 );
}
@Test
public void clientThrowsServerSideErrorMidwayThroughStreaming() throws Throwable
{
final String failureMessage = "Just failing";
MadeUpServerImplementation serverImplementation = new MadeUpServerImplementation( storeIdToUse )
{
@Override
public Response<Void> fetchDataStream( MadeUpWriter writer, int dataSize )
{
writer.write( new FailingByteChannel( dataSize, failureMessage ) );
return new TransactionStreamResponse<>( null, storeIdToUse, TransactionStream.EMPTY,
ResourceReleaser.NO_OP );
}
};
MadeUpServer server = builder.server( serverImplementation );
MadeUpClient client = builder.client();
addToLifeAndStart( server, client );
try
{
client.fetchDataStream( new ToAssertionWriter(), FRAME_LENGTH * 2 );
fail( "Should have thrown " + MadeUpException.class.getSimpleName() );
}
catch ( MadeUpException e )
{
assertEquals( failureMessage, e.getMessage() );
}
}
@Test
public void communicateBetweenJvms() throws Throwable
{
ServerInterface server = builder.serverInOtherJvm();
server.awaitStarted();
MadeUpClient client = builder.port( MadeUpServerProcess.PORT ).client();
life.add( client );
life.start();
assertEquals( (Integer) (9 * 5), client.multiply( 9, 5 ).response() );
client.fetchDataStream( new ToAssertionWriter(), 1024 * 1024 * 3 );
server.shutdown();
}
@Test
public void throwingServerSideExceptionBackToClient() throws Throwable
{
MadeUpServer server = builder.server();
MadeUpClient client = builder.client();
addToLifeAndStart( server, client );
String exceptionMessage = "The message";
try
{
client.throwException( exceptionMessage );
fail( "Should have thrown " + MadeUpException.class.getSimpleName() );
}
catch ( MadeUpException e )
{ // Good
assertEquals( exceptionMessage, e.getMessage() );
}
}
@Test
public void applicationProtocolVersionsMustMatch() throws Throwable
{
MadeUpServer server = builder.applicationProtocolVersion( (byte) (APPLICATION_PROTOCOL_VERSION + 1) ).server();
MadeUpClient client = builder.client();
addToLifeAndStart( server, client );
try
{
client.multiply( 10, 20 );
fail( "Shouldn't be able to communicate with different application protocol versions" );
}
catch ( IllegalProtocolVersionException e )
{ /* Good */ }
}
@Test
public void applicationProtocolVersionsMustMatchMultiJvm() throws Throwable
{
ServerInterface server = builder.applicationProtocolVersion( (byte) (APPLICATION_PROTOCOL_VERSION + 1) )
.serverInOtherJvm();
server.awaitStarted();
MadeUpClient client = builder.port( MadeUpServerProcess.PORT ).client();
life.add( client );
life.start();
try
{
client.multiply( 10, 20 );
fail( "Shouldn't be able to communicate with different application protocol versions" );
}
catch ( IllegalProtocolVersionException e )
{ /* Good */ }
server.shutdown();
}
@Test
public void internalProtocolVersionsMustMatch() throws Throwable
{
MadeUpServer server = builder.internalProtocolVersion( (byte) 1 ).server();
MadeUpClient client = builder.internalProtocolVersion( (byte) 2 ).client();
addToLifeAndStart( server, client );
try
{
client.multiply( 10, 20 );
fail( "Shouldn't be able to communicate with different application protocol versions" );
}
catch ( IllegalProtocolVersionException e )
{ /* Good */ }
}
@Test
public void internalProtocolVersionsMustMatchMultiJvm() throws Throwable
{
ServerInterface server = builder.internalProtocolVersion( (byte) 1 ).serverInOtherJvm();
server.awaitStarted();
MadeUpClient client = builder.port( MadeUpServerProcess.PORT ).internalProtocolVersion( (byte) 2 ).client();
life.add( client );
life.start();
try
{
client.multiply( 10, 20 );
fail( "Shouldn't be able to communicate with different application protocol versions" );
}
catch ( IllegalProtocolVersionException e )
{ /* Good */ }
server.shutdown();
}
@Test
public void serverStopsStreamingToDeadClient() throws Throwable
{
MadeUpServer server = builder.server();
MadeUpClient client = builder.client();
addToLifeAndStart( server, client );
int failAtSize = FRAME_LENGTH / 2;
ClientCrashingWriter writer = new ClientCrashingWriter( client, failAtSize );
try
{
client.fetchDataStream( writer, FRAME_LENGTH * 10 );
assertTrue( writer.getSizeRead() >= failAtSize );
fail( "Should fail in the middle" );
}
catch ( ComException e )
{ // Expected
}
assertTrue( writer.getSizeRead() >= failAtSize );
long maxWaitUntil = System.currentTimeMillis() + 2 * 1000;
while ( !server.responseFailureEncountered() && System.currentTimeMillis() < maxWaitUntil )
{
yield();
}
assertTrue( "Failure writing the response should have been encountered", server.responseFailureEncountered() );
assertFalse( "Response shouldn't have been successful", server.responseHasBeenWritten() );
}
@Test
public void serverContextVerificationCanThrowException() throws Throwable
{
final String failureMessage = "I'm failing";
TxChecksumVerifier failingVerifier = new TxChecksumVerifier()
{
@Override
public void assertMatch( long txId, long checksum )
{
throw new FailingException( failureMessage );
}
};
MadeUpServer server = builder.verifier( failingVerifier ).server();
MadeUpClient client = builder.client();
addToLifeAndStart( server, client );
try
{
client.multiply( 10, 5 );
fail( "Should have failed" );
}
catch ( Exception e )
{ // Good
// TODO catch FailingException instead of Exception and make Server throw the proper
// one instead of getting a "channel closed".
}
}
@Test
public void clientCanReadChunkSizeBiggerThanItsOwn() throws Throwable
{ // Given that frameLength is the same for both client and server.
int serverChunkSize = 20000;
int clientChunkSize = serverChunkSize / 10;
MadeUpServer server = builder.chunkSize( serverChunkSize ).server();
MadeUpClient client = builder.chunkSize( clientChunkSize ).client();
addToLifeAndStart( server, client );
// Tell server to stream data occupying roughly two chunks. The chunks
// from server are 10 times bigger than the clients chunk size.
client.fetchDataStream( new ToAssertionWriter(), serverChunkSize * 2 );
}
@Test
public void serverCanReadChunkSizeBiggerThanItsOwn() throws Throwable
{ // Given that frameLength is the same for both client and server.
int serverChunkSize = 1000;
int clientChunkSize = serverChunkSize * 10;
MadeUpServer server = builder.chunkSize( serverChunkSize ).server();
MadeUpClient client = builder.chunkSize( clientChunkSize ).client();
addToLifeAndStart( server, client );
// Tell server to stream data occupying roughly two chunks. The chunks
// from server are 10 times bigger than the clients chunk size.
client.sendDataStream( new DataProducer( clientChunkSize * 2 ) );
}
@Test
public void impossibleToHaveBiggerChunkSizeThanFrameSize() throws Throwable
{
Builder myBuilder = builder.chunkSize( MadeUpServer.FRAME_LENGTH + 10 );
try
{
MadeUpServer server = myBuilder.server();
server.init();
server.start();
fail( "Shouldn't be possible" );
}
catch ( IllegalArgumentException e )
{ // Good
}
try
{
myBuilder.client();
fail( "Shouldn't be possible" );
}
catch ( IllegalArgumentException e )
{ // Good
}
}
@Test
public void clientShouldUseHandlersToHandleComExceptions()
{
// Given
final String comExceptionMessage = "The ComException";
MadeUpCommunicationInterface communication = mock( MadeUpCommunicationInterface.class, new Answer<Response<?>>()
{
@Override
public Response<?> answer( InvocationOnMock _ ) throws ComException
{
throw new ComException( comExceptionMessage );
}
} );
ComExceptionHandler handler = mock( ComExceptionHandler.class );
life.add( builder.server( communication ) );
MadeUpClient client = life.add( builder.client() );
client.setComExceptionHandler( handler );
life.start();
// When
ComException exceptionThrownOnRequest = null;
try
{
client.multiply( 1, 10 );
}
catch ( ComException e )
{
exceptionThrownOnRequest = e;
}
// Then
assertNotNull( exceptionThrownOnRequest );
assertEquals( comExceptionMessage, exceptionThrownOnRequest.getMessage() );
ArgumentCaptor<ComException> exceptionCaptor = ArgumentCaptor.forClass( ComException.class );
verify( handler ).handle( exceptionCaptor.capture() );
assertEquals( comExceptionMessage, exceptionCaptor.getValue().getMessage() );
verifyNoMoreInteractions( handler );
}
@Test
@SuppressWarnings("rawtypes")
public void masterResponseShouldBeUnpackedIfRequestTypeRequires() throws Exception
{
// Given
ResponseUnpacker responseUnpacker = mock( ResponseUnpacker.class );
MadeUpClient client = builder.clientWith( responseUnpacker );
addToLifeAndStart( builder.server(), client );
// When
client.multiply( 42, 42 );
// Then
ArgumentCaptor<Response> captor = ArgumentCaptor.forClass( Response.class );
verify( responseUnpacker ).unpackResponse( captor.capture(), eq( NO_OP_TX_HANDLER ) );
assertEquals( storeIdToUse, captor.getValue().getStoreId() );
assertEquals( 42 * 42, captor.getValue().response() );
}
@Test
public void masterResponseShouldNotBeUnpackedIfRequestTypeDoesNotRequire()
{
// Given
ResponseUnpacker responseUnpacker = mock( ResponseUnpacker.class );
MadeUpClient client = builder.clientWith( responseUnpacker );
addToLifeAndStart( builder.server(), client );
// When
client.sendDataStream( new KnownDataByteChannel( 100 ) );
// Then
verifyZeroInteractions( responseUnpacker );
}
@Test
public void shouldStreamBackTransactions() throws Exception
{
// GIVEN
int value = 11, txCount = 5;
life.add( builder.server() );
MadeUpClient client = life.add( builder.client() );
life.start();
Response<Integer> respone = client.streamBackTransactions( value, txCount );
TransactionStreamVerifyingResponseHandler handler = new TransactionStreamVerifyingResponseHandler( txCount );
// WHEN
respone.accept( handler );
int responseValue = respone.response();
// THEN
assertEquals( value, responseValue );
assertEquals( txCount, handler.expectedTxId - TransactionIdStore.BASE_TX_ID );
}
@Test
public void shouldAdhereToTransactionObligations() throws Exception
{
// GIVEN
int value = 15;
long desiredObligation = 8;
life.add( builder.server() );
MadeUpClient client = life.add( builder.client() );
life.start();
Response<Integer> respone = client.informAboutTransactionObligations( value, desiredObligation );
TransactionObligationVerifyingResponseHandler handler = new TransactionObligationVerifyingResponseHandler();
// WHEN
respone.accept( handler );
int responseValue = respone.response();
// THEN
assertEquals( value, responseValue );
assertEquals( desiredObligation, handler.obligationTxId );
}
private void addToLifeAndStart( MadeUpServer server, MadeUpClient client )
{
life.add( server );
life.add( client );
life.init();
life.start();
}
class Builder
{
private final int port;
private final int chunkSize;
private final byte internalProtocolVersion;
private final byte applicationProtocolVersion;
private final TxChecksumVerifier verifier;
private final StoreId storeId;
public Builder()
{
this( PORT, FRAME_LENGTH, INTERNAL_PROTOCOL_VERSION, APPLICATION_PROTOCOL_VERSION,
ALWAYS_MATCH, storeIdToUse );
}
public Builder( int port, int chunkSize, byte internalProtocolVersion, byte applicationProtocolVersion,
TxChecksumVerifier verifier, StoreId storeId )
{
this.port = port;
this.chunkSize = chunkSize;
this.internalProtocolVersion = internalProtocolVersion;
this.applicationProtocolVersion = applicationProtocolVersion;
this.verifier = verifier;
this.storeId = storeId;
}
public Builder port( int port )
{
return new Builder(
port, chunkSize, internalProtocolVersion, applicationProtocolVersion, verifier, storeId );
}
public Builder chunkSize( int chunkSize )
{
return new Builder(
port, chunkSize, internalProtocolVersion, applicationProtocolVersion, verifier, storeId );
}
public Builder internalProtocolVersion( byte internalProtocolVersion )
{
return new Builder(
port, chunkSize, internalProtocolVersion, applicationProtocolVersion, verifier, storeId );
}
public Builder applicationProtocolVersion( byte applicationProtocolVersion )
{
return new Builder(
port, chunkSize, internalProtocolVersion, applicationProtocolVersion, verifier, storeId );
}
public Builder verifier( TxChecksumVerifier verifier )
{
return new Builder(
port, chunkSize, internalProtocolVersion, applicationProtocolVersion, verifier, storeId );
}
public Builder storeId( StoreId storeId )
{
return new Builder(
port, chunkSize, internalProtocolVersion, applicationProtocolVersion, verifier, storeId );
}
public MadeUpServer server()
{
return new MadeUpServer( new MadeUpServerImplementation( storeId ), port,
internalProtocolVersion, applicationProtocolVersion, verifier, chunkSize );
}
public MadeUpServer server( MadeUpCommunicationInterface target )
{
return new MadeUpServer(
target, port, internalProtocolVersion, applicationProtocolVersion, verifier, chunkSize );
}
public MadeUpClient client()
{
return new MadeUpClient( port, storeId, internalProtocolVersion, applicationProtocolVersion, chunkSize,
ResponseUnpacker.NO_OP_RESPONSE_UNPACKER );
}
public MadeUpClient clientWith( ResponseUnpacker responseUnpacker )
{
return new MadeUpClient( port, storeId, internalProtocolVersion, applicationProtocolVersion, chunkSize,
responseUnpacker );
}
public ServerInterface serverInOtherJvm()
{
ServerInterface server = new MadeUpServerProcess().start( new StartupData(
storeId.getCreationTime(), storeId.getRandomId(), internalProtocolVersion,
applicationProtocolVersion, chunkSize ) );
server.awaitStarted();
return server;
}
}
public class TransactionStreamVerifyingResponseHandler
implements Response.Handler, Visitor<CommittedTransactionRepresentation,Exception>
{
private final long txCount;
private long expectedTxId = 1;
public TransactionStreamVerifyingResponseHandler( int txCount )
{
this.txCount = txCount;
}
@Override
public void obligation( long txId ) throws IOException
{
fail( "Should not called" );
}
@Override
public Visitor<CommittedTransactionRepresentation,Exception> transactions()
{
return this;
}
@Override
public boolean visit( CommittedTransactionRepresentation element ) throws IOException
{
assertEquals( expectedTxId + TransactionIdStore.BASE_TX_ID, element.getCommitEntry().getTxId() );
expectedTxId++;
assertThat( element.getCommitEntry().getTxId(), lessThanOrEqualTo( txCount + TransactionIdStore.BASE_TX_ID ) );
return false;
}
}
public class TransactionObligationVerifyingResponseHandler implements Response.Handler
{
volatile long obligationTxId;
@Override
public void obligation( long txId )
{
this.obligationTxId = txId;
}
@Override
public Visitor<CommittedTransactionRepresentation,Exception> transactions()
{
throw new UnsupportedOperationException( "Should not be called" );
}
}
}