io.aeron.Subscription Java Examples

The following examples show how to use io.aeron.Subscription. 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: Common.java    From aeron with Apache License 2.0 6 votes vote down vote up
static void consume(final Subscription subscription, final int count, final String prefix)
{
    final MutableInteger received = new MutableInteger(0);

    final FragmentHandler fragmentHandler = new FragmentAssembler(
        (buffer, offset, length, header) ->
        {
            final String expected = prefix + received.value;
            final String actual = buffer.getStringWithoutLengthAscii(offset, length);

            assertEquals(expected, actual);

            received.value++;
        });

    while (received.value < count)
    {
        if (0 == subscription.poll(fragmentHandler, FRAGMENT_LIMIT))
        {
            Tests.yield();
        }
    }

    assertEquals(count, received.get());
}
 
Example #2
Source File: GapFiller.java    From artio with Apache License 2.0 6 votes vote down vote up
public GapFiller(
    final Subscription inboundSubscription,
    final GatewayPublication publication,
    final String agentNamePrefix,
    final SenderSequenceNumbers senderSequenceNumbers,
    final ReplayerCommandQueue replayerCommandQueue,
    final FixSessionCodecsFactory fixSessionCodecsFactory)
{
    this.inboundSubscription = inboundSubscription;
    this.publication = publication;
    this.agentNamePrefix = agentNamePrefix;
    this.senderSequenceNumbers = senderSequenceNumbers;
    this.replayerCommandQueue = replayerCommandQueue;
    this.fixSessionCodecsFactory = fixSessionCodecsFactory;
    this.protocolSubscription = ProtocolSubscription.of(this, fixSessionCodecsFactory);
}
 
Example #3
Source File: EmbeddedPingPong.java    From aeron with Apache License 2.0 6 votes vote down vote up
private static Thread startPong(final Aeron aeron)
{
    return new Thread(() ->
    {
        System.out.println("Subscribing Ping at " + PING_CHANNEL + " on stream id " + PING_STREAM_ID);
        System.out.println("Publishing Pong at " + PONG_CHANNEL + " on stream id " + PONG_STREAM_ID);

        try (Subscription pingSubscription = aeron.addSubscription(PING_CHANNEL, PING_STREAM_ID);
            Publication pongPublication = EXCLUSIVE_PUBLICATIONS ?
                aeron.addExclusivePublication(PONG_CHANNEL, PONG_STREAM_ID) :
                aeron.addPublication(PONG_CHANNEL, PONG_STREAM_ID))
        {
            final BufferClaim bufferClaim = new BufferClaim();
            final FragmentHandler fragmentHandler = (buffer, offset, length, header) ->
                pingHandler(bufferClaim, pongPublication, buffer, offset, length, header);

            while (RUNNING.get())
            {
                PING_HANDLER_IDLE_STRATEGY.idle(pingSubscription.poll(fragmentHandler, FRAME_COUNT_LIMIT));
            }

            System.out.println("Shutting down...");
        }
    });
}
 
Example #4
Source File: Indexer.java    From artio with Apache License 2.0 6 votes vote down vote up
public Indexer(
    final List<Index> indices,
    final Subscription subscription,
    final String agentNamePrefix,
    final CompletionPosition completionPosition,
    final AeronArchive aeronArchive,
    final ErrorHandler errorHandler,
    final int archiveReplayStream,
    final boolean gracefulShutdown)
{
    this.indices = indices;
    this.subscription = subscription;
    this.agentNamePrefix = agentNamePrefix;
    this.completionPosition = completionPosition;
    this.archiveReplayStream = archiveReplayStream;
    this.gracefulShutdown = gracefulShutdown;
    catchIndexUp(aeronArchive, errorHandler);
}
 
Example #5
Source File: ArchiveTests.java    From aeron with Apache License 2.0 6 votes vote down vote up
static void awaitResponse(final Subscription controlResponse, final long expectedCorrelationId)
{
    final ControlResponseAdapter controlResponseAdapter = new ControlResponseAdapter(
        new FailControlResponseListener()
        {
            public void onResponse(
                final long controlSessionId,
                final long correlationId,
                final long relevantId,
                final ControlResponseCode code,
                final String errorMessage)
            {
                if (correlationId != expectedCorrelationId)
                {
                    throw new IllegalStateException(
                        "expected=" + expectedCorrelationId + " actual=" + correlationId);
                }
            }
        },
        controlResponse,
        1
    );

    Tests.await(() -> controlResponseAdapter.poll() != 0, TIMEOUT_NS);
}
 
