muttakin2301/ccr_train_1000 huggingface dataset:
Code review comment: NIT: For code clean, we might be able to not repeat the similar code section. ``` // for each invalid transcription format of (TEXT, SRT, VTT) TranscriptionFormat transcriptionFormat = ...; translationOptions.setResponseFormat(transcriptionFormat); assertThrows(IllegalArgumentException.class, () -> {     client.getAudioTranslation(deploymentName, translationOptions, fileName); });

Code before review:
public void testGetAudioTranslationJsonWrongFormats(HttpClient httpClient, OpenAIServiceVersion serviceVersion) {
client = getOpenAIClient(httpClient, serviceVersion);
getAudioTranslationRunner((deploymentName, fileName) -> {
byte[] file = BinaryData.fromFile(openTestResourceFile(fileName)).toBytes();
AudioTranslationOptions translationOptions = new AudioTranslationOptions(file);
translationOptions.setResponseFormat(AudioTranscriptionFormat.TEXT);
assertThrows(IllegalArgumentException.class, () -> {
client.getAudioTranslation(deploymentName, translationOptions, fileName);
});
translationOptions.setResponseFormat(AudioTranscriptionFormat.SRT);
assertThrows(IllegalArgumentException.class, () -> {
client.getAudioTranslation(deploymentName, translationOptions, fileName);
});
translationOptions.setResponseFormat(AudioTranscriptionFormat.VTT);
assertThrows(IllegalArgumentException.class, () -> {
client.getAudioTranslation(deploymentName, translationOptions, fileName);
});
});
}

Line under review: });

Code after addressing the review:
public void testGetAudioTranslationJsonWrongFormats(HttpClient httpClient, OpenAIServiceVersion serviceVersion) {
client = getOpenAIClient(httpClient, serviceVersion);
List<AudioTranscriptionFormat> wrongFormats = Arrays.asList(
AudioTranscriptionFormat.TEXT,
AudioTranscriptionFormat.SRT,
AudioTranscriptionFormat.VTT
);
getAudioTranslationRunner((deploymentName, fileName) -> {
byte[] file = BinaryData.fromFile(openTestResourceFile(fileName)).toBytes();
AudioTranslationOptions translationOptions = new AudioTranslationOptions(file);
for (AudioTranscriptionFormat format: wrongFormats) {
translationOptions.setResponseFormat(format);
assertThrows(IllegalArgumentException.class, () -> {
client.getAudioTranslation(deploymentName, fileName, translationOptions);
});
}
});
}
Code review comment: Can we also verify the data written ?

Code before review:
public void testE2EBigQueryClusteringNoPartitionTableFunction() throws Exception {
String tableName = "weather_stations_clustered_table_function_" + System.currentTimeMillis();
Pipeline p = Pipeline.create(options);
p.apply(BigQueryIO.readTableRows().from(options.getBqcInput()))
.apply(ParDo.of(new KeepStationNumberAndConvertDate()))
.apply(
BigQueryIO.writeTableRows()
.to(
(ValueInSingleWindow<TableRow> vsw) ->
new TableDestination(
String.format("%s.%s", DATASET_NAME, tableName),
null,
null,
CLUSTERING))
.withClustering(CLUSTERING)
.withSchema(SCHEMA)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE));
p.run().waitUntilFinish();
Table table = bqClient.tables().get(options.getProject(), DATASET_NAME, tableName).execute();
Assert.assertEquals(CLUSTERING, table.getClustering());
}

Line under review: Assert.assertEquals(CLUSTERING, table.getClustering());

Code after addressing the review:
public void testE2EBigQueryClusteringNoPartitionTableFunction() throws Exception {
String tableName = "weather_stations_clustered_table_function_" + System.currentTimeMillis();
Pipeline p = Pipeline.create(options);
p.apply(BigQueryIO.readTableRows().from(options.getBqcInput()))
.apply(ParDo.of(new KeepStationNumberAndConvertDate()))
.apply(
BigQueryIO.writeTableRows()
.to(
(ValueInSingleWindow<TableRow> vsw) ->
new TableDestination(
String.format("%s.%s", DATASET_NAME, tableName),
null,
null,
CLUSTERING))
.withClustering(CLUSTERING)
.withSchema(SCHEMA)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)
.withMethod(BigQueryIO.Write.Method.DEFAULT));
p.run().waitUntilFinish();
Table table = bqClient.tables().get(options.getProject(), DATASET_NAME, tableName).execute();
Assert.assertEquals(CLUSTERING, table.getClustering());
Assert.assertEquals(EXPECTED_BYTES, table.getNumBytes());
Assert.assertEquals(EXPECTED_ROWS, table.getNumRows());
}
Code review comment: what's the ch is short for ?

Code before review:
public static String convertDelimiter(String originStr) throws AnalysisException {
if (Strings.isNullOrEmpty(originStr)) {
throw new AnalysisException("Delimiter cannot be empty or null");
}
StringWriter writer = new StringWriter();
for (int i = 0; i < originStr.length(); i++) {
char ch = originStr.charAt(i);
boolean outputOneChar = true;
if (ch == '\\') {
char nextChar = (i == originStr.length() - 1) ? '\\' : originStr.charAt(i + 1);
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case 'x':
case 'X': {
outputOneChar = false;
i = parseHexString(originStr, writer, i);
break;
}
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
default:
writer.append(ch);
continue;
}
if (outputOneChar) {
writer.append(ch);
i++;
}
} else if (ch == '0' && i != originStr.length() - 1
&& (originStr.charAt(i + 1) == 'x' || originStr.charAt(i + 1) == 'X')) {
i = parseHexString(originStr, writer, i);
} else {
writer.append(ch);
}
}
return writer.toString();
}

Line under review: char ch = originStr.charAt(i);

Code after addressing the review:
public static String convertDelimiter(String originStr) throws AnalysisException {
if (Strings.isNullOrEmpty(originStr)) {
throw new AnalysisException("Delimiter cannot be empty or null");
}
StringWriter writer = new StringWriter();
for (int i = 0; i < originStr.length(); i++) {
char ch = originStr.charAt(i);
boolean outputOneChar = true;
if (ch == '\\') {
char nextChar = (i == originStr.length() - 1) ? '\\' : originStr.charAt(i + 1);
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case 'x':
case 'X': {
outputOneChar = false;
i = parseHexString(originStr, writer, i);
break;
}
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
default:
writer.append(ch);
continue;
}
if (outputOneChar) {
writer.append(ch);
i++;
}
} else if (ch == '0' && i != originStr.length() - 1
&& (originStr.charAt(i + 1) == 'x' || originStr.charAt(i + 1) == 'X')) {
i = parseHexString(originStr, writer, i);
} else {
writer.append(ch);
}
}
return writer.toString();
}
Code review comment: ATM there are none. I've added a check if it ever happens.

Code before review:
private void generateJvmBridge(MethodInfo method) {
String descriptor = JandexUtil.getDescriptor(method, name -> null);
if (!userMethods.contains(method.name() + "/" + descriptor)) {
MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE,
method.name(),
descriptor,
null,
null);
List<org.jboss.jandex.Type> parameters = method.parameters();
for (int i = 0; i < parameters.size(); i++) {
mv.visitParameter(method.parameterName(i), 0 /* modifiers */);
}
mv.visitCode();
mv.visitIntInsn(Opcodes.ALOAD, 0);
for (int i = 0; i < parameters.size(); i++) {
org.jboss.jandex.Type paramType = parameters.get(i);
mv.visitIntInsn(Opcodes.ALOAD, i + 1);
if (paramType.kind() == Kind.TYPE_VARIABLE) {
String typeParamName = paramType.asTypeVariable().identifier();
switch (typeParamName) {
case "Entity":
mv.visitTypeInsn(Opcodes.CHECKCAST, entityBinaryType);
break;
case "Id":
mv.visitTypeInsn(Opcodes.CHECKCAST, idBinaryType);
break;
}
}
}
String targetDescriptor = JandexUtil.getDescriptor(method, name -> typeArguments.get(name));
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
daoBinaryName,
method.name(),
targetDescriptor, false);
String targetReturnTypeDescriptor = targetDescriptor.substring(targetDescriptor.indexOf(')') + 1);
mv.visitInsn(JandexUtil.getReturnInstruction(targetReturnTypeDescriptor));
mv.visitMaxs(0, 0);
mv.visitEnd();
}
}

Line under review: switch (typeParamName) {

Code after addressing the review:
private void generateJvmBridge(MethodInfo method) {
String descriptor = JandexUtil.getDescriptor(method, name -> null);
if (!userMethods.contains(method.name() + "/" + descriptor)) {
MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE,
method.name(),
descriptor,
null,
null);
List<org.jboss.jandex.Type> parameters = method.parameters();
for (int i = 0; i < parameters.size(); i++) {
mv.visitParameter(method.parameterName(i), 0 /* modifiers */);
}
mv.visitCode();
mv.visitIntInsn(Opcodes.ALOAD, 0);
for (int i = 0; i < parameters.size(); i++) {
org.jboss.jandex.Type paramType = parameters.get(i);
if (paramType.kind() == Kind.PRIMITIVE)
throw new IllegalStateException("BUG: Don't know how to generate JVM bridge method for " + method
+ ": has primitive parameters");
mv.visitIntInsn(Opcodes.ALOAD, i + 1);
if (paramType.kind() == Kind.TYPE_VARIABLE) {
String typeParamName = paramType.asTypeVariable().identifier();
switch (typeParamName) {
case "Entity":
mv.visitTypeInsn(Opcodes.CHECKCAST, entityBinaryType);
break;
case "Id":
mv.visitTypeInsn(Opcodes.CHECKCAST, idBinaryType);
break;
}
}
}
String targetDescriptor = JandexUtil.getDescriptor(method, name -> typeArguments.get(name));
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
daoBinaryName,
method.name(),
targetDescriptor, false);
String targetReturnTypeDescriptor = targetDescriptor.substring(targetDescriptor.indexOf(')') + 1);
mv.visitInsn(JandexUtil.getReturnInstruction(targetReturnTypeDescriptor));
mv.visitMaxs(0, 0);
mv.visitEnd();
}
}
Code review comment: It's still a hash join in the essence

Code before review:
public StatsDeriveResult visitLogicalJoin(LogicalJoin<Plan, Plan> join, Void context) {
return HashJoinEstimation.estimate(groupExpression.getCopyOfChildStats(0),
groupExpression.getCopyOfChildStats(1),
join.getCondition().get(), join.getJoinType());
}

Line under review: groupExpression.getCopyOfChildStats(1),

Code after addressing the review:
public StatsDeriveResult visitLogicalJoin(LogicalJoin<Plan, Plan> join, Void context) {
return JoinEstimation.estimate(groupExpression.getCopyOfChildStats(0),
groupExpression.getCopyOfChildStats(1),
join.getCondition().get(), join.getJoinType());
}
Code review comment: what if `nodesToPushImage` changed before next checkpoint?

Code before review:
protected void runAfterCatalogReady() {
long imageVersion = 0;
long logVersion = 0;
try {
Storage storage = new Storage(imageDir);
imageVersion = storage.getImageJournalId();
logVersion = journal.getFinalizedJournalId();
LOG.info("checkpoint imageVersion {}, logVersion {}", imageVersion, logVersion);
} catch (IOException e) {
LOG.error("Failed to get storage info", e);
return;
}
boolean newImageCreated = false;
if (imageVersion < logVersion) {
newImageCreated = createImage(logVersion);
}
if (newImageCreated) {
for (Frontend frontend : GlobalStateMgr.getServingState().getNodeMgr().getOtherFrontends()) {
nodesToPushImage.add(frontend.getNodeName());
}
}
int needToPushCnt = nodesToPushImage.size();
long newImageVersion = newImageCreated ? logVersion : imageVersion;
if (needToPushCnt > 0) {
pushImage(newImageVersion);
}
if ((newImageCreated && needToPushCnt == 0)
|| (needToPushCnt > 0 && nodesToPushImage.size() == 0)) {
deleteOldJournals(newImageVersion);
}
if (newImageCreated) {
MetaCleaner cleaner = new MetaCleaner(imageDir);
try {
cleaner.clean();
} catch (IOException e) {
LOG.error("Leader delete old image file fail.", e);
}
}
}

Line under review: }

Code after addressing the review:
protected void runAfterCatalogReady() {
long imageVersion = 0;
long logVersion = 0;
try {
Storage storage = new Storage(imageDir);
imageVersion = storage.getImageJournalId();
logVersion = journal.getFinalizedJournalId();
LOG.info("checkpoint imageVersion {}, logVersion {}", imageVersion, logVersion);
} catch (IOException e) {
LOG.error("Failed to get storage info", e);
return;
}
boolean newImageCreated = false;
if (imageVersion < logVersion) {
newImageCreated = createImage(logVersion);
}
if (newImageCreated) {
for (Frontend frontend : GlobalStateMgr.getServingState().getNodeMgr().getOtherFrontends()) {
nodesToPushImage.add(frontend.getNodeName());
}
}
int needToPushCnt = nodesToPushImage.size();
long newImageVersion = newImageCreated ? logVersion : imageVersion;
if (needToPushCnt > 0) {
pushImage(newImageVersion);
}
if ((newImageCreated && needToPushCnt == 0)
|| (needToPushCnt > 0 && nodesToPushImage.size() == 0)) {
deleteOldJournals(newImageVersion);
}
if (newImageCreated) {
MetaCleaner cleaner = new MetaCleaner(imageDir);
try {
cleaner.clean();
} catch (IOException e) {
LOG.error("Leader delete old image file fail.", e);
}
}
}
Code review comment: Got it. I changed the error message to something similar to what was suggested and the error reason to `OperationNotSupported`. Thank you for the feedback.  (Resolved with 333163ce157ccb8f3b4af493f2be2d358957f4cb)

Code before review:
private void validateTupleSizeAndInherentType() {
int numOfMandatoryTypes = this.tupleType.getTupleTypes().size();
if (numOfMandatoryTypes >= this.getLength()) {
throw ErrorHelper.getRuntimeException(
getModulePrefixedReason(ARRAY_LANG_LIB, SIZE_MISMATCH_ERROR_IDENTIFIER),
ErrorCodes.INVALID_MEMBER_SIZE, numOfMandatoryTypes + 1, this.getLength());
}
for (int i = 1; i <= numOfMandatoryTypes; i++) {
if (!TypeChecker.checkIsType(this.getRefValue(i), this.tupleType.getTupleTypes().get(i - 1))) {
throw ErrorHelper.getRuntimeException(
getModulePrefixedReason(ARRAY_LANG_LIB, INHERENT_TYPE_VIOLATION_ERROR_IDENTIFIER),
ErrorCodes.INCOMPATIBLE_TYPE, this.tupleType.getTupleTypes().get(i - 1),
(i == numOfMandatoryTypes) ?
this.tupleType.getRestType() : this.tupleType.getTupleTypes().get(i));
}
}
}

Line under review: getModulePrefixedReason(ARRAY_LANG_LIB, SIZE_MISMATCH_ERROR_IDENTIFIER),

Code after addressing the review:
private void validateTupleSizeAndInherentType() {
List<Type> tupleTypesList = this.tupleType.getTupleTypes();
int numOfMandatoryTypes = tupleTypesList.size();
if (numOfMandatoryTypes >= this.getLength()) {
throw ErrorHelper.getRuntimeException(getModulePrefixedReason(ARRAY_LANG_LIB,
OPERATION_NOT_SUPPORTED_IDENTIFIER), ErrorCodes.INVALID_TUPLE_MEMBER_SIZE, "shift");
}
for (int i = 1; i <= numOfMandatoryTypes; i++) {
if (!TypeChecker.checkIsType(this.getRefValue(i), tupleTypesList.get(i - 1))) {
throw ErrorHelper.getRuntimeException(getModulePrefixedReason(ARRAY_LANG_LIB,
INHERENT_TYPE_VIOLATION_ERROR_IDENTIFIER), ErrorCodes.INCOMPATIBLE_TYPE,
tupleTypesList.get(i - 1), (i == numOfMandatoryTypes) ?
this.tupleType.getRestType() : tupleTypesList.get(i));
}
}
}
Code review comment: Because it is a config parameter we can define a constant for this because then it will be easy to change. There's a similar constant in http. See if it makes sense to use it here.

Code before review:
private static void waitForHandshake(ObjectValue webSocketClient, CountDownLatch countDownLatch) {
long timeout = WebSocketUtil.findTimeoutInSeconds((MapValue<String, Object>) webSocketClient.getMapValue(
HttpConstants.CLIENT_ENDPOINT_CONFIG), "handShakeTimeoutInSeconds", 300);
try {
if (!countDownLatch.await(timeout, TimeUnit.SECONDS)) {
throw new WebSocketException(WebSocketConstants.ErrorCode.WsGenericError,
"Waiting for WebSocket handshake has not been successful", WebSocketUtil.createErrorCause(
"Connection timeout", IOConstants.ErrorCode.ConnectionTimedOut.errorCode(),
IOConstants.IO_PACKAGE_ID));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new WebSocketException(WebSocketConstants.ERROR_MESSAGE + e.getMessage());
}
}

Line under review: HttpConstants.CLIENT_ENDPOINT_CONFIG), "handShakeTimeoutInSeconds", 300);

Code after addressing the review:
private static void waitForHandshake(ObjectValue webSocketClient, CountDownLatch countDownLatch) {
@SuppressWarnings(WebSocketConstants.UNCHECKED)
long timeout = WebSocketUtil.findTimeoutInSeconds((MapValue<String, Object>) webSocketClient.getMapValue(
CLIENT_ENDPOINT_CONFIG), "handShakeTimeoutInSeconds", 300);
try {
if (!countDownLatch.await(timeout, TimeUnit.SECONDS)) {
throw new WebSocketException(WebSocketConstants.ErrorCode.WsGenericError,
"Waiting for WebSocket handshake has not been successful", WebSocketUtil.createErrorCause(
"Connection timeout", IOConstants.ErrorCode.ConnectionTimedOut.errorCode(),
IOConstants.IO_PACKAGE_ID));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new WebSocketException(WebSocketConstants.ERROR_MESSAGE + e.getMessage());
}
}
Code review comment: @TeslaCN - I've added the requested changes in a new commit. 

Code before review:
public void assertRouteAndParseShadowColumnConditions() {
RouteContext routeContext = mock(RouteContext.class);
Collection<RouteUnit> routeUnits = new LinkedList<>();
routeUnits.add(new RouteUnit(new RouteMapper("ds", "ds_shadow"), new LinkedList<>()));
when(routeContext.getRouteUnits()).thenReturn(routeUnits);
shadowRouteEngine.route(routeContext, new ShadowRule(createAlgorithmProvidedShadowRuleConfiguration()));
Optional<Collection<ShadowColumnCondition>> shadowColumnConditions = shadowRouteEngine.parseShadowColumnConditions();
assertThat(shadowColumnConditions.isPresent(), is(true));
Collection<ShadowColumnCondition> shadowColumns = shadowColumnConditions.get();
assertThat(shadowColumns.size(), is(1));
Iterator<ShadowColumnCondition> iterator = shadowColumns.iterator();
ShadowColumnCondition userId = iterator.next();
assertThat(userId.getColumn(), is("user_id"));
assertThat(userId.getTable(), is("t_order"));
assertThat(userId.getValues().iterator().next(), is("1"));
Optional<Collection<String>> sqlNotes = shadowRouteEngine.parseSqlNotes();
assertThat(sqlNotes.isPresent(), is(true));
assertThat(sqlNotes.get().size(), is(2));
Iterator<String> sqlNotesIt = sqlNotes.get().iterator();
assertThat(sqlNotesIt.next(), is("/*shadow:true,foo:bar*/"));
assertThat(sqlNotesIt.next(), is("/*aaa:bbb*/"));
}

Line under review: assertThat(shadowColumnConditions.isPresent(), is(true));

Code after addressing the review:
public void assertRouteAndParseShadowColumnConditions() {
RouteContext routeContext = mock(RouteContext.class);
Collection<RouteUnit> routeUnits = new LinkedList<>();
routeUnits.add(new RouteUnit(new RouteMapper("ds", "ds_shadow"), new LinkedList<>()));
when(routeContext.getRouteUnits()).thenReturn(routeUnits);
shadowRouteEngine.route(routeContext, new ShadowRule(createAlgorithmProvidedShadowRuleConfiguration()));
Optional<Collection<ShadowColumnCondition>> shadowColumnConditions = shadowRouteEngine.parseShadowColumnConditions();
assertTrue(shadowColumnConditions.isPresent());
Collection<ShadowColumnCondition> shadowColumns = shadowColumnConditions.get();
assertThat(shadowColumns.size(), is(1));
Iterator<ShadowColumnCondition> iterator = shadowColumns.iterator();
ShadowColumnCondition userId = iterator.next();
assertThat(userId.getColumn(), is("user_id"));
assertThat(userId.getTable(), is("t_order"));
assertThat(userId.getValues().iterator().next(), is("1"));
Optional<Collection<String>> sqlNotes = shadowRouteEngine.parseSqlNotes();
assertTrue(sqlNotes.isPresent());
assertThat(sqlNotes.get().size(), is(2));
Iterator<String> sqlNotesIt = sqlNotes.get().iterator();
assertThat(sqlNotesIt.next(), is("/*shadow:true,foo:bar*/"));
assertThat(sqlNotesIt.next(), is("/*aaa:bbb*/"));
}
Code review comment: or just a file path.

Code before review:
String resolve() throws IOException {
String from =
String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName());
if (!Strings.isNullOrEmpty(options.getPrismLocation())) {
checkArgument(
!options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX),
"Provided --prismLocation URL is not an Apache Beam Github "
+ "Release page URL or download URL: ",
from);
from = options.getPrismLocation();
}
String fromFileName = getNameWithoutExtension(from);
Path to = Paths.get(userHome(), PRISM_BIN_PATH, fromFileName);
if (Files.exists(to)) {
return to.toString();
}
createDirectoryIfNeeded(to);
if (from.startsWith("http")) {
String result = resolve(new URL(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}
String result = resolve(Paths.get(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}

Line under review: if (from.startsWith("http")) {

Code after addressing the review:
String resolve() throws IOException {
String from =
String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName());
if (!Strings.isNullOrEmpty(options.getPrismLocation())) {
checkArgument(
!options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX),
"Provided --prismLocation URL is not an Apache Beam Github "
+ "Release page URL or download URL: ",
from);
from = options.getPrismLocation();
}
String fromFileName = getNameWithoutExtension(from);
Path to = Paths.get(userHome(), PRISM_BIN_PATH, fromFileName);
if (Files.exists(to)) {
return to.toString();
}
createDirectoryIfNeeded(to);
if (from.startsWith("http")) {
String result = resolve(new URL(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}
String result = resolve(Paths.get(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}
Code review comment: Shall we simplify to `return !flagSet.contains(Flag.PUBLIC);`

Code before review:
private boolean isIsolationInferableFunction(BLangFunction funcNode) {
Set<Flag> flagSet = funcNode.flagSet;
if (flagSet.contains(Flag.INTERFACE)) {
return false;
}
if (!flagSet.contains(Flag.ATTACHED)) {
if (flagSet.contains(Flag.PUBLIC)) {
return false;
}
return true;
}
BSymbol owner = funcNode.symbol.owner;
if (!Symbols.isFlagOn(owner.flags, Flags.PUBLIC)) {
return true;
}
if (!(owner instanceof BClassSymbol)) {
return false;
}
BClassSymbol ownerClassSymbol = (BClassSymbol) owner;
return ownerClassSymbol.isServiceDecl || Symbols.isFlagOn(ownerClassSymbol.flags, Flags.OBJECT_CTOR);
}

Line under review: if (flagSet.contains(Flag.PUBLIC)) {

Code after addressing the review:
private boolean isIsolationInferableFunction(BLangFunction funcNode) {
Set<Flag> flagSet = funcNode.flagSet;
if (flagSet.contains(Flag.INTERFACE)) {
return false;
}
if (!flagSet.contains(Flag.ATTACHED)) {
return !flagSet.contains(Flag.PUBLIC);
}
BSymbol owner = funcNode.symbol.owner;
if (!Symbols.isFlagOn(owner.flags, Flags.PUBLIC)) {
return true;
}
if (!(owner instanceof BClassSymbol)) {
return false;
}
BClassSymbol ownerClassSymbol = (BClassSymbol) owner;
return ownerClassSymbol.isServiceDecl || Symbols.isFlagOn(ownerClassSymbol.flags, Flags.OBJECT_CTOR);
}
Code review comment: This test was for some removed logics in TimeUtils.  Currently this case can cause `ArithmeticException` thrown from `java.time.Duration`. But I think we do not need it, just like we do not need to add tests for formats validation, which should be tested by `java.time.Duration` itself.

Code before review:
public void testParseDurationInvalid() {
try {
TimeUtils.parseDuration(null);
fail("exception expected");
} catch (NullPointerException ignored) {
}
try {
TimeUtils.parseDuration("");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("     ");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("foobar or fubar or foo bazz");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("16 gjah");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("16 16 17 18 ms");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("-100 ms");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
}

Line under review: } catch (IllegalArgumentException ignored) {

Code after addressing the review:
public void testParseDurationInvalid() {
try {
TimeUtils.parseDuration(null);
fail("exception expected");
} catch (NullPointerException ignored) {
}
try {
TimeUtils.parseDuration("");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("     ");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("foobar or fubar or foo bazz");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("16 gjah");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("16 16 17 18 ms");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
try {
TimeUtils.parseDuration("-100 ms");
fail("exception expected");
} catch (IllegalArgumentException ignored) {
}
}
Code review comment: This could be logged at a different level than warn depending on the severity of this situation. LOG.warn("Failed to get WAL queue size, backend id: {}, status: {}", backend.getId(), response.getStatus()); Consider using exponential backoff or a configurable delay before retrying.

Code before review:
public boolean isPreviousWalFinished(long tableId, long endTransactionId, List<Long> aliveBeIds) {
boolean empty = true;
for (int i = 0; i < aliveBeIds.size(); i++) {
Backend backend = Env.getCurrentSystemInfo().getBackend(aliveBeIds.get(i));
PGetWalQueueSizeRequest request = PGetWalQueueSizeRequest.newBuilder()
.setTableId(tableId)
.setTxnId(endTransactionId)
.build();
PGetWalQueueSizeResponse response = null;
long start = System.currentTimeMillis();
boolean done = false;
long size = 0;
while (!done && System.currentTimeMillis() - start <= Config.check_wal_queue_timeout_threshold) {
try {
Future<PGetWalQueueSizeResponse> future = BackendServiceProxy.getInstance()
.getWalQueueSize(new TNetworkAddress(backend.getHost(), backend.getBrpcPort()), request);
response = future.get();
} catch (Exception e) {
LOG.warn("encounter exception while getting wal queue size on backend id: " + backend.getId()
+ ",exception:" + e);
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
LOG.info("group commit manager sleep wait InterruptedException: ", ie);
}
continue;
}
TStatusCode code = TStatusCode.findByValue(response.getStatus().getStatusCode());
if (code != TStatusCode.OK) {
String msg = "get wal queue size fail,backend id: " + backend.getId() + ", status: "
+ response.getStatus();
LOG.warn(msg);
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
LOG.info("group commit manager sleep wait InterruptedException: ", ie);
}
continue;
}
size = response.getSize();
done = true;
}
if (size > 0) {
LOG.info("backend id:" + backend.getId() + ",wal size:" + size);
empty = false;
}
}
return empty;
}

Line under review: continue;

Code after addressing the review:
public boolean isPreviousWalFinished(long tableId, long endTransactionId, List<Long> aliveBeIds) {
boolean empty = true;
for (int i = 0; i < aliveBeIds.size(); i++) {
Backend backend = Env.getCurrentSystemInfo().getBackend(aliveBeIds.get(i));
if (backend.getBrpcPort() < 0) {
return true;
}
PGetWalQueueSizeRequest request = PGetWalQueueSizeRequest.newBuilder()
.setTableId(tableId)
.setTxnId(endTransactionId)
.build();
long size = getWallQueueSize(backend, request);
if (size > 0) {
LOG.info("backend id:" + backend.getId() + ",wal size:" + size);
empty = false;
}
}
return empty;
}
Code review comment: Yes, that's intentional. The CompositeReadableBuffer has an optimized path when it wraps only one byte[] array. When sending such an inner byte[], the byte[] is directly used in fast path [here](https://github.com/apache/qpid-proton-j/blob/8c1f2326d46b9a67ae14bc3431acc6cddfbb7524/proton-j/src/main/java/org/apache/qpid/proton/engine/impl/DeliveryImpl.java#L379) (with allocation equivalent to old way [here](https://github.com/apache/qpid-proton-j/blob/8c1f2326d46b9a67ae14bc3431acc6cddfbb7524/proton-j/src/main/java/org/apache/qpid/proton/engine/impl/DeliveryImpl.java#L342)) 

Code before review:
public Mono<DeliveryState> send(byte[] bytes, int arrayOffset, int messageFormat, DeliveryState deliveryState) {
final CompositeReadableBuffer buffer = new CompositeReadableBuffer();
buffer.append(bytes).limit(arrayOffset);
return send(buffer, messageFormat, deliveryState);
}

Line under review: final CompositeReadableBuffer buffer = new CompositeReadableBuffer();

Code after addressing the review:
public Mono<DeliveryState> send(byte[] bytes, int arrayOffset, int messageFormat, DeliveryState deliveryState) {
return onEndpointActive().then(Mono.create(sink -> {
sendWork(new RetriableWorkItem(bytes, arrayOffset, messageFormat, sink, retryOptions.getTryTimeout(),
deliveryState, metricsProvider));
}));
}
Code review comment: According to [@aloubyansky](https://github.com/quarkusio/quarkus/pull/21890#issuecomment-984754188) it should be like:  ```suggestion         if (mavenSettings != null) {             return Files.exists(Path.of(mavenSettings)) ? mavenSettings : null;         } ```

Code before review:
private static String getMavenSettingsArg() {
final String mavenSettings = System.getProperty("maven.settings");
if (mavenSettings != null && Files.exists(Paths.get(mavenSettings))) {
return mavenSettings;
}
return BootstrapMavenOptions.newInstance().getOptionValue(BootstrapMavenOptions.ALTERNATE_USER_SETTINGS);
}

Line under review: }

Code after addressing the review:
private static String getMavenSettingsArg() {
final String mavenSettings = System.getProperty("maven.settings");
if (mavenSettings != null) {
return Files.exists(Paths.get(mavenSettings)) ? mavenSettings : null;
}
return BootstrapMavenOptions.newInstance().getOptionValue(BootstrapMavenOptions.ALTERNATE_USER_SETTINGS);
}
Code review comment: ```suggestion         keySpecifierNode.fieldNames().forEach(field -> this.addSemanticToken(field, TokenTypes.PROPERTY.getId(),                      TokenTypeModifiers.DECLARATION.getId() | TokenTypeModifiers.READONLY.getId(), false, -1, -1)); ```

Code before review:
public void visit(KeySpecifierNode keySpecifierNode) {
keySpecifierNode.fieldNames().forEach(field -> {
this.addSemanticToken(field, TokenTypes.PROPERTY.getId(), TokenTypeModifiers.DECLARATION.getId() |
TokenTypeModifiers.READONLY.getId(), false, -1, -1);
});
visitSyntaxNode(keySpecifierNode);
}

Line under review: });

Code after addressing the review:
public void visit(KeySpecifierNode keySpecifierNode) {
keySpecifierNode.fieldNames().forEach(field -> this.addSemanticToken(field, TokenTypes.PROPERTY.getId(),
TokenTypeModifiers.DECLARATION.getId(), false, -1, -1));
visitSyntaxNode(keySpecifierNode);
}
Code review comment: `ResponseImpl.java` is used by both the client and the server, is this change meant to change both?

Code before review:
public Object getEntity() {
checkClosed();
if (entity instanceof GenericEntity genericEntity) {
if (genericEntity.getRawType().equals(genericEntity.getType())) {
return ((GenericEntity<?>) entity).getEntity();
}
}
return entity == null ? entityStream : entity;
}

Line under review: return entity == null ? entityStream : entity;

Code after addressing the review:
public Object getEntity() {
checkClosed();
if (entity instanceof GenericEntity genericEntity) {
if (genericEntity.getRawType().equals(genericEntity.getType())) {
return ((GenericEntity<?>) entity).getEntity();
}
}
return entity == null ? entityStream : entity;
}
Code review comment: yes, this will be caught in the method that calls it, and the log will be printed

Code before review:
private void validateTableAndColumn(StatsCategoryDesc categoryDesc) throws AnalysisException {
long dbId = categoryDesc.getDbId();
long tblId = categoryDesc.getTableId();
String columnName = categoryDesc.getColumnName();
Database db = Catalog.getCurrentCatalog().getDbOrAnalysisException(dbId);
Table table = db.getTableOrAnalysisException(tblId);
if (!Strings.isNullOrEmpty(columnName)) {
Column column = table.getColumn(columnName);
if (column == null) {
throw new AnalysisException("Column " + columnName + " does not exist in table " + table.getName());
}
}
}

Line under review: if (column == null) {

Code after addressing the review:
private void validateTableAndColumn(StatsCategoryDesc categoryDesc) throws AnalysisException {
long dbId = categoryDesc.getDbId();
long tblId = categoryDesc.getTableId();
String columnName = categoryDesc.getColumnName();
Database db = Catalog.getCurrentCatalog().getDbOrAnalysisException(dbId);
Table table = db.getTableOrAnalysisException(tblId);
if (!Strings.isNullOrEmpty(columnName)) {
Column column = table.getColumn(columnName);
if (column == null) {
throw new AnalysisException("Column " + columnName + " does not exist in table " + table.getName());
}
}
}
Code review comment: `null` instead of `Optional.empty`? Missing unwrapping of `id`.

Code before review:
void summarize_bill() {
var req = request("/billing/v2/accountant/bill/id-1/summary?keys=plan,architecture")
.roles(Role.hostedAccountant());
tester.assertResponse(req, """
{"id":"BillId{value='id-1'}","summary":[{"key":{"plan":"paid","architecture":"Optional.empty"},"summary":{"cpu":{"cost":"0","hours":"0"},"memory":{"cost":"0","hours":"0"},"disk":{"cost":"0","hours":"0"},"gpu":{"cost":"0","hours":"0"}}}]}""");
}

Line under review: {"id":"BillId{value='id-1'}","summary":[{"key":{"plan":"paid","architecture":"Optional.empty"},"summary":{"cpu":{"cost":"0","hours":"0"},"memory":{"cost":"0","hours":"0"},"disk":{"cost":"0","hours":"0"},"gpu":{"cost":"0","hours":"0"}}}]}""");

Code after addressing the review:
void summarize_bill() {
var req = request("/billing/v2/accountant/bill/id-1/summary?keys=plan,architecture")
.roles(Role.hostedAccountant());
tester.assertResponse(req, """
{"id":"BillId{value='id-1'}","summary":[{"key":{"plan":"paid","architecture":null},"summary":{"cpu":{"cost":"0","hours":"0"},"memory":{"cost":"0","hours":"0"},"disk":{"cost":"0","hours":"0"},"gpu":{"cost":"0","hours":"0"}}}]}""");
}
Code review comment: A comment about the `-1 *`here would probably make a lot of sense.

Code before review:
public boolean triggerCheckpoint(long timestamp, boolean isPeriodic) {
try {
triggerCheckpoint(timestamp, checkpointProperties, null, isPeriodic, false);
return true;
} catch (CheckpointException e) {
try {
long latestGeneratedCheckpointId = getCheckpointIdCounter().getAndIncrement();
failureManager.handleCheckpointException(e, -1 * latestGeneratedCheckpointId);
} catch (Exception e1) {
LOG.warn("Get latest generated checkpoint id error : ", e1);
}
return false;
}
}

Line under review: failureManager.handleCheckpointException(e, -1 * latestGeneratedCheckpointId);

Code after addressing the review:
public boolean triggerCheckpoint(long timestamp, boolean isPeriodic) {
try {
triggerCheckpoint(timestamp, checkpointProperties, null, isPeriodic, false);
return true;
} catch (CheckpointException e) {
long latestGeneratedCheckpointId = getCheckpointIdCounter().get();
failureManager.handleCheckpointException(e, -1 * latestGeneratedCheckpointId);
return false;
}
}
Code review comment: Yes, I think this is fine. Once the migration is complete we can remove these conditions. 

Code before review:
static boolean useUnifiedWorker(DataflowPipelineOptions options) {
return hasExperiment(options, "beam_fn_api")
|| hasExperiment(options, "use_runner_v2")
|| hasExperiment(options, "use_unified_worker")
|| hasExperiment(options, "enable_prime");
}

Line under review: || hasExperiment(options, "enable_prime");

Code after addressing the review:
static boolean useUnifiedWorker(DataflowPipelineOptions options) {
return hasExperiment(options, "beam_fn_api")
|| hasExperiment(options, "use_runner_v2")
|| hasExperiment(options, "use_unified_worker")
|| hasExperiment(options, "enable_prime");
}
Code review comment: To add getDetectedLanguageEnglish(), getDetectedLanguageSpanish(), and getUnknownDetectedLanguage() helper methods. These result repeatedly used over many place, such as atomic operation. 

Code before review:
static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}

Line under review: final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);

Code after addressing the review:
static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
Code review comment: There should be an `else` to set `transactionQuotaSize` to Config.defaut_xxx;

Code before review:
public int hashCode() {
return Objects.hash(id, fullQualifiedName, dataQuotaBytes);
}

Line under review: return Objects.hash(id, fullQualifiedName, dataQuotaBytes);

Code after addressing the review:
public int hashCode() {
return Objects.hash(id, fullQualifiedName, dataQuotaBytes);
}
Code review comment: > Works only if the `generation.halt-on-error` is set to true. See `application-invalid-multiline-test.properties` and the associated test. I am still thinking about this.  What I meant to say is, the message will be displayed when ``` quarkus.hibernate-orm.database.generation.halt-on-error=true ``` config is set to true (only why to intercept the exception). Otherwise whatever went wrong regarding load script file will be logged and the application starts successfully (normal `ExceptionHandler` behaviour) but without our descriptive message related to multiline.

Code before review:
private PersistenceException persistenceException(String message, Exception cause) {
Throwable t = cause;
while (t != null) {
if (t instanceof NoSuchAlgorithmException) {
message += "Unable to enable SSL support. You might be in the case where you used the `quarkus.ssl.native=false` configuration"
+ " and SSL was not disabled automatically for your driver.";
break;
}
if (t instanceof CommandAcceptanceException) {
message = "Invalid import file. Make sure your statements are valid and properly separated by a semi-colon.";
break;
}
t = t.getCause();
}
return new PersistenceException(getExceptionHeader() + message, cause);
}

Line under review: }

Code after addressing the review:
private PersistenceException persistenceException(String message, Exception cause) {
Throwable t = cause;
while (t != null) {
if (t instanceof NoSuchAlgorithmException) {
message += "Unable to enable SSL support. You might be in the case where you used the `quarkus.ssl.native=false` configuration"
+ " and SSL was not disabled automatically for your driver.";
break;
}
if (t instanceof CommandAcceptanceException) {
message = "Invalid import file. Make sure your statements are valid and properly separated by a semi-colon.";
break;
}
t = t.getCause();
}
return new PersistenceException(getExceptionHeader() + message, cause);
}
Code review comment: ah, yes, I have seen. I should have changed it in the test instead in the provider class. Now (I think) it's ok

Code before review:
public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {
List<ConfigSource> result = new ArrayList<>();
try {
Response response = springCloudConfigClientGateway.exchange(applicationName, activeProfile).await()
.atMost(springCloudConfigClientConfig.readTimeout);
if (response != null) {
final List<Response.PropertySource> propertySources = response.getPropertySources();
Collections.reverse(propertySources);
for (int i = 0; i < propertySources.size(); i++) {
final Response.PropertySource propertySource = propertySources.get(i);
result.add(new InMemoryConfigSource(450 + i, propertySource.getName(),
propertySource.getSource()));
}
}
} catch (Exception e) {
final String errorMessage = "Unable to obtain configuration from Spring Cloud Config Server at "
+ springCloudConfigClientConfig.url;
if (springCloudConfigClientConfig.failFast) {
throw new RuntimeException(errorMessage, e);
} else {
log.error(errorMessage, e);
return Collections.emptyList();
}
} finally {
springCloudConfigClientGateway.close();
}
return result;
}

Line under review: .atMost(springCloudConfigClientConfig.readTimeout);

Code after addressing the review:
public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {
List<ConfigSource> result = new ArrayList<>();
try {
boolean connectionTimeoutIsGreaterThanZero = !springCloudConfigClientConfig.connectionTimeout.isNegative()
&& !springCloudConfigClientConfig.connectionTimeout.isZero();
boolean readTimeoutIsGreaterThanZero = !springCloudConfigClientConfig.readTimeout.isNegative()
&& !springCloudConfigClientConfig.readTimeout.isZero();
Response response;
if (connectionTimeoutIsGreaterThanZero || readTimeoutIsGreaterThanZero)
response = springCloudConfigClientGateway.exchange(applicationName, activeProfile).await()
.atMost(springCloudConfigClientConfig.connectionTimeout
.plus(springCloudConfigClientConfig.readTimeout.multipliedBy(2)));
else {
response = springCloudConfigClientGateway.exchange(applicationName, activeProfile).await().indefinitely();
}
if (response != null) {
final List<Response.PropertySource> propertySources = response.getPropertySources();
Collections.reverse(propertySources);
for (int i = 0; i < propertySources.size(); i++) {
final Response.PropertySource propertySource = propertySources.get(i);
result.add(new InMemoryConfigSource(450 + i, propertySource.getName(),
propertySource.getSource()));
}
}
} catch (Exception e) {
final String errorMessage = "Unable to obtain configuration from Spring Cloud Config Server at "
+ springCloudConfigClientConfig.url;
if (springCloudConfigClientConfig.failFast) {
throw new RuntimeException(errorMessage, e);
} else {
log.error(errorMessage, e);
return Collections.emptyList();
}
} finally {
springCloudConfigClientGateway.close();
}
return result;
}
Code review comment: I mean the last line.

Code before review:
public void testQuiesceOfMailboxRightBeforeSubmittingActionViaTimerService() throws Exception {
AtomicBoolean submitThroughputFail = new AtomicBoolean();
MockEnvironment mockEnvironment = new MockEnvironmentBuilder().build();
final UnAvailableTestInputProcessor inputProcessor = new UnAvailableTestInputProcessor();
RunningTask<StreamTask<?, ?>> task =
runTask(
() ->
new MockStreamTaskBuilder(mockEnvironment)
.setHandleAsyncException(
(str, t) -> submitThroughputFail.set(true))
.setStreamInputProcessor(inputProcessor)
.build());
waitTaskIsRunning(task.streamTask, task.invocationFuture);
TimerService timerService = task.streamTask.systemTimerService;
MailboxExecutor mainMailboxExecutor =
task.streamTask.mailboxProcessor.getMainMailboxExecutor();
CountDownLatch stoppintMailboxLatch = new CountDownLatch(1);
timerService.registerTimer(
timerService.getCurrentProcessingTime(),
(time) -> {
stoppintMailboxLatch.await();
Thread.sleep(5);
mainMailboxExecutor.submit(() -> {}, "test");
});
mainMailboxExecutor
.submit(
() -> {
stoppintMailboxLatch.countDown();
task.streamTask.afterInvoke();
},
"test")
.get();
assertFalse(submitThroughputFail.get());
inputProcessor.availabilityProvider.getUnavailableToResetAvailable().complete(null);
}

Line under review: inputProcessor.availabilityProvider.getUnavailableToResetAvailable().complete(null);

Code after addressing the review:
public void testQuiesceOfMailboxRightBeforeSubmittingActionViaTimerService() throws Exception {
AtomicBoolean submitThroughputFail = new AtomicBoolean();
MockEnvironment mockEnvironment = new MockEnvironmentBuilder().build();
final UnAvailableTestInputProcessor inputProcessor = new UnAvailableTestInputProcessor();
RunningTask<StreamTask<?, ?>> task =
runTask(
() ->
new MockStreamTaskBuilder(mockEnvironment)
.setHandleAsyncException(
(str, t) -> submitThroughputFail.set(true))
.setStreamInputProcessor(inputProcessor)
.build());
waitTaskIsRunning(task.streamTask, task.invocationFuture);
TimerService timerService = task.streamTask.systemTimerService;
MailboxExecutor mainMailboxExecutor =
task.streamTask.mailboxProcessor.getMainMailboxExecutor();
CountDownLatch stoppingMailboxLatch = new CountDownLatch(1);
timerService.registerTimer(
timerService.getCurrentProcessingTime(),
(time) -> {
stoppingMailboxLatch.await();
Thread.sleep(5);
mainMailboxExecutor.submit(() -> {}, "test");
});
mainMailboxExecutor
.submit(
() -> {
stoppingMailboxLatch.countDown();
task.streamTask.afterInvoke();
},
"test")
.get();
assertFalse(submitThroughputFail.get());
inputProcessor.availabilityProvider.getUnavailableToResetAvailable().complete(null);
}
Code review comment: Please use `assertThat` instead of `assertEquals`.

Code before review:
public void assertCRC32MatchMySQLSingleTableDataCalculatorSuccess() {
String algorithmType = new CRC32MatchMySQLSingleTableDataCalculator().getAlgorithmType();
Assert.assertEquals("CRC32_MATCH", algorithmType);
}

Line under review: Assert.assertEquals("CRC32_MATCH", algorithmType);

Code after addressing the review:
public void assertCRC32MatchMySQLSingleTableDataCalculatorSuccess() {
String actualAlgorithmType = new CRC32MatchMySQLSingleTableDataCalculator().getAlgorithmType();
String expectedAlgorithmType = "CRC32_MATCH";
assertThat(actualAlgorithmType, is(expectedAlgorithmType));
}
Code review comment: Yeah, here I can just do that. I'll update

Code before review:
public Response<CommunicationRelayConfiguration> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) {
context = context == null ? Context.NONE : context;
CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest();
body.setId(communicationUser.getId());
Response<CommunicationRelayConfiguration> response =
client.issueRelayConfigurationWithResponseAsync(body, context).block();
if (response == null || response.getValue() == null) {
throw logger.logExceptionAsError(new IllegalStateException("Service failed to return a response or expected value."));
}
return new SimpleResponse<CommunicationRelayConfiguration>(
response,
response.getValue());
}

Line under review: return new SimpleResponse<CommunicationRelayConfiguration>(

Code after addressing the review:
public Response<CommunicationRelayConfiguration> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) {
Response<CommunicationRelayConfiguration> response =
client.getRelayConfigurationWithResponse(communicationUser, context).block();
return response;
}
Code review comment: I don't think this is quite right; except the value of `resources`, the other query parameters are regular query parameters, so the `&` and `=` should not be URL encoded?

Code before review:
String urlEncodedPriceInformation() {
var parameters = "supportLevel=standard&committedSpend=0&enclave=false" +
"&resources=nodes=1,vcpu=1,memoryGb=1,diskGb=10,gpuMemoryGb=0" +
"&resources=nodes=1,vcpu=1,memoryGb=1,diskGb=10,gpuMemoryGb=0";
return URLEncoder.encode(parameters, UTF_8);
}

Line under review: return URLEncoder.encode(parameters, UTF_8);

Code after addressing the review:
String urlEncodedPriceInformation() {
String resources = URLEncoder.encode("nodes=1,vcpu=1,memoryGb=1,diskGb=10,gpuMemoryGb=0", UTF_8);
return "supportLevel=basic&committedSpend=0&enclave=false" +
"&resources=" + resources +
"&resources=" + resources;
}
Code review comment: Should be ensured thread-safe modification

Code before review:
public void setShouldFailRequest(boolean shouldFailRequest) {
this.shouldFailRequest = shouldFailRequest;
}

Line under review: this.shouldFailRequest = shouldFailRequest;

Code after addressing the review:
public void setShouldFailRequest(boolean shouldFailRequest) {
this.shouldFailRequest = shouldFailRequest;
}