Search in sources :

Example 46 with FakeClock

use of org.neo4j.time.FakeClock in project neo4j by neo4j.

the class TransactionHandleRegistryTest method shouldProvideInterruptHandlerForActiveTransaction.

@Test
void shouldProvideInterruptHandlerForActiveTransaction() throws TransactionLifecycleException {
    // Given
    AssertableLogProvider logProvider = new AssertableLogProvider();
    FakeClock clock = Clocks.fakeClock();
    var memoryPool = mock(MemoryPool.class);
    int timeoutLength = 123;
    TransactionHandleRegistry registry = new TransactionHandleRegistry(clock, Duration.ofMillis(timeoutLength), logProvider, memoryPool);
    TransactionHandle handle = mock(TransactionHandle.class);
    // Active Tx in Registry
    long id = registry.begin(handle);
    // When
    registry.terminate(id);
    // Then
    verify(handle).terminate();
    verifyNoMoreInteractions(handle);
    verify(memoryPool).reserveHeap(TransactionHandleRegistry.ACTIVE_TRANSACTION_SHALLOW_SIZE);
    verify(memoryPool).releaseHeap(TransactionHandleRegistry.ACTIVE_TRANSACTION_SHALLOW_SIZE);
    verifyNoMoreInteractions(memoryPool);
}
Also used : FakeClock(org.neo4j.time.FakeClock) AssertableLogProvider(org.neo4j.logging.AssertableLogProvider) Test(org.junit.jupiter.api.Test)

Example 47 with FakeClock

use of org.neo4j.time.FakeClock in project neo4j by neo4j.

the class DelayedBufferTest method shouldHandleTheWholeWorkloadShebang.

@Test
void shouldHandleTheWholeWorkloadShebang() throws Throwable {
    // GIVEN
    final int size = 1_000;
    final long bufferTime = 3;
    VerifyingConsumer consumer = new VerifyingConsumer(size);
    final FakeClock clock = Clocks.fakeClock();
    Supplier<Long> chunkThreshold = clock::millis;
    AtomicBoolean end = new AtomicBoolean();
    Predicate<Long> safeThreshold = time -> end.get() || clock.millis() - bufferTime >= time;
    final DelayedBuffer<Long> buffer = new DelayedBuffer<>(chunkThreshold, safeThreshold, 10, consumer);
    MaintenanceThread maintenance = new MaintenanceThread(buffer, 5);
    Race adders = new Race();
    final int numberOfAdders = 20;
    final byte[] offeredIds = new byte[size];
    for (int i = 0; i < numberOfAdders; i++) {
        final int finalI = i;
        adders.addContestant(() -> {
            for (int j = 0; j < size; j++) {
                if (j % numberOfAdders == finalI) {
                    buffer.offer(j);
                    offeredIds[j] = 1;
                    clock.forward(2, MILLISECONDS);
                }
            }
        });
    }
    // WHEN (multi-threaded) offering of ids
    adders.go();
    // ... ensuring the test is sane itself (did we really offer all these IDs?)
    for (int i = 0; i < size; i++) {
        assertEquals((byte) 1, offeredIds[i], "ID " + i);
    }
    maintenance.halt();
    end.set(true);
    buffer.maintenance(NULL);
    buffer.close();
    // THEN
    consumer.assertHaveOnlySeenRange(0, size - 1);
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) Suppliers.singleton(org.neo4j.function.Suppliers.singleton) Predicate(java.util.function.Predicate) CursorContext(org.neo4j.io.pagecache.context.CursorContext) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) CONCURRENT(org.junit.jupiter.api.parallel.ExecutionMode.CONCURRENT) Supplier(java.util.function.Supplier) Test(org.junit.jupiter.api.Test) LockSupport(java.util.concurrent.locks.LockSupport) AtomicLong(java.util.concurrent.atomic.AtomicLong) FakeClock(org.neo4j.time.FakeClock) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) NULL(org.neo4j.io.pagecache.context.CursorContext.NULL) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Execution(org.junit.jupiter.api.parallel.Execution) Clocks(org.neo4j.time.Clocks) Predicates.alwaysTrue(org.neo4j.function.Predicates.alwaysTrue) Race(org.neo4j.test.Race) Numbers.safeCastLongToInt(org.neo4j.internal.helpers.Numbers.safeCastLongToInt) Mockito.mock(org.mockito.Mockito.mock) FakeClock(org.neo4j.time.FakeClock) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Race(org.neo4j.test.Race) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.junit.jupiter.api.Test)

Example 48 with FakeClock

use of org.neo4j.time.FakeClock in project neo4j by neo4j.

the class CappedLoggerTest method mustNotLogMessagesWithinConfiguredTimeLimit.

@ParameterizedTest(name = "{1}")
@MethodSource("argumentsProvider")
public void mustNotLogMessagesWithinConfiguredTimeLimit(LogMethod logMethod, String name) {
    FakeClock clock = getDefaultFakeClock();
    logger = new CappedLogger(logProvider.getLog(CappedLogger.class), 1, TimeUnit.MILLISECONDS, clock);
    logMethod.log(logger, "### AAA ###");
    logMethod.log(logger, "### BBB ###");
    clock.forward(1, TimeUnit.MILLISECONDS);
    logMethod.log(logger, "### CCC ###");
    assertThat(logProvider).containsMessages("### AAA ###");
    assertThat(logProvider).forClass(CappedLogger.class).doesNotContainMessage("### BBB ###");
    assertThat(logProvider).containsMessages("### CCC ###");
}
Also used : FakeClock(org.neo4j.time.FakeClock) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 49 with FakeClock

