You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hugegraph.apache.org by ji...@apache.org on 2026/10/10 09:50:01 UTC
(hugegraph) 03/11: refactor(store): separate RPC and shutdown reviews
This is an automated email from the ASF dual-hosted git repository.
imbajin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hugegraph.git
commit de7eb085654f4898aea6bd627c673edc5d8f32e0
Author: imbajin <ji...@apache.org>
AuthorDate: Sat Oct 10 03:19:41 2026 +0800
refactor(store): separate RPC and shutdown reviews
- keep client and server request lifecycle changes together
- retain scoped scan and query cleanup before database close
- partition lifecycle tests without changing their assertions
- defer global RPC and TTL shutdown to a dependent PR
---
.github/workflows/pd-store-ci.yml | 17 +-
docs/store-lifecycle.md | 45 +-
.../travis/run-native-runtime-smoke-test.sh | 2 +-
.../assembly/travis/test-stop-hugegraph-store.sh | 42 --
hugegraph-store/README.md | 17 +-
.../assembly/static/bin/stop-hugegraph-store.sh | 6 +-
.../store/node/grpc/GrpcShutdownBarrier.java | 110 ---
.../store/node/listener/ContextClosedListener.java | 39 +-
.../hugegraph/store/node/task/TTLCleaner.java | 41 +-
...est.java => AggregativeQueryLifecycleTest.java} | 738 +--------------------
.../grpc/query/AggregativeQueryTestSupport.java | 165 +++++
...t.java => GraphPartitionScanLifecycleTest.java} | 95 +--
.../service/GraphPartitionScanTestSupport.java | 55 ++
.../store/service/GrpcShutdownBarrierTest.java | 131 ----
...stenerTest.java => ScanContextCleanupTest.java} | 111 +---
...canShutdownTest.java => ScanLifecycleTest.java} | 211 +-----
.../hugegraph/store/service/ScanTestSupport.java | 98 +++
.../hugegraph/store/service/ServerSuiteTest.java | 12 +-
.../store/service/TTLCleanerCleanupTest.java | 155 -----
19 files changed, 379 insertions(+), 1711 deletions(-)
diff --git a/.github/workflows/pd-store-ci.yml b/.github/workflows/pd-store-ci.yml
index 89d5f5f4e..47a8abaef 100644
--- a/.github/workflows/pd-store-ci.yml
+++ b/.github/workflows/pd-store-ci.yml
@@ -8,21 +8,6 @@ permissions:
contents: read
jobs:
- store-stop-shell-test:
- permissions:
- contents: read
- runs-on: ubuntu-24.04
- steps:
- - name: Checkout
- uses: actions/checkout@v7
- with:
- persist-credentials: false
-
- - name: Verify Store stop failure propagation and PID retention
- run: |
- docker run --rm -v "$GITHUB_WORKSPACE:/work:ro" -w /work ubuntu:24.04 \
- bash hugegraph-server/hugegraph-dist/src/assembly/travis/test-stop-hugegraph-store.sh
-
rocksdb-compatibility:
permissions:
contents: read
@@ -446,7 +431,7 @@ jobs:
mvn test -pl hugegraph-store/hg-store-test -am \
-P store-core-test -Djacoco.sessionId=store-core-test
- - name: Run server shutdown test
+ - name: Run server lifecycle test
run: |
mvn test -pl hugegraph-store/hg-store-test -am \
-P store-server-test -Djacoco.sessionId=store-server-test
diff --git a/docs/store-lifecycle.md b/docs/store-lifecycle.md
index d766c92ea..9524b9f69 100644
--- a/docs/store-lifecycle.md
+++ b/docs/store-lifecycle.md
@@ -1,19 +1,26 @@
-# Store RPC, scan and shutdown lifecycle
-
-Store shutdown refuses new RPCs, cancels active RPCs and scans, and waits for their callbacks and scan/TTL workers before Spring destroys the Store engine and its databases. A failed aggregate-query response callback is logged without skipping cancellation or cleanup waits for other queries. Cancellation may fail in-flight requests; stop writes and check their outcomes before planned maintenance. This is not a guarantee that every in-flight request drains successfully or that a leader tr [...]
-
-If a callback cannot finish, or an ordinary scan or bidirectional aggregate query fails to release its plan or partition iterators, shutdown remains pending rather than closing its database underneath it. This also includes iterators discarded while advancing past empty partitions, initializing a sequential scan, or counting rows. RocksDB iterators retain the first failure during automatic or explicit close so that later cleanup cannot hide it; concurrent close calls wait for the release [...]
-
-If shutdown cancellation wins while a one-shot scan releases its iterator, the
-response terminates with `CANCELLED`; it does not report successful completion
-without its result. Iterator cleanup still finishes before the scan unregisters.
-
-A normal aggregate-query request half-close ends feedback without cancelling already permitted work. A subsequent transport cancellation or deadline still interrupts the workers and releases their resources. A batch-scan RPC accepts one initial query; repeated query requests are ignored before allocating another iterator, including after its final batch. If the remaining feedback credit cannot finish the query, the server returns an explicit query error. Scan task rejection reports `UNAV [...]
-
-See the [Store shutdown instructions](../hugegraph-store/README.md#stopping-a-store-node)
-and the Server [module test guidance](../hugegraph-server/AGENTS.md#tests).
-
-
-Client response parsing runs outside the short state lock. Accepted final batches remain visible across response completion; errors and iterator close discard in-flight parsing results. Early query close cancels the transport without waiting for a blocked request send. Normal request half-close remains serialized with sends.
-
-An interrupted shutdown thread still waits for heartbeat producers and Raft groups to finish. The Store engine restores that interrupt only after partition and native database teardown.
+# Store RPC and Scan lifecycle
+
+Client and server changes keep request half-close separate from transport cancellation.
+An aggregate query finishes work already supported by feedback credit after half-close;
+a later transport cancellation or deadline still cancels its workers. Graph partition
+scans deliver their permitted pages and final batch, or return an explicit error when
+half-close leaves insufficient feedback credit. Batch-scan RPCs accept one initial query.
+
+Response parsing runs outside the client state lock. Accepted final batches remain
+visible across response completion; errors and iterator close discard unpublished data.
+Early query close cancels the transport without waiting for a blocked request send.
+Normal half-close stays serialized with sends. Closing a composite iterator closes
+all started children once.
+
+Each scan/query owns its workers and iterators until cleanup finishes. Iterator cleanup
+failures remain visible, including automatic native iterator close and empty-partition
+selection. Final aggregate success is sent only after plan and iterator cleanup succeeds.
+
+The request services stop scan/query admission, cancel their active calls and run queued
+cleanup before Spring destroys their databases. This scoped cleanup reuses the same
+per-call owners; it does not create a second shutdown registry. Interrupted cleanup waits
+and native teardown preserve interruption without abandoning these owners.
+
+The subsequent Store-wide shutdown change extends this boundary to ordinary RPC
+callbacks and sticky TTL cleanup failures. It also defines distribution stop timeout
+handling; those guarantees are not introduced by this request-lifecycle change.
diff --git a/hugegraph-server/hugegraph-dist/src/assembly/travis/run-native-runtime-smoke-test.sh b/hugegraph-server/hugegraph-dist/src/assembly/travis/run-native-runtime-smoke-test.sh
index 6631c0456..e8570eef0 100755
--- a/hugegraph-server/hugegraph-dist/src/assembly/travis/run-native-runtime-smoke-test.sh
+++ b/hugegraph-server/hugegraph-dist/src/assembly/travis/run-native-runtime-smoke-test.sh
@@ -39,7 +39,7 @@ cleanup() {
local status=$?
trap - EXIT
if [[ "$SERVER_START_ATTEMPTED" == "true" ]]; then
- "$SERVER_DIR/bin/stop-hugegraph.sh" -m false || status=1
+ "$SERVER_DIR/bin/stop-hugegraph.sh" -m false >/dev/null 2>&1 || status=1
fi
rm -rf "$WORK_DIR"
exit "$status"
diff --git a/hugegraph-server/hugegraph-dist/src/assembly/travis/test-stop-hugegraph-store.sh b/hugegraph-server/hugegraph-dist/src/assembly/travis/test-stop-hugegraph-store.sh
deleted file mode 100755
index 5d05ab6ef..000000000
--- a/hugegraph-server/hugegraph-dist/src/assembly/travis/test-stop-hugegraph-store.sh
+++ /dev/null
@@ -1,42 +0,0 @@
-#!/bin/bash
-#
-# 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.
-#
-# Verify stop failure propagation and PID retention without signalling real processes.
-set -euo pipefail
-
-ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../../.." && pwd)"
-SCRIPT="$ROOT/hugegraph-store/hg-store-dist/src/assembly/static/bin/stop-hugegraph-store.sh"
-FIXTURE=$(mktemp -d)
-trap 'rm -rf "$FIXTURE"' EXIT
-mkdir -p "$FIXTURE/bin"
-cp "$SCRIPT" "$FIXTURE/bin/stop-hugegraph-store.sh"
-cat > "$FIXTURE/bin/util.sh" <<'UTIL'
-kill_process_and_wait() {
- [[ "$1" == HugeGraphStoreServer && "$2" == 12345 && "$3" == 30 ]] || return 99
- return "$STOP_RESULT"
-}
-UTIL
-printf '12345\n' > "$FIXTURE/bin/pid"
-if STOP_RESULT=1 bash "$FIXTURE/bin/stop-hugegraph-store.sh"; then
- echo "Stop timeout incorrectly returned success" >&2
- exit 1
-fi
-[[ "$(cat "$FIXTURE/bin/pid")" == 12345 ]]
-STOP_RESULT=0 bash "$FIXTURE/bin/stop-hugegraph-store.sh"
-[[ ! -e "$FIXTURE/bin/pid" ]]
-STOP_RESULT=0 bash "$FIXTURE/bin/stop-hugegraph-store.sh"
-echo "store-stop-contract-ok"
diff --git a/hugegraph-store/README.md b/hugegraph-store/README.md
index 960162c43..c70de1cbd 100644
--- a/hugegraph-store/README.md
+++ b/hugegraph-store/README.md
@@ -397,22 +397,11 @@ For Docker and Kubernetes deployment details, see [Deployment Guide](docs/deploy
---
-## Stopping a Store node
-
-For an unpacked distribution, run `bin/stop-hugegraph-store.sh`. It waits up to
-30 seconds for process exit. A timeout returns a nonzero status and retains
-`bin/pid` for diagnosis; it does not force-kill the process or remove its data.
-Check the Store log and thread dump before taking further action.
-
-Spring owns shutdown: new RPCs are refused, active RPCs are cancelled, and context
-close waits for their callbacks and scan/TTL workers to release resources. The
-Store engine then stops and joins partition Raft services before releasing
-databases. A stuck callback keeps shutdown pending rather than allowing its
-database to close underneath it. Do not add a separate JVM hook that closes
-those databases concurrently.
-
## Documentation
+See [RPC and Scan lifecycle](../docs/store-lifecycle.md) for request ownership,
+cancellation and feedback semantics.
+
Comprehensive documentation for HugeGraph Store:
| Documentation | Description |
diff --git a/hugegraph-store/hg-store-dist/src/assembly/static/bin/stop-hugegraph-store.sh b/hugegraph-store/hg-store-dist/src/assembly/static/bin/stop-hugegraph-store.sh
index e9f503b02..8f898df7d 100644
--- a/hugegraph-store/hg-store-dist/src/assembly/static/bin/stop-hugegraph-store.sh
+++ b/hugegraph-store/hg-store-dist/src/assembly/static/bin/stop-hugegraph-store.sh
@@ -41,8 +41,8 @@ if [ ! -f ${PID_FILE} ]; then
fi
PID=`cat $PID_FILE`
-if kill_process_and_wait "HugeGraphStoreServer" "$PID" "$SERVER_SHUTDOWN_TIMEOUT_S"; then
+kill_process_and_wait "HugeGraphStoreServer" "$PID" "$SERVER_SHUTDOWN_TIMEOUT_S"
+
+if [ $? -eq 0 ]; then
rm "$PID_FILE"
-else
- exit 1
fi
diff --git a/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/grpc/GrpcShutdownBarrier.java b/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/grpc/GrpcShutdownBarrier.java
deleted file mode 100644
index a9a6a9f95..000000000
--- a/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/grpc/GrpcShutdownBarrier.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * 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.hugegraph.store.node.grpc;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.lognet.springboot.grpc.GRpcGlobalInterceptor;
-import org.springframework.stereotype.Component;
-
-import io.grpc.ForwardingServerCallListener;
-import io.grpc.Metadata;
-import io.grpc.ServerCall;
-import io.grpc.ServerCallHandler;
-import io.grpc.ServerInterceptor;
-import io.grpc.Status;
-import lombok.extern.slf4j.Slf4j;
-
-/** Waits for terminal application callbacks, not just transport termination. */
-@Slf4j
-@Component
-@GRpcGlobalInterceptor
-public class GrpcShutdownBarrier implements ServerInterceptor {
-
- private final Set<Object> calls = new HashSet<>();
- private boolean closing;
-
- public synchronized void stopAcceptingCalls() {
- this.closing = true;
- }
-
- @Override
- public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
- ServerCall<ReqT, RespT> call, Metadata headers,
- ServerCallHandler<ReqT, RespT> next) {
- Object token = new Object();
- synchronized (this) {
- if (this.closing) {
- call.close(Status.UNAVAILABLE.withDescription("Store is stopping"), new Metadata());
- return new ServerCall.Listener<ReqT>() { };
- }
- this.calls.add(token);
- }
- try {
- return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
- next.startCall(call, headers)) {
- @Override
- public void onCancel() {
- try {
- super.onCancel();
- } finally {
- finished(token);
- }
- }
-
- @Override
- public void onComplete() {
- try {
- super.onComplete();
- } finally {
- finished(token);
- }
- }
- };
- } catch (RuntimeException | Error e) {
- finished(token);
- throw e;
- }
- }
-
- private synchronized void finished(Object token) {
- this.calls.remove(token);
- this.notifyAll();
- }
-
- public synchronized void awaitCallbacks() {
- boolean interrupted = false;
- try {
- while (!this.calls.isEmpty()) {
- try {
- this.wait(5000);
- if (!this.calls.isEmpty()) {
- log.warn("Waiting for {} RPC callbacks before closing databases", this.calls.size());
- }
- } catch (InterruptedException e) {
- interrupted = true;
- }
- }
- } finally {
- if (interrupted) {
- Thread.currentThread().interrupt();
- }
- }
- }
-}
diff --git a/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/listener/ContextClosedListener.java b/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/listener/ContextClosedListener.java
index 03b6443f8..5cc82cb5d 100644
--- a/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/listener/ContextClosedListener.java
+++ b/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/listener/ContextClosedListener.java
@@ -17,57 +17,40 @@
package org.apache.hugegraph.store.node.listener;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
-import org.apache.hugegraph.store.node.grpc.GrpcShutdownBarrier;
import org.apache.hugegraph.store.node.grpc.HgStoreStreamImpl;
import org.apache.hugegraph.store.node.grpc.query.AggregativeQueryService;
import org.apache.hugegraph.store.node.task.TTLCleaner;
-import org.lognet.springboot.grpc.context.GRpcServerInitializedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
-import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
-import io.grpc.Server;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class ContextClosedListener implements ApplicationListener<ContextClosedEvent> {
- private final List<Server> grpcServers = new CopyOnWriteArrayList<>();
-
@Autowired
HgStoreStreamImpl storeStream;
@Autowired
AggregativeQueryService queryService;
@Autowired
TTLCleaner cleaner;
- @Autowired
- GrpcShutdownBarrier grpcBarrier;
-
- @EventListener
- public void onServerInitialized(GRpcServerInitializedEvent event) {
- this.grpcServers.add(event.getServer());
- }
@Override
public void onApplicationEvent(ContextClosedEvent event) {
// Spring invokes HgStoreNodeService.destroy() after this event. Raft and
// its databases must remain available until local workers have stopped.
- this.grpcBarrier.stopAcceptingCalls();
if (storeStream != null) {
storeStream.stopAcceptingScans();
}
if (queryService != null) {
queryService.stopAcceptingQueries();
}
- this.grpcServers.forEach(Server::shutdownNow);
if (cleaner != null) {
// The scheduler can create the worker pool while a job is starting.
stopAndWait(cleaner.getScheduler(), "TTL scheduler");
@@ -82,32 +65,12 @@ public class ContextClosedListener implements ApplicationListener<ContextClosedE
queryService.shutdownQueries();
awaitWorkers(queryService.getThreadPool(), "aggregate query workers");
}
- boolean interrupted = false;
- try {
- for (Server server : this.grpcServers) {
- while (!server.isTerminated()) {
- try {
- if (!server.awaitTermination(5, TimeUnit.SECONDS)) {
- log.warn("Still waiting for gRPC callbacks before closing databases");
- }
- } catch (InterruptedException e) {
- interrupted = true;
- }
- }
- }
- } finally {
- if (interrupted) {
- Thread.currentThread().interrupt();
- }
- }
- this.grpcBarrier.awaitCallbacks();
if (storeStream != null) {
storeStream.awaitScanCleanup();
}
if (cleaner != null) {
- cleaner.awaitCleanup();
}
- log.info("closed gRPC callbacks, scan, aggregate query and TTL workers");
+ log.info("closed scan, aggregate query and TTL workers");
}
private static void stopAndWait(ExecutorService executor, String name) {
diff --git a/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/task/TTLCleaner.java b/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/task/TTLCleaner.java
index bdba7a1d8..6e40dc8ba 100644
--- a/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/task/TTLCleaner.java
+++ b/hugegraph-store/hg-store-node/src/main/java/org/apache/hugegraph/store/node/task/TTLCleaner.java
@@ -33,7 +33,6 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import org.apache.commons.lang3.ArrayUtils;
@@ -98,7 +97,6 @@ public class TTLCleaner implements Runnable {
@Autowired
private HgStoreNodeService service;
private final AtomicBoolean running = new AtomicBoolean(false);
- private final AtomicReference<Throwable> cleanupFailure = new AtomicReference<>();
private final AppConfig appConfig;
private final AppConfig.JobConfig jobConfig;
@@ -303,7 +301,7 @@ public class TTLCleaner implements Runnable {
LinkedList<ByteString> all = new LinkedList<>();
AtomicBoolean state = new AtomicBoolean(true);
AtomicLong partitionCounter = pc.get(id);
- while (!Thread.currentThread().isInterrupted() && state.get() && filter.hasNext()) {
+ while (filter.hasNext() && state.get()) {
RocksDBSession.BackendColumn current = filter.next();
byte[] realKey =
Arrays.copyOfRange(current.name, 0, current.name.length - Short.BYTES);
@@ -317,7 +315,7 @@ public class TTLCleaner implements Runnable {
all = new LinkedList<>();
}
}
- if (!Thread.currentThread().isInterrupted() && all.size() > 0 && state.get()) {
+ if (all.size() > 0 && state.get()) {
submitter.submitClean(id, graph, table, all, state, tableCounter,
partitionCounter);
}
@@ -328,43 +326,14 @@ public class TTLCleaner implements Runnable {
String msg = String.format(s, id, graph, table);
log.error(msg, e);
} finally {
- try {
- if (scan != null) {
- scan.close();
- }
- } catch (RuntimeException | Error failure) {
- this.cleanupFailure.compareAndSet(null, failure);
- log.error("TTL scan cleanup failed; database close stays blocked", failure);
- } finally {
- latch.countDown();
+ latch.countDown();
+ if (scan != null) {
+ scan.close();
}
}
};
}
- /** Call after workers terminate: a failed native release must remain a shutdown blocker. */
- public void awaitCleanup() {
- boolean interrupted = false;
- long nextLog = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
- synchronized (this.cleanupFailure) {
- while (this.cleanupFailure.get() != null) {
- try {
- this.cleanupFailure.wait(5000L);
- } catch (InterruptedException e) {
- interrupted = true;
- }
- if (System.nanoTime() - nextLog >= 0) {
- log.warn("TTL scan cleanup failed; database close stays blocked",
- this.cleanupFailure.get());
- nextLog = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
- }
- }
- }
- if (interrupted) {
- Thread.currentThread().interrupt();
- }
- }
-
public ScheduledFuture<?> getFuture() {
return future;
}
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/AggregativeQueryShutdownTest.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/AggregativeQueryLifecycleTest.java
similarity index 53%
rename from hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/AggregativeQueryShutdownTest.java
rename to hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/AggregativeQueryLifecycleTest.java
index 53343e06a..a0affeca5 100644
--- a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/AggregativeQueryShutdownTest.java
+++ b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/AggregativeQueryLifecycleTest.java
@@ -17,26 +17,22 @@
package org.apache.hugegraph.store.node.grpc.query;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import java.lang.reflect.Field;
+import io.grpc.Status;
+import io.grpc.stub.StreamObserver;
import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
@@ -44,99 +40,16 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.LockSupport;
-
-import org.apache.hugegraph.rocksdb.access.RocksDBScanIterator;
-import org.apache.hugegraph.rocksdb.access.ScanIterator;
import org.apache.hugegraph.rocksdb.access.RocksDBSession;
-import org.apache.hugegraph.store.business.InnerKeyFilter;
+import org.apache.hugegraph.rocksdb.access.ScanIterator;
import org.apache.hugegraph.store.business.MultiPartitionIterator;
import org.apache.hugegraph.store.grpc.query.QueryRequest;
import org.apache.hugegraph.store.grpc.query.QueryResponse;
-import org.apache.hugegraph.store.node.grpc.GrpcShutdownBarrier;
-import org.apache.hugegraph.store.node.grpc.HgStoreStreamImpl;
import org.apache.hugegraph.store.node.grpc.query.model.PipelineResult;
import org.apache.hugegraph.store.node.grpc.query.model.QueryPlan;
-import org.apache.hugegraph.store.node.listener.ContextClosedListener;
-import org.apache.hugegraph.store.node.task.TTLCleaner;
import org.junit.Test;
-import org.rocksdb.RocksIterator;
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-
-import io.grpc.Status;
-import io.grpc.StatusRuntimeException;
-import io.grpc.stub.StreamObserver;
-public class AggregativeQueryShutdownTest {
-
- @Test(timeout = 5000)
- public void testContextCloseContinuesAfterCancellationResponseFailure() throws Exception {
- assertContextCloseContinuesAfterCancellationFailure(
- new IllegalStateException("response completion failed"));
- }
-
- @Test(timeout = 5000)
- public void testContextCloseContinuesAfterCancellationResponseError() throws Exception {
- assertContextCloseContinuesAfterCancellationFailure(new AssertionError("response completion failed"));
- }
-
- @Test(timeout = 5000)
- public void testContextWaitsForIteratorFinallyAfterRpcCancellation() throws Exception {
- ThreadPoolExecutor pool = pool(1);
- CountDownLatch reading = new CountDownLatch(1);
- CountDownLatch closingIterator = new CountDownLatch(1);
- CountDownLatch allowClose = new CountDownLatch(1);
- AtomicBoolean databaseClosed = new AtomicBoolean();
- ScanIterator iterator = mock(ScanIterator.class);
- when(iterator.hasNext()).thenAnswer(invocation -> {
- reading.countDown();
- try {
- new CountDownLatch(1).await();
- } catch (InterruptedException ignored) {
- return false;
- }
- return false;
- });
- doAnswer(invocation -> {
- closingIterator.countDown();
- awaitUninterruptibly(allowClose);
- return null;
- }).when(iterator).close();
- AggregativeQueryService service = service(pool, iterator, new QueryPlan(), 500);
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
- try {
- context.getBeanFactory().registerSingleton("queryService", service);
- context.getBeanFactory().registerSingleton("storeStream", mock(HgStoreStreamImpl.class));
- context.getBeanFactory().registerSingleton("cleaner", mock(TTLCleaner.class));
- context.getDefaultListableBeanFactory().registerDisposableBean(
- "database", () -> databaseClosed.set(true));
- context.register(ContextClosedListener.class, GrpcShutdownBarrier.class);
- context.refresh();
- StreamObserver<QueryRequest> request = service.query(sender());
- request.onNext(QueryRequest.getDefaultInstance());
- assertTrue(reading.await(1, TimeUnit.SECONDS));
- request.onError(Status.CANCELLED.asRuntimeException());
- assertTrue(closingIterator.await(1, TimeUnit.SECONDS));
- FutureTask<Boolean> closing = new FutureTask<>(() -> {
- context.close();
- return Thread.currentThread().isInterrupted();
- });
- Thread closer = start(closing);
- awaitShutdownWait(closer);
- closer.interrupt();
- awaitShutdownWait(closer);
- assertFalse("RPC cancellation must not release a still-closing iterator", closing.isDone());
- assertFalse(databaseClosed.get());
- allowClose.countDown();
- assertTrue("context close must preserve interruption", closing.get(2, TimeUnit.SECONDS));
- assertTrue(databaseClosed.get());
- verify(iterator).close();
- } finally {
- allowClose.countDown();
- context.close();
- pool.shutdownNow();
- }
- }
+public class AggregativeQueryLifecycleTest extends AggregativeQueryTestSupport {
@Test(timeout = 5000)
public void testPartitionTimeoutDoesNotClearPlanOrFinishBeforeChildFinally() throws Exception {
@@ -194,90 +107,6 @@ public class AggregativeQueryShutdownTest {
}
}
- @Test(timeout = 5000)
- public void testQueuedParentsAreDrainedAndNewQueriesAreRejected() throws Exception {
- ThreadPoolExecutor pool = pool(1);
- CountDownLatch blockerStarted = new CountDownLatch(1);
- CountDownLatch release = new CountDownLatch(1);
- ScanIterator iterator = mock(ScanIterator.class);
- AtomicInteger closed = new AtomicInteger();
- doAnswer(invocation -> {
- closed.incrementAndGet();
- return null;
- }).when(iterator).close();
- AggregativeQueryService service = service(pool, iterator, new QueryPlan(), 500);
- pool.execute(() -> {
- blockerStarted.countDown();
- awaitUninterruptibly(release);
- });
- try {
- assertTrue(blockerStarted.await(1, TimeUnit.SECONDS));
- service.query(sender()).onNext(QueryRequest.getDefaultInstance());
- service.query(sender()).onNext(QueryRequest.getDefaultInstance());
- service.stopAcceptingQueries();
- try {
- service.query(sender());
- fail("new queries must be rejected after admission closes");
- } catch (StatusRuntimeException expected) {
- assertEquals(Status.Code.UNAVAILABLE, expected.getStatus().getCode());
- }
- FutureTask<Void> closing = close(service);
- awaitShutdownWait(start(closing));
- assertFalse(closing.isDone());
- release.countDown();
- closing.get(2, TimeUnit.SECONDS);
- assertEquals(2, closed.get());
- verify(iterator, never()).hasNext();
- assertTrue(pool.awaitTermination(1, TimeUnit.SECONDS));
- } finally {
- release.countDown();
- service.shutdownQueries();
- pool.shutdownNow();
- }
- }
-
- @Test(timeout = 5000)
- public void testQueuedPartitionRunsCleanupAfterParentTimeout() throws Exception {
- CountDownLatch childQueued = new CountDownLatch(1);
- CountDownLatch releaseSubmission = new CountDownLatch(1);
- AtomicInteger submissions = new AtomicInteger();
- ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
- new LinkedBlockingQueue<>()) {
- @Override
- public void execute(Runnable task) {
- super.execute(task);
- if (submissions.incrementAndGet() == 2) {
- childQueued.countDown();
- awaitUninterruptibly(releaseSubmission);
- }
- }
- };
- ScanIterator child = mock(ScanIterator.class);
- MultiPartitionIterator iterator = mock(MultiPartitionIterator.class);
- when(iterator.getIterators()).thenReturn(Arrays.asList(child));
- QueryPlan plan = mock(QueryPlan.class);
- when(plan.hasIteratorResult()).thenReturn(true);
- AggregativeQueryService service = service(pool, iterator, plan, 50);
- try {
- StreamObserver<QueryRequest> request = service.query(sender());
- request.onNext(QueryRequest.getDefaultInstance());
- assertTrue(childQueued.await(1, TimeUnit.SECONDS));
- request.onError(Status.CANCELLED.asRuntimeException());
- FutureTask<Void> closing = close(service);
- start(closing);
- releaseSubmission.countDown();
- closing.get(2, TimeUnit.SECONDS);
- verify(child).close();
- verify(child, never()).hasNext();
- verify(plan).clear();
- verify(iterator).close();
- } finally {
- releaseSubmission.countDown();
- service.shutdownQueries();
- pool.shutdownNow();
- }
- }
-
@Test(timeout = 5000)
public void testRejectedPartitionsReleaseAllOpenedIterators() throws Exception {
AtomicInteger submissions = new AtomicInteger();
@@ -320,38 +149,6 @@ public class AggregativeQueryShutdownTest {
}
}
- @Test(timeout = 5000)
- public void testIdleRpcAndInitializationFailureDoNotBlockShutdown() throws Exception {
- ThreadPoolExecutor pool = pool(1);
- ScanIterator iterator = mock(ScanIterator.class);
- AggregativeQueryService service = new AggregativeQueryService(pool, 500, 10) {
- @Override
- AggregativeQueryObserver newObserver(StreamObserver<QueryResponse> sender) {
- AggregativeQueryObserver observer = spy(super.newObserver(sender));
- doReturn(iterator).when(observer).getIterator(org.mockito.ArgumentMatchers.any());
- org.mockito.Mockito.doThrow(new IllegalArgumentException("invalid query plan"))
- .when(observer).buildPlan(org.mockito.ArgumentMatchers.any());
- return observer;
- }
- };
- ResponseRecorder failedResponse = new ResponseRecorder();
- try {
- service.query(sender());
- try {
- service.query(failedResponse).onNext(QueryRequest.getDefaultInstance());
- fail("invalid query must fail initialization");
- } catch (IllegalArgumentException expected) {
- assertEquals("invalid query plan", expected.getMessage());
- }
- assertEquals("framework must retain the synchronous error", 0, failedResponse.completed.get());
- assertTrue(failedResponse.responses.isEmpty());
- service.shutdownQueries();
- verify(iterator).close();
- } finally {
- pool.shutdownNow();
- }
- }
-
@Test(timeout = 5000)
public void testHasNextFailureSendsErrorBeforeSingleCompletion() throws Exception {
ThreadPoolExecutor pool = pool(1);
@@ -843,218 +640,6 @@ public class AggregativeQueryShutdownTest {
}
}
- @Test(timeout = 5000)
- public void testParentCleanupFailuresReportErrorAndKeepShutdownBlocked() throws Exception {
- ThreadPoolExecutor pool = pool(1);
- ScanIterator iterator = mock(ScanIterator.class);
- QueryPlan plan = mock(QueryPlan.class);
- when(plan.onlyStopStage()).thenReturn(true);
- IllegalStateException planFailure = new IllegalStateException("plan cleanup failed");
- IllegalStateException iteratorFailure = new IllegalStateException("iterator cleanup failed");
- doThrow(planFailure).when(plan).clear();
- doThrow(iteratorFailure).when(iterator).close();
- ResponseRecorder response = new ResponseRecorder();
- AggregativeQueryService service = service(pool, iterator, plan, 500);
- FutureTask<Void> closing = close(service);
- try {
- service.query(response).onNext(QueryRequest.newBuilder().setQueryId("cleanup-query").build());
- assertTrue(response.finished.await(1, TimeUnit.SECONDS));
- assertError(response, "cleanup-query");
- assertEquals("plan cleanup failed", response.responses.get(0).getMessage());
- assertEquals(1, planFailure.getSuppressed().length);
- org.junit.Assert.assertSame(iteratorFailure, planFailure.getSuppressed()[0]);
- verify(plan).clear();
- verify(iterator).close();
- awaitShutdownWait(start(closing));
- assertFalse(closing.isDone());
- assertFalse("failed cleanup cannot release the executor", pool.isShutdown());
- } finally {
- releaseMockQueries(service);
- closing.run();
- closing.get(1, TimeUnit.SECONDS);
- pool.shutdownNow();
- }
- }
-
- @Test(timeout = 5000)
- public void testPartitionCloseFailurePreventsSuccessfulAggregation() throws Exception {
- ThreadPoolExecutor pool = pool(2);
- ScanIterator child = mock(ScanIterator.class);
- doThrow(new IllegalStateException("child cleanup failed")).when(child).close();
- MultiPartitionIterator iterator = mock(MultiPartitionIterator.class);
- when(iterator.getIterators()).thenReturn(Arrays.asList(child));
- QueryPlan plan = mock(QueryPlan.class);
- when(plan.hasIteratorResult()).thenReturn(true);
- ResponseRecorder response = new ResponseRecorder();
- AggregativeQueryService service = service(pool, iterator, plan, 500);
- FutureTask<Void> closing = close(service);
- try {
- service.query(response).onNext(QueryRequest.newBuilder().setQueryId("child-query").build());
- assertTrue(response.finished.await(1, TimeUnit.SECONDS));
- assertError(response, "child-query");
- verify(plan, never()).execute(PipelineResult.EMPTY);
- verify(plan).clear();
- verify(iterator).close();
- verify(child).close();
- awaitShutdownWait(start(closing));
- assertFalse(closing.isDone());
- } finally {
- releaseMockQueries(service);
- closing.run();
- closing.get(1, TimeUnit.SECONDS);
- pool.shutdownNow();
- }
- }
-
- @Test(timeout = 5000)
- public void testRejectedPartitionCloseFailureStillClosesRemainingChildren() throws Exception {
- AtomicInteger submissions = new AtomicInteger();
- ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
- new LinkedBlockingQueue<>()) {
- @Override
- public void execute(Runnable task) {
- if (submissions.incrementAndGet() > 1) {
- throw new RejectedExecutionException("partition rejected");
- }
- super.execute(task);
- }
- };
- ScanIterator failed = mock(ScanIterator.class);
- doThrow(new IllegalStateException("rejected child cleanup failed")).when(failed).close();
- ScanIterator remaining = mock(ScanIterator.class);
- MultiPartitionIterator iterator = mock(MultiPartitionIterator.class);
- when(iterator.getIterators()).thenReturn(Arrays.asList(failed, remaining));
- QueryPlan plan = mock(QueryPlan.class);
- when(plan.hasIteratorResult()).thenReturn(true);
- ResponseRecorder response = new ResponseRecorder();
- AggregativeQueryService service = service(pool, iterator, plan, 500);
- FutureTask<Void> closing = close(service);
- try {
- service.query(response).onNext(QueryRequest.newBuilder().setQueryId("reject-query").build());
- assertTrue(response.finished.await(1, TimeUnit.SECONDS));
- assertError(response, "reject-query");
- verify(failed).close();
- verify(remaining).close();
- verify(plan).clear();
- verify(iterator).close();
- awaitShutdownWait(start(closing));
- assertFalse(closing.isDone());
- } finally {
- releaseMockQueries(service);
- closing.run();
- closing.get(1, TimeUnit.SECONDS);
- pool.shutdownNow();
- }
- }
-
- @Test(timeout = 5000)
- public void testSpringDoesNotDestroyDatabaseWhenIteratorCloseFails() throws Exception {
- ThreadPoolExecutor pool = pool(1);
- ScanIterator iterator = mock(ScanIterator.class);
- doThrow(new IllegalStateException("native iterator close failed")).when(iterator).close();
- AggregativeQueryService service = service(pool, iterator, new QueryPlan(), 500);
- AtomicBoolean databaseClosed = new AtomicBoolean();
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
- context.getBeanFactory().registerSingleton("queryService", service);
- context.getBeanFactory().registerSingleton("storeStream", mock(HgStoreStreamImpl.class));
- context.getBeanFactory().registerSingleton("cleaner", mock(TTLCleaner.class));
- context.getDefaultListableBeanFactory().registerDisposableBean(
- "database", () -> databaseClosed.set(true));
- context.register(ContextClosedListener.class, GrpcShutdownBarrier.class);
- context.refresh();
- ResponseRecorder response = new ResponseRecorder();
- FutureTask<Void> closing = new FutureTask<>(() -> {
- context.close();
- return null;
- });
- try {
- service.query(response).onNext(QueryRequest.newBuilder().setQueryId("spring-query").build());
- assertTrue(response.finished.await(1, TimeUnit.SECONDS));
- assertError(response, "spring-query");
- Thread closer = start(closing);
- awaitShutdownWait(closer);
- closer.interrupt();
- awaitShutdownWait(closer);
- assertFalse(closing.isDone());
- assertFalse("Spring must retain the database after cleanup failure", databaseClosed.get());
- } finally {
- releaseMockQueries(service);
- closing.run();
- closing.get(1, TimeUnit.SECONDS);
- context.close();
- pool.shutdownNow();
- }
- }
-
- @Test(timeout = 5000)
- public void testSynchronousFailureRetainsCleanupErrorAndShutdownBarrier() throws Exception {
- ThreadPoolExecutor pool = pool(1);
- ScanIterator iterator = mock(ScanIterator.class);
- IllegalStateException original = new IllegalStateException("plan initialization failed");
- IllegalStateException cleanup = new IllegalStateException("iterator cleanup failed");
- doThrow(cleanup).when(iterator).close();
- AggregativeQueryService service = new AggregativeQueryService(pool, 500, 10) {
- @Override
- AggregativeQueryObserver newObserver(StreamObserver<QueryResponse> sender) {
- AggregativeQueryObserver observer = spy(super.newObserver(sender));
- doReturn(iterator).when(observer).getIterator(org.mockito.ArgumentMatchers.any());
- doThrow(original).when(observer).buildPlan(org.mockito.ArgumentMatchers.any());
- return observer;
- }
- };
- ResponseRecorder response = new ResponseRecorder();
- FutureTask<Void> closing = close(service);
- try {
- IllegalStateException thrown = org.junit.Assert.assertThrows(IllegalStateException.class,
- () -> service.query(response).onNext(QueryRequest.getDefaultInstance()));
- org.junit.Assert.assertSame(original, thrown);
- assertEquals(1, thrown.getSuppressed().length);
- org.junit.Assert.assertSame(cleanup, thrown.getSuppressed()[0]);
- assertEquals(0, response.completed.get());
- assertTrue(response.responses.isEmpty());
- awaitShutdownWait(start(closing));
- assertFalse(closing.isDone());
- } finally {
- releaseMockQueries(service);
- closing.run();
- closing.get(1, TimeUnit.SECONDS);
- pool.shutdownNow();
- }
- }
-
- @Test(timeout = 5000)
- public void testPartialPartitionInitializationCleanupFailureRetainsQueryBarrier() throws Exception {
- ThreadPoolExecutor pool = pool(1);
- ScanIterator first = mock(ScanIterator.class);
- when(first.hasNext()).thenReturn(true);
- doThrow(new IllegalStateException("opened partition cleanup failed")).when(first).close();
- MultiPartitionIterator iterator = MultiPartitionIterator.of(Arrays.asList(1, 2), (id, key) -> {
- if (id == 1) {
- return first;
- }
- throw new IllegalStateException("second partition initialization failed");
- });
- QueryPlan plan = mock(QueryPlan.class);
- when(plan.hasIteratorResult()).thenReturn(true);
- ResponseRecorder response = new ResponseRecorder();
- AggregativeQueryService service = service(pool, iterator, plan, 500);
- FutureTask<Void> closing = close(service);
- try {
- service.query(response).onNext(QueryRequest.newBuilder().setQueryId("init-query").build());
- assertTrue(response.finished.await(1, TimeUnit.SECONDS));
- assertError(response, "init-query");
- verify(first).close();
- verify(plan).clear();
- awaitShutdownWait(start(closing));
- assertFalse(closing.isDone());
- } finally {
- releaseMockQueries(service);
- closing.run();
- closing.get(1, TimeUnit.SECONDS);
- pool.shutdownNow();
- }
- }
-
@Test
public void testPartitionInitializationFailureClosesEveryOpenedChild() {
ScanIterator first = mock(ScanIterator.class);
@@ -1214,113 +799,6 @@ public class AggregativeQueryShutdownTest {
verify(child).close();
}
- @Test(timeout = 5000)
- public void testSequentialEmptyPartitionCleanupFailureRetainsQueryBarrier() throws Exception {
- ThreadPoolExecutor pool = pool(1);
- ScanIterator child = mock(ScanIterator.class);
- doThrow(new IllegalStateException("empty partition cleanup failed")).when(child).close();
- MultiPartitionIterator iterator = MultiPartitionIterator.of(Arrays.asList(1), (id, key) -> child);
- AggregativeQueryService service = service(pool, iterator, new QueryPlan(), 500);
- ResponseRecorder response = new ResponseRecorder();
- FutureTask<Void> closing = close(service);
- try {
- service.query(response).onNext(QueryRequest.newBuilder().setQueryId("empty-query").build());
- assertTrue(response.finished.await(1, TimeUnit.SECONDS));
- assertError(response, "empty-query");
- verify(child).close();
- awaitShutdownWait(start(closing));
- assertFalse(closing.isDone());
- assertFalse("failed sequential cleanup cannot release the executor", pool.isShutdown());
- } finally {
- releaseMockQueries(service);
- closing.run();
- closing.get(1, TimeUnit.SECONDS);
- pool.shutdownNow();
- }
- }
-
- @Test(timeout = 5000)
- public void testNativeAutomaticCloseFailureRetainsSequentialQueryBarrier() throws Exception {
- ThreadPoolExecutor pool = pool(1);
- RocksIterator raw = mock(RocksIterator.class);
- when(raw.isOwningHandle()).thenReturn(true);
- IllegalStateException failure = new IllegalStateException("native close failed once");
- doThrow(failure).doNothing().when(raw).close();
- // Native close fails before the callback or reference release can be reached.
- RocksDBScanIterator<?> child = new RocksDBScanIterator<>(raw, null, null,
- ScanIterator.Trait.SCAN_ANY, null, ignored -> { });
- MultiPartitionIterator iterator = MultiPartitionIterator.of(Arrays.asList(1), (id, key) -> child);
- AggregativeQueryService service = service(pool, iterator, new QueryPlan(), 500);
- ResponseRecorder response = new ResponseRecorder();
- FutureTask<Void> closing = close(service);
- try {
- service.query(response).onNext(QueryRequest.newBuilder().setQueryId("native-close-query").build());
- assertTrue(response.finished.await(1, TimeUnit.SECONDS));
- assertError(response, "native-close-query");
- org.junit.Assert.assertSame(failure,
- org.junit.Assert.assertThrows(IllegalStateException.class, child::close));
- org.junit.Assert.assertThrows(IllegalStateException.class, iterator::close);
- verify(raw).close();
- awaitShutdownWait(start(closing));
- assertFalse("automatic native-close failure must retain the query registry", closing.isDone());
- assertFalse(pool.isShutdown());
- } finally {
- releaseMockQueries(service);
- closing.run();
- closing.get(1, TimeUnit.SECONDS);
- pool.shutdownNow();
- }
- }
-
- @Test(timeout = 10000)
- public void testSupplierInnerKeyFilterCloseFailureRetainsQueryBarrier() throws Exception {
- for (int constructor = 0; constructor < 3; constructor++) {
- assertSupplierFilterCloseFailureRetainsQueryBarrier(constructor);
- }
- }
-
- private static void assertSupplierFilterCloseFailureRetainsQueryBarrier(int constructor) throws Exception {
- ThreadPoolExecutor pool = pool(1);
- RocksIterator raw = mock(RocksIterator.class);
- when(raw.isOwningHandle()).thenReturn(true);
- IllegalStateException failure = new IllegalStateException("supplier iterator close failed once");
- doThrow(failure).doNothing().when(raw).close();
- RocksDBScanIterator<?> child = new RocksDBScanIterator<>(raw, null, null,
- ScanIterator.Trait.SCAN_ANY, null, ignored -> { });
- AtomicInteger supplierReturned = new AtomicInteger();
- MultiPartitionIterator iterator = MultiPartitionIterator.of(Arrays.asList(1), (id, key) -> {
- InnerKeyFilter<?> filter;
- if (constructor == 0) {
- filter = new InnerKeyFilter<>(child);
- } else if (constructor == 1) {
- filter = new InnerKeyFilter<>(child, true);
- } else {
- filter = new InnerKeyFilter<>(child, 10, 20);
- }
- supplierReturned.incrementAndGet();
- return filter;
- });
- AggregativeQueryService service = service(pool, iterator, new QueryPlan(), 500);
- ResponseRecorder response = new ResponseRecorder();
- FutureTask<Void> closing = close(service);
- try {
- service.query(response).onNext(QueryRequest.newBuilder().setQueryId("supplier-close-query").build());
- assertTrue(response.finished.await(1, TimeUnit.SECONDS));
- assertError(response, "supplier-close-query");
- assertEquals("factory must transfer ownership before any failing prefetch", 1, supplierReturned.get());
- org.junit.Assert.assertThrows(IllegalStateException.class, iterator::close);
- verify(raw).close();
- awaitShutdownWait(start(closing));
- assertFalse("factory prefetch failure must retain the aggregate query barrier", closing.isDone());
- assertFalse(pool.isShutdown());
- } finally {
- releaseMockQueries(service);
- closing.run();
- closing.get(1, TimeUnit.SECONDS);
- pool.shutdownNow();
- }
- }
-
@Test
public void testPlanCleanupContinuesAfterStageFailure() {
QueryStage failed = mock(QueryStage.class);
@@ -1334,208 +812,4 @@ public class AggregativeQueryShutdownTest {
verify(remaining).close();
assertTrue(plan.isEmpty());
}
-
- private static void awaitShutdownWait(Thread closer) {
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
- while (System.nanoTime() < deadline) {
- if (closer.getState() == Thread.State.TIMED_WAITING &&
- Arrays.stream(closer.getStackTrace()).anyMatch(frame ->
- frame.getClassName().equals(AggregativeQueryService.class.getName()) &&
- frame.getMethodName().equals("shutdownQueries"))) {
- return;
- }
- LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
- }
- fail("shutdown must enter the aggregate-query cleanup wait");
- }
-
- private static void assertContextCloseContinuesAfterCancellationFailure(Throwable failure) throws Exception {
- ThreadPoolExecutor pool = pool(1);
- CountDownLatch reading = new CountDownLatch(1);
- CountDownLatch closingIterator = new CountDownLatch(1);
- CountDownLatch allowClose = new CountDownLatch(1);
- AtomicBoolean iteratorClosed = new AtomicBoolean();
- AtomicBoolean databaseClosed = new AtomicBoolean();
- AtomicBoolean prematureDestruction = new AtomicBoolean();
- ScanIterator iterator = mock(ScanIterator.class);
- when(iterator.hasNext()).thenAnswer(invocation -> {
- reading.countDown();
- try {
- new CountDownLatch(1).await();
- } catch (InterruptedException ignored) {
- return false;
- }
- return false;
- });
- doAnswer(invocation -> {
- closingIterator.countDown();
- awaitUninterruptibly(allowClose);
- iteratorClosed.set(true);
- return null;
- }).when(iterator).close();
- AggregativeQueryService service = service(pool, iterator, new QueryPlan(), 500);
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
- try {
- context.getBeanFactory().registerSingleton("queryService", service);
- context.getBeanFactory().registerSingleton("storeStream", mock(HgStoreStreamImpl.class));
- context.getBeanFactory().registerSingleton("cleaner", mock(TTLCleaner.class));
- context.getDefaultListableBeanFactory().registerDisposableBean("database", () -> {
- prematureDestruction.set(!iteratorClosed.get() || !pool.isTerminated());
- databaseClosed.set(true);
- });
- context.register(ContextClosedListener.class, GrpcShutdownBarrier.class);
- context.refresh();
- StreamObserver<QueryResponse> firstSender = sender();
- StreamObserver<QueryResponse> secondSender = sender();
- StreamObserver<QueryRequest> first = service.query(firstSender);
- StreamObserver<QueryRequest> second = service.query(secondSender);
- Field field = AggregativeQueryService.class.getDeclaredField("queries");
- field.setAccessible(true);
- // Fail the first cancellation in the actual HashSet snapshot, regardless of identity hashes.
- boolean firstCancelsFirst = ((Set<?>) field.get(service)).iterator().next() == first;
- StreamObserver<QueryResponse> broken = firstCancelsFirst ? firstSender : secondSender;
- StreamObserver<QueryRequest> active = firstCancelsFirst ? second : first;
- doThrow(failure).when(broken).onCompleted();
- active.onNext(QueryRequest.getDefaultInstance());
- assertTrue(reading.await(1, TimeUnit.SECONDS));
- FutureTask<Void> closing = new FutureTask<>(() -> {
- context.close();
- return null;
- });
- Thread closer = start(closing);
- assertTrue("other queries must still be cancelled", closingIterator.await(1, TimeUnit.SECONDS));
- awaitShutdownWait(closer);
- assertFalse(closing.isDone());
- assertFalse(databaseClosed.get());
- assertFalse(pool.isShutdown());
- allowClose.countDown();
- closing.get(2, TimeUnit.SECONDS);
- assertTrue(databaseClosed.get());
- assertFalse("Spring must destroy databases only after query cleanup and worker termination",
- prematureDestruction.get());
- verify(broken).onCompleted();
- verify(iterator).close();
- } finally {
- allowClose.countDown();
- service.shutdownQueries();
- context.close();
- pool.shutdownNow();
- }
- }
-
- private static void releaseMockQueries(AggregativeQueryService service) throws Exception {
- // Only test mocks are discarded here; production deliberately has no bypass for this barrier.
- Field field = AggregativeQueryService.class.getDeclaredField("queries");
- field.setAccessible(true);
- synchronized (service) {
- ((Set<?>) field.get(service)).clear();
- service.notifyAll();
- }
- }
-
- private static void assertError(ResponseRecorder response, String queryId) {
- assertEquals(1, response.responses.size());
- QueryResponse error = response.responses.get(0);
- assertEquals(queryId, error.getQueryId());
- assertFalse(error.getIsOk());
- assertFalse(error.getIsFinished());
- assertFalse(error.getMessage().isEmpty());
- }
-
- private static class ResponseRecorder implements StreamObserver<QueryResponse> {
-
- private final List<QueryResponse> responses = new CopyOnWriteArrayList<>();
- private final AtomicInteger completed = new AtomicInteger();
- private final AtomicInteger errors = new AtomicInteger();
- private final CountDownLatch received = new CountDownLatch(1);
- private final CountDownLatch finished = new CountDownLatch(1);
-
- @Override
- public void onNext(QueryResponse response) {
- this.responses.add(response);
- this.received.countDown();
- }
-
- @Override
- public void onError(Throwable error) {
- this.errors.incrementAndGet();
- this.finished.countDown();
- }
-
- @Override
- public void onCompleted() {
- this.completed.incrementAndGet();
- this.finished.countDown();
- }
- }
-
- private static ThreadPoolExecutor pool(int size) {
- return (ThreadPoolExecutor) Executors.newFixedThreadPool(size);
- }
-
- private static AggregativeQueryService service(ThreadPoolExecutor pool, ScanIterator iterator,
- QueryPlan plan, long timeout) {
- return new AggregativeQueryService(pool, timeout, 10) {
- @Override
- AggregativeQueryObserver newObserver(StreamObserver<QueryResponse> sender) {
- return fixture(super.newObserver(sender), iterator, plan, null);
- }
- };
- }
-
- private static AggregativeQueryObserver fixture(AggregativeQueryObserver observer,
- ScanIterator iterator,
- QueryPlan plan, CountDownLatch parentReturned) {
- AggregativeQueryObserver managed = spy(observer);
- doReturn(iterator).when(managed).getIterator(org.mockito.ArgumentMatchers.any());
- doReturn(plan).when(managed).buildPlan(org.mockito.ArgumentMatchers.any());
- if (parentReturned != null) {
- doAnswer(invocation -> {
- try {
- invocation.callRealMethod();
- return null;
- } finally {
- parentReturned.countDown();
- }
- }).when(managed).sendData();
- }
- return managed;
- }
-
- @SuppressWarnings("unchecked")
- private static StreamObserver<QueryResponse> sender() {
- return mock(StreamObserver.class);
- }
-
- private static FutureTask<Void> close(AggregativeQueryService service) {
- return new FutureTask<>(() -> {
- service.shutdownQueries();
- return null;
- });
- }
-
- private static Thread start(FutureTask<?> task) {
- Thread thread = new Thread(task, "test-aggregate-query-close");
- thread.setDaemon(true);
- thread.start();
- return thread;
- }
-
- private static void awaitUninterruptibly(CountDownLatch latch) {
- boolean interrupted = false;
- try {
- for (;;) {
- try {
- latch.await();
- return;
- } catch (InterruptedException e) {
- interrupted = true;
- }
- }
- } finally {
- if (interrupted) {
- Thread.currentThread().interrupt();
- }
- }
- }
}
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/AggregativeQueryTestSupport.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/AggregativeQueryTestSupport.java
new file mode 100644
index 000000000..b8d7f4056
--- /dev/null
+++ b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/AggregativeQueryTestSupport.java
@@ -0,0 +1,165 @@
+/*
+ * 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.hugegraph.store.node.grpc.query;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import io.grpc.stub.StreamObserver;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.LockSupport;
+import org.apache.hugegraph.rocksdb.access.ScanIterator;
+import org.apache.hugegraph.store.grpc.query.QueryResponse;
+import org.apache.hugegraph.store.node.grpc.query.model.QueryPlan;
+
+abstract class AggregativeQueryTestSupport {
+
+ static void awaitShutdownWait(Thread closer) {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
+ while (System.nanoTime() < deadline) {
+ if (closer.getState() == Thread.State.TIMED_WAITING &&
+ Arrays.stream(closer.getStackTrace()).anyMatch(frame ->
+ frame.getClassName().equals(AggregativeQueryService.class.getName()) &&
+ frame.getMethodName().equals("shutdownQueries"))) {
+ return;
+ }
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
+ }
+ fail("shutdown must enter the aggregate-query cleanup wait");
+ }
+
+ static void assertError(ResponseRecorder response, String queryId) {
+ assertEquals(1, response.responses.size());
+ QueryResponse error = response.responses.get(0);
+ assertEquals(queryId, error.getQueryId());
+ assertFalse(error.getIsOk());
+ assertFalse(error.getIsFinished());
+ assertFalse(error.getMessage().isEmpty());
+ }
+
+ static ThreadPoolExecutor pool(int size) {
+ return (ThreadPoolExecutor) Executors.newFixedThreadPool(size);
+ }
+
+ static AggregativeQueryService service(ThreadPoolExecutor pool, ScanIterator iterator,
+ QueryPlan plan, long timeout) {
+ return new AggregativeQueryService(pool, timeout, 10) {
+ @Override
+ AggregativeQueryObserver newObserver(StreamObserver<QueryResponse> sender) {
+ return fixture(super.newObserver(sender), iterator, plan, null);
+ }
+ };
+ }
+
+ static AggregativeQueryObserver fixture(AggregativeQueryObserver observer,
+ ScanIterator iterator,
+ QueryPlan plan, CountDownLatch parentReturned) {
+ AggregativeQueryObserver managed = spy(observer);
+ doReturn(iterator).when(managed).getIterator(org.mockito.ArgumentMatchers.any());
+ doReturn(plan).when(managed).buildPlan(org.mockito.ArgumentMatchers.any());
+ if (parentReturned != null) {
+ doAnswer(invocation -> {
+ try {
+ invocation.callRealMethod();
+ return null;
+ } finally {
+ parentReturned.countDown();
+ }
+ }).when(managed).sendData();
+ }
+ return managed;
+ }
+
+ @SuppressWarnings("unchecked")
+ static StreamObserver<QueryResponse> sender() {
+ return mock(StreamObserver.class);
+ }
+
+ static FutureTask<Void> close(AggregativeQueryService service) {
+ return new FutureTask<>(() -> {
+ service.shutdownQueries();
+ return null;
+ });
+ }
+
+ static Thread start(FutureTask<?> task) {
+ Thread thread = new Thread(task, "test-aggregate-query-close");
+ thread.setDaemon(true);
+ thread.start();
+ return thread;
+ }
+
+ static void awaitUninterruptibly(CountDownLatch latch) {
+ boolean interrupted = false;
+ try {
+ for (;;) {
+ try {
+ latch.await();
+ return;
+ } catch (InterruptedException e) {
+ interrupted = true;
+ }
+ }
+ } finally {
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ static class ResponseRecorder implements StreamObserver<QueryResponse> {
+
+ final List<QueryResponse> responses = new CopyOnWriteArrayList<>();
+ final AtomicInteger completed = new AtomicInteger();
+ final AtomicInteger errors = new AtomicInteger();
+ final CountDownLatch received = new CountDownLatch(1);
+ final CountDownLatch finished = new CountDownLatch(1);
+
+ @Override
+ public void onNext(QueryResponse response) {
+ this.responses.add(response);
+ this.received.countDown();
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ this.errors.incrementAndGet();
+ this.finished.countDown();
+ }
+
+ @Override
+ public void onCompleted() {
+ this.completed.incrementAndGet();
+ this.finished.countDown();
+ }
+ }
+}
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GraphPartitionScanShutdownTest.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GraphPartitionScanLifecycleTest.java
similarity index 79%
rename from hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GraphPartitionScanShutdownTest.java
rename to hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GraphPartitionScanLifecycleTest.java
index 9be061563..8ee7898e7 100644
--- a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GraphPartitionScanShutdownTest.java
+++ b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GraphPartitionScanLifecycleTest.java
@@ -18,7 +18,6 @@
package org.apache.hugegraph.store.service;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -52,7 +51,7 @@ import org.junit.Test;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
-public class GraphPartitionScanShutdownTest {
+public class GraphPartitionScanLifecycleTest extends GraphPartitionScanTestSupport {
@Test
public void testNaturalEndAndLimitCloseIteratorBeforeCompleting() throws Exception {
@@ -148,74 +147,6 @@ public class GraphPartitionScanShutdownTest {
}
}
- @Test
- public void testFailedNativeCloseRemainsInShutdownBarrier() throws Exception {
- ThreadPoolExecutor executor = executor();
- try {
- HgStoreStreamImpl service = service(executor);
- GraphStoreIterator<?> iterator = mock(GraphStoreIterator.class);
- RuntimeException failure = new IllegalStateException("native close failed");
- doThrow(failure).when(iterator).close();
- BusinessHandler handler = mock(BusinessHandler.class);
- doReturn(iterator).when(handler).scan(any());
- StreamObserver<ScanResponse> response = mock(StreamObserver.class);
- service.scanGraphPartition(response, handler).onNext(request(0));
- verify(response, timeout(2000)).onError(failure);
- assertEquals(1, registry(service).size());
- Object lifecycle = registry(service).keySet().iterator().next();
- java.lang.reflect.Method cleanup = lifecycle.getClass().getDeclaredMethod("cleanupFailure");
- cleanup.setAccessible(true);
- assertSame(failure, cleanup.invoke(lifecycle));
- verify(iterator).close();
- } finally {
- executor.shutdown();
- assertTrue(executor.awaitTermination(2, TimeUnit.SECONDS));
- }
- }
-
- @Test
- public void testShutdownWaitsForActiveReadBeforeClosingNativeIterator() throws Exception {
- ThreadPoolExecutor executor = executor();
- CountDownLatch entered = new CountDownLatch(1);
- CountDownLatch release = new CountDownLatch(1);
- CountDownLatch stopped = new CountDownLatch(1);
- CountDownLatch stoppingStarted = new CountDownLatch(1);
- try {
- HgStoreStreamImpl service = service(executor);
- GraphStoreIterator<?> iterator = mock(GraphStoreIterator.class);
- when(iterator.hasNext()).thenAnswer(call -> {
- entered.countDown();
- assertTrue(release.await(2, TimeUnit.SECONDS));
- return false;
- });
- BusinessHandler handler = mock(BusinessHandler.class);
- doReturn(iterator).when(handler).scan(any());
- StreamObserver<ScanResponse> response = mock(StreamObserver.class);
- service.scanGraphPartition(response, handler).onNext(request(0));
- assertTrue(entered.await(2, TimeUnit.SECONDS));
- Thread stopping = new Thread(() -> {
- service.stopAcceptingScans();
- stoppingStarted.countDown();
- service.shutdownScans();
- service.awaitScanCleanup();
- stopped.countDown();
- });
- stopping.start();
- assertTrue(stoppingStarted.await(2, TimeUnit.SECONDS));
- assertFalse(stopped.await(100, TimeUnit.MILLISECONDS));
- release.countDown();
- assertTrue(stopped.await(2, TimeUnit.SECONDS));
- stopping.join(2000);
- verify(iterator).close();
- verify(response).onError(any());
- assertTrue(registry(service).isEmpty());
- } finally {
- release.countDown();
- executor.shutdown();
- assertTrue(executor.awaitTermination(2, TimeUnit.SECONDS));
- }
- }
-
@Test
public void testClientCompletionBeforeInitializationReleasesBarrier() throws Exception {
ThreadPoolExecutor executor = executor();
@@ -454,28 +385,4 @@ public class GraphPartitionScanShutdownTest {
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
}
}
-
- private static ScanPartitionRequest request(long limit) {
- return ScanPartitionRequest.newBuilder().setScanRequest(Graphpb.ScanPartitionRequest.Request.newBuilder()
- .setGraphName("TEST/credit-window")
- .setScanType(Graphpb.ScanPartitionRequest.ScanType.SCAN_VERTEX).setLimit(limit)).build();
- }
-
- private static ThreadPoolExecutor executor() {
- return new ThreadPoolExecutor(2, 2, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
- }
-
- private static HgStoreStreamImpl service(ThreadPoolExecutor executor) throws Exception {
- HgStoreStreamImpl service = new HgStoreStreamImpl();
- Field field = HgStoreStreamImpl.class.getDeclaredField("executor");
- field.setAccessible(true);
- field.set(service, executor);
- return service;
- }
-
- private static Map<?, ?> registry(HgStoreStreamImpl service) throws Exception {
- Field field = HgStoreStreamImpl.class.getDeclaredField("scans");
- field.setAccessible(true);
- return (Map<?, ?>) field.get(service);
- }
}
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GraphPartitionScanTestSupport.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GraphPartitionScanTestSupport.java
new file mode 100644
index 000000000..1742ac64c
--- /dev/null
+++ b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GraphPartitionScanTestSupport.java
@@ -0,0 +1,55 @@
+/*
+ * 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.hugegraph.store.service;
+
+import java.lang.reflect.Field;
+import java.util.Map;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.hugegraph.store.grpc.Graphpb;
+import org.apache.hugegraph.store.grpc.Graphpb.ScanPartitionRequest;
+import org.apache.hugegraph.store.node.grpc.HgStoreStreamImpl;
+
+abstract class GraphPartitionScanTestSupport {
+
+ static ScanPartitionRequest request(long limit) {
+ return ScanPartitionRequest.newBuilder().setScanRequest(Graphpb.ScanPartitionRequest.Request.newBuilder()
+ .setGraphName("TEST/credit-window")
+ .setScanType(Graphpb.ScanPartitionRequest.ScanType.SCAN_VERTEX).setLimit(limit)).build();
+ }
+
+ static ThreadPoolExecutor executor() {
+ return new ThreadPoolExecutor(2, 2, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
+ }
+
+ static HgStoreStreamImpl service(ThreadPoolExecutor executor) throws Exception {
+ HgStoreStreamImpl service = new HgStoreStreamImpl();
+ Field field = HgStoreStreamImpl.class.getDeclaredField("executor");
+ field.setAccessible(true);
+ field.set(service, executor);
+ return service;
+ }
+
+ static Map<?, ?> registry(HgStoreStreamImpl service) throws Exception {
+ Field field = HgStoreStreamImpl.class.getDeclaredField("scans");
+ field.setAccessible(true);
+ return (Map<?, ?>) field.get(service);
+ }
+}
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GrpcShutdownBarrierTest.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GrpcShutdownBarrierTest.java
deleted file mode 100644
index c32bcb039..000000000
--- a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/GrpcShutdownBarrierTest.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * 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.hugegraph.store.service;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.hugegraph.store.node.grpc.GrpcShutdownBarrier;
-import org.junit.Test;
-
-import io.grpc.CallOptions;
-import io.grpc.ManagedChannel;
-import io.grpc.MethodDescriptor;
-import io.grpc.Server;
-import io.grpc.ServerServiceDefinition;
-import io.grpc.inprocess.InProcessChannelBuilder;
-import io.grpc.inprocess.InProcessServerBuilder;
-import io.grpc.stub.ClientCalls;
-import io.grpc.stub.ServerCalls;
-import io.grpc.stub.StreamObserver;
-
-public class GrpcShutdownBarrierTest {
-
- @Test(timeout = 7000)
- public void testTransportTerminationDoesNotReleaseActiveCallback() throws Exception {
- CountDownLatch started = new CountDownLatch(1);
- CountDownLatch release = new CountDownLatch(1);
- AtomicBoolean finished = new AtomicBoolean();
- ExecutorService executor = Executors.newSingleThreadExecutor();
- MethodDescriptor.Marshaller<byte[]> marshaller = new MethodDescriptor.Marshaller<byte[]>() {
- @Override
- public InputStream stream(byte[] value) {
- return new ByteArrayInputStream(value);
- }
- @Override
- public byte[] parse(InputStream stream) {
- return new byte[0];
- }
- };
- MethodDescriptor<byte[], byte[]> method = MethodDescriptor.<byte[], byte[]>newBuilder()
- .setType(MethodDescriptor.MethodType.UNARY).setFullMethodName("probe/hold")
- .setRequestMarshaller(marshaller).setResponseMarshaller(marshaller).build();
- String name = InProcessServerBuilder.generateName();
- GrpcShutdownBarrier barrier = new GrpcShutdownBarrier();
- Server server = InProcessServerBuilder.forName(name).executor(executor).intercept(barrier)
- .addService(ServerServiceDefinition.builder("probe").addMethod(method,
- ServerCalls.asyncUnaryCall((request, response) -> {
- started.countDown();
- try {
- release.await();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- } finally {
- finished.set(true);
- }
- response.onNext(new byte[0]);
- response.onCompleted();
- })).build()).build().start();
- ManagedChannel channel = InProcessChannelBuilder.forName(name).directExecutor().build();
- try {
- ClientCalls.asyncUnaryCall(channel.newCall(method, CallOptions.DEFAULT), new byte[0],
- new StreamObserver<byte[]>() {
- @Override
- public void onNext(byte[] value) {
- }
- @Override
- public void onError(Throwable error) {
- }
- @Override
- public void onCompleted() {
- }
- });
- assertTrue("handler must start", started.await(2, TimeUnit.SECONDS));
- barrier.stopAcceptingCalls();
- server.shutdownNow();
- assertTrue(server.awaitTermination(1, TimeUnit.SECONDS));
- assertFalse("transport termination must not be mistaken for callback exit", finished.get());
- CountDownLatch waiting = new CountDownLatch(1);
- FutureTask<Void> drained = new FutureTask<>(() -> {
- waiting.countDown();
- barrier.awaitCallbacks();
- return null;
- });
- Thread waiter = new Thread(drained, "test-rpc-drain");
- waiter.setDaemon(true);
- waiter.start();
- assertTrue(waiting.await(1, TimeUnit.SECONDS));
- try {
- drained.get(100, TimeUnit.MILLISECONDS);
- fail("barrier passed while a handler still owns resources");
- } catch (TimeoutException expected) {
- // The active handler must prevent database destruction.
- }
- release.countDown();
- drained.get(2, TimeUnit.SECONDS);
- assertTrue(finished.get());
- } finally {
- release.countDown();
- channel.shutdownNow();
- server.shutdownNow();
- executor.shutdown();
- assertTrue("cleanup must finish", executor.awaitTermination(2, TimeUnit.SECONDS));
- }
- }
-}
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ContextClosedListenerTest.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanContextCleanupTest.java
similarity index 50%
rename from hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ContextClosedListenerTest.java
rename to hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanContextCleanupTest.java
index bc22769a3..618d9913a 100644
--- a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ContextClosedListenerTest.java
+++ b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanContextCleanupTest.java
@@ -31,21 +31,18 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
-import org.apache.hugegraph.store.node.grpc.GrpcShutdownBarrier;
import org.apache.hugegraph.store.node.grpc.HgStoreStreamImpl;
import org.apache.hugegraph.store.node.grpc.query.AggregativeQueryService;
import org.apache.hugegraph.store.node.listener.ContextClosedListener;
import org.apache.hugegraph.store.node.task.TTLCleaner;
import org.junit.Test;
-import org.lognet.springboot.grpc.context.GRpcServerInitializedEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-import io.grpc.Server;
-public class ContextClosedListenerTest {
+public class ScanContextCleanupTest {
@Test(timeout = 5000)
- public void testContextCloseStopsActiveWorkersWithoutPartitionDelay() throws Exception {
+ public void testScopedWorkersFinishBeforeBeanDestruction() throws Exception {
ThreadPoolExecutor scan = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
ThreadPoolExecutor ttl = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
@@ -73,6 +70,7 @@ public class ContextClosedListenerTest {
Thread.currentThread().interrupt();
}
};
+ AtomicBoolean databaseClosed = new AtomicBoolean();
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
try {
HgStoreStreamImpl stream = mock(HgStoreStreamImpl.class);
@@ -87,7 +85,9 @@ public class ContextClosedListenerTest {
context.getBeanFactory().registerSingleton("storeStream", stream);
context.getBeanFactory().registerSingleton("queryService", mock(AggregativeQueryService.class));
context.getBeanFactory().registerSingleton("cleaner", cleaner);
- context.register(ContextClosedListener.class, GrpcShutdownBarrier.class);
+ context.getDefaultListableBeanFactory().registerDisposableBean(
+ "database", () -> databaseClosed.set(true));
+ context.register(ContextClosedListener.class);
context.refresh();
scan.execute(work);
ttl.execute(work);
@@ -104,12 +104,14 @@ public class ContextClosedListenerTest {
// Scheduler shutdown must not let DB destruction overtake resource cleanup.
assertTrue(cleanupStarted.await(1, TimeUnit.SECONDS));
assertFalse("context close must wait for worker cleanup", closing.isDone());
+ assertFalse("database must remain open during worker cleanup", databaseClosed.get());
cleanupAllowed.countDown();
closing.get(2, TimeUnit.SECONDS);
assertTrue("close must interrupt active workers", interrupted.await(1, TimeUnit.SECONDS));
assertTrue(scan.awaitTermination(1, TimeUnit.SECONDS));
assertTrue(ttl.awaitTermination(1, TimeUnit.SECONDS));
assertTrue(scheduler.awaitTermination(1, TimeUnit.SECONDS));
+ assertTrue(databaseClosed.get());
} finally {
cleanupAllowed.countDown();
release.countDown();
@@ -120,101 +122,4 @@ public class ContextClosedListenerTest {
}
}
- @Test(timeout = 5000)
- public void testGrpcCallbacksFinishBeforeBeanDestructionEvenWhenInterrupted() throws Exception {
- CountDownLatch awaitingCallbacks = new CountDownLatch(1);
- CountDownLatch releaseCallbacks = new CountDownLatch(1);
- AtomicBoolean terminated = new AtomicBoolean();
- AtomicBoolean databaseClosed = new AtomicBoolean();
- Server server = mock(Server.class);
- when(server.shutdownNow()).thenReturn(server);
- when(server.isTerminated()).thenAnswer(invocation -> terminated.get());
- when(server.awaitTermination(5, TimeUnit.SECONDS)).thenAnswer(invocation -> {
- awaitingCallbacks.countDown();
- releaseCallbacks.await();
- terminated.set(true);
- return true;
- });
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
- try {
- context.getBeanFactory().registerSingleton("storeStream", mock(HgStoreStreamImpl.class));
- context.getBeanFactory().registerSingleton("queryService", mock(AggregativeQueryService.class));
- context.getBeanFactory().registerSingleton("cleaner", mock(TTLCleaner.class));
- context.getDefaultListableBeanFactory().registerDisposableBean("database", () -> databaseClosed.set(true));
- context.register(ContextClosedListener.class, GrpcShutdownBarrier.class);
- context.refresh();
- context.publishEvent(new GRpcServerInitializedEvent(context, server));
- FutureTask<Boolean> closing = new FutureTask<>(() -> {
- context.close();
- return Thread.currentThread().isInterrupted();
- });
- Thread closeThread = new Thread(closing, "test-grpc-context-close");
- closeThread.setDaemon(true);
- closeThread.start();
- assertTrue(awaitingCallbacks.await(1, TimeUnit.SECONDS));
- closeThread.interrupt();
- assertFalse("DB must remain open while callbacks own its resources", databaseClosed.get());
- releaseCallbacks.countDown();
- assertTrue("shutdown must preserve interruption", closing.get(2, TimeUnit.SECONDS));
- assertTrue(terminated.get());
- assertTrue(databaseClosed.get());
- } finally {
- releaseCallbacks.countDown();
- context.close();
- }
- }
- @Test(timeout = 5000)
- public void testTtlCleanupBlocksBeanDestructionAfterWorkersTerminate() throws Exception {
- CountDownLatch awaitingCleanup = new CountDownLatch(1);
- CountDownLatch interruptedCleanup = new CountDownLatch(1);
- CountDownLatch releaseCleanup = new CountDownLatch(1);
- AtomicBoolean databaseClosed = new AtomicBoolean();
- TTLCleaner cleaner = mock(TTLCleaner.class);
- doAnswer(invocation -> {
- boolean interrupted = false;
- awaitingCleanup.countDown();
- boolean released = false;
- while (!released) {
- try {
- releaseCleanup.await();
- released = true;
- } catch (InterruptedException e) {
- interrupted = true;
- interruptedCleanup.countDown();
- }
- }
- if (interrupted) {
- Thread.currentThread().interrupt();
- }
- return null;
- }).when(cleaner).awaitCleanup();
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
- try {
- context.getBeanFactory().registerSingleton("storeStream", mock(HgStoreStreamImpl.class));
- context.getBeanFactory().registerSingleton("queryService", mock(AggregativeQueryService.class));
- context.getBeanFactory().registerSingleton("cleaner", cleaner);
- context.getDefaultListableBeanFactory().registerDisposableBean("database", () -> databaseClosed.set(true));
- context.register(ContextClosedListener.class, GrpcShutdownBarrier.class);
- context.refresh();
- FutureTask<Boolean> closing = new FutureTask<>(() -> {
- context.close();
- return Thread.currentThread().isInterrupted();
- });
- Thread closeThread = new Thread(closing, "test-ttl-context-close");
- closeThread.setDaemon(true);
- closeThread.start();
- assertTrue(awaitingCleanup.await(1, TimeUnit.SECONDS));
- closeThread.interrupt();
- assertTrue(interruptedCleanup.await(1, TimeUnit.SECONDS));
- assertFalse("TTL native cleanup must finish before DB destruction", databaseClosed.get());
- assertFalse(closing.isDone());
- releaseCleanup.countDown();
- assertTrue("shutdown must preserve interruption", closing.get(2, TimeUnit.SECONDS));
- assertTrue(databaseClosed.get());
- } finally {
- releaseCleanup.countDown();
- context.close();
- }
- }
-
}
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanShutdownTest.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanLifecycleTest.java
similarity index 87%
rename from hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanShutdownTest.java
rename to hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanLifecycleTest.java
index d7f382e70..59b193cba 100644
--- a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanShutdownTest.java
+++ b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanLifecycleTest.java
@@ -20,7 +20,6 @@ package org.apache.hugegraph.store.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
@@ -41,7 +40,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -67,7 +65,6 @@ import org.apache.hugegraph.store.grpc.stream.ScanQueryRequest;
import org.apache.hugegraph.store.grpc.stream.ScanStreamBatchReq;
import org.apache.hugegraph.store.grpc.stream.ScanStreamReq;
import org.apache.hugegraph.store.node.AppConfig;
-import org.apache.hugegraph.store.node.grpc.GrpcShutdownBarrier;
import org.apache.hugegraph.store.node.grpc.HgStoreStreamImpl;
import org.apache.hugegraph.store.node.grpc.HgStoreWrapperEx;
import org.apache.hugegraph.store.node.grpc.ParallelScanIterator;
@@ -77,13 +74,9 @@ import org.apache.hugegraph.store.node.grpc.ScanBatchResponse;
import org.apache.hugegraph.store.node.grpc.ScanBatchResponse3;
import org.apache.hugegraph.store.node.grpc.ScanOneShotResponse;
import org.apache.hugegraph.store.node.grpc.ScanStreamResponse;
-import org.apache.hugegraph.store.node.grpc.query.AggregativeQueryService;
-import org.apache.hugegraph.store.node.listener.ContextClosedListener;
-import org.apache.hugegraph.store.node.task.TTLCleaner;
import org.apache.hugegraph.store.node.util.HgChannel;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import io.grpc.Context;
import io.grpc.ManagedChannel;
@@ -94,7 +87,7 @@ import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.StreamObserver;
-public class ScanShutdownTest {
+public class ScanLifecycleTest extends ScanTestSupport {
@Test
public void testFailedSelectionCleanupBlocksLifecycleCompletion() throws Exception {
@@ -284,98 +277,6 @@ public class ScanShutdownTest {
}
}
- @Test(timeout = 20000)
- public void testOrdinaryScanCleanupFailureBlocksSpringDestruction() throws Exception {
- for (int mode = 0; mode < 5; mode++) {
- assertCleanupBlocksDestruction(mode);
- }
- }
-
- private static void assertCleanupBlocksDestruction(int mode) throws Exception {
- ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
- HgStoreWrapperEx wrapper = mock(HgStoreWrapperEx.class);
- ScanIterator broken = mock(ScanIterator.class);
- ScanIterator healthy = mock(ScanIterator.class);
- IllegalStateException failure = new IllegalStateException("injected native release failure");
- doThrow(failure).when(broken).close();
- when(wrapper.scanAll(anyString(), anyString(), any(byte[].class))).thenReturn(broken, healthy);
- HgStoreStreamImpl service = scanService(executor, wrapper);
- AnnotationConfigApplicationContext context =
- new AnnotationConfigApplicationContext();
- AtomicBoolean destroyed = new AtomicBoolean();
- FutureTask<Void> closing = new FutureTask<>(() -> {
- context.close();
- return null;
- });
- Thread closer = new Thread(closing, "scan-failed-cleanup-context-close");
- try {
- context.getBeanFactory().registerSingleton("storeStream", service);
- context.getBeanFactory().registerSingleton("queryService",
- mock(AggregativeQueryService.class));
- context.getBeanFactory().registerSingleton("cleaner",
- mock(TTLCleaner.class));
- context.getDefaultListableBeanFactory().registerDisposableBean("database", () -> destroyed.set(true));
- context.register(ContextClosedListener.class,
- GrpcShutdownBarrier.class);
- context.refresh();
- for (int i = 0; i < 2; i++) {
- ScanStreamReq request = ScanStreamReq.newBuilder().setMethod(ScanMethod.ALL)
- .setPageSize(1).setLimit(10).build();
- switch (mode) {
- case 0:
- service.scan(mock(StreamObserver.class)).onNext(request);
- break;
- case 1:
- service.scanBatch2(mock(StreamObserver.class)).onNext(batchRequest());
- break;
- case 2:
- service.scanBatch(mock(StreamObserver.class)).onNext(batchRequest());
- break;
- case 3:
- service.scanOneShot(request, mock(StreamObserver.class));
- break;
- default:
- service.scanBatchOneShot(batchRequest(), mock(StreamObserver.class));
- }
- }
- verify(broken, timeout(2000)).close();
- verify(healthy, timeout(2000)).close();
- closer.start();
- assertTrue(executor.awaitTermination(2, TimeUnit.SECONDS));
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
- Thread.State observed = closer.getState();
- while (observed != Thread.State.TIMED_WAITING && System.nanoTime() < deadline) {
- Thread.yield();
- observed = closer.getState();
- }
- // Assert the captured wait observation: a second state read can see a
- // notification wakeup even though database destruction remains blocked.
- assertEquals(Thread.State.TIMED_WAITING, observed);
- assertFalse("terminated workers do not confirm native cleanup", closing.isDone());
- assertFalse(destroyed.get());
- verify(broken).close();
- verify(healthy).close();
- Map<?, ?> pending = scanRegistry(service);
- assertEquals(1, pending.size());
- Object retained = pending.keySet().iterator().next();
- Field cleanupFailure = retained.getClass().getDeclaredField("cleanupFailure");
- cleanupFailure.setAccessible(true);
- assertSame(failure, cleanupFailure.get(retained));
- } finally {
- // Test-only teardown: production never clears a failed native release.
- Map<?, ?> pending = scanRegistry(service);
- synchronized (pending) {
- pending.clear();
- pending.notifyAll();
- }
- executor.shutdownNow();
- if (closer.isAlive()) {
- closing.get(2, TimeUnit.SECONDS);
- }
- context.close();
- }
- }
-
@Test(timeout = 5000)
public void testUnsupportedPausedBatchClosesOwnedIteratorAndRetainsFailure() throws Exception {
for (boolean fails : new boolean[]{false, true}) {
@@ -716,83 +617,6 @@ public class ScanShutdownTest {
}
}
- private static HgStoreStreamImpl scanService(ThreadPoolExecutor executor,
- HgStoreWrapperEx wrapper) throws Exception {
- HgStoreStreamImpl service = new HgStoreStreamImpl();
- AppConfig config = mock(AppConfig.class);
- when(config.getServerWaitTime()).thenReturn(5);
- for (String name : new String[]{"executor", "wrapper", "appConfig"}) {
- Field field = HgStoreStreamImpl.class.getDeclaredField(name);
- field.setAccessible(true);
- field.set(service, name.equals("executor") ? executor : name.equals("wrapper") ? wrapper : config);
- }
- return service;
- }
-
- private static Map<?, ?> scanRegistry(HgStoreStreamImpl service) throws Exception {
- Field scans = HgStoreStreamImpl.class.getDeclaredField("scans");
- scans.setAccessible(true);
- return (Map<?, ?>) scans.get(service);
- }
-
- @Test
- public void testClosingPreventsLazyExecutorAndStateCreation() {
- HgStoreStreamImpl service = new HgStoreStreamImpl();
- service.stopAcceptingScans();
- assertUnavailable(service::getExecutor);
- assertUnavailable(service::getState);
- assertUnavailable(() -> service.scan(mock(StreamObserver.class)));
- service.shutdownScans();
- assertNull(service.getRealExecutor());
- }
-
- @Test(timeout = 5000)
- public void testQueuedStreamCancellationDrainsWithoutOpeningIterator() throws Exception {
- ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
- CountDownLatch release = new CountDownLatch(1);
- CountDownLatch occupied = new CountDownLatch(1);
- executor.execute(() -> {
- occupied.countDown();
- try {
- release.await();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- });
- HgStoreWrapperEx wrapper = mock(HgStoreWrapperEx.class);
- AppConfig config = mock(AppConfig.class);
- when(config.getServerWaitTime()).thenReturn(60);
- StreamObserver<KvPageRes> output = mock(StreamObserver.class);
- ScanStreamResponse response = ScanStreamResponse.of(output, wrapper, executor, config);
- FutureTask<Void> request = new FutureTask<>(() -> {
- response.onNext(ScanStreamReq.newBuilder().setMethod(ScanMethod.ALL)
- .setPageSize(1).setLimit(10).build());
- return null;
- });
- Thread caller = new Thread(request, "scan-shutdown-test");
- try {
- assertTrue(occupied.await(1, TimeUnit.SECONDS));
- caller.start();
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
- while (executor.getQueue().isEmpty() && System.nanoTime() < deadline) {
- Thread.yield();
- }
- assertEquals(1, executor.getQueue().size());
- response.onError(Status.CANCELLED.asRuntimeException());
- executor.shutdown();
- release.countDown();
- request.get(1, TimeUnit.SECONDS);
- assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS));
- verifyNoInteractions(wrapper);
- assertEquals(2L, executor.getCompletedTaskCount());
- } finally {
- response.onCompleted();
- release.countDown();
- executor.shutdownNow();
- caller.join(1000);
- }
- }
-
@Test(timeout = 10000)
public void testInProcessOneShotCancellationDuringCloseReportsCancelled() throws Exception {
for (boolean batch : new boolean[]{false, true}) {
@@ -1694,37 +1518,4 @@ public class ScanShutdownTest {
producer.join(1000);
}
}
-
- private static void awaitTimedWaiting(Thread thread) {
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
- Thread.State observed = thread.getState();
- while (observed != Thread.State.TIMED_WAITING && System.nanoTime() < deadline) {
- Thread.yield();
- observed = thread.getState();
- }
- assertEquals(Thread.State.TIMED_WAITING, observed);
- }
-
- private static ScanStreamBatchReq batchRequest() {
- return ScanStreamBatchReq.newBuilder().setHeader(Header.newBuilder().setGraph("g"))
- .setQueryRequest(ScanQueryRequest.newBuilder().setMethod(ScanMethod.ALL)
- .setTable("t").setLimit(10)
- .setPerKeyMax(Long.MAX_VALUE)
- .setPageSize(1)).build();
- }
-
- private static void assertCancelled(StreamObserver<KvPageRes> output) {
- ArgumentCaptor<Throwable> failure = ArgumentCaptor.forClass(Throwable.class);
- verify(output).onError(failure.capture());
- assertEquals(Status.Code.CANCELLED, Status.fromThrowable(failure.getValue()).getCode());
- }
-
- private static void assertUnavailable(Runnable action) {
- try {
- action.run();
- fail("Scan admission must be closed");
- } catch (StatusRuntimeException e) {
- assertEquals(Status.Code.UNAVAILABLE, e.getStatus().getCode());
- }
- }
}
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanTestSupport.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanTestSupport.java
new file mode 100644
index 000000000..c3755a10d
--- /dev/null
+++ b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ScanTestSupport.java
@@ -0,0 +1,98 @@
+/*
+ * 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.hugegraph.store.service;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Field;
+import java.util.Map;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.hugegraph.store.grpc.common.Header;
+import org.apache.hugegraph.store.grpc.common.ScanMethod;
+import org.apache.hugegraph.store.grpc.stream.KvPageRes;
+import org.apache.hugegraph.store.grpc.stream.ScanQueryRequest;
+import org.apache.hugegraph.store.grpc.stream.ScanStreamBatchReq;
+import org.apache.hugegraph.store.node.AppConfig;
+import org.apache.hugegraph.store.node.grpc.HgStoreStreamImpl;
+import org.apache.hugegraph.store.node.grpc.HgStoreWrapperEx;
+import org.mockito.ArgumentCaptor;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+
+abstract class ScanTestSupport {
+
+ static HgStoreStreamImpl scanService(ThreadPoolExecutor executor,
+ HgStoreWrapperEx wrapper) throws Exception {
+ HgStoreStreamImpl service = new HgStoreStreamImpl();
+ AppConfig config = mock(AppConfig.class);
+ when(config.getServerWaitTime()).thenReturn(5);
+ for (String name : new String[]{"executor", "wrapper", "appConfig"}) {
+ Field field = HgStoreStreamImpl.class.getDeclaredField(name);
+ field.setAccessible(true);
+ field.set(service, name.equals("executor") ? executor : name.equals("wrapper") ? wrapper : config);
+ }
+ return service;
+ }
+
+ static Map<?, ?> scanRegistry(HgStoreStreamImpl service) throws Exception {
+ Field scans = HgStoreStreamImpl.class.getDeclaredField("scans");
+ scans.setAccessible(true);
+ return (Map<?, ?>) scans.get(service);
+ }
+
+ static void awaitTimedWaiting(Thread thread) {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
+ Thread.State observed = thread.getState();
+ while (observed != Thread.State.TIMED_WAITING && System.nanoTime() < deadline) {
+ Thread.yield();
+ observed = thread.getState();
+ }
+ assertEquals(Thread.State.TIMED_WAITING, observed);
+ }
+
+ static ScanStreamBatchReq batchRequest() {
+ return ScanStreamBatchReq.newBuilder().setHeader(Header.newBuilder().setGraph("g"))
+ .setQueryRequest(ScanQueryRequest.newBuilder().setMethod(ScanMethod.ALL)
+ .setTable("t").setLimit(10)
+ .setPerKeyMax(Long.MAX_VALUE)
+ .setPageSize(1)).build();
+ }
+
+ static void assertCancelled(StreamObserver<KvPageRes> output) {
+ ArgumentCaptor<Throwable> failure = ArgumentCaptor.forClass(Throwable.class);
+ verify(output).onError(failure.capture());
+ assertEquals(Status.Code.CANCELLED, Status.fromThrowable(failure.getValue()).getCode());
+ }
+
+ static void assertUnavailable(Runnable action) {
+ try {
+ action.run();
+ fail("Scan admission must be closed");
+ } catch (StatusRuntimeException e) {
+ assertEquals(Status.Code.UNAVAILABLE, e.getStatus().getCode());
+ }
+ }
+}
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ServerSuiteTest.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ServerSuiteTest.java
index 51a119d5c..7c283e7a9 100644
--- a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ServerSuiteTest.java
+++ b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/ServerSuiteTest.java
@@ -19,7 +19,7 @@ package org.apache.hugegraph.store.service;
import org.apache.hugegraph.rocksdb.access.RocksDBScanIteratorCloseTest;
import org.apache.hugegraph.store.business.OrderedMultiPartitionIteratorTest;
-import org.apache.hugegraph.store.node.grpc.query.AggregativeQueryShutdownTest;
+import org.apache.hugegraph.store.node.grpc.query.AggregativeQueryLifecycleTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@@ -29,13 +29,11 @@ import lombok.extern.slf4j.Slf4j;
@Suite.SuiteClasses({
RocksDBScanIteratorCloseTest.class,
OrderedMultiPartitionIteratorTest.class,
- ContextClosedListenerTest.class,
+ ScanContextCleanupTest.class,
PartitionEngineShutdownTest.class,
- TTLCleanerCleanupTest.class,
- AggregativeQueryShutdownTest.class,
- GrpcShutdownBarrierTest.class,
- ScanShutdownTest.class,
- GraphPartitionScanShutdownTest.class
+ AggregativeQueryLifecycleTest.class,
+ ScanLifecycleTest.class,
+ GraphPartitionScanLifecycleTest.class
})
@Slf4j
diff --git a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/TTLCleanerCleanupTest.java b/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/TTLCleanerCleanupTest.java
deleted file mode 100644
index b47547f88..000000000
--- a/hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/service/TTLCleanerCleanupTest.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * 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.hugegraph.store.service;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.Collections;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.apache.commons.lang3.tuple.Triple;
-import org.apache.hugegraph.rocksdb.access.RocksDBSession;
-import org.apache.hugegraph.rocksdb.access.ScanIterator;
-import org.apache.hugegraph.rocksdb.access.SessionOperator;
-import org.apache.hugegraph.store.business.BusinessHandlerImpl;
-import org.apache.hugegraph.store.business.InnerKeyCreator;
-import org.apache.hugegraph.store.constant.HugeServerTables;
-import org.apache.hugegraph.store.node.AppConfig;
-import org.apache.hugegraph.store.node.task.TTLCleaner;
-import org.apache.hugegraph.store.node.task.ttl.TaskInfo;
-import org.junit.Test;
-
-public class TTLCleanerCleanupTest {
-
- @Test(timeout = 5000)
- public void testCompletionWaitsForNativeClose() throws Exception {
- TTLCleaner cleaner = newCleaner();
- CountDownLatch completed = new CountDownLatch(1);
- CountDownLatch closing = new CountDownLatch(1);
- CountDownLatch release = new CountDownLatch(1);
- ScanIterator scan = mock(ScanIterator.class);
- doAnswer(invocation -> {
- closing.countDown();
- release.await();
- return null;
- }).when(scan).close();
- FutureTask<Void> task = new FutureTask<>(task(cleaner, scan, completed), null);
- Thread worker = new Thread(task, "test-ttl-close");
- worker.setDaemon(true);
- try {
- worker.start();
- assertTrue(closing.await(1, TimeUnit.SECONDS));
- assertEquals("TTL must not compact before native close finishes", 1L,
- completed.getCount());
- release.countDown();
- task.get(1, TimeUnit.SECONDS);
- assertEquals(0L, completed.getCount());
- cleaner.awaitCleanup();
- } finally {
- release.countDown();
- cleaner.getScheduler().shutdownNow();
- }
- }
-
- @Test(timeout = 5000)
- public void testFailedCloseStaysBlockedAfterInterruption() throws Exception {
- TTLCleaner cleaner = newCleaner();
- RuntimeException failure = new IllegalStateException("native release failed");
- ScanIterator scan = mock(ScanIterator.class);
- doAnswer(invocation -> { throw failure; }).when(scan).close();
- CountDownLatch completed = new CountDownLatch(1);
- CountDownLatch awaiting = new CountDownLatch(1);
- FutureTask<Boolean> cleanup = new FutureTask<>(() -> {
- awaiting.countDown();
- cleaner.awaitCleanup();
- return Thread.currentThread().isInterrupted();
- });
- Thread shutdown = new Thread(cleanup, "test-ttl-cleanup-failure");
- shutdown.setDaemon(true);
- Field field = TTLCleaner.class.getDeclaredField("cleanupFailure");
- field.setAccessible(true);
- @SuppressWarnings("unchecked")
- AtomicReference<Throwable> retained = (AtomicReference<Throwable>) field.get(cleaner);
- try {
- task(cleaner, scan, completed).run();
- assertEquals(0L, completed.getCount());
- assertSame(failure, retained.get());
- shutdown.start();
- assertTrue(awaiting.await(1, TimeUnit.SECONDS));
- shutdown.interrupt();
- assertFalse("interruption cannot authorize native storage destruction",
- cleanup.isDone());
- assertSame(failure, retained.get());
- } finally {
- // Production never clears this failure. Release only this test's daemon waiter.
- synchronized (retained) {
- retained.set(null);
- retained.notifyAll();
- }
- shutdown.interrupt();
- assertTrue(cleanup.get(1, TimeUnit.SECONDS));
- cleaner.getScheduler().shutdownNow();
- }
- }
-
- private static TTLCleaner newCleaner() {
- AppConfig config = mock(AppConfig.class);
- AppConfig.JobConfig job = mock(AppConfig.JobConfig.class);
- when(config.getJobConfig()).thenReturn(job);
- when(job.getStartTime()).thenReturn(19);
- return new TTLCleaner(config);
- }
-
- private static Runnable task(TTLCleaner cleaner, ScanIterator scan,
- CountDownLatch completed) throws Exception {
- BusinessHandlerImpl handler = mock(BusinessHandlerImpl.class);
- RocksDBSession session = mock(RocksDBSession.class);
- SessionOperator operator = mock(SessionOperator.class);
- when(handler.getSession(1)).thenReturn(session);
- when(handler.getKeyCreator()).thenReturn(mock(InnerKeyCreator.class));
- when(session.sessionOp()).thenReturn(operator);
- when(operator.scan(anyString(), any(), any(), anyInt())).thenReturn(scan);
- TaskInfo info = mock(TaskInfo.class);
- when(info.getTableCounter()).thenReturn(new ConcurrentHashMap<>(
- Collections.singletonMap(HugeServerTables.VERTEX_TABLE, new AtomicLong())));
- Method method = TTLCleaner.class.getDeclaredMethod("getTask", BusinessHandlerImpl.class,
- CountDownLatch.class, Triple.class, Map.class, Map.class);
- method.setAccessible(true);
- return (Runnable) method.invoke(cleaner, handler, completed,
- Triple.of(1, "graph", HugeServerTables.VERTEX_TABLE),
- Collections.singletonMap("graph", info),
- Collections.singletonMap(1, new AtomicLong()));
- }
-}