/*
 * 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.JobID;
import org.apache.flink.api.common.functions.RuntimeContext;

import javax.transaction.xa.Xid;

import java.security.SecureRandom;
import java.util.Optional;

/**
 * Generates {@link Xid} from:
 *
 * <ol>
 *   <li>To provide uniqueness over other jobs and apps, and other instances
 *   <li>of this job, gtrid consists of
 *   <li>job id (16 bytes)
 *   <li>subtask index (4 bytes)
 *   <li>checkpoint id (4 bytes)
 *   <li>bqual consists of 4 random bytes (generated using {@link SecureRandom})
 * </ol>
 *
 * <p>Each {@link SemanticXidGenerator} instance MUST be used for only one Sink (otherwise Xids will
 * 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 transient byte[]
            gtridBuffer; // globalTransactionId = job id + task index + checkpoint id
    private transient byte[] bqualBuffer; // branchQualifier = random bytes

    @Override
    public void open() {
        gtridBuffer = new byte[3 * Long.BYTES];
        bqualBuffer = getRandomBytes(Integer.BYTES);
    }

    @Override
    public Xid generateXid(RuntimeContext runtimeContext, long checkpointId) {
        Optional<JobID> jobId = runtimeContext.getJobId();
        if (jobId.isPresent()) {
            System.arraycopy(jobId.get().getBytes(), 0, gtridBuffer, 0, JobID.SIZE);
        } else {
            // fall back to RNG if jobId is unavailable for some reason
            System.arraycopy(getRandomBytes(JobID.SIZE), 0, gtridBuffer, 0, JobID.SIZE);
        }

        writeNumber(runtimeContext.getIndexOfThisSubtask(), gtridBuffer, JobID.SIZE);
        // deliberately write only 4 bytes of checkpoint id
        writeNumber((int) checkpointId, gtridBuffer, JobID.SIZE + Integer.BYTES);
        // relying on arrays copying inside XidImpl constructor
        return new XidImpl(FORMAT_ID, gtridBuffer, bqualBuffer);
    }

    private static void writeNumber(int number, byte[] dst, int dstOffset) {
        for (int i = dstOffset; i < dstOffset + Integer.BYTES; i++) {
            dst[i] = (byte) number;
            number >>>= Byte.SIZE;
        }
    }

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

@@ -987,16 +987,57 @@
 Context;
+%0Aimport org.apache.flink.util.AbstractID;
 %0A%0Aimport
@@ -1102,35 +1102,8 @@
 dom;
-%0Aimport java.util.Optional;
 %0A%0A/*
@@ -1835,28 +1835,16 @@
 t byte%5B%5D
-%0A           
  gtridBu
@@ -1852,69 +1852,8 @@
 fer;
- // globalTransactionId = job id + task index + checkpoint id
 %0A   
@@ -1894,42 +1894,8 @@
 fer;
- // branchQualifier = random bytes
 %0A%0A  
@@ -1943,47 +1943,183 @@
     
-gtridBuffer = new byte%5B3 * Long.BYTES%5D;
+// globalTransactionId = job id + task index + checkpoint id%0A        gtridBuffer = new byte%5BJobID.SIZE + Integer.BYTES + Long.BYTES%5D;%0A        // branchQualifier = random bytes
 %0A   
@@ -2280,46 +2280,91 @@
     
-Optional%3CJobID%3E jobId = runtimeContext
+byte%5B%5D jobIdOrRandomBytes =%0A                runtimeContext%0A                        
 .get
@@ -2370,17 +2370,16 @@
 tJobId()
-;
 %0A       
@@ -2383,211 +2383,112 @@
     
-if (jobId.isPresent()) %7B%0A            System.arraycopy(jobId.get().getBytes(), 0, gtridBuffer, 0, JobID.SIZE);%0A        %7D else %7B%0A            // fall back to RNG if jobId is unavailable for some reason%0A    
+                .map(AbstractID::getBytes)%0A                        .orElse(getRandomBytes(JobID.SIZE));%0A
     
@@ -2508,19 +2508,23 @@
 raycopy(
-get
+jobIdOr
 RandomBy
@@ -2526,28 +2526,16 @@
 domBytes
-(JobID.SIZE)
 , 0, gtr
@@ -2559,26 +2559,16 @@
 D.SIZE);
-%0A        %7D
 %0A%0A      
@@ -2620,16 +2620,31 @@
 btask(),
+ Integer.BYTES,
  gtridBu
@@ -2666,68 +2666,8 @@
 E);%0A
-        // deliberately write only 4 bytes of checkpoint id%0A
     
@@ -2686,14 +2686,8 @@
 ber(
-(int) 
 chec
@@ -2695,16 +2695,28 @@
 pointId,
+ Long.BYTES,
  gtridBu
@@ -2926,18 +2926,33 @@
 ber(
+long number, 
 int num
-ber
+Bytes
 , by
@@ -3026,29 +3026,24 @@
 ffset + 
-Integer.BYTES
+numBytes
 ; i++) %7B

Use full checkpoint ID in XA global transaction ID