use of org.neo4j.time.FakeClock in project neo4j by neo4j.

the class LoggingIndexedIdGeneratorMonitorTest method shouldDumpLogFilesInCorrectOrder.

@Test
void shouldDumpLogFilesInCorrectOrder() throws IOException {
    // given
    Path file = directory.file("file");
    FakeClock clock = Clocks.fakeClock();
    int numberOfIds = 100;
    try (LoggingIndexedIdGeneratorMonitor monitor = new LoggingIndexedIdGeneratorMonitor(fs, file, clock, 100, ByteUnit.Byte, 1, SECONDS)) {
        for (int i = 0; i < numberOfIds; i++) {
            monitor.allocatedFromHigh(i);
            clock.forward(50, MILLISECONDS);
            monitor.markSessionDone();
        }
    }
    // when/then
    MutableLong lastId = new MutableLong(-1);
    LoggingIndexedIdGeneratorMonitor.Dumper dumper = new LoggingIndexedIdGeneratorMonitor.Dumper() {

        private long lastFileMillis = -1;

        private boolean lastFileWasTheBaseFile;

        @Override
        public void path(Path dumpFile) {
            assertFalse(lastFileWasTheBaseFile);
            long timestamp = LoggingIndexedIdGeneratorMonitor.millisOf(dumpFile);
            if (lastFileMillis != -1) {
                assertTrue(timestamp > lastFileMillis);
            }
            lastFileMillis = timestamp;
            if (dumpFile.equals(file)) {
                lastFileWasTheBaseFile = true;
            }
        }

        @Override
        public void type(LoggingIndexedIdGeneratorMonitor.Type type, long time) {
        }

        @Override
        public void typeAndId(LoggingIndexedIdGeneratorMonitor.Type type, long time, long id) {
            if (lastId.longValue() != -1) {
                assertTrue(id > lastId.longValue());
            }
            lastId.setValue(id);
        }

        @Override
        public void typeAndTwoIds(LoggingIndexedIdGeneratorMonitor.Type type, long time, long id1, long id2) {
        }
    };
    LoggingIndexedIdGeneratorMonitor.dump(fs, file, dumper);
    assertEquals(numberOfIds - 1, lastId.getValue());
}
Also used : Path(java.nio.file.Path) MutableLong(org.apache.commons.lang3.mutable.MutableLong) FakeClock(org.neo4j.time.FakeClock) Test(org.junit.jupiter.api.Test)

Example 50 with FakeClock

use of org.neo4j.time.FakeClock in project neo4j by neo4j.

the class LoggingIndexedIdGeneratorMonitorTest method shouldRotateAndPrune.

@Test
void shouldRotateAndPrune() throws IOException {
    // given
    long sizeOfOneEntry = LoggingIndexedIdGeneratorMonitor.HEADER_SIZE + Long.BYTES;
    Path file = directory.file("file");
    FakeClock clock = Clocks.fakeClock();
    int entriesPerFile = 10;
    // when
    try (LoggingIndexedIdGeneratorMonitor monitor = new LoggingIndexedIdGeneratorMonitor(fs, file, clock, sizeOfOneEntry * entriesPerFile, ByteUnit.Byte, 3500, MILLISECONDS)) {
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < entriesPerFile; j++) {
                monitor.markedAsUsed(0);
            }
            clock.forward(1, SECONDS);
            monitor.markSessionDone();
            MutableLong numberOfFiles = new MutableLong();
            try (DirectoryStream<Path> paths = Files.newDirectoryStream(file.getParent(), entry -> entry.getFileName().toString().startsWith(file.getFileName() + "-"))) {
                paths.forEach(p -> numberOfFiles.increment());
            }
            assertEquals(min(i + 1, 4), numberOfFiles.getValue());
        }
    }
}
Also used : Path(java.nio.file.Path) MutableLong(org.apache.commons.lang3.mutable.MutableLong) FakeClock(org.neo4j.time.FakeClock) Test(org.junit.jupiter.api.Test)

Aggregations

FakeClock (org.neo4j.time.FakeClock)111 Test (org.junit.Test)82 Test (org.junit.jupiter.api.Test)21 AssertableLogProvider (org.neo4j.logging.AssertableLogProvider)20 ControlledRenewableTimeoutService (org.neo4j.causalclustering.core.consensus.schedule.ControlledRenewableTimeoutService)17 MembershipEntry (org.neo4j.causalclustering.core.consensus.membership.MembershipEntry)16 RaftCoreState (org.neo4j.causalclustering.core.state.snapshot.RaftCoreState)16 ExecutingQuery (org.neo4j.kernel.api.query.ExecutingQuery)9 QueryLogger (org.neo4j.kernel.impl.query.QueryLoggerKernelExtension.QueryLogger)9 User (org.neo4j.kernel.impl.security.User)9 FollowerState (org.neo4j.causalclustering.core.consensus.roles.follower.FollowerState)7 Channel (org.jboss.netty.channel.Channel)5 Path (java.nio.file.Path)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 Response (javax.ws.rs.core.Response)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 InputStream (java.io.InputStream)3 ExecutionException (java.util.concurrent.ExecutionException)3 BeforeEach (org.junit.jupiter.api.BeforeEach)3 RaftMachine (org.neo4j.causalclustering.core.consensus.RaftMachine)3