/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.flink.connector.jdbc.xa;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.functions.RuntimeContext;

import javax.transaction.xa.Xid;

import java.security.SecureRandom;

/**
 * Generates {@link Xid} from:
 *
 * <ol>
 *   <li>checkpoint id
 *   <li>subtask index
 *   <li>4 random bytes to provide uniqueness across other jobs and apps (generated at startup using
 *       {@link SecureRandom})
 * </ol>
 *
 * <p>Each {@link SemanticXidGenerator} instance MUST be used for only one Sink (otherwise Xids
 * could collide).
 */
@Internal
class SemanticXidGenerator implements XidGenerator {

    private static final long serialVersionUID = 1L;

    private static final SecureRandom SECURE_RANDOM = new SecureRandom();

    private static final int FORMAT_ID = 201;
    private static final int BQUAL_DYN_PART_LEN =
            Integer.BYTES; // length of the branchQualifier dynamic part, which is task index
    private static final int BQUAL_DYN_PART_POS = 0; // and it's starting position

    private transient byte[] gtridBuffer; // globalTransactionId = checkpoint id (long)
    private transient byte[] bqualBuffer; // branchQualifier = task index + random bytes

    @Override
    public void open() {
        bqualBuffer = new byte[Long.BYTES];
        byte[] bqualStaticPart = getRandomBytes(bqualBuffer.length - BQUAL_DYN_PART_LEN);
        System.arraycopy(
                bqualStaticPart, 0, bqualBuffer, BQUAL_DYN_PART_LEN, bqualStaticPart.length);
        gtridBuffer = new byte[Long.BYTES];
    }

    @Override
    public Xid generateXid(RuntimeContext runtimeContext, long checkpointId) {
        writeNumber(
                runtimeContext.getIndexOfThisSubtask(),
                Integer.BYTES,
                bqualBuffer,
                BQUAL_DYN_PART_POS);
        writeNumber(checkpointId, Long.BYTES, gtridBuffer, 0);
        // relying on arrays copying inside XidImpl constructor
        return new XidImpl(FORMAT_ID, gtridBuffer, bqualBuffer);
    }

    private static void writeNumber(long number, int numberLength, byte[] dst, int dstPos) {
        for (int i = dstPos; i < numberLength; i++) {
            dst[i] = (byte) number;
            number >>= 8;
        }
    }

    private byte[] getRandomBytes(int size) {
        byte[] bytes = new byte[size];
        SECURE_RANDOM.nextBytes(bytes);
        return bytes;
    }
}

@@ -1085,16 +1085,26 @@
 point id
+ (4 bytes)
 %0A *   %3Cl
@@ -1128,17 +1128,17 @@
 *   %3Cli%3E
-4
+8
  random 
@@ -1624,235 +1624,8 @@
 201;
-%0A    private static final int BQUAL_DYN_PART_LEN =%0A            Integer.BYTES; // length of the branchQualifier dynamic part, which is task index%0A    private static final int BQUAL_DYN_PART_POS = 0; // and it's starting position
 %0A%0A  
@@ -1865,237 +1865,33 @@
 r = 
-new byte%5BLong.BYTES%5D;%0A        byte%5B%5D bqualStaticPart = getRandomBytes(bqualBuffer.length - BQUAL_DYN_PART_LEN);%0A        System.arraycopy(%0A                bqualStaticPart, 0, bqualBuffer, BQUAL_DYN_PART_LEN, bqualStaticPart.length
+getRandomBytes(Long.BYTES
 );%0A 
@@ -2053,33 +2053,16 @@
 eNumber(
-%0A                
 runtimeC
@@ -2096,105 +2096,115 @@
 k(),
-%0A                Integer.BYTES,%0A                bqualBuffer,%0A                BQUAL_DYN_PART_POS);
+ gtridBuffer, 0);%0A        // deliberately write only 4 bytes of checkpoint id and rely on random generation
 %0A   
@@ -2220,16 +2220,22 @@
 eNumber(
+(int) 
 checkpoi
@@ -2243,20 +2243,8 @@
 tId,
- Long.BYTES,
  gtr
@@ -2245,33 +2245,45 @@
 d, gtridBuffer, 
-0
+Integer.BYTES
 );%0A        // re
@@ -2445,21 +2445,8 @@
 ber(
-long number, 
 int 
@@ -2451,22 +2451,16 @@
 t number
-Length
 , byte%5B%5D
@@ -2472,19 +2472,22 @@
  int dst
-Pos
+Offset
 ) %7B%0A    
@@ -2510,29 +2510,45 @@
  dst
-Pos; i %3C numberLength
+Offset; i %3C dstOffset + Integer.BYTES
 ; i+
@@ -2613,11 +2613,20 @@
 r %3E%3E
+%3E
 = 
-8
+Byte.SIZE
 ;%0A  

Use more random bytes in Xid