/*
 * Copyright 2014-2019 Real Logic Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.aeron.cluster.service;

import io.aeron.Aeron;
import io.aeron.DirectBufferVector;
import io.aeron.Publication;
import io.aeron.exceptions.RegistrationException;
import org.agrona.CloseHelper;
import org.agrona.DirectBuffer;

/**
 * Session representing a connected client to the cluster.
 */
public class ClientSession
{
    /**
     * Return value to indicate egress to a session is mocked out by the cluster when in follower mode.
     */
    public static final long MOCKED_OFFER = 1;

    private final long id;
    private final int responseStreamId;
    private final String responseChannel;
    private final byte[] encodedPrincipal;

    private final ClusteredServiceAgent cluster;
    private Publication responsePublication;
    private boolean isClosing;

    ClientSession(
        final long sessionId,
        final int responseStreamId,
        final String responseChannel,
        final byte[] encodedPrincipal,
        final ClusteredServiceAgent cluster)
    {
        this.id = sessionId;
        this.responseStreamId = responseStreamId;
        this.responseChannel = responseChannel;
        this.encodedPrincipal = encodedPrincipal;
        this.cluster = cluster;
    }

    /**
     * Cluster session identity uniquely allocated when the session was opened.
     *
     * @return the cluster session identity uniquely allocated when the session was opened.
     */
    public long id()
    {
        return id;
    }

    /**
     * The response channel stream id for responding to the client.
     *
     * @return response channel stream id for responding to the client.
     */
    public int responseStreamId()
    {
        return responseStreamId;
    }

    /**
     * The response channel for responding to the client.
     *
     * @return response channel for responding to the client.
     */
    public String responseChannel()
    {
        return responseChannel;
    }

    /**
     * Cluster session encoded principal from when the session was authenticated.
     *
     * @return The encoded Principal passed. May be 0 length to indicate none present.
     */
    public byte[] encodedPrincipal()
    {
        return encodedPrincipal;
    }

    /**
     * Close of this {@link ClientSession} by sending the request to the consensus module.
     * <p>
     * This method is idempotent.
     */
    public void close()
    {
        if (null != cluster.getClientSession(id))
        {
            cluster.closeSession(id);
        }
    }

    /**
     * Indicates that a request to close this session has been made.
     *
     * @return whether a request to close this session has been made.
     */
    public boolean isClosing()
    {
        return isClosing;
    }

    /**
     * Non-blocking publish of a partial buffer containing a message to a cluster.
     *
     * @param buffer containing message.
     * @param offset offset in the buffer at which the encoded message begins.
     * @param length in bytes of the encoded message.
     * @return the same as {@link Publication#offer(DirectBuffer, int, int)} when in {@link Cluster.Role#LEADER}
     * otherwise {@link #MOCKED_OFFER}.
     */
    public long offer(final DirectBuffer buffer, final int offset, final int length)
    {
        return cluster.offer(id, responsePublication, buffer, offset, length);
    }

    /**
     * Non-blocking publish by gathering buffer vectors into a message. The first vector will be replaced by the cluster
     * egress header so must be left unused.
     *
     * @param vectors which make up the message.
     * @return the same as {@link Publication#offer(DirectBufferVector[])}.
     * @see Publication#offer(DirectBufferVector[]) when in {@link Cluster.Role#LEADER}
     * otherwise {@link #MOCKED_OFFER}.
     */
    public long offer(final DirectBufferVector[] vectors)
    {
        return cluster.offer(id, responsePublication, vectors);
    }

    void connect(final Aeron aeron)
    {
        if (null == responsePublication)
        {
            try
            {
                responsePublication = aeron.addPublication(responseChannel, responseStreamId);
            }
            catch (final RegistrationException ex)
            {
                cluster.handleError(ex);
            }
        }
    }

    void markClosing()
    {
        this.isClosing = true;
    }

    void resetClosing()
    {
        isClosing = false;
    }

    void disconnect()
    {
        CloseHelper.close(responsePublication);
        responsePublication = null;
    }
}


/*
 * Copyright 2014-2019 Real Logic Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.aeron.logbuffer;

import org.agrona.DirectBuffer;
import org.agrona.MutableDirectBuffer;
import org.agrona.concurrent.AtomicBuffer;
import org.agrona.concurrent.UnsafeBuffer;

import java.nio.ByteOrder;

import static io.aeron.protocol.DataHeaderFlyweight.*;
import static java.nio.ByteOrder.LITTLE_ENDIAN;

/**
 * Represents a claimed range in a buffer to be used for recording a message without copy semantics for later commit.
 *

 * The claimed space is in {@link #buffer()} between {@link #offset()} and {@link #offset()} + {@link #length()}.
 * When the buffer is filled with message data, use {@link #commit()} to make it available to subscribers.
 *

 * If the claimed space is no longer required it can be aborted by calling {@link #abort()}.
 *
 * @see io.aeron.Publication#tryClaim(int, BufferClaim)
 */
