Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use cache in BlockchainController.GetTransactionsAsync (take 2) #12275

Merged
merged 23 commits into from Mar 18, 2024

Conversation

kiminuo
Copy link
Collaborator

@kiminuo kiminuo commented Jan 18, 2024

Alternative to #12263

uint256 txId = parsedTxIds[i];
string cacheKey = GetCacheKeyForTransaction(txId);

if (Cache.TryGetValue(cacheKey, out TaskCompletionSource<Transaction>? tcs))
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it would be better to be more defensive and verify that tcs.Task is not a failed task which can happen I think.

@@ -140,76 +143,107 @@ private async Task<IEnumerable<string>> GetRawMempoolStringsNoCacheAsync(Cancell
[HttpGet("transaction-hexes")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
public async Task<IActionResult> GetTransactionsAsync([FromQuery, Required] IEnumerable<string> transactionIds, CancellationToken cancellationToken)
public async Task<IActionResult> GetTransactionsAsync([FromQuery, Required] List<string> transactionIds, CancellationToken cancellationToken)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is safe but maybe not. Not sure. If not, we can create a copy of the input parameter.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would revert this.

If you want to change it setup a RegTest and make sure it is working when this happens:

https://github.com/molnard/WalletWasabi/blob/master/WalletWasabi/CoinJoin/Client/CoinJoinProcessor.cs#L53

Or was that already done that's why it was resolved?

@kiminuo
Copy link
Collaborator Author

kiminuo commented Jan 18, 2024

More or less ready. We should have unit tests. Anyway, this PR waits for concept ACK / NACK.

@turbolay
Copy link
Collaborator

turbolay commented Mar 8, 2024

@molnard Can you take a decision about this PR or the other alternate and work towards merge please?

Copy link
Collaborator

@adamPetho adamPetho left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm getting 500 Internal Server Error no matter what. I debugged into the backend and the transactions are fetched properly, but there is a problem with serialization.

fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HN22KEDCI5QI", Request id "0HN22KEDCI5QI:00000005": An unhandled exception was thrown by the application.
      Newtonsoft.Json.JsonSerializationException: Error getting value from 'Date' on 'NBitcoin.LockTime'.
       ---> System.InvalidOperationException: This is not a time based lock
         at lambda_method167(Closure, Object)
         at Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(Object target)
         --- End of inner exception stack trace ---
         at Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(Object target)
         at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
         at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
         at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
         at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
         at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)

@molnard
Copy link
Collaborator

molnard commented Mar 12, 2024

@molnard Can you take a decision about this PR or the other alternate and work towards merge please?

It's fine we will make the decision with @adamPetho when it will be required.

@adamPetho
Copy link
Collaborator

It's fine we will make the decision with @adamPetho when it will be required.

It is required right now, so it's time to make up our minds.

Personally, I don't care which approach gets merged in as long as it's working and does the job.

According to Kimi #12263 (review) that PR has major bugs.

According to my testing, this PR is almost working, we only need to fix the return type.

Whichever PR we decide on, it will be a great help on my current task. Just please choose and push one of these forward.

kiminuo and others added 2 commits March 12, 2024 18:33
Co-authored-by: adamPetho <45069029+adamPetho@users.noreply.github.com>
Copy link
Collaborator

@molnard molnard left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator

@molnard molnard left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you make this happen? A running version that is tested and not PoC?

WalletWasabi.Backend/Controllers/BlockchainController.cs Outdated Show resolved Hide resolved
WalletWasabi.Backend/Controllers/BlockchainController.cs Outdated Show resolved Hide resolved
WalletWasabi.Backend/Controllers/BlockchainController.cs Outdated Show resolved Hide resolved
@kiminuo kiminuo force-pushed the feature/2024-01-18-gettxcache branch from b128a68 to 6263538 Compare March 14, 2024 08:22
@kiminuo kiminuo marked this pull request as ready for review March 14, 2024 09:51
adamPetho
adamPetho previously approved these changes Mar 14, 2024
Copy link
Collaborator

@adamPetho adamPetho left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tACK, Code LGTM

WalletWasabi.Backend/Controllers/BlockchainController.cs Outdated Show resolved Hide resolved
@adamPetho adamPetho requested a review from molnard March 14, 2024 16:04
Copy link
Collaborator

@molnard molnard left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, couple of small things to consider but in general OK.

}
catch
{
return BadRequest("Invalid transaction Ids.");
}

Transaction[] txs = await FetchTransactionsAsync(parsedTxIds, cancellationToken).ConfigureAwait(false);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was that intentional to go with the Internal Server Error in case of exception instead of BadRequest(ex.Message); like it was before? If so what is the benefit and how will the client react to that?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverted back in 70a9b75