Example #6
Source File: ReplayOperation.java    From artio with Apache License 2.0 6 votes vote down vote up
ReplayOperation(
    final List<RecordingRange> ranges,
    final AeronArchive aeronArchive,
    final ErrorHandler errorHandler,
    final Subscription subscription,
    final int archiveReplayStream,
    final LogTag logTag,
    final MessageTracker messageTracker)
{
    this.messageTracker = messageTracker;
    assembler = new ControlledFragmentAssembler(this.messageTracker);

    this.ranges = ranges;
    this.aeronArchive = aeronArchive;
    this.errorHandler = errorHandler;
    this.archiveReplayStream = archiveReplayStream;
    this.logTag = logTag;

    final Aeron aeron = aeronArchive.context().aeron();
    countersReader = aeron.countersReader();
    this.subscription = subscription;
}
 
Example #7
Source File: ListRecordingSubscriptionsSession.java    From aeron with Apache License 2.0 6 votes vote down vote up
ListRecordingSubscriptionsSession(
    final Object2ObjectHashMap<String, Subscription> subscriptionByKeyMap,
    final int pseudoIndex,
    final int subscriptionCount,
    final int streamId,
    final boolean applyStreamId,
    final String channelFragment,
    final long correlationId,
    final ControlSession controlSession,
    final ControlResponseProxy proxy)
{
    this.subscriptionByKeyMap = subscriptionByKeyMap;
    this.pseudoIndex = pseudoIndex;
    this.subscriptionCount = subscriptionCount;
    this.streamId = streamId;
    this.applyStreamId = applyStreamId;
    this.channelFragment = channelFragment;
    this.correlationId = correlationId;
    this.controlSession = controlSession;
    this.proxy = proxy;
}
 
Example #8
Source File: FixEngine.java    From artio with Apache License 2.0 6 votes vote down vote up
private Image replayImage(final String name, final int replaySessionId)
{
    final Subscription subscription = aeron.addSubscription(
        IPC_CHANNEL, configuration.outboundReplayStream());
    StreamInformation.print(name, subscription, configuration);

    // Await replay publication
    while (true)
    {
        final Image image = subscription.imageBySessionId(replaySessionId);
        if (image != null)
        {
            return image;
        }

        invokeAeronConductor();

        Thread.yield();
    }
}
 
Example #9
Source File: ControlResponseProxy.java    From aeron with Apache License 2.0 6 votes vote down vote up
boolean sendSubscriptionDescriptor(
    final long controlSessionId,
    final long correlationId,
    final Subscription subscription,
    final ControlSession session)
{
    recordingSubscriptionDescriptorEncoder
        .wrapAndApplyHeader(buffer, 0, messageHeaderEncoder)
        .controlSessionId(controlSessionId)
        .correlationId(correlationId)
        .subscriptionId(subscription.registrationId())
        .streamId(subscription.streamId())
        .strippedChannel(subscription.channel());

    final int length = MESSAGE_HEADER_LENGTH + recordingSubscriptionDescriptorEncoder.encodedLength();

    return send(session, buffer, length);
}
 
Example #10
Source File: ControlResponseAdapter.java    From aeron with Apache License 2.0 5 votes vote down vote up
/**
 * Create an adapter for a given subscription to an archive for control response messages.
 *
 * @param listener      to which responses are dispatched.
 * @param subscription  to poll for new events.
 * @param fragmentLimit to apply for each polling operation.
 */
public ControlResponseAdapter(
    final ControlResponseListener listener, final Subscription subscription, final int fragmentLimit)
{
    this.fragmentLimit = fragmentLimit;
    this.listener = listener;
    this.subscription = subscription;
}
 
Example #11
Source File: BasicSubscriber.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args)
{
    System.out.println("Subscribing to " + CHANNEL + " on stream id " + STREAM_ID);

    final MediaDriver driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launchEmbedded() : null;
    final Aeron.Context ctx = new Aeron.Context()
        .availableImageHandler(SamplesUtil::printAvailableImage)
        .unavailableImageHandler(SamplesUtil::printUnavailableImage);

    if (EMBEDDED_MEDIA_DRIVER)
    {
        ctx.aeronDirectoryName(driver.aeronDirectoryName());
    }

    final FragmentHandler fragmentHandler = SamplesUtil.printStringMessage(STREAM_ID);
    final AtomicBoolean running = new AtomicBoolean(true);

    // Register a SIGINT handler for graceful shutdown.
    SigInt.register(() -> running.set(false));

    // Create an Aeron instance using the configured Context and create a
    // Subscription on that instance that subscribes to the configured
    // channel and stream ID.
    // The Aeron and Subscription classes implement "AutoCloseable" and will automatically
    // clean up resources when this try block is finished
    try (Aeron aeron = Aeron.connect(ctx);
        Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID))
    {
        SamplesUtil.subscriberLoop(fragmentHandler, FRAGMENT_COUNT_LIMIT, running).accept(subscription);

        System.out.println("Shutting down...");
    }

    CloseHelper.quietClose(driver);
}
 