public class BufferClaim
{
    protected final UnsafeBuffer buffer = new UnsafeBuffer(0, 0);

    /**
     * Wrap a region of an underlying log buffer so can can represent a claimed space for use by a publisher.
     *
     * @param buffer to be wrapped.
     * @param offset at which the claimed region begins including space for the header.
     * @param length length of the underlying claimed region including space for the header.
     */
    public final void wrap(final AtomicBuffer buffer, final int offset, final int length)
    {
        this.buffer.wrap(buffer, offset, length);
    }

    /**
     * The referenced buffer to be used.
     *
     * @return the referenced buffer to be used..
     */
    public final MutableDirectBuffer buffer()
    {
        return buffer;
    }

    /**
     * The offset in the buffer at which the claimed range begins.
     *
     * @return offset in the buffer at which the range begins.
     */
    public final int offset()
    {
        return HEADER_LENGTH;
    }

    /**
     * The length of the claimed range in the buffer.
     *
     * @return length of the range in the buffer.
     */
    public final int length()
    {
        return buffer.capacity() - HEADER_LENGTH;
    }

    /**
     * Get the value of the header type field. The lower 16 bits are valid.
     *
     * @return the value of the header type field.
     * @see io.aeron.protocol.DataHeaderFlyweight
     */
    public final int headerType()
    {
        return buffer.getShort(TYPE_FIELD_OFFSET, LITTLE_ENDIAN) & 0xFFFF;
    }

    /**
     * Get the value of the flags field.
     *
     * @return the value of the header flags field.
     * @see io.aeron.protocol.DataHeaderFlyweight
     */
    public final byte flags()
    {
        return buffer.getByte(FLAGS_FIELD_OFFSET);
    }

    /**
     * Set the value of the header flags field.
     *
     * @param flags value to be set in the header.
     * @return this for a fluent API.
     * @see io.aeron.protocol.DataHeaderFlyweight
     */
    public BufferClaim flags(final byte flags)
    {
        buffer.putByte(FLAGS_FIELD_OFFSET, flags);
        return this;
    }

    /**
     * Set the value of the header type field. The lower 16 bits are valid.
     *
     * @param type value to be set in the header.
     * @return this for a fluent API.
     * @see io.aeron.protocol.DataHeaderFlyweight
     */
    public BufferClaim headerType(final int type)
    {
        buffer.putShort(TYPE_FIELD_OFFSET, (short)type, LITTLE_ENDIAN);
        return this;
    }

    /**
     * Get the value stored in the reserve space at the end of a data frame header.
     *

     * Note: The value is in {@link ByteOrder#LITTLE_ENDIAN} format.
     *
     * @return the value stored in the reserve space at the end of a data frame header.
     * @see io.aeron.protocol.DataHeaderFlyweight
     */
    public final long reservedValue()
    {
        return buffer.getLong(RESERVED_VALUE_OFFSET, LITTLE_ENDIAN);
    }

    /**
     * Write the provided value into the reserved space at the end of the data frame header.
     *

     * Note: The value will be written in {@link ByteOrder#LITTLE_ENDIAN} format.
     *
     * @param value to be stored in the reserve space at the end of a data frame header.
     * @return this for fluent API semantics.
     * @see io.aeron.protocol.DataHeaderFlyweight
     */
    public BufferClaim reservedValue(final long value)
    {
        buffer.putLong(RESERVED_VALUE_OFFSET, value, LITTLE_ENDIAN);
        return this;
    }

    /**
     * Put bytes into the claimed buffer space for a message. To write multiple parts then use {@link #buffer()}
     * and {@link #offset()}.
     *
     * @param srcBuffer to copy into the claimed space.
     * @param srcIndex  in the source buffer from which to copy.
     * @param length    of the source buffer to copy.
     * @return this for a fluent API.
     */
    public final BufferClaim putBytes(final DirectBuffer srcBuffer, final int srcIndex, final int length)
    {
        buffer.putBytes(HEADER_LENGTH, srcBuffer, srcIndex, length);
        return this;
    }

    /**
     * Commit the message to the log buffer so that is it available to subscribers.
     */
    public final void commit()
    {
        int frameLength = buffer.capacity();
        if (ByteOrder.nativeOrder() != LITTLE_ENDIAN)
        {
            frameLength = Integer.reverseBytes(frameLength);
        }

        buffer.putIntOrdered(FRAME_LENGTH_FIELD_OFFSET, frameLength);
    }

    /**
     * Abort a claim of the message space to the log buffer so that the log can progress by ignoring this claim.
     */
    public final void abort()
    {
        int frameLength = buffer.capacity();
        if (ByteOrder.nativeOrder() != LITTLE_ENDIAN)
        {
            frameLength = Integer.reverseBytes(frameLength);
        }

        buffer.putShort(TYPE_FIELD_OFFSET, (short)HDR_TYPE_PAD, LITTLE_ENDIAN);
        buffer.putIntOrdered(FRAME_LENGTH_FIELD_OFFSET, frameLength);
    }
}