Java Code Examples for io.atomix.primitive.session.SessionId#from()

The following examples show how to use io.atomix.primitive.session.SessionId#from() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RaftSessionSequencerTest.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Tests sequencing callbacks with the sequencer.
 */
@Test
public void testSequenceResponses() throws Throwable {
  RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
  long sequence1 = sequencer.nextRequest();
  long sequence2 = sequencer.nextRequest();
  assertTrue(sequence2 == sequence1 + 1);

  CommandResponse commandResponse = CommandResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(2)
      .withEventIndex(0)
      .build();

  QueryResponse queryResponse = QueryResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(2)
      .withEventIndex(0)
      .build();

  AtomicBoolean run = new AtomicBoolean();
  sequencer.sequenceResponse(sequence2, queryResponse, () -> run.set(true));
  sequencer.sequenceResponse(sequence1, commandResponse, () -> assertFalse(run.get()));
  assertTrue(run.get());
}
 
Example 2
Source File: RaftSessionSequencerTest.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Tests sequencing an event that arrives before a command response.
 */
@Test
public void testSequenceEventAbsentCommand() throws Throwable {
  RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));

  PublishRequest request1 = PublishRequest.builder()
      .withSession(1)
      .withEventIndex(2)
      .withPreviousIndex(0)
      .withEvents(Collections.emptyList())
      .build();

  PublishRequest request2 = PublishRequest.builder()
      .withSession(1)
      .withEventIndex(3)
      .withPreviousIndex(2)
      .withEvents(Collections.emptyList())
      .build();

  AtomicInteger run = new AtomicInteger();
  sequencer.sequenceEvent(request1, () -> assertEquals(0, run.getAndIncrement()));
  sequencer.sequenceEvent(request2, () -> assertEquals(1, run.getAndIncrement()));
  assertEquals(2, run.get());
}
 
Example 3
Source File: RaftSessionInvokerTest.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Tests submitting a command to the cluster.
 */
@Test
public void testSubmitCommand() throws Throwable {
  RaftSessionConnection connection = mock(RaftSessionConnection.class);
  when(connection.command(any(CommandRequest.class)))
      .thenReturn(CompletableFuture.completedFuture(CommandResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withIndex(10)
          .withResult("Hello world!".getBytes())
          .build()));

  RaftSessionState state = new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000);
  RaftSessionManager manager = mock(RaftSessionManager.class);
  ThreadContext threadContext = new TestContext();

  RaftSessionInvoker submitter = new RaftSessionInvoker(connection, mock(RaftSessionConnection.class), state, new RaftSessionSequencer(state), manager, threadContext);
  assertArrayEquals(submitter.invoke(operation(COMMAND, HeapBytes.EMPTY)).get(), "Hello world!".getBytes());
  assertEquals(1, state.getCommandRequest());
  assertEquals(1, state.getCommandResponse());
  assertEquals(10, state.getResponseIndex());
}
 
Example 4
Source File: RaftSessionSequencerTest.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Tests sequencing an event that arrives before a command response.
 */
@Test
public void testSequenceEventAtCommand() throws Throwable {
  RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
  long sequence = sequencer.nextRequest();

  PublishRequest request = PublishRequest.builder()
      .withSession(1)
      .withEventIndex(2)
      .withPreviousIndex(0)
      .withEvents(Collections.emptyList())
      .build();

  CommandResponse response = CommandResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(2)
      .withEventIndex(2)
      .build();

  AtomicInteger run = new AtomicInteger();
  sequencer.sequenceResponse(sequence, response, () -> assertEquals(1, run.getAndIncrement()));
  sequencer.sequenceEvent(request, () -> assertEquals(0, run.getAndIncrement()));
  assertEquals(2, run.get());
}
 