Example #12
Source File: AeronUtil.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
/**
 * Return a reusable, parameterized event
 * loop that calls and idler
 * when no messages are received
 *
 * @param fragmentHandler to be called back for each message.
 * @param limit           passed to {@link Subscription#poll(FragmentHandler, int)}
 * @param running         indication for loop
 * @param idleStrategy    to use for loop
 * @return loop function
 */
public static Consumer<Subscription> subscriberLoop(final FragmentHandler fragmentHandler, final int limit,
                final AtomicBoolean running, final IdleStrategy idleStrategy, final AtomicBoolean launched) {
    return (subscription) -> {
        try {
            while (running.get()) {
                idleStrategy.idle(subscription.poll(fragmentHandler, limit));
                launched.set(true);
            }
        } catch (final Exception ex) {
            LangUtil.rethrowUnchecked(ex);
        }
    };
}
 
Example #13
Source File: MultipleSubscribersWithFragmentAssembly.java    From aeron with Apache License 2.0 5 votes vote down vote up
/**
 * Print the information for an available image to stdout.
 *
 * @param image that has been created.
 */
public static void eventAvailableImage(final Image image)
{
    final Subscription subscription = image.subscription();
    System.out.format(
        "new image on %s streamId %x sessionId %x from %s%n",
        subscription.channel(), subscription.streamId(), image.sessionId(), image.sourceIdentity());
}
 
Example #14
Source File: FixArchiveScanner.java    From artio with Apache License 2.0 5 votes vote down vote up
private Image lookupImage(final Subscription replaySubscription, final int sessionId)
{
    Image image = null;

    while (image == null)
    {
        idleStrategy.idle();
        image = replaySubscription.imageBySessionId(sessionId);
    }
    idleStrategy.reset();

    return image;
}
 
Example #15
Source File: MultipleSubscribersWithFragmentAssembly.java    From aeron with Apache License 2.0 5 votes vote down vote up
/**
 * This handler is called when image is unavailable.
 *
 * @param image that has gone inactive.
 */
public static void eventUnavailableImage(final Image image)
{
    final Subscription subscription = image.subscription();
    System.out.format(
        "inactive image on %s streamId %d sessionId %x%n",
        subscription.channel(), subscription.streamId(), image.sessionId());
}
 
Example #16
Source File: ReplayedBasicSubscriber.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args)
{
    System.out.println("Subscribing to " + CHANNEL + " on stream id " + STREAM_ID);

    final FragmentHandler fragmentHandler = SamplesUtil.printStringMessage(STREAM_ID);
    final AtomicBoolean running = new AtomicBoolean(true);

    SigInt.register(() -> running.set(false));

    // Create a unique response stream id so not to clash with other archive clients.
    final AeronArchive.Context archiveCtx = new AeronArchive.Context()
        .controlResponseStreamId(AeronArchive.Configuration.controlResponseStreamId() + 2);

    try (AeronArchive archive = AeronArchive.connect(archiveCtx))
    {
        final long recordingId = findLatestRecording(archive);
        final long position = 0L;
        final long length = Long.MAX_VALUE;

        final long sessionId = archive.startReplay(recordingId, position, length, CHANNEL, REPLAY_STREAM_ID);
        final String channel = ChannelUri.addSessionId(CHANNEL, (int)sessionId);

        try (Subscription subscription = archive.context().aeron().addSubscription(channel, REPLAY_STREAM_ID))
        {
            SamplesUtil.subscriberLoop(fragmentHandler, FRAGMENT_COUNT_LIMIT, running).accept(subscription);
            System.out.println("Shutting down...");
        }
    }
}
 
Example #17
Source File: EngineContext.java    From artio with Apache License 2.0 5 votes vote down vote up
public Subscription outboundLibrarySubscription(
    final String name, final UnavailableImageHandler unavailableImageHandler)
{
    final Subscription subscription = aeron.addSubscription(
        configuration.libraryAeronChannel(),
        configuration.outboundLibraryStream(),
        null,
        unavailableImageHandler);
    StreamInformation.print(name, subscription, configuration);
    return subscription;
}
 