@@ -32,6 +36,7 @@ public class BlockchainController : ControllerBase
{
public static readonly TimeSpan FilterTimeout = TimeSpan.FromMinutes(20);
private static readonly MemoryCacheEntryOptions CacheEntryOptions = new() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60) };
private static MemoryCacheEntryOptions TransactionCacheOptions { get; } = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1) };
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How long should we store the tx in the cache? Can it change meanwhile?

  • Transactions are not changing. Mempool information is stored on another level but the tx will remain the same. So we could store the tx indefinitely - nothing gets outdated.
  • On the other hand, we need to preserve the memory, so the must be a timeout when after we release the memory.
  • Let's do a practical approach, the client uses this request the most while transition are in the mempool mostly when it appeared in the mempool with the sync requests. The request interval is 30 seconds. However the new functionality will add one more use case with the unconfirmed tx chain that is requesting may transactions from time to time.
    Are there any risks if we increase this to like to 20 minutes?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed to 20 minutes.

@@ -140,76 +143,107 @@ private async Task<IEnumerable<string>> GetRawMempoolStringsNoCacheAsync(Cancell
[HttpGet("transaction-hexes")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
public async Task<IActionResult> GetTransactionsAsync([FromQuery, Required] IEnumerable<string> transactionIds, CancellationToken cancellationToken)
public async Task<IActionResult> GetTransactionsAsync([FromQuery, Required] List<string> transactionIds, CancellationToken cancellationToken)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would revert this.

If you want to change it setup a RegTest and make sure it is working when this happens:

https://github.com/molnard/WalletWasabi/blob/master/WalletWasabi/CoinJoin/Client/CoinJoinProcessor.cs#L53

Or was that already done that's why it was resolved?

Copy link
Collaborator

@molnard molnard left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

AbsoluteExpirationRelativeToNow I am not sure about. WDY guys think about such a long caching?

#12275 (comment)

@kiminuo
Copy link
Collaborator Author

kiminuo commented Mar 15, 2024

Storing a transaction in memory for some time is cheaper than repeatedly getting it via RPC.

Copy link
Collaborator

@turbolay turbolay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is hard for me to review this PR but LGTM, I've seen no issues in it.

/// </summary>
/// <returns><c>true</c> if the key was added to the cache, <c>false</c> otherwise.</returns>
/// <remarks>Caller is responsible to ALWAYS set a result to <paramref name="responseTcs"/> even if an exception is thrown.</remarks>
public bool TryAddKey<TRequest, TResponse>(TRequest cacheKey, MemoryCacheEntryOptions options, out TaskCompletionSource<TResponse> responseTcs)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good function, it might be useful elsewhere

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, though one must be extra cautious when using it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I know how one can make it safer but it would be more lines of code, so ... :)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well the original PR created by me was not touching IdempotenceRequestCache at all. But that was down-voted so this is the solution you guys wanted.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not aware of any downvoting per se (only major bugs in your PR that were not addressed).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator

@molnard molnard Mar 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't make sense to address any bugs if the concept is not ACKed by the godfather of IdempotencyRequestCache.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You guys went with the alternative solution which is perfectly fine for me. Now that we are at the end of this, are you saying that adding TryAddKey is not safe? I hope this is not the case...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not safe in the sense that if one forgets to assign the result, then bad things will happen. This is not an issue if one has good tests.

Personally, I would like more to return from TryAddKey a disposable that would make sure that either a result is assigned or an exception is assigned and if not, it would throw an exception so it would be very much visible that something unexpected has happened. Anyway, even without this it should work well but one must be careful.

Copy link
Collaborator

@molnard molnard left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK - feel free to merge @kiminuo if it is ready.

/// </summary>
/// <returns><c>true</c> if the key was added to the cache, <c>false</c> otherwise.</returns>
/// <remarks>Caller is responsible to ALWAYS set a result to <paramref name="responseTcs"/> even if an exception is thrown.</remarks>
public bool TryAddKey<TRequest, TResponse>(TRequest cacheKey, MemoryCacheEntryOptions options, out TaskCompletionSource<TResponse> responseTcs)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well the original PR created by me was not touching IdempotenceRequestCache at all. But that was down-voted so this is the solution you guys wanted.

@molnard
Copy link
Collaborator

molnard commented Mar 18, 2024

CF issues are not related to this PR - but discovered by CF now. Don't need to fix them here.

@kiminuo
Copy link
Collaborator Author

kiminuo commented Mar 18, 2024

ACK - feel free to merge @kiminuo if it is ready.

I cannot:

image

@molnard
Copy link
Collaborator

molnard commented Mar 18, 2024

Oh Got it, because of CF... Can I merge then?

@kiminuo
Copy link
Collaborator Author

kiminuo commented Mar 18, 2024

Oh Got it, because of CF...

I think so.

Can I merge then?

Yes.

@molnard molnard merged commit 8fa5f97 into zkSNACKs:master Mar 18, 2024
7 of 8 checks passed
@kiminuo kiminuo deleted the feature/2024-01-18-gettxcache branch March 18, 2024 12:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

None yet

4 participants