Example 5
Source File: RaftSessionRegistryTest.java    From atomix with Apache License 2.0 6 votes vote down vote up
private RaftSession createSession(long sessionId) {
  RaftServiceContext context = mock(RaftServiceContext.class);
  when(context.serviceType()).thenReturn(TestPrimitiveType.instance());
  when(context.serviceName()).thenReturn("test");
  when(context.serviceId()).thenReturn(PrimitiveId.from(1));

  RaftContext server = mock(RaftContext.class);
  when(server.getProtocol()).thenReturn(mock(RaftServerProtocol.class));
  RaftServiceManager manager = mock(RaftServiceManager.class);
  when(manager.executor()).thenReturn(mock(ThreadContext.class));
  when(server.getServiceManager()).thenReturn(manager);

  return new RaftSession(
      SessionId.from(sessionId),
      MemberId.from("1"),
      "test",
      TestPrimitiveType.instance(),
      ReadConsistency.LINEARIZABLE,
      100,
      5000,
      System.currentTimeMillis(),
      Serializer.using(Namespaces.BASIC),
      context,
      server,
      mock(ThreadContextFactory.class));
}
 
Example 6
Source File: RaftSessionSequencerTest.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Tests sequencing an event that arrives before a command response.
 */
@Test
public void testSequenceEventAfterCommand() throws Throwable {
  RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
  long sequence = sequencer.nextRequest();

  PublishRequest request = PublishRequest.builder()
      .withSession(1)
      .withEventIndex(1)
      .withPreviousIndex(0)
      .withEvents(Collections.emptyList())
      .build();

  CommandResponse response = CommandResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(2)
      .withEventIndex(1)
      .build();

  AtomicInteger run = new AtomicInteger();
  sequencer.sequenceResponse(sequence, response, () -> assertEquals(0, run.getAndIncrement()));
  sequencer.sequenceEvent(request, () -> assertEquals(1, run.getAndIncrement()));
  assertEquals(2, run.get());
}
 
Example 7
Source File: RaftSessionSequencerTest.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Tests sequencing an event that arrives before a command response.
 */
@Test
public void testSequenceEventBeforeCommand() throws Throwable {
  RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
  long sequence = sequencer.nextRequest();

  PublishRequest request = PublishRequest.builder()
      .withSession(1)
      .withEventIndex(1)
      .withPreviousIndex(0)
      .withEvents(Collections.emptyList())
      .build();

  CommandResponse response = CommandResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(2)
      .withEventIndex(1)
      .build();

  AtomicInteger run = new AtomicInteger();
  sequencer.sequenceEvent(request, () -> assertEquals(0, run.getAndIncrement()));
  sequencer.sequenceResponse(sequence, response, () -> assertEquals(1, run.getAndIncrement()));
  assertEquals(2, run.get());
}
 
Example 8
Source File: RaftSessionStateTest.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Tests updating client session state.
 */
@Test
public void testSessionState() {
  RaftSessionState state = new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000);
  assertEquals(state.getSessionId(), SessionId.from(1));
  assertEquals(1, state.getResponseIndex());
  assertEquals(1, state.getEventIndex());
  state.setCommandRequest(2);
  assertEquals(2, state.getCommandRequest());
  assertEquals(3, state.nextCommandRequest());
  assertEquals(3, state.getCommandRequest());
  state.setCommandResponse(3);
  assertEquals(3, state.getCommandResponse());
  state.setResponseIndex(4);
  assertEquals(4, state.getResponseIndex());
  state.setResponseIndex(3);
  assertEquals(4, state.getResponseIndex());
  state.setEventIndex(5);
  assertEquals(5, state.getEventIndex());
}
 
Example 9
Source File: RaftServiceManager.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Applies an open session entry to the state machine.
 */