Example #18
Source File: SnapshotRetrieveMonitor.java    From aeron with Apache License 2.0 5 votes vote down vote up
SnapshotRetrieveMonitor(final AeronArchive archive, final long expectedStopPosition)
{
    this.expectedStopPosition = expectedStopPosition;

    final Subscription subscription = archive.controlResponsePoller().subscription();
    recordingSignalAdapter = new RecordingSignalAdapter(
        archive.controlSessionId(), this, this, subscription, FRAGMENT_LIMIT);
}
 
Example #19
Source File: StreamInformation.java    From artio with Apache License 2.0 5 votes vote down vote up
public static void print(
    final String name, final Subscription subscription, final boolean printAeronStreamIdentifiers)
{
    if (printAeronStreamIdentifiers)
    {
        System.out.printf(
            "%-40s - registrationId=%d,streamId=%d%n",
            name,
            subscription.registrationId(),
            subscription.streamId());
    }
}
 
Example #20
Source File: ListRecordingSubscriptionsSession.java    From aeron with Apache License 2.0 5 votes vote down vote up
public int doWork()
{
    int workCount = 0;
    int index = 0;
    final int size = subscriptionByKeyMap.size();

    for (final Subscription subscription : subscriptionByKeyMap.values())
    {
        if (index++ >= pseudoIndex)
        {
            if (!(applyStreamId && subscription.streamId() != streamId) &&
                subscription.channel().contains(channelFragment))
            {
                if (!controlSession.sendSubscriptionDescriptor(correlationId, subscription, proxy))
                {
                    break;
                }

                workCount += 1;

                if (++sent >= subscriptionCount)
                {
                    isDone = true;
                    break;
                }
            }

            pseudoIndex = index - 1;
        }
    }

    if (!isDone && index >= size)
    {
        controlSession.sendSubscriptionUnknown(correlationId, proxy);
        isDone = true;
        workCount += 1;
    }

    return workCount;
}
 
