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
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
100 changes: 55 additions & 45 deletions WalletWasabi.Backend/Controllers/BlockchainController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@
using Microsoft.Extensions.Caching.Memory;
using NBitcoin;
using NBitcoin.RPC;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Cache;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Backend.Models;
Expand All @@ -32,6 +36,7 @@
{
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.


public BlockchainController(IMemoryCache memoryCache, Global global)
{
Expand All @@ -42,8 +47,6 @@
private IRPCClient RpcClient => Global.RpcClient;
private Network Network => Global.Config.Network;

public static Dictionary<uint256, string> TransactionHexCache { get; } = new();
public static object TransactionHexCacheLock { get; } = new();
public IdempotencyRequestCache Cache { get; }

public Global Global { get; }
Expand Down Expand Up @@ -140,76 +143,83 @@
[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?

{
var maxTxToRequest = 10;
if (transactionIds.Count() > maxTxToRequest)
const int MaxTxToRequest = 10;
int requestCount = transactionIds.Count;

if (requestCount > MaxTxToRequest)
{
return BadRequest($"Maximum {maxTxToRequest} transactions can be requested.");
return BadRequest($"Maximum {MaxTxToRequest} transactions can be requested.");
}

var parsedIds = new List<uint256>();
uint256[] parsedTxIds;

// Make sure TXIDs are not malformed.
try
{
// Remove duplicates, do not use Distinct(), order is not guaranteed.
foreach (var txid in transactionIds.Select(x => new uint256(x)))
{
if (!parsedIds.Contains(txid))
{
parsedIds.Add(txid);
}
}
parsedTxIds = transactionIds.Select(x => new uint256(x)).ToArray();
}
catch
{
return BadRequest("Invalid transaction Ids.");
}

Dictionary<uint256, TaskCompletionSource<Transaction>> txIdsRetrieve = [];
TaskCompletionSource<Transaction>[] txsCompletionSources = new TaskCompletionSource<Transaction>[requestCount];
molnard marked this conversation as resolved.
Show resolved Hide resolved

try
{
var hexes = new Dictionary<uint256, string>();
List<uint256> missingTxs = new();
lock (TransactionHexCacheLock)
// Get task completion sources for transactions. They are either new (no one else is getting that transaction right now) or existing
// and then some other caller needs the same transaction so we can use the existing task completion source.
for (int i = 0; i < requestCount; i++)
{
foreach (var txid in parsedIds)
uint256 txId = parsedTxIds[i];
string cacheKey = $"{nameof(BlockchainController)}#{txId}";
kiminuo marked this conversation as resolved.
Show resolved Hide resolved

if (Cache.TryAddKey(cacheKey, TransactionCacheOptions, out TaskCompletionSource<Transaction> tcs))
{
if (TransactionHexCache.TryGetValue(txid, out string? hex))
{
hexes.Add(txid, hex);
}
else
{
missingTxs.Add(txid);
}
txIdsRetrieve.Add(txId, tcs);
}

txsCompletionSources[i] = tcs;
}

if (missingTxs.Count != 0)
if (txIdsRetrieve.Count > 0)
{
foreach (var tx in await RpcClient.GetRawTransactionsAsync(missingTxs, cancellationToken))
// Ask to get missing transactions over RPC.
IEnumerable<Transaction> txs = await RpcClient.GetRawTransactionsAsync(txIdsRetrieve.Keys, cancellationToken).ConfigureAwait(false);
Dictionary<uint256, Transaction> rpcBatch = txs.ToDictionary(x => x.GetHash(), x => x);

foreach (KeyValuePair<uint256, Transaction> kvp in rpcBatch)
{
string hex = tx.ToHex();
hexes.Add(tx.GetHash(), hex);

lock (TransactionHexCacheLock)
{
if (TransactionHexCache.TryAdd(tx.GetHash(), hex) && TransactionHexCache.Count >= 1000)
{
TransactionHexCache.Remove(TransactionHexCache.Keys.First());
}
}
_ = txIdsRetrieve[kvp.Key].TrySetResult(kvp.Value);
kiminuo marked this conversation as resolved.
Show resolved Hide resolved
}
}

// Order hexes according to the order of the query.
var orderedResult = parsedIds.Where(x => hexes.ContainsKey(x)).Select(x => hexes[x]);
return Ok(orderedResult);
Transaction[] result = new Transaction[requestCount];

// Add missing transactions to the result array.
for (int i = 0; i < requestCount; i++)
{
uint256 txId = parsedTxIds[i];
result[i] = await txsCompletionSources[i].Task.ConfigureAwait(false);
}
}
catch (Exception ex)
finally
{
Logger.LogDebug(ex);
return BadRequest(ex.Message);
if (txIdsRetrieve.Count > 0)
{
// It's necessary to always set a result to the task completion sources. Otherwise, cache can get corrupted.
Exception ex = new InvalidOperationException("Failed to get the transaction.");
foreach (TaskCompletionSource<Transaction> tcs in txIdsRetrieve.Values)
{
_ = tcs.TrySetException(ex);
kiminuo marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

return Ok(txsCompletionSources);

Check notice on line 222 in WalletWasabi.Backend/Controllers/BlockchainController.cs

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (master)

✅ Getting better: Complex Method

GetTransactionsAsync decreases in cyclomatic complexity from 11 to 9, threshold = 9. This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.
kiminuo marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
Expand Down
37 changes: 24 additions & 13 deletions WalletWasabi/Cache/IdempotencyRequestCache.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Microsoft.Extensions.Caching.Memory;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Extensions;

namespace WalletWasabi.Cache;

Expand All @@ -28,6 +27,29 @@ public IdempotencyRequestCache(IMemoryCache cache)
/// <remarks>Guarded by <see cref="ResponseCacheLock"/>.</remarks>
private IMemoryCache ResponseCache { get; }

/// <summary>
/// Tries to add the cache key to cache to avoid other callers to add such a key in parallel.
/// </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.

where TRequest : notnull
{
lock (ResponseCacheLock)
{
if (!ResponseCache.TryGetValue(cacheKey, out TaskCompletionSource<TResponse>? tcs))
{
responseTcs = new();
ResponseCache.Set(cacheKey, responseTcs, options);

return true;
}

responseTcs = tcs!;
return false;
}
}

/// <typeparam name="TRequest">
/// <see langword="record"/>s are preferred as <see cref="object.GetHashCode"/>
/// and <see cref="object.Equals(object?)"/> are generated for <see langword="record"/> types automatically.
Expand All @@ -47,18 +69,7 @@ public IdempotencyRequestCache(IMemoryCache cache)
public async Task<TResponse> GetCachedResponseAsync<TRequest, TResponse>(TRequest request, ProcessRequestDelegateAsync<TRequest, TResponse> action, MemoryCacheEntryOptions options, CancellationToken cancellationToken)
where TRequest : notnull
{
bool callAction = false;
TaskCompletionSource<TResponse>? responseTcs;

lock (ResponseCacheLock)
{
if (!ResponseCache.TryGetValue(request, out responseTcs))
{
callAction = true;
responseTcs = new();
ResponseCache.Set(request, responseTcs, options);
}
}
bool callAction = TryAddKey(request, options, out TaskCompletionSource<TResponse>? responseTcs);

if (callAction)
{
Expand Down