private long applyOpenSession(Indexed<OpenSessionEntry> entry) {
  PrimitiveType primitiveType = raft.getPrimitiveTypes().getPrimitiveType(entry.entry().serviceType());

  // Get the state machine executor or create one if it doesn't already exist.
  RaftServiceContext service = getOrInitializeService(
      PrimitiveId.from(entry.index()),
      primitiveType,
      entry.entry().serviceName(),
      entry.entry().serviceConfig());

  if (service == null) {
    throw new RaftException.UnknownService("Unknown service type " + entry.entry().serviceType());
  }

  SessionId sessionId = SessionId.from(entry.index());
  RaftSession session = raft.getSessions().addSession(new RaftSession(
      sessionId,
      MemberId.from(entry.entry().memberId()),
      entry.entry().serviceName(),
      primitiveType,
      entry.entry().readConsistency(),
      entry.entry().minTimeout(),
      entry.entry().maxTimeout(),
      entry.entry().timestamp(),
      service.serializer(),
      service,
      raft,
      threadContextFactory));
  return service.openSession(entry.index(), entry.entry().timestamp(), session);
}
 
Example 10
Source File: RaftSessionSequencerTest.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Tests sequencing an event that arrives before a command response.
 */
@Test
public void testSequenceEventAfterAllCommands() throws Throwable {
  RaftSessionSequencer sequencer = new RaftSessionSequencer(new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000));
  long sequence = sequencer.nextRequest();

  PublishRequest request1 = PublishRequest.builder()
      .withSession(1)
      .withEventIndex(2)
      .withPreviousIndex(0)
      .withEvents(Collections.emptyList())
      .build();

  PublishRequest request2 = PublishRequest.builder()
      .withSession(1)
      .withEventIndex(3)
      .withPreviousIndex(2)
      .withEvents(Collections.emptyList())
      .build();

  CommandResponse response = CommandResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(2)
      .withEventIndex(2)
      .build();

  AtomicInteger run = new AtomicInteger();
  sequencer.sequenceEvent(request1, () -> assertEquals(0, run.getAndIncrement()));
  sequencer.sequenceEvent(request2, () -> assertEquals(2, run.getAndIncrement()));
  sequencer.sequenceResponse(sequence, response, () -> assertEquals(1, run.getAndIncrement()));
  assertEquals(3, run.get());
}
 
Example 11
Source File: RaftSessionInvokerTest.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Tests skipping over a failed query attempt.
 */
@Test
public void testSkippingOverFailedQuery() throws Throwable {
  CompletableFuture<QueryResponse> future1 = new CompletableFuture<>();
  CompletableFuture<QueryResponse> future2 = new CompletableFuture<>();

  RaftSessionConnection connection = mock(RaftSessionConnection.class);
  Mockito.when(connection.query(any(QueryRequest.class)))
      .thenReturn(future1)
      .thenReturn(future2);

  RaftSessionState state = new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000);
  RaftSessionManager manager = mock(RaftSessionManager.class);
  ThreadContext threadContext = new TestContext();

  RaftSessionInvoker submitter = new RaftSessionInvoker(mock(RaftSessionConnection.class), connection, state, new RaftSessionSequencer(state), manager, threadContext);

  CompletableFuture<byte[]> result1 = submitter.invoke(operation(QUERY));
  CompletableFuture<byte[]> result2 = submitter.invoke(operation(QUERY));

  assertEquals(1, state.getResponseIndex());

  assertFalse(result1.isDone());
  assertFalse(result2.isDone());

  future1.completeExceptionally(new RaftException.QueryFailure("failure"));
  future2.complete(QueryResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(10)
      .withResult("Hello world!".getBytes())
      .build());

  assertTrue(result1.isCompletedExceptionally());
  assertTrue(result2.isDone());
  assertTrue(Arrays.equals(result2.get(), "Hello world!".getBytes()));

  assertEquals(10, state.getResponseIndex());
}
 
Example 12
Source File: PrimaryBackupServiceContext.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a service session.
 *
 * @param sessionId the session to create
 * @param memberId  the owning node ID
 * @return the service session
 */
public PrimaryBackupSession createSession(long sessionId, MemberId memberId) {
  PrimaryBackupSession session = new PrimaryBackupSession(SessionId.from(sessionId), memberId, service.serializer(), this);
  if (sessions.putIfAbsent(sessionId, session) == null) {
    service.register(session);
  }
  return session;
}
 
Example 13
Source File: RaftSessionStateTest.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Tests session state defaults.
 */
