PluginDrivenTransactionManager.java

// 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.doris.transaction;

import org.apache.doris.catalog.Env;
import org.apache.doris.common.UserException;
import org.apache.doris.connector.api.handle.ConnectorTransaction;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Transaction manager for plugin-driven external catalogs.
 *
 * <p>Two entry points:</p>
 * <ul>
 *   <li>{@link #begin()} ��� legacy auto-commit path used by
 *       {@code BaseExternalTableInsertExecutor}. The manager allocates a txn id via
 *       {@link Env#getNextId()} and stores a no-op transaction; the actual write side
 *       effects are produced by {@code ConnectorWriteOps.finishInsert/abortInsert}.
 *       This path is used by connectors that do not implement SPI transactions
 *       (e.g. JDBC, ES).</li>
 *   <li>{@link #begin(ConnectorTransaction)} ��� SPI path for connectors that return a
 *       real {@link ConnectorTransaction} from {@code ConnectorWriteOps.beginTransaction}.
 *       The manager uses {@link ConnectorTransaction#getTransactionId()} as the txn id
 *       and delegates commit/rollback/close to the connector.</li>
 * </ul>
 *
 * <p>Both paths share the same {@link #commit(long)} / {@link #rollback(long)} surface
 * required by {@link TransactionManager}.</p>
 */
public class PluginDrivenTransactionManager implements TransactionManager {

    private static final Logger LOG = LogManager.getLogger(PluginDrivenTransactionManager.class);

    private final ConcurrentHashMap<Long, PluginDrivenTransaction> transactions =
            new ConcurrentHashMap<>();

    @Override
    public long begin() {
        long txnId = Env.getCurrentEnv().getNextId();
        transactions.put(txnId, new PluginDrivenTransaction(txnId, null));
        LOG.debug("Plugin-driven transaction begun: {}", txnId);
        return txnId;
    }

    /**
     * Registers a connector-provided {@link ConnectorTransaction}. Commit / rollback
     * lifecycle is delegated to it (including {@code close()}).
     *
     * @return the txn id, taken from {@code connectorTx.getTransactionId()}
     */
    public long begin(ConnectorTransaction connectorTx) {
        Objects.requireNonNull(connectorTx, "connectorTx");
        long txnId = connectorTx.getTransactionId();
        transactions.put(txnId, new PluginDrivenTransaction(txnId, connectorTx));
        LOG.debug("Plugin-driven transaction begun with SPI ConnectorTransaction: {}", txnId);
        return txnId;
    }

    @Override
    public void commit(long id) throws UserException {
        PluginDrivenTransaction txn = transactions.remove(id);
        if (txn != null) {
            txn.commit();
            LOG.debug("Plugin-driven transaction committed: {}", id);
        }
    }

    @Override
    public void rollback(long id) {
        PluginDrivenTransaction txn = transactions.remove(id);
        if (txn != null) {
            txn.rollback();
            LOG.debug("Plugin-driven transaction rolled back: {}", id);
        }
    }

    @Override
    public Transaction getTransaction(long id) throws UserException {
        PluginDrivenTransaction txn = transactions.get(id);
        if (txn == null) {
            throw new UserException("Plugin-driven transaction not found: " + id);
        }
        return txn;
    }

    /**
     * Internal transaction record. When {@code connectorTx} is non-null the SPI is
     * the source of truth and commit/rollback delegate to it; close() always runs
     * after delegation. When null, this is the legacy no-op marker (the executor
     * drives write side effects via {@code ConnectorWriteOps} directly).
     */
    private static final class PluginDrivenTransaction implements Transaction {
        private final long id;
        private final ConnectorTransaction connectorTx;

        PluginDrivenTransaction(long id, ConnectorTransaction connectorTx) {
            this.id = id;
            this.connectorTx = connectorTx;
        }

        @Override
        public void commit() {
            if (connectorTx == null) {
                return;
            }
            try {
                connectorTx.commit();
            } finally {
                closeQuietly();
            }
        }

        @Override
        public void rollback() {
            if (connectorTx == null) {
                return;
            }
            try {
                connectorTx.rollback();
            } finally {
                closeQuietly();
            }
        }

        private void closeQuietly() {
            try {
                connectorTx.close();
            } catch (Exception e) {
                LOG.warn("Failed to close ConnectorTransaction {}: {}", id, e.getMessage());
            }
        }
    }
}