Example #21
Source File: AeronUtil.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * Return a reusable, parameterized event
 * loop that calls and idler
 * when no messages are received
 *
 * @param fragmentHandler to be called back for each message.
 * @param limit           passed to {@link Subscription#poll(FragmentHandler, int)}
 * @param running         indication for loop
 * @param idleStrategy    to use for loop
 * @return loop function
 */
public static Consumer<Subscription> subscriberLoop(final FragmentHandler fragmentHandler, final int limit,
                final AtomicBoolean running, final IdleStrategy idleStrategy, final AtomicBoolean launched) {
    return (subscription) -> {
        try {
            while (running.get()) {
                idleStrategy.idle(subscription.poll(fragmentHandler, limit));
                launched.set(true);
            }
        } catch (final Exception ex) {
            LangUtil.rethrowUnchecked(ex);
        }
    };
}
 
Example #22
Source File: EmbeddedPingPong.java    From aeron with Apache License 2.0 5 votes vote down vote up
private static void roundTripMessages(
    final FragmentHandler fragmentHandler,
    final Publication pingPublication,
    final Subscription pongSubscription,
    final long numMessages)
{
    while (!pongSubscription.isConnected())
    {
        Thread.yield();
    }

    final Image image = pongSubscription.imageAtIndex(0);

    for (long i = 0; i < numMessages; i++)
    {
        long offeredPosition;

        do
        {
            OFFER_BUFFER.putLong(0, System.nanoTime());
        }
        while ((offeredPosition = pingPublication.offer(OFFER_BUFFER, 0, MESSAGE_LENGTH, null)) < 0L);

        PONG_HANDLER_IDLE_STRATEGY.reset();
        do
        {
            while (image.poll(fragmentHandler, FRAGMENT_COUNT_LIMIT) <= 0)
            {
                PONG_HANDLER_IDLE_STRATEGY.idle();
            }
        }
        while (image.position() < offeredPosition);
    }
}
 
Example #23
Source File: RecordingDescriptorPoller.java    From aeron with Apache License 2.0 5 votes vote down vote up
/**
 * Create a poller for a given subscription to an archive for control response messages.
 *
 * @param subscription     to poll for new events.
 * @param errorHandler     to call for asynchronous errors.
 * @param controlSessionId to filter the responses.
 * @param fragmentLimit    to apply for each polling operation.
 */
public RecordingDescriptorPoller(
    final Subscription subscription,
    final ErrorHandler errorHandler,
    final long controlSessionId,
    final int fragmentLimit)
{
    this.subscription = subscription;
    this.errorHandler = errorHandler;
    this.fragmentLimit = fragmentLimit;
    this.controlSessionId = controlSessionId;
}
 
Example #24
Source File: EgressAdapter.java    From aeron with Apache License 2.0 5 votes vote down vote up
public EgressAdapter(
    final EgressListener listener,
    final long clusterSessionId,
    final Subscription subscription,
    final int fragmentLimit)
{
    this.clusterSessionId = clusterSessionId;
    this.listener = listener;
    this.subscription = subscription;
    this.fragmentLimit = fragmentLimit;
}
 
Example #25
Source File: RecordingEventsAdapter.java    From aeron with Apache License 2.0 5 votes vote down vote up
/**
 * Create an adapter for a given subscription to an archive for recording events.
 *
 * @param listener      to which events are dispatched.
 * @param subscription  to poll for new events.
 * @param fragmentLimit to apply for each polling operation.
 */
public RecordingEventsAdapter(
    final RecordingEventsListener listener, final Subscription subscription, final int fragmentLimit)
{
    this.fragmentLimit = fragmentLimit;
    this.listener = listener;
    this.subscription = subscription;
}
 
Example #26
Source File: EmbeddedPingPong.java    From aeron with Apache License 2.0 5 votes vote down vote up
private static void availablePongImageHandler(final Image image)
{
    final Subscription subscription = image.subscription();
    if (PONG_STREAM_ID == subscription.streamId() && PONG_CHANNEL.equals(subscription.channel()))
    {
        PONG_IMAGE_LATCH.countDown();
    }
}
 
Example #27
Source File: ArchiveTests.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void awaitConnectedReply(
    final Subscription controlResponse,
    final long expectedCorrelationId,
    final LongConsumer receiveSessionId)
{
    final ControlResponseAdapter controlResponseAdapter = new ControlResponseAdapter(
        new FailControlResponseListener()
        {
            public void onResponse(
                final long controlSessionId,
                final long correlationId,
                final long relevantId,
                final ControlResponseCode code,
                final String errorMessage)
            {
                if (ControlResponseCode.OK != code)
                {
                    throw new IllegalStateException(
                        "expected=" + ControlResponseCode.OK + " actual=" + code);
                }

                if (correlationId != expectedCorrelationId)
                {
                    throw new IllegalStateException(
                        "expected=" + expectedCorrelationId + " actual=" + correlationId);
                }

                receiveSessionId.accept(controlSessionId);
            }
        },
        controlResponse,
        1
    );

    Tests.await(() -> controlResponseAdapter.poll() != 0, TIMEOUT_NS);
}
 
Example #28
Source File: ArchiveTests.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void awaitOk(final Subscription controlResponse, final long expectedCorrelationId)
{
    final ControlResponseAdapter controlResponseAdapter = new ControlResponseAdapter(
        new FailControlResponseListener()
        {
            public void onResponse(
                final long controlSessionId,
                final long correlationId,
                final long relevantId,
                final ControlResponseCode code,
                final String errorMessage)
            {
                if (ControlResponseCode.OK != code)
                {
                    System.out.println(errorMessage);
                    throw new IllegalStateException(
                        "expected=" + ControlResponseCode.OK + " actual=" + code);
                }

                if (correlationId != expectedCorrelationId)
                {
                    throw new IllegalStateException(
                        "expected=" + expectedCorrelationId + " actual=" + correlationId);
                }
            }
        },
        controlResponse,
        1
    );

    Tests.await(() -> controlResponseAdapter.poll() != 0, TIMEOUT_NS);
}
 
Example #29
Source File: RecordingSessionTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
private static Subscription mockSubscription()
{
    final Subscription subscription = mock(Subscription.class);

    when(subscription.channel()).thenReturn(CHANNEL);
    when(subscription.streamId()).thenReturn(STREAM_ID);

    return subscription;
}
 
Example #30
Source File: RecordingSessionTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
private static Image mockImage(final Subscription subscription)
{
    final Image image = mock(Image.class);

    when(image.sessionId()).thenReturn(SESSION_ID);
    when(image.initialTermId()).thenReturn(INITIAL_TERM_ID);
    when(image.sourceIdentity()).thenReturn(SOURCE_IDENTITY);
    when(image.termBufferLength()).thenReturn(TERM_BUFFER_LENGTH);
    when(image.mtuLength()).thenReturn(MTU_LENGTH);
    when(image.joinPosition()).thenReturn(START_POSITION);
    when(image.subscription()).thenReturn(subscription);

    return image;
}