@Test
public void testSessionStateDefaults() {
  String sessionName = UUID.randomUUID().toString();
  RaftSessionState state = new RaftSessionState("test", SessionId.from(1), sessionName, TestPrimitiveType.instance(), 1000);
  assertEquals(state.getSessionId(), SessionId.from(1));
  assertEquals(sessionName, state.getPrimitiveName());
  assertEquals("test", state.getPrimitiveType().name());
  assertEquals(0, state.getCommandRequest());
  assertEquals(0, state.getCommandResponse());
  assertEquals(1, state.getResponseIndex());
  assertEquals(1, state.getEventIndex());
}
 
Example 14
Source File: RaftSessionInvokerTest.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that the client's session is expired when an UnknownSessionException is received from the cluster.
 */
@Test
public void testExpireSessionOnCommandFailure() throws Throwable {
  CompletableFuture<CommandResponse> future = new CompletableFuture<>();

  RaftSessionConnection connection = mock(RaftSessionConnection.class);
  Mockito.when(connection.command(any(CommandRequest.class))).thenReturn(future);

  RaftSessionState state = new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000);
  RaftSessionManager manager = mock(RaftSessionManager.class);
  ThreadContext threadContext = new TestContext();

  RaftSessionInvoker submitter = new RaftSessionInvoker(connection, mock(RaftSessionConnection.class), state, new RaftSessionSequencer(state), manager, threadContext);

  CompletableFuture<byte[]> result = submitter.invoke(operation(COMMAND));

  assertEquals(1, state.getResponseIndex());

  assertFalse(result.isDone());

  future.completeExceptionally(new RaftException.UnknownSession("unknown session"));

  assertTrue(result.isCompletedExceptionally());
}
 
Example 15
Source File: RaftSessionInvokerTest.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that the client's session is expired when an UnknownSessionException is received from the cluster.
 */
@Test
public void testExpireSessionOnQueryFailure() throws Throwable {
  CompletableFuture<QueryResponse> future = new CompletableFuture<>();

  RaftSessionConnection connection = mock(RaftSessionConnection.class);
  Mockito.when(connection.query(any(QueryRequest.class)))
      .thenReturn(future);

  RaftSessionState state = new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000);
  RaftSessionManager manager = mock(RaftSessionManager.class);
  ThreadContext threadContext = new TestContext();

  RaftSessionInvoker submitter = new RaftSessionInvoker(mock(RaftSessionConnection.class), connection, state, new RaftSessionSequencer(state), manager, threadContext);

  CompletableFuture<byte[]> result = submitter.invoke(operation(QUERY));

  assertEquals(1, state.getResponseIndex());

  assertFalse(result.isDone());

  future.completeExceptionally(new RaftException.UnknownSession("unknown session"));

  assertTrue(result.isCompletedExceptionally());
}
 
Example 16
Source File: RaftSessionInvokerTest.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Tests resequencing a query response.
 */
@Test
public void testResequenceQuery() throws Throwable {
  CompletableFuture<QueryResponse> future1 = new CompletableFuture<>();
  CompletableFuture<QueryResponse> future2 = new CompletableFuture<>();

  RaftSessionConnection connection = mock(RaftSessionConnection.class);
  Mockito.when(connection.query(any(QueryRequest.class)))
      .thenReturn(future1)
      .thenReturn(future2);

  RaftSessionState state = new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000);
  RaftSessionManager manager = mock(RaftSessionManager.class);
  ThreadContext threadContext = new TestContext();

  RaftSessionInvoker submitter = new RaftSessionInvoker(mock(RaftSessionConnection.class), connection, state, new RaftSessionSequencer(state), manager, threadContext);

  CompletableFuture<byte[]> result1 = submitter.invoke(operation(QUERY));
  CompletableFuture<byte[]> result2 = submitter.invoke(operation(QUERY));

  future2.complete(QueryResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(10)
      .withResult("Hello world again!".getBytes())
      .build());

  assertEquals(1, state.getResponseIndex());

  assertFalse(result1.isDone());
  assertFalse(result2.isDone());

  future1.complete(QueryResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(9)
      .withResult("Hello world!".getBytes())
      .build());

  assertTrue(result1.isDone());
  assertTrue(Arrays.equals(result1.get(), "Hello world!".getBytes()));
  assertTrue(result2.isDone());
  assertTrue(Arrays.equals(result2.get(), "Hello world again!".getBytes()));

  assertEquals(10, state.getResponseIndex());
}
 
