Search in sources :

Example 11 with Frame

use of com.datastax.oss.protocol.internal.Frame in project java-driver by datastax.

the class InFlightHandler method write.

private void write(ChannelHandlerContext ctx, RequestMessage message, ChannelPromise promise) {
    if (closingGracefully) {
        promise.setFailure(new IllegalStateException("Channel is closing"));
        streamIds.cancelPreAcquire();
        return;
    }
    int streamId = streamIds.acquire();
    if (streamId < 0) {
        // Should not happen with the preAcquire mechanism, but handle gracefully
        promise.setFailure(new BusyConnectionException(String.format("Couldn't acquire a stream id from InFlightHandler on %s", ctx.channel())));
        streamIds.cancelPreAcquire();
        return;
    }
    if (inFlight.containsKey(streamId)) {
        promise.setFailure(new IllegalStateException("Found pending callback for stream id " + streamId));
        streamIds.cancelPreAcquire();
        return;
    }
    LOG.trace("[{}] Writing {} on stream id {}", logPrefix, message.responseCallback, streamId);
    Frame frame = Frame.forRequest(protocolVersion.getCode(), streamId, message.tracing, message.customPayload, message.request);
    inFlight.put(streamId, message.responseCallback);
    ChannelFuture writeFuture = ctx.write(frame, promise);
    writeFuture.addListener(future -> {
        if (future.isSuccess()) {
            message.responseCallback.onStreamIdAssigned(streamId);
        } else {
            release(streamId, ctx);
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Frame(com.datastax.oss.protocol.internal.Frame) BusyConnectionException(com.datastax.oss.driver.api.core.connection.BusyConnectionException)

Example 12 with Frame

use of com.datastax.oss.protocol.internal.Frame in project java-driver by datastax.

the class SegmentToFrameDecoder method decodeSelfContained.

private void decodeSelfContained(Segment<ByteBuf> segment, List<Object> out) {
    ByteBuf payload = segment.payload;
    int frameCount = 0;
    try {
        do {
            Frame frame = frameCodec.decode(payload);
            LOG.trace("[{}] Decoded response frame {} from self-contained segment", logPrefix, frame.streamId);
            out.add(frame);
            frameCount += 1;
        } while (payload.isReadable());
    } finally {
        payload.release();
    }
    LOG.trace("[{}] Done processing self-contained segment ({} frames)", logPrefix, frameCount);
}
Also used : Frame(com.datastax.oss.protocol.internal.Frame) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf)

Example 13 with Frame

use of com.datastax.oss.protocol.internal.Frame in project java-driver by datastax.

the class SegmentToFrameDecoderTest method should_decode_sequence_of_slices.

@Test
public void should_decode_sequence_of_slices() {
    ByteBuf encodedFrame = encodeFrame(new AuthResponse(Bytes.fromHexString("0x" + Strings.repeat("aa", 1011))));
    int sliceLength = 100;
    do {
        ByteBuf payload = encodedFrame.readRetainedSlice(Math.min(sliceLength, encodedFrame.readableBytes()));
        channel.writeInbound(new Segment<>(payload, false));
    } while (encodedFrame.isReadable());
    Frame frame = channel.readInbound();
    assertThat(frame.message).isInstanceOf(AuthResponse.class);
}
Also used : Frame(com.datastax.oss.protocol.internal.Frame) ByteBuf(io.netty.buffer.ByteBuf) AuthResponse(com.datastax.oss.protocol.internal.request.AuthResponse) Test(org.junit.Test)

Example 14 with Frame

use of com.datastax.oss.protocol.internal.Frame in project java-driver by datastax.

the class InFlightHandler method channelRead.

@Override
@SuppressWarnings("NonAtomicVolatileUpdate")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Frame responseFrame = (Frame) msg;
    int streamId = responseFrame.streamId;
    if (streamId < 0) {
        Message event = responseFrame.message;
        if (eventCallback == null) {
            LOG.debug("[{}] Received event {} but no callback was registered", logPrefix, event);
        } else {
            LOG.debug("[{}] Received event {}, notifying callback", logPrefix, event);
            try {
                eventCallback.onEvent(event);
            } catch (Throwable t) {
                Loggers.warnWithException(LOG, "[{}] Unexpected error while invoking event handler", logPrefix, t);
            }
        }
    } else {
        boolean wasInFlight = true;
        ResponseCallback callback = inFlight.get(streamId);
        if (callback == null) {
            wasInFlight = false;
            callback = orphaned.get(streamId);
            if (callback == null) {
                LOG.trace("[{}] Got response on unknown stream id {}, skipping", logPrefix, streamId);
                return;
            }
        }
        try {
            if (callback.isLastResponse(responseFrame)) {
                LOG.debug("[{}] Got last response on {} stream id {}, completing and releasing", logPrefix, wasInFlight ? "in-flight" : "orphaned", streamId);
                release(streamId, ctx);
            } else {
                LOG.trace("[{}] Got non-last response on {} stream id {}, still holding", logPrefix, wasInFlight ? "in-flight" : "orphaned", streamId);
            }
            if (wasInFlight) {
                callback.onResponse(responseFrame);
            }
        } catch (Throwable t) {
            if (wasInFlight) {
                fail(callback, new IllegalArgumentException("Unexpected error while invoking response handler", t));
            } else {
                // Assume the callback is already completed, so it's better to log
                Loggers.warnWithException(LOG, "[{}] Unexpected error while invoking response handler on stream id {}", logPrefix, t, streamId);
            }
        }
    }
}
Also used : Frame(com.datastax.oss.protocol.internal.Frame) RequestMessage(com.datastax.oss.driver.internal.core.channel.DriverChannel.RequestMessage) Message(com.datastax.oss.protocol.internal.Message)

Example 15 with Frame

use of com.datastax.oss.protocol.internal.Frame in project java-driver by datastax.

the class FrameDecoderTest method should_decode_valid_payload.

@Test
public void should_decode_valid_payload() {
    // Given
    FrameDecoder decoder = new FrameDecoder(frameCodec, 1024);
    channel.pipeline().addLast(decoder);
    // When
    // The decoder releases the buffer, so make sure we retain it for the other tests
    VALID_PAYLOAD.retain();
    channel.writeInbound(VALID_PAYLOAD.duplicate());
    Frame frame = readInboundFrame();
    // Then
    assertThat(frame.message).isInstanceOf(AuthSuccess.class);
}
Also used : Frame(com.datastax.oss.protocol.internal.Frame) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) Test(org.junit.Test)

Aggregations

Frame (com.datastax.oss.protocol.internal.Frame)34 Test (org.junit.Test)29 ChannelFuture (io.netty.channel.ChannelFuture)13 Ready (com.datastax.oss.protocol.internal.response.Ready)12 InetSocketAddress (java.net.InetSocketAddress)12 Error (com.datastax.oss.protocol.internal.response.Error)8 Query (com.datastax.oss.protocol.internal.request.Query)6 ByteBuf (io.netty.buffer.ByteBuf)4 UnsupportedProtocolVersionException (com.datastax.oss.driver.api.core.UnsupportedProtocolVersionException)3 AuthProvider (com.datastax.oss.driver.api.core.auth.AuthProvider)3 AuthResponse (com.datastax.oss.protocol.internal.request.AuthResponse)3 SetKeyspace (com.datastax.oss.protocol.internal.response.result.SetKeyspace)3 UseDataProvider (com.tngtech.java.junit.dataprovider.UseDataProvider)3 Register (com.datastax.oss.protocol.internal.request.Register)2 Authenticate (com.datastax.oss.protocol.internal.response.Authenticate)2 Void (com.datastax.oss.protocol.internal.response.result.Void)2 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)2 BusyConnectionException (com.datastax.oss.driver.api.core.connection.BusyConnectionException)1 ClosedConnectionException (com.datastax.oss.driver.api.core.connection.ClosedConnectionException)1 EndPoint (com.datastax.oss.driver.api.core.metadata.EndPoint)1