use of com.hederahashgraph.api.proto.java.HederaFunctionality in project hedera-services by hashgraph.
the class PlatformTxnAccessorTest method usesExtractorToGetFunctionAsExpected.
@Test
void usesExtractorToGetFunctionAsExpected() {
// setup:
var memory = SignedTxnAccessor.functionExtractor;
Function<TransactionBody, HederaFunctionality> mockFn = (Function<TransactionBody, HederaFunctionality>) mock(Function.class);
SignedTxnAccessor.functionExtractor = mockFn;
// and:
someTxn = someTxn.toBuilder().setConsensusCreateTopic(ConsensusCreateTopicTransactionBody.newBuilder()).build();
Transaction signedTxn = Transaction.newBuilder().setBodyBytes(someTxn.toByteString()).build();
given(mockFn.apply(any())).willReturn(ConsensusCreateTopic);
var subject = SignedTxnAccessor.uncheckedFrom(signedTxn);
// when:
var first = subject.getFunction();
var second = subject.getFunction();
// then:
assertEquals(ConsensusCreateTopic, first);
assertEquals(second, first);
// and:
verify(mockFn, times(1)).apply(any());
// cleanup:
SignedTxnAccessor.functionExtractor = memory;
}
use of com.hederahashgraph.api.proto.java.HederaFunctionality in project hedera-services by hashgraph.
the class ProviderRun method submitOp.
@Override
protected boolean submitOp(HapiApiSpec spec) {
int MAX_N = Runtime.getRuntime().availableProcessors();
int MAX_OPS_PER_SEC = maxOpsPerSecSupplier.getAsInt();
int MAX_PENDING_OPS = maxPendingOpsSupplier.getAsInt();
int BACKOFF_SLEEP_SECS = backoffSleepSecsSupplier.getAsInt();
long duration = durationSupplier.getAsLong();
OpProvider provider = providerFn.apply(spec);
allRunFor(spec, provider.suggestedInitializers().toArray(new HapiSpecOperation[0]));
log.info("Finished initialization for provider run...");
TimeUnit unit = unitSupplier.get();
Stopwatch stopwatch = Stopwatch.createStarted();
final var remainingOpsToSubmit = new AtomicInteger(totalOpsToSubmit.getAsInt());
final boolean fixedOpSubmission = (remainingOpsToSubmit.get() < 0) ? false : true;
int submittedSoFar = 0;
long durationMs = unit.toMillis(duration);
long logIncrementMs = durationMs / 100;
long nextLogTargetMs = logIncrementMs;
long lastDeltaLogged = -1;
final var opsThisSecond = new AtomicInteger(0);
final var submissionBoundaryMs = new AtomicLong(stopwatch.elapsed(MILLISECONDS) + 1_000);
while (stopwatch.elapsed(unit) < duration) {
long elapsedMs = stopwatch.elapsed(MILLISECONDS);
if (elapsedMs > submissionBoundaryMs.get()) {
submissionBoundaryMs.getAndAdd(1_000);
opsThisSecond.set(0);
}
int numPending = spec.numPendingOps();
if (elapsedMs > nextLogTargetMs) {
nextLogTargetMs += logIncrementMs;
long delta = duration - stopwatch.elapsed(unit);
if (delta != lastDeltaLogged) {
log.info(delta + " " + unit.toString().toLowerCase() + (fixedOpSubmission ? (" or " + remainingOpsToSubmit + " ops ") : "") + " left in test - " + submittedSoFar + " ops submitted so far (" + numPending + " pending).");
log.info("Precheck txn status counts :: " + spec.precheckStatusCounts());
log.info("Resolved txn status counts :: " + spec.finalizedStatusCounts());
log.info("\n------------------------------\n");
lastDeltaLogged = delta;
}
}
if (fixedOpSubmission && remainingOpsToSubmit.get() <= 0) {
if (numPending > 0) {
continue;
}
log.info("Finished submission of total {} operations", totalOpsToSubmit.getAsInt());
break;
}
if (numPending < MAX_PENDING_OPS) {
HapiSpecOperation[] burst = IntStream.range(0, Math.min(MAX_N, fixedOpSubmission ? Math.min(remainingOpsToSubmit.get(), MAX_OPS_PER_SEC - opsThisSecond.get()) : MAX_OPS_PER_SEC - opsThisSecond.get())).mapToObj(ignore -> provider.get()).flatMap(Optional::stream).peek(op -> counts.get(op.type()).getAndIncrement()).toArray(HapiSpecOperation[]::new);
if (burst.length > 0) {
allRunFor(spec, inParallel(burst));
submittedSoFar += burst.length;
if (fixedOpSubmission) {
remainingOpsToSubmit.getAndAdd(-burst.length);
}
opsThisSecond.getAndAdd(burst.length);
}
} else {
log.warn("Now " + numPending + " ops pending; backing off for " + BACKOFF_SLEEP_SECS + "s!");
try {
Thread.sleep(BACKOFF_SLEEP_SECS * 1_000L);
} catch (InterruptedException ignore) {
}
}
}
Map<HederaFunctionality, Integer> finalCounts = counts.entrySet().stream().filter(entry -> entry.getValue().get() > 0).collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get()));
log.info("Final breakdown of *provided* ops: " + finalCounts);
log.info("Final breakdown of *resolved* statuses: " + spec.finalizedStatusCounts());
return false;
}
use of com.hederahashgraph.api.proto.java.HederaFunctionality in project hedera-services by hashgraph.
the class DeterministicThrottling method rebuildFor.
@Override
public void rebuildFor(ThrottleDefinitions defs) {
List<DeterministicThrottle> newActiveThrottles = new ArrayList<>();
EnumMap<HederaFunctionality, List<Pair<DeterministicThrottle, Integer>>> reqLists = new EnumMap<>(HederaFunctionality.class);
int n = capacitySplitSource.getAsInt();
for (var bucket : defs.getBuckets()) {
try {
var mapping = bucket.asThrottleMapping(n);
var throttle = mapping.getLeft();
var reqs = mapping.getRight();
for (var req : reqs) {
reqLists.computeIfAbsent(req.getLeft(), ignore -> new ArrayList<>()).add(Pair.of(throttle, req.getRight()));
}
newActiveThrottles.add(throttle);
} catch (IllegalStateException badBucket) {
log.error("When constructing bucket '{}' from state: {}", bucket.getName(), badBucket.getMessage());
}
}
EnumMap<HederaFunctionality, ThrottleReqsManager> newFunctionReqs = new EnumMap<>(HederaFunctionality.class);
reqLists.forEach((function, reqs) -> newFunctionReqs.put(function, new ThrottleReqsManager(reqs)));
functionReqs = newFunctionReqs;
activeThrottles = newActiveThrottles;
logResolvedDefinitions();
}
use of com.hederahashgraph.api.proto.java.HederaFunctionality in project hedera-services by hashgraph.
the class UsageBasedFeeCalculatorTest method setup.
@BeforeEach
private void setup() throws Throwable {
view = mock(StateView.class);
query = mock(Query.class);
payerKey = complexKey.asJKey();
exchange = mock(HbarCentExchange.class);
signedTxn = newSignedCryptoCreate().balance(balance).payerKt(complexKey).txnValidStart(at).get();
accessor = new SignedTxnAccessor(signedTxn);
usagePrices = mock(UsagePricesProvider.class);
given(usagePrices.activePrices(accessor)).willReturn(currentPrices);
correctOpEstimator = mock(TxnResourceUsageEstimator.class);
incorrectOpEstimator = mock(TxnResourceUsageEstimator.class);
correctQueryEstimator = mock(QueryResourceUsageEstimator.class);
incorrectQueryEstimator = mock(QueryResourceUsageEstimator.class);
autoRenewCalcs = mock(AutoRenewCalcs.class);
pricedUsageCalculator = mock(PricedUsageCalculator.class);
txnUsageEstimators = (Map<HederaFunctionality, List<TxnResourceUsageEstimator>>) mock(Map.class);
subject = new UsageBasedFeeCalculator(autoRenewCalcs, exchange, mock(AutoCreationLogic.class), usagePrices, new NestedMultiplierSource(), pricedUsageCalculator, Set.of(incorrectQueryEstimator, correctQueryEstimator), txnUsageEstimators);
}
use of com.hederahashgraph.api.proto.java.HederaFunctionality in project hedera-services by hashgraph.
the class GasCalculatorHederaUtil method logOperationGasCost.
@SuppressWarnings("unused")
public static Gas logOperationGasCost(final UsagePricesProvider usagePrices, final HbarCentExchange exchange, final MessageFrame frame, final long storageDuration, final long dataOffset, final long dataLength, final int numTopics) {
long gasPrice = frame.getGasPrice().toLong();
long timestamp = frame.getBlockValues().getTimestamp();
long logStorageTotalSize = GasCalculatorHederaUtil.calculateLogSize(numTopics, dataLength);
HederaFunctionality functionType = GasCalculatorHederaUtil.getFunctionType(frame);
long gasCost = GasCalculatorHederaUtil.calculateStorageGasNeeded(logStorageTotalSize, storageDuration, GasCalculatorHederaUtil.ramByteHoursTinyBarsGiven(usagePrices, exchange, timestamp, functionType), gasPrice);
return Gas.of(gasCost);
}
Aggregations