Example 17
Source File: RaftSessionInvokerTest.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Test resequencing a command response.
 */
@Test
public void testResequenceCommand() throws Throwable {
  CompletableFuture<CommandResponse> future1 = new CompletableFuture<>();
  CompletableFuture<CommandResponse> future2 = new CompletableFuture<>();

  RaftSessionConnection connection = mock(RaftSessionConnection.class);
  Mockito.when(connection.command(any(CommandRequest.class)))
      .thenReturn(future1)
      .thenReturn(future2);

  RaftSessionState state = new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000);
  RaftSessionManager manager = mock(RaftSessionManager.class);
  ThreadContext threadContext = new TestContext();

  RaftSessionInvoker submitter = new RaftSessionInvoker(connection, mock(RaftSessionConnection.class), state, new RaftSessionSequencer(state), manager, threadContext);

  CompletableFuture<byte[]> result1 = submitter.invoke(operation(COMMAND));
  CompletableFuture<byte[]> result2 = submitter.invoke(operation(COMMAND));

  future2.complete(CommandResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(10)
      .withResult("Hello world again!".getBytes())
      .build());

  assertEquals(2, state.getCommandRequest());
  assertEquals(0, state.getCommandResponse());
  assertEquals(1, state.getResponseIndex());

  assertFalse(result1.isDone());
  assertFalse(result2.isDone());

  future1.complete(CommandResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(9)
      .withResult("Hello world!".getBytes())
      .build());

  assertTrue(result1.isDone());
  assertTrue(Arrays.equals(result1.get(), "Hello world!".getBytes()));
  assertTrue(result2.isDone());
  assertTrue(Arrays.equals(result2.get(), "Hello world again!".getBytes()));

  assertEquals(2, state.getCommandRequest());
  assertEquals(2, state.getCommandResponse());
  assertEquals(10, state.getResponseIndex());
}
 
