This is an automated email from the ASF dual-hosted git repository.

pvillard31 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/nifi.git


The following commit(s) were added to refs/heads/main by this push:
     new 934fe127563 NIFI-16589 Answer Git registry synchronization from a 
cache while the branch head is unchanged (#11926)
934fe127563 is described below

commit 934fe127563e8dd928dcaf78c17df1a6856e8618
Author: Raul Roberto da Silva <[email protected]>
AuthorDate: Wed Nov 18 08:23:58 2026 -0300

    NIFI-16589 Answer Git registry synchronization from a cache while the 
branch head is unchanged (#11926)
---
 .../flow/git/AbstractGitFlowRegistryClient.java    |  41 +++-
 .../registry/flow/git/GitBranchStateCache.java     | 228 +++++++++++++++++
 .../flow/git/client/GitRepositoryClient.java       |  48 ++++
 .../git/AbstractGitFlowRegistryClientTest.java     | 126 +++++++++-
 .../registry/flow/git/GitBranchStateCacheTest.java | 273 +++++++++++++++++++++
 .../ConditionalBranchReferenceConnector.java       | 169 +++++++++++++
 .../apache/nifi/github/GitHubRepositoryClient.java | 124 +++++++++-
 .../ConditionalBranchReferenceConnectorTest.java   | 254 +++++++++++++++++++
 .../nifi/github/GitHubRepositoryClientTest.java    |  92 ++++++-
 9 files changed, 1342 insertions(+), 13 deletions(-)

diff --git 
a/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/AbstractGitFlowRegistryClient.java
 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/AbstractGitFlowRegistryClient.java
index 2ed97ef832f..21858298676 100644
--- 
a/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/AbstractGitFlowRegistryClient.java
+++ 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/AbstractGitFlowRegistryClient.java
@@ -147,6 +147,7 @@ public abstract class AbstractGitFlowRegistryClient extends 
AbstractFlowRegistry
     private volatile GitRepositoryClient repositoryClient;
     private volatile Pattern directoryExclusionPattern;
     private final AtomicBoolean clientInitialized = new AtomicBoolean(false);
+    private final GitBranchStateCache branchStateCache = new 
GitBranchStateCache(this::getLogger);
 
     private volatile List<PropertyDescriptor> propertyDescriptors;
 
@@ -347,12 +348,22 @@ public abstract class AbstractGitFlowRegistryClient 
extends AbstractFlowRegistry
         final String branch = flowLocation.getBranch();
         final String filePath = getSnapshotFilePath(flowLocation);
 
-        final RegisteredFlowSnapshot existingSnapshot = 
getSnapshot(repositoryClient, filePath, branch);
+        final Optional<GitBranchStateCache.BranchState> branchState = 
branchStateCache.getState(repositoryClient, branch);
+        final Optional<RegisteredFlow> cachedFlow = branchState.flatMap(state 
-> state.getFlow(filePath));
+        if (cachedFlow.isPresent()) {
+            return cachedFlow.get();
+        }
+
+        // Read at the head commit of the state, so the remembered flow 
matches the head it is answered for
+        final RegisteredFlowSnapshot existingSnapshot = branchState.isPresent()
+                ? getSnapshot(repositoryClient.getContentFromCommit(filePath, 
branchState.get().getHeadSha()))
+                : getSnapshot(repositoryClient, filePath, branch);
         populateFlowAndSnapshotMetadata(existingSnapshot, flowLocation);
         updateBucketReferences(repositoryClient, existingSnapshot, 
flowLocation.getBucketId());
 
         final RegisteredFlow registeredFlow = existingSnapshot.getFlow();
         registeredFlow.setBranch(branch);
+        branchState.ifPresent(state -> state.putFlow(filePath, 
registeredFlow));
         return registeredFlow;
     }
 
@@ -561,7 +572,32 @@ public abstract class AbstractGitFlowRegistryClient 
extends AbstractFlowRegistry
         final String branch = flowLocation.getBranch();
         final String filePath = getSnapshotFilePath(flowLocation);
 
-        return repositoryClient.getLatestCommitSha(filePath, branch);
+        final Optional<GitBranchStateCache.BranchState> branchState = 
branchStateCache.getState(repositoryClient, branch);
+        final Optional<GitBranchStateCache.LatestVersion> cachedLatestVersion 
= branchState.flatMap(state -> state.getLatestVersion(filePath));
+        if (cachedLatestVersion.isPresent()) {
+            return cachedLatestVersion.get().toOptional();
+        }
+
+        if (branchState.isEmpty()) {
+            return repositoryClient.getLatestCommitSha(filePath, branch);
+        }
+
+        // Read at the head commit of the state, so the remembered version 
matches the head it is answered for
+        final GitBranchStateCache.BranchState state = branchState.get();
+        final Optional<String> latestVersion = 
getLatestCommitShaAtCommit(repositoryClient, filePath, state.getHeadSha());
+        state.putLatestVersion(filePath, latestVersion);
+        return latestVersion;
+    }
+
+    // A client that returns a branch head must implement this method, so a 
runtime failure such as an unsupported operation
+    // is reported as a registry failure
+    private Optional<String> getLatestCommitShaAtCommit(final 
GitRepositoryClient repositoryClient, final String filePath, final String 
commitSha)
+            throws IOException, FlowRegistryException {
+        try {
+            return repositoryClient.getLatestCommitShaAtCommit(filePath, 
commitSha);
+        } catch (final RuntimeException e) {
+            throw new FlowRegistryException("Failed to get the latest commit 
of [%s] from commit [%s]".formatted(filePath, commitSha), e);
+        }
     }
 
     @Override
@@ -739,6 +775,7 @@ public abstract class AbstractGitFlowRegistryClient extends 
AbstractFlowRegistry
 
     protected void invalidateClient() {
         clientInitialized.set(false);
+        branchStateCache.clear();
         if (repositoryClient != null) {
             try {
                 repositoryClient.close();
diff --git 
a/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/GitBranchStateCache.java
 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/GitBranchStateCache.java
new file mode 100644
index 00000000000..54b7b2c48cb
--- /dev/null
+++ 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/GitBranchStateCache.java
@@ -0,0 +1,228 @@
+/*
+ *  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.nifi.registry.flow.git;
+
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.registry.flow.FlowRegistryException;
+import org.apache.nifi.registry.flow.FlowRegistryPermissions;
+import org.apache.nifi.registry.flow.RegisteredFlow;
+import org.apache.nifi.registry.flow.RegisteredFlowVersionInfo;
+import org.apache.nifi.registry.flow.git.client.GitRepositoryClient;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Supplier;
+
+/**
+ * Remembers, per branch, what was read for each flow file at the head of the 
branch.
+ * <p>
+ * The framework asks for the flow and its latest version for every versioned 
Process Group on every
+ * registry synchronization. Without this cache each of those questions costs 
requests to the Git provider,
+ * so the cost of a synchronization grows with the number of versioned Process 
Groups. With it, each question
+ * costs a check of the branch head, which the repository client makes cheap 
while the head is unchanged, plus
+ * requests for the files touched since the previous head.
+ * <p>
+ * Each value is read at the head commit of the state that holds it, and a 
state is used only while the branch head
+ * is still that commit, so a value is never answered for another head. A 
state is also used only with the repository
+ * client instance it was read with, so values read before a change of 
configuration are never answered after it.
+ */
+final class GitBranchStateCache {
+
+    private final Supplier<ComponentLog> loggerSupplier;
+    private final Map<String, BranchState> branchStates = new 
ConcurrentHashMap<>();
+
+    GitBranchStateCache(final Supplier<ComponentLog> loggerSupplier) {
+        this.loggerSupplier = loggerSupplier;
+    }
+
+    /**
+     * Gets the state of the branch at its current head. When the head moved 
since the state was read, the values for
+     * files touched between the two heads are dropped; when those files 
cannot be determined, every value is dropped.
+     *
+     * @param repositoryClient the repository client
+     * @param branch the branch
+     * @return the state of the branch, or empty when the repository client 
cannot report the branch head
+     */
+    Optional<BranchState> getState(final GitRepositoryClient repositoryClient, 
final String branch) throws IOException, FlowRegistryException {
+        final Optional<String> headSha = getBranchHeadSha(repositoryClient, 
branch);
+        if (headSha.isEmpty()) {
+            return Optional.empty();
+        }
+
+        final BranchState state = branchStates.get(branch);
+        if (state != null && state.isReadWith(repositoryClient) && 
state.headSha.equals(headSha.get())) {
+            return Optional.of(state);
+        }
+        return Optional.of(moveState(repositoryClient, branch, state, 
headSha.get()));
+    }
+
+    // A client that returns a branch head is expected to answer for it, so a 
runtime failure is reported as a registry failure
+    private static Optional<String> getBranchHeadSha(final GitRepositoryClient 
repositoryClient, final String branch) throws IOException, 
FlowRegistryException {
+        try {
+            return repositoryClient.getBranchHeadSha(branch);
+        } catch (final RuntimeException e) {
+            throw new FlowRegistryException("Failed to get the head commit of 
branch [%s]".formatted(branch), e);
+        }
+    }
+
+    // Each call answers for the head it saw. The heads are compared before 
the state is replaced, so no call waits for
+    // another call's comparison: concurrent calls that saw the same new head 
may each compare the heads, and calls that
+    // saw different heads may move the state back and forth, which costs 
requests but never answers a value for another head.
+    private BranchState moveState(final GitRepositoryClient repositoryClient, 
final String branch, final BranchState previousState, final String headSha) {
+        final boolean previousStateUsable = previousState != null && 
previousState.isReadWith(repositoryClient);
+        final Optional<Set<String>> changedPaths = previousStateUsable
+                ? getChangedPaths(repositoryClient, branch, 
previousState.headSha, headSha)
+                : Optional.empty();
+
+        return branchStates.compute(branch, (key, currentState) -> {
+            if (currentState != null && 
currentState.isReadWith(repositoryClient) && 
currentState.headSha.equals(headSha)) {
+                return currentState;
+            }
+
+            // Values of the previous state were read at its head, so those 
for files not touched since are valid at the new head
+            final BranchState movedState = new BranchState(repositoryClient, 
headSha);
+            changedPaths.ifPresent(paths -> 
movedState.retainUnchanged(previousState, paths));
+            return movedState;
+        });
+    }
+
+    // A failed comparison, such as Not Found when the previous head was 
removed by a force push, leaves the touched
+    // files unknown, so the new state starts empty
+    private Optional<Set<String>> getChangedPaths(final GitRepositoryClient 
repositoryClient, final String branch, final String fromCommitSha, final String 
toCommitSha) {
+        try {
+            return repositoryClient.getChangedPaths(fromCommitSha, 
toCommitSha);
+        } catch (final FileNotFoundException e) {
+            loggerSupplier.get().debug("Paths changed on branch [{}] from [{}] 
to [{}] not found, dropping every cached value", branch, fromCommitSha, 
toCommitSha, e);
+            return Optional.empty();
+        } catch (final IOException | FlowRegistryException | RuntimeException 
e) {
+            loggerSupplier.get().warn("Paths changed on branch [{}] from [{}] 
to [{}] could not be determined, dropping every cached value", branch, 
fromCommitSha, toCommitSha, e);
+            return Optional.empty();
+        }
+    }
+
+    /**
+     * Drops every state, releasing the repository client they were read with.
+     */
+    void clear() {
+        branchStates.clear();
+    }
+
+    /**
+     * The latest commit of a file as read from the repository; the SHA is 
null when no commit changed the file.
+     */
+    record LatestVersion(String commitSha) {
+        Optional<String> toOptional() {
+            return Optional.ofNullable(commitSha);
+        }
+    }
+
+    static final class BranchState {
+        private final GitRepositoryClient repositoryClient;
+        private final String headSha;
+        private final Map<String, LatestVersion> latestVersions = new 
ConcurrentHashMap<>();
+        private final Map<String, RegisteredFlow> flows = new 
ConcurrentHashMap<>();
+
+        private BranchState(final GitRepositoryClient repositoryClient, final 
String headSha) {
+            this.repositoryClient = repositoryClient;
+            this.headSha = headSha;
+        }
+
+        /**
+         * @return the SHA of the head commit the values of this state are 
read at
+         */
+        String getHeadSha() {
+            return headSha;
+        }
+
+        private boolean isReadWith(final GitRepositoryClient client) {
+            return repositoryClient == client;
+        }
+
+        /**
+         * @return the latest version read for the file, empty when it was not 
read since the head of the branch changed
+         */
+        Optional<LatestVersion> getLatestVersion(final String path) {
+            return Optional.ofNullable(latestVersions.get(path));
+        }
+
+        void putLatestVersion(final String path, final Optional<String> 
commitSha) {
+            latestVersions.put(path, new 
LatestVersion(commitSha.orElse(null)));
+        }
+
+        Optional<RegisteredFlow> getFlow(final String path) {
+            return Optional.ofNullable(flows.get(path)).map(BranchState::copy);
+        }
+
+        void putFlow(final String path, final RegisteredFlow flow) {
+            flows.put(path, copy(flow));
+        }
+
+        private void retainUnchanged(final BranchState previousState, final 
Set<String> changedPaths) {
+            previousState.latestVersions.forEach((path, latestVersion) -> {
+                if (!changedPaths.contains(path)) {
+                    latestVersions.put(path, latestVersion);
+                }
+            });
+            previousState.flows.forEach((path, flow) -> {
+                if (!changedPaths.contains(path)) {
+                    flows.put(path, flow);
+                }
+            });
+        }
+
+        // Callers change the returned flow, so the cache keeps and hands out 
copies
+        private static RegisteredFlow copy(final RegisteredFlow flow) {
+            final RegisteredFlow copy = new RegisteredFlow();
+            copy.setIdentifier(flow.getIdentifier());
+            copy.setName(flow.getName());
+            copy.setDescription(flow.getDescription());
+            copy.setBranch(flow.getBranch());
+            copy.setBucketIdentifier(flow.getBucketIdentifier());
+            copy.setBucketName(flow.getBucketName());
+            copy.setCreatedTimestamp(flow.getCreatedTimestamp());
+            copy.setLastModifiedTimestamp(flow.getLastModifiedTimestamp());
+            copy.setPermissions(copy(flow.getPermissions()));
+            copy.setVersionCount(flow.getVersionCount());
+            copy.setVersionInfo(copy(flow.getVersionInfo()));
+            return copy;
+        }
+
+        private static FlowRegistryPermissions copy(final 
FlowRegistryPermissions permissions) {
+            if (permissions == null) {
+                return null;
+            }
+            final FlowRegistryPermissions copy = new FlowRegistryPermissions();
+            copy.setCanRead(permissions.getCanRead());
+            copy.setCanWrite(permissions.getCanWrite());
+            copy.setCanDelete(permissions.getCanDelete());
+            return copy;
+        }
+
+        private static RegisteredFlowVersionInfo copy(final 
RegisteredFlowVersionInfo versionInfo) {
+            if (versionInfo == null) {
+                return null;
+            }
+            final RegisteredFlowVersionInfo copy = new 
RegisteredFlowVersionInfo();
+            copy.setVersion(versionInfo.getVersion());
+            return copy;
+        }
+    }
+}
diff --git 
a/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/client/GitRepositoryClient.java
 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/client/GitRepositoryClient.java
index b7aa4ad8459..bfa806a2b79 100644
--- 
a/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/client/GitRepositoryClient.java
+++ 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/main/java/org/apache/nifi/registry/flow/git/client/GitRepositoryClient.java
@@ -94,6 +94,54 @@ public interface GitRepositoryClient {
         return getCommits(path, 
branch).stream().findFirst().map(GitCommit::id);
     }
 
+    /**
+     * Retrieves the SHA of the commit at the head of the given branch. 
Clients that support it let the registry client
+     * answer repeated questions about unchanged flows without further 
requests. The registry client checks the head
+     * before answering each question from what it remembers, so 
implementations should make this check cheap while the
+     * head is unchanged. Clients that return a head must also implement 
{@link #getLatestCommitShaAtCommit(String, String)},
+     * and should implement {@link #getChangedPaths(String, String)}, without 
which every remembered value is dropped
+     * whenever the head moves.
+     *
+     * @param branch the branch name
+     * @return the SHA of the head commit, or empty if the client does not 
support it
+     * @throws IOException if an I/O error occurs
+     * @throws FlowRegistryException if a non-I/O error occurs
+     */
+    default Optional<String> getBranchHeadSha(String branch) throws 
IOException, FlowRegistryException {
+        return Optional.empty();
+    }
+
+    /**
+     * Retrieves the SHA of the most recent commit that changed the given 
path, among the given commit and its ancestors.
+     *
+     * @param path the path of the file
+     * @param commitSha the SHA of the commit to start from
+     * @return the SHA of the latest commit for the path, or empty when no 
commit changed the path
+     * @throws IOException if an I/O error occurs
+     * @throws FlowRegistryException if a non-I/O error occurs
+     * @throws UnsupportedOperationException if the client does not return a 
branch head from {@link #getBranchHeadSha(String)}
+     */
+    default Optional<String> getLatestCommitShaAtCommit(String path, String 
commitSha) throws IOException, FlowRegistryException {
+        throw new UnsupportedOperationException("Latest commit from a given 
commit not supported by " + getClass().getSimpleName());
+    }
+
+    /**
+     * Retrieves the paths of the files touched by any commit from one commit, 
exclusive, to a later one, inclusive,
+     * relative to the repository path of the client. A renamed file 
contributes both its old and its new path. The
+     * result is not the net difference between the two commits: a file 
changed and then reverted within the range is
+     * included.
+     *
+     * @param fromCommitSha the SHA of the earlier commit
+     * @param toCommitSha the SHA of the later commit
+     * @return the touched paths, or empty if they cannot be determined, for 
example when the later commit does not
+     *         descend from the earlier one
+     * @throws IOException if an I/O error occurs
+     * @throws FlowRegistryException if a non-I/O error occurs
+     */
+    default Optional<Set<String>> getChangedPaths(String fromCommitSha, String 
toCommitSha) throws IOException, FlowRegistryException {
+        return Optional.empty();
+    }
+
     /**
      * Retrieves the content for the file at the given path on the given 
branch.
      *
diff --git 
a/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/test/java/org/apache/nifi/registry/flow/git/AbstractGitFlowRegistryClientTest.java
 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/test/java/org/apache/nifi/registry/flow/git/AbstractGitFlowRegistryClientTest.java
index 3466b6fcd3d..877e0c08cca 100644
--- 
a/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/test/java/org/apache/nifi/registry/flow/git/AbstractGitFlowRegistryClientTest.java
+++ 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/test/java/org/apache/nifi/registry/flow/git/AbstractGitFlowRegistryClientTest.java
@@ -20,11 +20,17 @@ import org.apache.nifi.components.ConfigVerificationResult;
 import org.apache.nifi.components.ConfigVerificationResult.Outcome;
 import org.apache.nifi.components.PropertyDescriptor;
 import org.apache.nifi.components.PropertyValue;
+import org.apache.nifi.flow.VersionedProcessGroup;
 import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.registry.flow.FlowLocation;
 import org.apache.nifi.registry.flow.FlowRegistryClientConfigurationContext;
 import org.apache.nifi.registry.flow.FlowRegistryClientInitializationContext;
 import org.apache.nifi.registry.flow.FlowRegistryException;
 import org.apache.nifi.registry.flow.FlowVersionLocation;
+import org.apache.nifi.registry.flow.RegisterAction;
+import org.apache.nifi.registry.flow.RegisteredFlow;
+import org.apache.nifi.registry.flow.RegisteredFlowSnapshot;
+import org.apache.nifi.registry.flow.RegisteredFlowSnapshotMetadata;
 import org.apache.nifi.registry.flow.git.client.GitCommit;
 import org.apache.nifi.registry.flow.git.client.GitCreateContentRequest;
 import org.apache.nifi.registry.flow.git.client.GitRepositoryClient;
@@ -32,8 +38,10 @@ import org.apache.nifi.util.MockComponentLog;
 import org.apache.nifi.util.MockPropertyValue;
 import org.junit.jupiter.api.Test;
 
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
@@ -43,10 +51,20 @@ import java.util.concurrent.atomic.AtomicReference;
 import javax.net.ssl.SSLContext;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 class AbstractGitFlowRegistryClientTest {
+    private static final String FLOW_PATH = "bucket-a/flow-1.json";
+    private static final FlowLocation FLOW_LOCATION = new FlowLocation("main", 
"bucket-a", "flow-1");
 
     @Test
     void verifySuccessful() {
@@ -161,10 +179,116 @@ class AbstractGitFlowRegistryClientTest {
         assertTrue(repositoryClient.getCreatedBranchCommit().isEmpty());
     }
 
+    @Test
+    void repeatedQuestionsForUnchangedBranchAreAnsweredFromCache() throws 
Exception {
+        final GitRepositoryClient repositoryClient = mockRepositoryClient(new 
AtomicReference<>("head-1"));
+        when(repositoryClient.getLatestCommitShaAtCommit(FLOW_PATH, 
"head-1")).thenReturn(Optional.of("commit-1"));
+        when(repositoryClient.getContentFromCommit(FLOW_PATH, 
"head-1")).thenAnswer(invocation -> getFlowContent("Flow 1"));
+
+        final TestGitFlowRegistryClient flowRegistryClient = 
createFlowRegistryClient(repositoryClient);
+        final FlowRegistryClientConfigurationContext context = 
createContext("main", "[.].*");
+
+        for (int i = 0; i < 3; i++) {
+            assertEquals(Optional.of("commit-1"), 
flowRegistryClient.getLatestVersion(context, FLOW_LOCATION));
+            final RegisteredFlow flow = flowRegistryClient.getFlow(context, 
FLOW_LOCATION);
+            assertEquals("Flow 1", flow.getName());
+            assertEquals("bucket-a", flow.getBucketIdentifier());
+            assertEquals("main", flow.getBranch());
+        }
+
+        verify(repositoryClient, times(6)).getBranchHeadSha("main");
+        verify(repositoryClient, 
times(1)).getLatestCommitShaAtCommit(FLOW_PATH, "head-1");
+        verify(repositoryClient, times(1)).getContentFromCommit(FLOW_PATH, 
"head-1");
+        verify(repositoryClient, never()).getLatestCommitSha(anyString(), 
anyString());
+        verify(repositoryClient, never()).getContentFromBranch(anyString(), 
anyString());
+    }
+
+    @Test
+    void commitIsVisibleOnNextRead() throws Exception {
+        final AtomicReference<String> head = new AtomicReference<>("head-1");
+        final GitRepositoryClient repositoryClient = 
mockRepositoryClient(head);
+        when(repositoryClient.getLatestCommitShaAtCommit(FLOW_PATH, 
"head-1")).thenReturn(Optional.of("head-1"));
+        when(repositoryClient.getContentFromCommit(FLOW_PATH, 
"head-1")).thenAnswer(invocation -> getFlowContent("Flow 1"));
+
+        final TestGitFlowRegistryClient flowRegistryClient = 
createFlowRegistryClient(repositoryClient);
+        final FlowRegistryClientConfigurationContext context = 
createContext("main", "[.].*");
+        assertEquals(Optional.of("head-1"), 
flowRegistryClient.getLatestVersion(context, FLOW_LOCATION));
+        assertEquals("Flow 1", flowRegistryClient.getFlow(context, 
FLOW_LOCATION).getName());
+
+        when(repositoryClient.hasWritePermission()).thenReturn(true);
+        when(repositoryClient.getLatestCommitSha(FLOW_PATH, 
"main")).thenReturn(Optional.of("head-1"));
+        when(repositoryClient.getContentShaAtCommit(FLOW_PATH, 
"head-1")).thenReturn(Optional.of("blob-1"));
+        when(repositoryClient.getContentFromBranch(FLOW_PATH, 
"main")).thenAnswer(invocation -> getFlowContent("Flow 1"));
+        when(repositoryClient.createContent(any())).thenAnswer(invocation -> {
+            head.set("head-2");
+            return "head-2";
+        });
+        flowRegistryClient.registerFlowSnapshot(context, 
createFlowSnapshot("head-1"), RegisterAction.COMMIT);
+
+        when(repositoryClient.getChangedPaths("head-1", 
"head-2")).thenReturn(Optional.of(Set.of(FLOW_PATH)));
+        when(repositoryClient.getLatestCommitShaAtCommit(FLOW_PATH, 
"head-2")).thenReturn(Optional.of("head-2"));
+        when(repositoryClient.getContentFromCommit(FLOW_PATH, 
"head-2")).thenAnswer(invocation -> getFlowContent("Flow 2"));
+
+        assertEquals(Optional.of("head-2"), 
flowRegistryClient.getLatestVersion(context, FLOW_LOCATION));
+        assertEquals("Flow 2", flowRegistryClient.getFlow(context, 
FLOW_LOCATION).getName());
+        verify(repositoryClient, times(1)).getContentFromCommit(FLOW_PATH, 
"head-1");
+        verify(repositoryClient, times(1)).getContentFromCommit(FLOW_PATH, 
"head-2");
+    }
+
+    @Test
+    void runtimeFailureOfLatestCommitAtCommitIsRegistryFailure() throws 
Exception {
+        final GitRepositoryClient repositoryClient = mockRepositoryClient(new 
AtomicReference<>("head-1"));
+        when(repositoryClient.getLatestCommitShaAtCommit(FLOW_PATH, 
"head-1")).thenThrow(new UnsupportedOperationException("Not supported"));
+
+        final TestGitFlowRegistryClient flowRegistryClient = 
createFlowRegistryClient(repositoryClient);
+        final FlowRegistryClientConfigurationContext context = 
createContext("main", "[.].*");
+
+        final FlowRegistryException exception = 
assertThrows(FlowRegistryException.class, () -> 
flowRegistryClient.getLatestVersion(context, FLOW_LOCATION));
+        assertInstanceOf(UnsupportedOperationException.class, 
exception.getCause());
+    }
+
+    private GitRepositoryClient mockRepositoryClient(final 
AtomicReference<String> head) throws Exception {
+        final GitRepositoryClient repositoryClient = 
mock(GitRepositoryClient.class);
+        when(repositoryClient.hasReadPermission()).thenReturn(true);
+        when(repositoryClient.getBranchHeadSha("main")).thenAnswer(invocation 
-> Optional.of(head.get()));
+        
when(repositoryClient.getTopLevelDirectoryNames("main")).thenReturn(Set.of("bucket-a"));
+        return repositoryClient;
+    }
+
+    private TestGitFlowRegistryClient createFlowRegistryClient(final 
GitRepositoryClient repositoryClient) {
+        final TestGitFlowRegistryClient flowRegistryClient = new 
TestGitFlowRegistryClient(() -> repositoryClient, "[email protected]");
+        flowRegistryClient.initialize(createInitializationContext());
+        return flowRegistryClient;
+    }
+
+    private static RegisteredFlowSnapshot createFlowSnapshot(final String 
version) {
+        final RegisteredFlowSnapshotMetadata snapshotMetadata = new 
RegisteredFlowSnapshotMetadata();
+        snapshotMetadata.setBranch("main");
+        snapshotMetadata.setBucketIdentifier("bucket-a");
+        snapshotMetadata.setFlowIdentifier("flow-1");
+        snapshotMetadata.setVersion(version);
+
+        final VersionedProcessGroup flowContents = new VersionedProcessGroup();
+        flowContents.setIdentifier("contents");
+
+        final RegisteredFlowSnapshot flowSnapshot = new 
RegisteredFlowSnapshot();
+        flowSnapshot.setSnapshotMetadata(snapshotMetadata);
+        flowSnapshot.setFlowContents(flowContents);
+        return flowSnapshot;
+    }
+
+    private static InputStream getFlowContent(final String name) {
+        return new ByteArrayInputStream("""
+                {"flow": {"identifier": "flow-1", "name": "%s"}, 
"flowContents": {"identifier": "contents"}}
+                """.formatted(name).getBytes(StandardCharsets.UTF_8));
+    }
+
     private FlowRegistryClientConfigurationContext createContext(final String 
branch, final String exclusionPattern) {
         final Map<PropertyDescriptor, PropertyValue> properties = Map.of(
                 AbstractGitFlowRegistryClient.REPOSITORY_BRANCH, new 
MockPropertyValue(branch),
-                AbstractGitFlowRegistryClient.DIRECTORY_FILTER_EXCLUDE, new 
MockPropertyValue(exclusionPattern)
+                AbstractGitFlowRegistryClient.DIRECTORY_FILTER_EXCLUDE, new 
MockPropertyValue(exclusionPattern),
+                AbstractGitFlowRegistryClient.COMMIT_AUTHOR_SOURCE, new 
MockPropertyValue(AbstractGitFlowRegistryClient.CommitAuthorSource.SERVICE_USER.getValue()),
+                AbstractGitFlowRegistryClient.PARAMETER_CONTEXT_VALUES, new 
MockPropertyValue(AbstractGitFlowRegistryClient.ParameterContextValuesStrategy.RETAIN.getValue())
         );
 
         return new FlowRegistryClientConfigurationContext() {
diff --git 
a/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/test/java/org/apache/nifi/registry/flow/git/GitBranchStateCacheTest.java
 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/test/java/org/apache/nifi/registry/flow/git/GitBranchStateCacheTest.java
new file mode 100644
index 00000000000..cae75562f06
--- /dev/null
+++ 
b/nifi-extension-bundles/nifi-extension-utils/nifi-git-flow-registry/src/test/java/org/apache/nifi/registry/flow/git/GitBranchStateCacheTest.java
@@ -0,0 +1,273 @@
+/*
+ *  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.nifi.registry.flow.git;
+
+import org.apache.nifi.registry.flow.FlowRegistryException;
+import org.apache.nifi.registry.flow.FlowRegistryPermissions;
+import org.apache.nifi.registry.flow.RegisteredFlow;
+import org.apache.nifi.registry.flow.RegisteredFlowVersionInfo;
+import org.apache.nifi.registry.flow.git.client.GitRepositoryClient;
+import org.apache.nifi.util.MockComponentLog;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.FileNotFoundException;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class GitBranchStateCacheTest {
+    private static final String BRANCH = "main";
+    private static final String CHANGED_PATH = "bucket/changed.json";
+    private static final String UNCHANGED_PATH = "bucket/unchanged.json";
+    private static final long WAIT_SECONDS = 5;
+
+    private GitRepositoryClient repositoryClient;
+    private GitBranchStateCache cache;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        repositoryClient = mock(GitRepositoryClient.class);
+        
when(repositoryClient.getBranchHeadSha(BRANCH)).thenReturn(Optional.of("head-1"));
+        cache = new GitBranchStateCache(() -> new MockComponentLog("cache", 
this));
+    }
+
+    @Test
+    void testHeadCheckedOnEveryCall() throws Exception {
+        final GitBranchStateCache.BranchState firstState = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+        firstState.putLatestVersion(UNCHANGED_PATH, Optional.of("commit-1"));
+        final GitBranchStateCache.BranchState secondState = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+
+        assertSame(firstState, secondState);
+        assertEquals("head-1", secondState.getHeadSha());
+        assertEquals(Optional.of("commit-1"), 
secondState.getLatestVersion(UNCHANGED_PATH).orElseThrow().toOptional());
+        verify(repositoryClient, times(2)).getBranchHeadSha(BRANCH);
+        verify(repositoryClient, never()).getChangedPaths(anyString(), 
anyString());
+    }
+
+    @Test
+    void testMovedHeadDropsOnlyChangedPaths() throws Exception {
+        final GitBranchStateCache.BranchState firstState = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+        firstState.putLatestVersion(CHANGED_PATH, Optional.of("commit-1"));
+        firstState.putLatestVersion(UNCHANGED_PATH, Optional.of("commit-1"));
+        firstState.putFlow(CHANGED_PATH, createFlow("changed"));
+        firstState.putFlow(UNCHANGED_PATH, createFlow("unchanged"));
+
+        
when(repositoryClient.getBranchHeadSha(BRANCH)).thenReturn(Optional.of("head-2"));
+        when(repositoryClient.getChangedPaths("head-1", 
"head-2")).thenReturn(Optional.of(Set.of(CHANGED_PATH)));
+        final GitBranchStateCache.BranchState state = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+
+        assertEquals("head-2", state.getHeadSha());
+        assertTrue(state.getLatestVersion(CHANGED_PATH).isEmpty());
+        assertTrue(state.getFlow(CHANGED_PATH).isEmpty());
+        assertEquals(Optional.of("commit-1"), 
state.getLatestVersion(UNCHANGED_PATH).orElseThrow().toOptional());
+        assertEquals("unchanged", 
state.getFlow(UNCHANGED_PATH).orElseThrow().getName());
+    }
+
+    @Test
+    void testMovedHeadWithUnknownChangesDropsEverything() throws Exception {
+        cache.getState(repositoryClient, 
BRANCH).orElseThrow().putLatestVersion(UNCHANGED_PATH, Optional.of("commit-1"));
+
+        
when(repositoryClient.getBranchHeadSha(BRANCH)).thenReturn(Optional.of("head-2"));
+        when(repositoryClient.getChangedPaths("head-1", 
"head-2")).thenReturn(Optional.empty());
+
+        assertTrue(cache.getState(repositoryClient, 
BRANCH).orElseThrow().getLatestVersion(UNCHANGED_PATH).isEmpty());
+    }
+
+    @Test
+    void testFailedComparisonDropsEverythingAndMovesToNewHead() throws 
Exception {
+        cache.getState(repositoryClient, 
BRANCH).orElseThrow().putLatestVersion(UNCHANGED_PATH, Optional.of("commit-1"));
+
+        
when(repositoryClient.getBranchHeadSha(BRANCH)).thenReturn(Optional.of("head-2"));
+        when(repositoryClient.getChangedPaths("head-1", 
"head-2")).thenThrow(new FileNotFoundException("Not Found"));
+
+        final GitBranchStateCache.BranchState state = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+        assertEquals("head-2", state.getHeadSha());
+        assertTrue(state.getLatestVersion(UNCHANGED_PATH).isEmpty());
+
+        assertSame(state, cache.getState(repositoryClient, 
BRANCH).orElseThrow());
+        verify(repositoryClient, times(1)).getChangedPaths(anyString(), 
anyString());
+    }
+
+    @Test
+    void testRuntimeFailureOfComparisonDropsEverythingAndMovesToNewHead() 
throws Exception {
+        cache.getState(repositoryClient, 
BRANCH).orElseThrow().putLatestVersion(UNCHANGED_PATH, Optional.of("commit-1"));
+
+        
when(repositoryClient.getBranchHeadSha(BRANCH)).thenReturn(Optional.of("head-2"));
+        when(repositoryClient.getChangedPaths("head-1", 
"head-2")).thenThrow(new IllegalStateException("Comparison failed"));
+
+        final GitBranchStateCache.BranchState state = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+        assertEquals("head-2", state.getHeadSha());
+        assertTrue(state.getLatestVersion(UNCHANGED_PATH).isEmpty());
+
+        assertSame(state, cache.getState(repositoryClient, 
BRANCH).orElseThrow());
+        verify(repositoryClient, times(1)).getChangedPaths(anyString(), 
anyString());
+    }
+
+    @Test
+    void testRuntimeFailureOfHeadCheckIsRegistryFailure() throws Exception {
+        when(repositoryClient.getBranchHeadSha(BRANCH)).thenThrow(new 
UnsupportedOperationException("Not supported"));
+
+        final FlowRegistryException exception = 
assertThrows(FlowRegistryException.class, () -> 
cache.getState(repositoryClient, BRANCH));
+        assertInstanceOf(UnsupportedOperationException.class, 
exception.getCause());
+    }
+
+    @Test
+    void testComparisonDoesNotHoldOtherCallsForTheBranch() throws Exception {
+        cache.getState(repositoryClient, 
BRANCH).orElseThrow().putLatestVersion(UNCHANGED_PATH, Optional.of("commit-1"));
+
+        
when(repositoryClient.getBranchHeadSha(BRANCH)).thenReturn(Optional.of("head-2"));
+        final CountDownLatch comparisonStarted = new CountDownLatch(1);
+        final CountDownLatch comparisonReleased = new CountDownLatch(1);
+        final AtomicInteger comparisons = new AtomicInteger();
+        when(repositoryClient.getChangedPaths("head-1", 
"head-2")).thenAnswer(invocation -> {
+            if (comparisons.incrementAndGet() == 1) {
+                comparisonStarted.countDown();
+                comparisonReleased.await(WAIT_SECONDS, TimeUnit.SECONDS);
+            }
+            return Optional.of(Set.of());
+        });
+
+        final ExecutorService executor = Executors.newFixedThreadPool(2);
+        try {
+            final Future<GitBranchStateCache.BranchState> slowCall = 
executor.submit(() -> cache.getState(repositoryClient, BRANCH).orElseThrow());
+            assertTrue(comparisonStarted.await(WAIT_SECONDS, 
TimeUnit.SECONDS));
+
+            // Answered while the first comparison is still running
+            final Future<GitBranchStateCache.BranchState> otherCall = 
executor.submit(() -> cache.getState(repositoryClient, BRANCH).orElseThrow());
+            final GitBranchStateCache.BranchState state = 
otherCall.get(WAIT_SECONDS, TimeUnit.SECONDS);
+            assertEquals("head-2", state.getHeadSha());
+            assertEquals(Optional.of("commit-1"), 
state.getLatestVersion(UNCHANGED_PATH).orElseThrow().toOptional());
+
+            comparisonReleased.countDown();
+            assertSame(state, slowCall.get(WAIT_SECONDS, TimeUnit.SECONDS));
+        } finally {
+            comparisonReleased.countDown();
+            executor.shutdownNow();
+        }
+    }
+
+    @Test
+    void testEachCallAnswersForTheHeadItSaw() throws Exception {
+        cache.getState(repositoryClient, 
BRANCH).orElseThrow().putLatestVersion(UNCHANGED_PATH, Optional.of("commit-1"));
+
+        // While this call waits for its head check, another call sees the 
head moved to head-2 and moves the state there;
+        // this call's check is answered last, still with the earlier head-1
+        final AtomicInteger headChecks = new AtomicInteger();
+        final AtomicReference<GitBranchStateCache.BranchState> laterState = 
new AtomicReference<>();
+        when(repositoryClient.getBranchHeadSha(BRANCH)).thenAnswer(invocation 
-> {
+            if (headChecks.incrementAndGet() > 1) {
+                return Optional.of("head-2");
+            }
+            final GitBranchStateCache.BranchState state = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+            state.putLatestVersion(UNCHANGED_PATH, Optional.of("commit-2"));
+            laterState.set(state);
+            return Optional.of("head-1");
+        });
+        when(repositoryClient.getChangedPaths("head-1", 
"head-2")).thenReturn(Optional.of(Set.of()));
+
+        final GitBranchStateCache.BranchState state = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+
+        assertEquals("head-2", laterState.get().getHeadSha());
+        assertEquals("head-1", state.getHeadSha());
+        assertTrue(state.getLatestVersion(UNCHANGED_PATH).isEmpty());
+    }
+
+    @Test
+    void testStateIsNotUsedWithOtherRepositoryClient() throws Exception {
+        cache.getState(repositoryClient, 
BRANCH).orElseThrow().putLatestVersion(UNCHANGED_PATH, Optional.of("commit-1"));
+
+        final GitRepositoryClient reconfiguredClient = 
mock(GitRepositoryClient.class);
+        
when(reconfiguredClient.getBranchHeadSha(BRANCH)).thenReturn(Optional.of("head-1"));
+        final GitBranchStateCache.BranchState state = 
cache.getState(reconfiguredClient, BRANCH).orElseThrow();
+
+        assertTrue(state.getLatestVersion(UNCHANGED_PATH).isEmpty());
+        verify(reconfiguredClient, never()).getChangedPaths(anyString(), 
anyString());
+
+        // A call still running with the previous client does not get the new 
client's state either
+        state.putLatestVersion(UNCHANGED_PATH, Optional.of("commit-2"));
+        assertTrue(cache.getState(repositoryClient, 
BRANCH).orElseThrow().getLatestVersion(UNCHANGED_PATH).isEmpty());
+    }
+
+    @Test
+    void testUnsupportedBranchHeadDisablesCache() throws Exception {
+        
when(repositoryClient.getBranchHeadSha(BRANCH)).thenReturn(Optional.empty());
+
+        assertTrue(cache.getState(repositoryClient, BRANCH).isEmpty());
+    }
+
+    @Test
+    void testFlowsAreCopied() throws Exception {
+        final GitBranchStateCache.BranchState state = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+        final RegisteredFlow flow = createFlow("original");
+        state.putFlow(CHANGED_PATH, flow);
+        flow.setName("changed after put");
+        state.getFlow(CHANGED_PATH).orElseThrow().setName("changed after get");
+
+        assertEquals("original", 
state.getFlow(CHANGED_PATH).orElseThrow().getName());
+    }
+
+    @Test
+    void testFlowPermissionsAndVersionInfoAreCopied() throws Exception {
+        final GitBranchStateCache.BranchState state = 
cache.getState(repositoryClient, BRANCH).orElseThrow();
+        final RegisteredFlow flow = createFlow("original");
+        final FlowRegistryPermissions permissions = new 
FlowRegistryPermissions();
+        permissions.setCanRead(true);
+        flow.setPermissions(permissions);
+        final RegisteredFlowVersionInfo versionInfo = new 
RegisteredFlowVersionInfo();
+        versionInfo.setVersion(1);
+        flow.setVersionInfo(versionInfo);
+        state.putFlow(CHANGED_PATH, flow);
+
+        permissions.setCanRead(false);
+        versionInfo.setVersion(2);
+        final RegisteredFlow returned = 
state.getFlow(CHANGED_PATH).orElseThrow();
+        returned.getPermissions().setCanWrite(true);
+        returned.getVersionInfo().setVersion(3);
+
+        final RegisteredFlow cached = 
state.getFlow(CHANGED_PATH).orElseThrow();
+        assertTrue(cached.getPermissions().getCanRead());
+        assertFalse(cached.getPermissions().getCanWrite());
+        assertEquals(1, cached.getVersionInfo().getVersion());
+    }
+
+    private static RegisteredFlow createFlow(final String name) {
+        final RegisteredFlow flow = new RegisteredFlow();
+        flow.setIdentifier(name);
+        flow.setName(name);
+        return flow;
+    }
+}
diff --git 
a/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/main/java/org/apache/nifi/github/ConditionalBranchReferenceConnector.java
 
b/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/main/java/org/apache/nifi/github/ConditionalBranchReferenceConnector.java
new file mode 100644
index 00000000000..b2f36dd0d32
--- /dev/null
+++ 
b/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/main/java/org/apache/nifi/github/ConditionalBranchReferenceConnector.java
@@ -0,0 +1,169 @@
+/*
+ *  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.nifi.github;
+
+import org.kohsuke.github.connector.GitHubConnector;
+import org.kohsuke.github.connector.GitHubConnectorRequest;
+import org.kohsuke.github.connector.GitHubConnectorResponse;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Sends each request for a branch reference as a conditional request carrying 
the entity tag of the previous answer.
+ * While the branch head is unchanged GitHub answers Not Modified, which does 
not count against the primary rate limit,
+ * and the previous answer is returned instead. Checking the branch head 
before each cached read is then free while the
+ * head is unchanged. Other requests are sent unchanged.
+ */
+final class ConditionalBranchReferenceConnector implements GitHubConnector {
+
+    private static final String GET_METHOD = "GET";
+    private static final String BRANCH_REFERENCE_PATH = "/git/refs/heads/";
+    private static final String ENTITY_TAG_HEADER = "ETag";
+    private static final String IF_NONE_MATCH_HEADER = "If-None-Match";
+    // The stored body is already decoded, so headers describing the encoded 
body no longer apply
+    private static final Set<String> ENCODED_BODY_HEADERS = 
Set.of("content-encoding", "content-length");
+
+    private final GitHubConnector connector;
+    private final Map<String, StoredResponse> storedResponses = new 
ConcurrentHashMap<>();
+
+    ConditionalBranchReferenceConnector(final GitHubConnector connector) {
+        this.connector = Objects.requireNonNull(connector, "Connector 
required");
+    }
+
+    @Override
+    public GitHubConnectorResponse send(final GitHubConnectorRequest request) 
throws IOException {
+        if (!isBranchReferenceRequest(request)) {
+            return connector.send(request);
+        }
+
+        final String url = request.url().toString();
+        final StoredResponse storedResponse = storedResponses.get(url);
+        final GitHubConnectorRequest sentRequest = storedResponse == null ? 
request : new ConditionalRequest(request, storedResponse.entityTag());
+
+        final GitHubConnectorResponse response = connector.send(sentRequest);
+        final int statusCode = response.statusCode();
+        if (storedResponse != null && statusCode == 
HttpURLConnection.HTTP_NOT_MODIFIED) {
+            try (response) {
+                return new StoredBodyResponse(request, 
HttpURLConnection.HTTP_OK, getDecodedBodyHeaders(response), 
storedResponse.body());
+            }
+        }
+
+        final String entityTag = response.header(ENTITY_TAG_HEADER);
+        if (statusCode != HttpURLConnection.HTTP_OK || entityTag == null) {
+            // Keep the stored answer through transient failures such as rate 
limiting, so the next check stays conditional
+            if (statusCode == HttpURLConnection.HTTP_NOT_FOUND || statusCode 
== HttpURLConnection.HTTP_GONE) {
+                storedResponses.remove(url);
+            }
+            return response;
+        }
+
+        final byte[] body;
+        try (response; InputStream bodyStream = response.bodyStream()) {
+            body = bodyStream.readAllBytes();
+        }
+        storedResponses.put(url, new StoredResponse(entityTag, body));
+        return new StoredBodyResponse(request, statusCode, 
getDecodedBodyHeaders(response), body);
+    }
+
+    private static boolean isBranchReferenceRequest(final 
GitHubConnectorRequest request) {
+        return GET_METHOD.equals(request.method()) && 
request.url().getPath().contains(BRANCH_REFERENCE_PATH);
+    }
+
+    private static Map<String, List<String>> getDecodedBodyHeaders(final 
GitHubConnectorResponse response) {
+        final Map<String, List<String>> headers = new LinkedHashMap<>();
+        response.allHeaders().forEach((name, values) -> {
+            if (name != null && 
!ENCODED_BODY_HEADERS.contains(name.toLowerCase())) {
+                headers.put(name, values);
+            }
+        });
+        return headers;
+    }
+
+    private record StoredResponse(String entityTag, byte[] body) {
+    }
+
+    private static final class ConditionalRequest implements 
GitHubConnectorRequest {
+        private final GitHubConnectorRequest request;
+        private final Map<String, List<String>> headers;
+
+        private ConditionalRequest(final GitHubConnectorRequest request, final 
String entityTag) {
+            this.request = request;
+            final Map<String, List<String>> conditionalHeaders = new 
LinkedHashMap<>(request.allHeaders());
+            conditionalHeaders.put(IF_NONE_MATCH_HEADER, List.of(entityTag));
+            this.headers = conditionalHeaders;
+        }
+
+        @Override
+        public String method() {
+            return request.method();
+        }
+
+        @Override
+        public Map<String, List<String>> allHeaders() {
+            return headers;
+        }
+
+        @Override
+        public String header(final String name) {
+            return IF_NONE_MATCH_HEADER.equalsIgnoreCase(name) ? 
headers.get(IF_NONE_MATCH_HEADER).getFirst() : request.header(name);
+        }
+
+        @Override
+        public String contentType() {
+            return request.contentType();
+        }
+
+        @Override
+        public InputStream body() {
+            return request.body();
+        }
+
+        @Override
+        public URL url() {
+            return request.url();
+        }
+
+        @Override
+        public boolean hasBody() {
+            return request.hasBody();
+        }
+    }
+
+    private static final class StoredBodyResponse extends 
GitHubConnectorResponse {
+        private final byte[] body;
+
+        private StoredBodyResponse(final GitHubConnectorRequest request, final 
int statusCode, final Map<String, List<String>> headers, final byte[] body) {
+            super(request, statusCode, headers);
+            this.body = body;
+        }
+
+        @Override
+        protected InputStream rawBodyStream() {
+            return new ByteArrayInputStream(body);
+        }
+    }
+}
diff --git 
a/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/main/java/org/apache/nifi/github/GitHubRepositoryClient.java
 
b/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/main/java/org/apache/nifi/github/GitHubRepositoryClient.java
index 24bfb297ba9..07010f2db55 100644
--- 
a/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/main/java/org/apache/nifi/github/GitHubRepositoryClient.java
+++ 
b/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/main/java/org/apache/nifi/github/GitHubRepositoryClient.java
@@ -29,6 +29,7 @@ import 
org.apache.nifi.registry.flow.git.client.GitCreateContentRequest;
 import org.apache.nifi.registry.flow.git.client.GitRepositoryClient;
 import org.apache.nifi.ssl.SSLContextProvider;
 import org.kohsuke.github.GHCommit;
+import org.kohsuke.github.GHCompare;
 import org.kohsuke.github.GHContent;
 import org.kohsuke.github.GHContentBuilder;
 import org.kohsuke.github.GHContentUpdateResponse;
@@ -46,6 +47,7 @@ import org.kohsuke.github.PagedIterable;
 import org.kohsuke.github.PagedIterator;
 import org.kohsuke.github.authorization.AppInstallationAuthorizationProvider;
 import org.kohsuke.github.authorization.AuthorizationProvider;
+import org.kohsuke.github.connector.GitHubConnector;
 import org.kohsuke.github.connector.GitHubConnectorResponse;
 import org.kohsuke.github.extras.HttpClientGitHubConnector;
 import org.kohsuke.github.extras.authorization.JWTTokenProvider;
@@ -56,6 +58,7 @@ import java.io.InputStream;
 import java.net.http.HttpClient;
 import java.security.PrivateKey;
 import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -78,6 +81,8 @@ public class GitHubRepositoryClient implements 
GitRepositoryClient {
 
     private static final String BRANCH_REF_PATTERN = "refs/heads/%s";
     private static final int COMMIT_PAGE_SIZE = 10;
+    // GitHub lists at most 300 files in a comparison
+    static final int COMPARE_FILES_LIMIT = 300;
     private static final String UNKNOWN_AUTHOR = "unknown";
 
     private final String repoOwner;
@@ -127,12 +132,16 @@ public class GitHubRepositoryClient implements 
GitRepositoryClient {
         });
 
         // Configure HttpClient connector with SSL context if provided
+        final GitHubConnector connector;
         if (builder.sslContextProvider != null) {
             final HttpClient httpClient = HttpClient.newBuilder()
                     .sslContext(builder.sslContextProvider.createContext())
                     .build();
-            gitHubBuilder.withConnector(new 
HttpClientGitHubConnector(httpClient));
+            connector = new HttpClientGitHubConnector(httpClient);
+        } else {
+            connector = GitHubConnector.DEFAULT;
         }
+        gitHubBuilder.withConnector(new 
ConditionalBranchReferenceConnector(connector));
 
         gitHub = gitHubBuilder.build();
 
@@ -358,7 +367,9 @@ public class GitHubRepositoryClient implements 
GitRepositoryClient {
 
         return execute(() -> {
             try {
-                return getLatestCommitSha(repository, resolvedPath, branch);
+                // The full branch reference is the starting point of the 
listing: no separate request resolves it, and GitHub
+                // does not fall back to a tag or commit with the same name, 
so an unknown branch still fails with Not Found
+                return getLatestCommitSha(repository, resolvedPath, 
BRANCH_REF_PATTERN.formatted(branch));
             } catch (final FileNotFoundException fnf) {
                 throwPathOrBranchNotFound(fnf, resolvedPath, 
BRANCH_REF_PATTERN.formatted(branch));
                 return null;
@@ -366,12 +377,35 @@ public class GitHubRepositoryClient implements 
GitRepositoryClient {
         });
     }
 
-    static Optional<String> getLatestCommitSha(final GHRepository repository, 
final String resolvedPath, final String branch) throws IOException {
-        // The full branch reference is the starting point of the listing: no 
separate request resolves it, and GitHub does
-        // not fall back to a tag or commit with the same name, so an unknown 
branch still fails with Not Found
+    /**
+     * Gets the SHA of the most recent commit that changed the given path, 
among the given commit and its ancestors, with
+     * a single request.
+     *
+     * @param path the path
+     * @param commitSha the SHA of the commit to start from
+     * @return the SHA of the latest commit for the path, or empty when no 
commit changed the path
+     *
+     * @throws IOException if an I/O error happens calling GitHub
+     * @throws FlowRegistryException if a non I/O error happens calling 
GitHub, or the commit does not exist
+     */
+    @Override
+    public Optional<String> getLatestCommitShaAtCommit(final String path, 
final String commitSha) throws IOException, FlowRegistryException {
+        final String resolvedPath = getResolvedPath(path);
+        logger.debug("Getting latest commit for [{}] from commit [{}] in repo 
[{}]", resolvedPath, commitSha, repository.getName());
+
+        return execute(() -> {
+            try {
+                return getLatestCommitSha(repository, resolvedPath, commitSha);
+            } catch (final FileNotFoundException fnf) {
+                throw new FlowRegistryException("Path [" + resolvedPath + "] 
or Commit [" + commitSha + "] not found", fnf);
+            }
+        });
+    }
+
+    static Optional<String> getLatestCommitSha(final GHRepository repository, 
final String resolvedPath, final String startingPoint) throws IOException {
         final PagedIterator<GHCommit> commits = repository.queryCommits()
                 .path(resolvedPath)
-                .from(BRANCH_REF_PATTERN.formatted(branch))
+                .from(startingPoint)
                 .pageSize(1)
                 .list()
                 .iterator();
@@ -386,6 +420,84 @@ public class GitHubRepositoryClient implements 
GitRepositoryClient {
         }
     }
 
+    /**
+     * Gets the SHA of the commit at the head of the given branch with a 
single request. The request is conditional:
+     * while the head is unchanged GitHub answers Not Modified, which does not 
count against the rate limit.
+     *
+     * @param branch the branch
+     * @return the SHA of the head commit
+     *
+     * @throws IOException if an I/O error happens calling GitHub
+     * @throws FlowRegistryException if a non I/O error happens calling 
GitHub, or the branch does not exist
+     */
+    @Override
+    public Optional<String> getBranchHeadSha(final String branch) throws 
IOException, FlowRegistryException {
+        final String branchRef = BRANCH_REF_PATTERN.formatted(branch);
+        logger.debug("Getting head commit of branch [{}] in repo [{}]", 
branch, repository.getName());
+
+        return execute(() -> {
+            try {
+                return 
Optional.of(repository.getRef(branchRef).getObject().getSha());
+            } catch (final FileNotFoundException fnf) {
+                throw new FlowRegistryException("Branch [" + branchRef + "] 
not found", fnf);
+            }
+        });
+    }
+
+    /**
+     * Gets the paths touched from one commit to a later one with a single 
compare request, when the later commit is
+     * the only commit after the earlier one, as for a direct commit to the 
branch. Any other range, such as the merge
+     * of a pull request with its own commits, is not resolved, because the 
compared files are only the net difference
+     * of the range and would miss a file changed and then reverted within it.
+     *
+     * @param fromCommitSha the SHA of the earlier commit
+     * @param toCommitSha the SHA of the later commit
+     * @return the touched paths relative to the repository path, or empty 
when the later commit is not the only commit
+     *         after the earlier one, or the comparison lists as many files as 
GitHub returns at most
+     *
+     * @throws IOException if an I/O error happens calling GitHub
+     * @throws FlowRegistryException if a non I/O error happens calling GitHub
+     */
+    @Override
+    public Optional<Set<String>> getChangedPaths(final String fromCommitSha, 
final String toCommitSha) throws IOException, FlowRegistryException {
+        logger.debug("Getting paths changed from [{}] to [{}] in repo [{}]", 
fromCommitSha, toCommitSha, repository.getName());
+        return execute(() -> 
getChangedPaths(repository.getCompare(fromCommitSha, toCommitSha), repoPath));
+    }
+
+    static Optional<Set<String>> getChangedPaths(final GHCompare compare, 
final String repoPath) {
+        if (compare.getStatus() != GHCompare.Status.ahead || 
compare.getAheadBy() != 1) {
+            return Optional.empty();
+        }
+
+        final GHCommit.File[] files = compare.getFiles();
+        if (files.length >= COMPARE_FILES_LIMIT) {
+            return Optional.empty();
+        }
+
+        final Set<String> changedPaths = new HashSet<>();
+        for (final GHCommit.File file : files) {
+            addChangedPaths(file, repoPath, changedPaths);
+        }
+        return Optional.of(changedPaths);
+    }
+
+    private static void addChangedPaths(final GHCommit.File file, final String 
repoPath, final Set<String> changedPaths) {
+        getRelativePath(file.getFileName(), 
repoPath).ifPresent(changedPaths::add);
+        if (file.getPreviousFilename() != null) {
+            getRelativePath(file.getPreviousFilename(), 
repoPath).ifPresent(changedPaths::add);
+        }
+    }
+
+    private static Optional<String> getRelativePath(final String path, final 
String repoPath) {
+        // Compared paths never start with a slash, while the configured 
repository path may start or end with one
+        final String normalizedRepoPath = repoPath == null ? "" : 
StringUtils.strip(repoPath, "/");
+        if (normalizedRepoPath.isEmpty()) {
+            return Optional.of(path);
+        }
+        final String prefix = normalizedRepoPath + "/";
+        return path.startsWith(prefix) ? 
Optional.of(path.substring(prefix.length())) : Optional.empty();
+    }
+
     /**
      * Gets the top-level directory names, which are the directories at the 
root of the repo, or within the prefix if specified.
      *
diff --git 
a/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/test/java/org/apache/nifi/github/ConditionalBranchReferenceConnectorTest.java
 
b/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/test/java/org/apache/nifi/github/ConditionalBranchReferenceConnectorTest.java
new file mode 100644
index 00000000000..b6a8af106e9
--- /dev/null
+++ 
b/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/test/java/org/apache/nifi/github/ConditionalBranchReferenceConnectorTest.java
@@ -0,0 +1,254 @@
+/*
+ *  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.nifi.github;
+
+import org.junit.jupiter.api.Test;
+import org.kohsuke.github.GHRepository;
+import org.kohsuke.github.GitHub;
+import org.kohsuke.github.GitHubBuilder;
+import org.kohsuke.github.connector.GitHubConnector;
+import org.kohsuke.github.connector.GitHubConnectorRequest;
+import org.kohsuke.github.connector.GitHubConnectorResponse;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.GZIPOutputStream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
+class ConditionalBranchReferenceConnectorTest {
+    private static final String BRANCH_REFERENCE_URL = 
"https://api.github.com/repos/owner/repo/git/refs/heads/main";;
+    private static final String CONTENTS_URL = 
"https://api.github.com/repos/owner/repo/contents/bucket/flow.json";;
+    private static final String GET_METHOD = "GET";
+    private static final String DELETE_METHOD = "DELETE";
+    private static final String ENTITY_TAG_HEADER = "ETag";
+    private static final String IF_NONE_MATCH_HEADER = "If-None-Match";
+    private static final String CONTENT_ENCODING_HEADER = "Content-Encoding";
+    private static final String GZIP_ENCODING = "gzip";
+    private static final String HEAD_1_ENTITY_TAG = "W/\"head-1\"";
+    private static final String HEAD_2_ENTITY_TAG = "W/\"head-2\"";
+    private static final String HEAD_1_BODY = 
"{\"object\":{\"sha\":\"head-1\"}}";
+    private static final String HEAD_2_BODY = 
"{\"object\":{\"sha\":\"head-2\"}}";
+    private static final String API_URL = "https://api.github.com";;
+    private static final String BRANCH_REFERENCE = "refs/heads/main";
+    private static final String REPOSITORY_BODY = """
+            {"name": "repo", "full_name": "owner/repo", "url": 
"https://api.github.com/repos/owner/repo";, "owner": {"login": "owner"}}
+            """;
+    private static final String REFERENCE_BODY = """
+            {"ref": "refs/heads/main", "url": 
"https://api.github.com/repos/owner/repo/git/refs/heads/main";, "object": 
{"sha": "head-1", "type": "commit"}}
+            """;
+
+    private final RecordingConnector recordingConnector = new 
RecordingConnector();
+    private final ConditionalBranchReferenceConnector connector = new 
ConditionalBranchReferenceConnector(recordingConnector);
+
+    @Test
+    void testUnchangedReferenceAnsweredWithStoredBody() throws IOException {
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, 
Map.of(ENTITY_TAG_HEADER, List.of(HEAD_1_ENTITY_TAG), CONTENT_ENCODING_HEADER, 
List.of(GZIP_ENCODING)), gzip(HEAD_1_BODY));
+        recordingConnector.respond(HttpURLConnection.HTTP_NOT_MODIFIED, 
Map.of(), "");
+
+        final GitHubConnectorResponse first = connector.send(new 
TestRequest(GET_METHOD, BRANCH_REFERENCE_URL));
+        assertEquals(HttpURLConnection.HTTP_OK, first.statusCode());
+        assertNull(first.header(CONTENT_ENCODING_HEADER));
+        assertEquals(HEAD_1_BODY, readBody(first));
+
+        final GitHubConnectorResponse second = connector.send(new 
TestRequest(GET_METHOD, BRANCH_REFERENCE_URL));
+        assertEquals(HttpURLConnection.HTTP_OK, second.statusCode());
+        assertEquals(HEAD_1_BODY, readBody(second));
+
+        
assertNull(recordingConnector.getRequest(0).header(IF_NONE_MATCH_HEADER));
+        assertEquals(HEAD_1_ENTITY_TAG, 
recordingConnector.getRequest(1).header(IF_NONE_MATCH_HEADER));
+        assertEquals(List.of(HEAD_1_ENTITY_TAG), 
recordingConnector.getRequest(1).allHeaders().get(IF_NONE_MATCH_HEADER));
+    }
+
+    @Test
+    void testChangedReferenceReplacesStoredBody() throws IOException {
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, 
Map.of(ENTITY_TAG_HEADER, List.of(HEAD_1_ENTITY_TAG)), HEAD_1_BODY);
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, 
Map.of(ENTITY_TAG_HEADER, List.of(HEAD_2_ENTITY_TAG)), HEAD_2_BODY);
+        recordingConnector.respond(HttpURLConnection.HTTP_NOT_MODIFIED, 
Map.of(), "");
+
+        assertEquals(HEAD_1_BODY, readBody(connector.send(new 
TestRequest(GET_METHOD, BRANCH_REFERENCE_URL))));
+        assertEquals(HEAD_2_BODY, readBody(connector.send(new 
TestRequest(GET_METHOD, BRANCH_REFERENCE_URL))));
+        assertEquals(HEAD_2_BODY, readBody(connector.send(new 
TestRequest(GET_METHOD, BRANCH_REFERENCE_URL))));
+
+        assertEquals(HEAD_1_ENTITY_TAG, 
recordingConnector.getRequest(1).header(IF_NONE_MATCH_HEADER));
+        assertEquals(HEAD_2_ENTITY_TAG, 
recordingConnector.getRequest(2).header(IF_NONE_MATCH_HEADER));
+    }
+
+    @Test
+    void testFailedReferenceRequestForgetsStoredBody() throws IOException {
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, 
Map.of(ENTITY_TAG_HEADER, List.of(HEAD_1_ENTITY_TAG)), HEAD_1_BODY);
+        recordingConnector.respond(HttpURLConnection.HTTP_NOT_FOUND, Map.of(), 
"");
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, 
Map.of(ENTITY_TAG_HEADER, List.of(HEAD_1_ENTITY_TAG)), HEAD_1_BODY);
+
+        readBody(connector.send(new TestRequest(GET_METHOD, 
BRANCH_REFERENCE_URL)));
+        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, connector.send(new 
TestRequest(GET_METHOD, BRANCH_REFERENCE_URL)).statusCode());
+        readBody(connector.send(new TestRequest(GET_METHOD, 
BRANCH_REFERENCE_URL)));
+
+        
assertNull(recordingConnector.getRequest(2).header(IF_NONE_MATCH_HEADER));
+    }
+
+    @Test
+    void testRateLimitedReferenceRequestKeepsStoredBody() throws IOException {
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, 
Map.of(ENTITY_TAG_HEADER, List.of(HEAD_1_ENTITY_TAG)), HEAD_1_BODY);
+        recordingConnector.respond(HttpURLConnection.HTTP_FORBIDDEN, Map.of(), 
"");
+        recordingConnector.respond(HttpURLConnection.HTTP_NOT_MODIFIED, 
Map.of(), "");
+
+        readBody(connector.send(new TestRequest(GET_METHOD, 
BRANCH_REFERENCE_URL)));
+        assertEquals(HttpURLConnection.HTTP_FORBIDDEN, connector.send(new 
TestRequest(GET_METHOD, BRANCH_REFERENCE_URL)).statusCode());
+        assertEquals(HEAD_1_BODY, readBody(connector.send(new 
TestRequest(GET_METHOD, BRANCH_REFERENCE_URL))));
+
+        assertEquals(HEAD_1_ENTITY_TAG, 
recordingConnector.getRequest(2).header(IF_NONE_MATCH_HEADER));
+    }
+
+    @Test
+    void testGitHubReadsBranchHeadFromNotModifiedAnswer() throws IOException {
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, Map.of(), 
REPOSITORY_BODY);
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, 
Map.of(ENTITY_TAG_HEADER, List.of(HEAD_1_ENTITY_TAG)), REFERENCE_BODY);
+        recordingConnector.respond(HttpURLConnection.HTTP_NOT_MODIFIED, 
Map.of(), "");
+        final GitHub gitHub = new 
GitHubBuilder().withEndpoint(API_URL).withConnector(connector).build();
+        final GHRepository repository = gitHub.getRepository("owner/repo");
+
+        assertEquals("head-1", 
repository.getRef(BRANCH_REFERENCE).getObject().getSha());
+        assertEquals("head-1", 
repository.getRef(BRANCH_REFERENCE).getObject().getSha());
+
+        assertEquals(BRANCH_REFERENCE_URL, 
recordingConnector.getRequest(2).url().toString());
+        assertEquals(HEAD_1_ENTITY_TAG, 
recordingConnector.getRequest(2).header(IF_NONE_MATCH_HEADER));
+    }
+
+    @Test
+    void testOtherRequestsSentUnchanged() throws IOException {
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, 
Map.of(ENTITY_TAG_HEADER, List.of(HEAD_1_ENTITY_TAG)), HEAD_1_BODY);
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, 
Map.of(ENTITY_TAG_HEADER, List.of(HEAD_1_ENTITY_TAG)), HEAD_1_BODY);
+        recordingConnector.respond(HttpURLConnection.HTTP_OK, Map.of(), "");
+        final TestRequest contentsRequest = new TestRequest(GET_METHOD, 
CONTENTS_URL);
+        final TestRequest deleteReferenceRequest = new 
TestRequest(DELETE_METHOD, BRANCH_REFERENCE_URL);
+
+        // A stored answer for the contents would make the second request 
conditional
+        connector.send(contentsRequest);
+        connector.send(contentsRequest);
+        connector.send(deleteReferenceRequest);
+
+        assertSame(contentsRequest, recordingConnector.getRequest(0));
+        assertSame(contentsRequest, recordingConnector.getRequest(1));
+        assertSame(deleteReferenceRequest, recordingConnector.getRequest(2));
+    }
+
+    private static String readBody(final GitHubConnectorResponse response) 
throws IOException {
+        try (response; InputStream bodyStream = response.bodyStream()) {
+            return new String(bodyStream.readAllBytes(), 
StandardCharsets.UTF_8);
+        }
+    }
+
+    private static byte[] gzip(final String body) throws IOException {
+        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+        try (GZIPOutputStream gzipOutputStream = new 
GZIPOutputStream(outputStream)) {
+            gzipOutputStream.write(body.getBytes(StandardCharsets.UTF_8));
+        }
+        return outputStream.toByteArray();
+    }
+
+    private record ResponseDefinition(int statusCode, Map<String, 
List<String>> headers, byte[] body) {
+    }
+
+    private static final class RecordingConnector implements GitHubConnector {
+        private final List<GitHubConnectorRequest> requests = new 
ArrayList<>();
+        private final Deque<ResponseDefinition> responseDefinitions = new 
ArrayDeque<>();
+
+        void respond(final int statusCode, final Map<String, List<String>> 
headers, final String body) {
+            respond(statusCode, headers, 
body.getBytes(StandardCharsets.UTF_8));
+        }
+
+        void respond(final int statusCode, final Map<String, List<String>> 
headers, final byte[] body) {
+            responseDefinitions.add(new ResponseDefinition(statusCode, 
headers, body));
+        }
+
+        GitHubConnectorRequest getRequest(final int index) {
+            return requests.get(index);
+        }
+
+        @Override
+        public GitHubConnectorResponse send(final GitHubConnectorRequest 
request) {
+            requests.add(request);
+            final ResponseDefinition definition = 
responseDefinitions.removeFirst();
+            return new TestResponse(request, definition.statusCode(), 
definition.headers(), definition.body());
+        }
+    }
+
+    private static final class TestResponse extends GitHubConnectorResponse {
+        private final byte[] body;
+
+        private TestResponse(final GitHubConnectorRequest request, final int 
statusCode, final Map<String, List<String>> headers, final byte[] body) {
+            super(request, statusCode, headers);
+            this.body = body;
+        }
+
+        @Override
+        protected InputStream rawBodyStream() {
+            return new ByteArrayInputStream(body);
+        }
+    }
+
+    private record TestRequest(String method, String address) implements 
GitHubConnectorRequest {
+        @Override
+        public Map<String, List<String>> allHeaders() {
+            return Map.of("Accept", List.of("application/vnd.github+json"));
+        }
+
+        @Override
+        public String header(final String name) {
+            final List<String> values = allHeaders().get(name);
+            return values == null ? null : values.getFirst();
+        }
+
+        @Override
+        public String contentType() {
+            return null;
+        }
+
+        @Override
+        public InputStream body() {
+            return null;
+        }
+
+        @Override
+        public URL url() {
+            try {
+                return URI.create(address).toURL();
+            } catch (final IOException e) {
+                throw new IllegalStateException(e);
+            }
+        }
+
+        @Override
+        public boolean hasBody() {
+            return false;
+        }
+    }
+}
diff --git 
a/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/test/java/org/apache/nifi/github/GitHubRepositoryClientTest.java
 
b/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/test/java/org/apache/nifi/github/GitHubRepositoryClientTest.java
index 48c532a6896..90483020b0a 100644
--- 
a/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/test/java/org/apache/nifi/github/GitHubRepositoryClientTest.java
+++ 
b/nifi-extension-bundles/nifi-github-bundle/nifi-github-extensions/src/test/java/org/apache/nifi/github/GitHubRepositoryClientTest.java
@@ -20,6 +20,7 @@ package org.apache.nifi.github;
 import org.junit.jupiter.api.Test;
 import org.kohsuke.github.GHCommit;
 import org.kohsuke.github.GHCommitQueryBuilder;
+import org.kohsuke.github.GHCompare;
 import org.kohsuke.github.GHException;
 import org.kohsuke.github.GHFileNotFoundException;
 import org.kohsuke.github.GHRepository;
@@ -30,7 +31,9 @@ import org.kohsuke.github.PagedIterator;
 
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.util.List;
 import java.util.Optional;
+import java.util.Set;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -44,7 +47,6 @@ import static org.mockito.Mockito.when;
 class GitHubRepositoryClientTest {
 
     private static final String PATH = "bucket/flow.json";
-    private static final String BRANCH = "main";
     private static final String BRANCH_REF = "refs/heads/main";
     private static final String COMMIT_SHA = "0123456789abcdef";
 
@@ -111,7 +113,7 @@ class GitHubRepositoryClientTest {
         when(iterator.next()).thenReturn(ghCommit);
         final GHRepository repository = mockRepository(iterator);
 
-        assertEquals(Optional.of(COMMIT_SHA), 
GitHubRepositoryClient.getLatestCommitSha(repository, PATH, BRANCH));
+        assertEquals(Optional.of(COMMIT_SHA), 
GitHubRepositoryClient.getLatestCommitSha(repository, PATH, BRANCH_REF));
 
         final GHCommitQueryBuilder queryBuilder = repository.queryCommits();
         verify(queryBuilder).path(PATH);
@@ -121,12 +123,23 @@ class GitHubRepositoryClientTest {
         verify(repository, never()).getRef(anyString());
     }
 
+    @Test
+    void testGetLatestCommitShaQueriesFromCommit() throws IOException {
+        final PagedIterator<GHCommit> iterator = mockIterator();
+        when(iterator.hasNext()).thenReturn(false);
+        final GHRepository repository = mockRepository(iterator);
+
+        assertEquals(Optional.empty(), 
GitHubRepositoryClient.getLatestCommitSha(repository, PATH, COMMIT_SHA));
+
+        verify(repository.queryCommits()).from(COMMIT_SHA);
+    }
+
     @Test
     void testGetLatestCommitShaEmptyWhenPathHasNoCommits() throws IOException {
         final PagedIterator<GHCommit> iterator = mockIterator();
         when(iterator.hasNext()).thenReturn(false);
 
-        assertEquals(Optional.empty(), 
GitHubRepositoryClient.getLatestCommitSha(mockRepository(iterator), PATH, 
BRANCH));
+        assertEquals(Optional.empty(), 
GitHubRepositoryClient.getLatestCommitSha(mockRepository(iterator), PATH, 
BRANCH_REF));
     }
 
     @Test
@@ -136,7 +149,7 @@ class GitHubRepositoryClientTest {
         when(iterator.hasNext()).thenThrow(new GHException("Failed to 
retrieve", notFound));
 
         final FileNotFoundException thrown = 
assertThrows(FileNotFoundException.class,
-                () -> 
GitHubRepositoryClient.getLatestCommitSha(mockRepository(iterator), PATH, 
BRANCH));
+                () -> 
GitHubRepositoryClient.getLatestCommitSha(mockRepository(iterator), PATH, 
BRANCH_REF));
         assertEquals(notFound, thrown);
     }
 
@@ -155,4 +168,75 @@ class GitHubRepositoryClientTest {
         when(repository.queryCommits()).thenReturn(queryBuilder);
         return repository;
     }
+
+    @Test
+    void testGetChangedPathsRelativeToRepositoryPath() {
+        final GHCompare compare = mockCompare(GHCompare.Status.ahead, 1,
+                mockFile("flows/bucket/changed.json", null),
+                mockFile("flows/bucket/renamed.json", 
"flows/bucket/original.json"),
+                mockFile("README.md", null));
+
+        assertEquals(Optional.of(Set.of("bucket/changed.json", 
"bucket/renamed.json", "bucket/original.json")),
+                GitHubRepositoryClient.getChangedPaths(compare, "flows"));
+    }
+
+    @Test
+    void testGetChangedPathsWithoutRepositoryPath() {
+        final GHCompare compare = mockCompare(GHCompare.Status.ahead, 1,
+                mockFile("bucket/changed.json", null),
+                mockFile("bucket/renamed.json", "bucket/original.json"));
+
+        assertEquals(Optional.of(Set.of("bucket/changed.json", 
"bucket/renamed.json", "bucket/original.json")),
+                GitHubRepositoryClient.getChangedPaths(compare, null));
+    }
+
+    @Test
+    void testGetChangedPathsWithSlashesAroundRepositoryPath() {
+        final GHCompare compare = mockCompare(GHCompare.Status.ahead, 1, 
mockFile("flows/bucket/changed.json", null));
+
+        assertEquals(Optional.of(Set.of("bucket/changed.json")), 
GitHubRepositoryClient.getChangedPaths(compare, "/flows/"));
+    }
+
+    @Test
+    void testGetChangedPathsUnknownWhenMoreThanOneCommit() {
+        // The compared files are the net difference: a file changed by one 
commit and reverted by the next is not listed
+        final GHCompare compare = mockCompare(GHCompare.Status.ahead, 2, 
mockFile("bucket/other.json", null));
+
+        assertEquals(Optional.empty(), 
GitHubRepositoryClient.getChangedPaths(compare, null));
+        verify(compare, never()).getFiles();
+    }
+
+    @Test
+    void testGetChangedPathsUnknownWhenNotAhead() {
+        for (final GHCompare.Status status : List.of(GHCompare.Status.behind, 
GHCompare.Status.diverged, GHCompare.Status.identical)) {
+            final GHCompare compare = mockCompare(status, 1, 
mockFile("bucket/changed.json", null));
+
+            assertEquals(Optional.empty(), 
GitHubRepositoryClient.getChangedPaths(compare, null), status.name());
+        }
+    }
+
+    @Test
+    void testGetChangedPathsUnknownWhenFileListMayBeTruncated() {
+        final GHCommit.File[] files = new 
GHCommit.File[GitHubRepositoryClient.COMPARE_FILES_LIMIT];
+        for (int i = 0; i < files.length; i++) {
+            files[i] = mockFile("bucket/flow-" + i + ".json", null);
+        }
+
+        assertEquals(Optional.empty(), 
GitHubRepositoryClient.getChangedPaths(mockCompare(GHCompare.Status.ahead, 1, 
files), null));
+    }
+
+    private static GHCompare mockCompare(final GHCompare.Status status, final 
int aheadBy, final GHCommit.File... files) {
+        final GHCompare compare = mock(GHCompare.class);
+        when(compare.getStatus()).thenReturn(status);
+        when(compare.getAheadBy()).thenReturn(aheadBy);
+        when(compare.getFiles()).thenReturn(files);
+        return compare;
+    }
+
+    private static GHCommit.File mockFile(final String fileName, final String 
previousFileName) {
+        final GHCommit.File file = mock(GHCommit.File.class);
+        when(file.getFileName()).thenReturn(fileName);
+        when(file.getPreviousFilename()).thenReturn(previousFileName);
+        return file;
+    }
 }

Reply via email to