Example 18
Source File: RaftSessionInvokerTest.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Test
public void testReSubmitCommand() throws Throwable {
  // given
  // setup  thread context
  final Logger log = LoggerFactory.getLogger(getClass());
  final int threadPoolSize = Math.max(Math.min(Runtime.getRuntime().availableProcessors() * 2, 16), 4);
  final ThreadContext context = new BlockingAwareThreadPoolContextFactory(
      "raft-partition-group-data-%d", threadPoolSize, log).createContext();

  // collecting request futures
  final List<CompletableFuture<CommandResponse>> futures = new CopyOnWriteArrayList<>();
  final List<Long> sequences = new CopyOnWriteArrayList<>();
  final RaftSessionConnection connection = mock(RaftSessionConnection.class);
  when(connection.command(any(CommandRequest.class)))
      .thenAnswer(invocationOnMock -> {
        final CommandRequest commandRequest = (CommandRequest) invocationOnMock.getArguments()[0];
        sequences.add(commandRequest.sequenceNumber());
        final CompletableFuture<CommandResponse> future = new CompletableFuture<>();
        futures.add(future);
        return future;
      });

  // raft session invoker
  final RaftSessionState state = new RaftSessionState("test", SessionId.from(1), UUID.randomUUID().toString(), TestPrimitiveType.instance(), 1000);
  final RaftSessionManager manager = mock(RaftSessionManager.class);
  final RaftSessionInvoker submitter =
      new RaftSessionInvoker(connection,
          mock(RaftSessionConnection.class),
          state,
          new RaftSessionSequencer(state),
          manager,
          context);

  // send five commands
  submitter.invoke(operation(COMMAND, HeapBytes.EMPTY));
  submitter.invoke(operation(COMMAND, HeapBytes.EMPTY));
  submitter.invoke(operation(COMMAND, HeapBytes.EMPTY));
  submitter.invoke(operation(COMMAND, HeapBytes.EMPTY));
  final CompletableFuture<byte[]> lastFuture = submitter.invoke(operation(COMMAND, HeapBytes.EMPTY));

  verify(connection, timeout(2000).times(5)).command(any());

  // when we missed second command
  futures.get(0).complete(CommandResponse.builder()
      .withStatus(RaftResponse.Status.OK)
      .withIndex(10)
      .withResult("Hello world!".getBytes())
      .build());
  final ArrayList<CompletableFuture<CommandResponse>> copiedFutures = new ArrayList<>(futures.subList(1, futures.size()));
  futures.clear();
  sequences.clear();
  copiedFutures.forEach(f ->
      f.complete(CommandResponse.builder()
        .withStatus(RaftResponse.Status.ERROR)
        .withError(RaftError.Type.COMMAND_FAILURE)
        .withLastSequence(1)
        .build()));

  // then session invoker should resubmit 4 commands
  verify(connection, timeout(2000).times(9)).command(any());
  final CountDownLatch latch = new CountDownLatch(1);
  // context thread pool ensures execution of task in order
  context.execute(latch::countDown);
  latch.await();

  assertEquals(4, futures.size());
  assertArrayEquals(new Long[]{2L, 3L, 4L, 5L}, sequences.toArray(new Long[0]));

  futures.forEach(f -> f.complete(CommandResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withIndex(10)
          .withResult("Hello world!".getBytes())
          .build()));

  assertArrayEquals(lastFuture.get(), "Hello world!".getBytes());
  assertEquals(5, state.getCommandRequest());
  assertEquals(5, state.getCommandResponse());
  assertEquals(10, state.getResponseIndex());
}
 
Example 19
Source File: RaftServiceContext.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Installs a snapshot.
 */
public void installSnapshot(SnapshotReader reader) {
  log.debug("Installing snapshot {}", reader.snapshot().index());
  reader.skip(Bytes.LONG); // Skip the service ID
  PrimitiveType primitiveType;
  try {
    primitiveType = raft.getPrimitiveTypes().getPrimitiveType(reader.readString());
  } catch (ConfigurationException e) {
    log.error(e.getMessage(), e);
    return;
  }

  String serviceName = reader.readString();
  currentIndex = reader.readLong();
  currentTimestamp = reader.readLong();
  timestampDelta = reader.readLong();

  int sessionCount = reader.readInt();
  for (int i = 0; i < sessionCount; i++) {
    SessionId sessionId = SessionId.from(reader.readLong());
    MemberId node = MemberId.from(reader.readString());
    ReadConsistency readConsistency = ReadConsistency.valueOf(reader.readString());
    long minTimeout = reader.readLong();
    long maxTimeout = reader.readLong();
    long sessionTimestamp = reader.readLong();

    // Only create a new session if one does not already exist. This is necessary to ensure only a single session
    // is ever opened and exposed to the state machine.
    RaftSession session = raft.getSessions().addSession(new RaftSession(
        sessionId,
        node,
        serviceName,
        primitiveType,
        readConsistency,
        minTimeout,
        maxTimeout,
        sessionTimestamp,
        service.serializer(),
        this,
        raft,
        threadContextFactory));

    session.setRequestSequence(reader.readLong());
    session.setCommandSequence(reader.readLong());
    session.setEventIndex(reader.readLong());
    session.setLastCompleted(reader.readLong());
    session.setLastApplied(reader.snapshot().index());
    session.setLastUpdated(sessionTimestamp);
    session.open();
    service.register(sessions.addSession(session));
  }
  service.restore(new DefaultBackupInput(reader, service.serializer()));
}
 
Example 20
Source File: PrimaryBackupTest.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the next unique session identifier.
 */
private SessionId nextSessionId() {
  return SessionId.from(++sessionId);
}