cs-codex-dist-tests/Tools/AutoClient/Purchaser.cs

240 lines
8.0 KiB
C#
Raw Normal View History

using CodexOpenApi;
2024-04-01 18:40:03 +00:00
using CodexPlugin;
using Logging;
using Newtonsoft.Json;
2024-04-01 18:40:03 +00:00
using Utils;
namespace AutoClient
{
2024-06-28 06:47:09 +00:00
public class Purchaser
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
private readonly App app;
private readonly string nodeId;
2024-04-01 18:40:03 +00:00
private readonly ILog log;
private readonly HttpClient client;
private readonly Address address;
private readonly CodexApi codex;
2024-09-12 12:38:15 +00:00
private Task workerTask = Task.CompletedTask;
2024-04-01 18:40:03 +00:00
2024-09-12 12:38:15 +00:00
public Purchaser(App app, string nodeId, ILog log, HttpClient client, Address address, CodexApi codex)
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
this.app = app;
this.nodeId = nodeId;
2024-04-01 18:40:03 +00:00
this.log = log;
this.client = client;
this.address = address;
2024-04-01 18:40:03 +00:00
this.codex = codex;
}
2024-06-28 06:47:09 +00:00
public void Start()
{
2024-09-12 12:38:15 +00:00
workerTask = Task.Run(Worker);
}
public void Stop()
{
workerTask.Wait();
2024-06-28 06:47:09 +00:00
}
private async Task Worker()
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
log.Log("Worker started.");
while (!app.Cts.Token.IsCancellationRequested)
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
try
{
var pid = await StartNewPurchase();
await WaitTillFinished(pid);
await DownloadForeignCid();
}
catch (Exception ex)
{
log.Error("Worker failed with: " + ex);
await Task.Delay(TimeSpan.FromHours(6));
}
}
}
private async Task DownloadForeignCid()
{
var cid = app.CidRepo.GetForeignCid(nodeId);
if (cid == null) return;
var size = app.CidRepo.GetSizeForCid(cid);
if (size == null) return;
2024-09-12 12:38:15 +00:00
try
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var filename = Guid.NewGuid().ToString().ToLowerInvariant();
{
using var fileStream = File.OpenWrite(filename);
var fileResponse = await codex.DownloadNetworkAsync(cid);
fileResponse.Stream.CopyTo(fileStream);
}
var time = sw.Elapsed;
File.Delete(filename);
app.Performance.DownloadSuccessful(size.Value, time);
2024-09-12 12:38:15 +00:00
}
catch (Exception ex)
{
app.Performance.DownloadFailed(ex);
2024-04-01 18:40:03 +00:00
}
}
2024-06-28 06:47:09 +00:00
private async Task<string> StartNewPurchase()
2024-04-01 18:40:03 +00:00
{
var file = await CreateFile();
var cid = await UploadFile(file);
2024-06-28 06:47:09 +00:00
return await RequestStorage(cid);
2024-04-01 18:40:03 +00:00
}
private async Task<string> CreateFile()
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
return await app.Generator.Generate();
2024-04-01 18:40:03 +00:00
}
private async Task<ContentId> UploadFile(string filename)
2024-04-01 18:40:03 +00:00
{
using var fileStream = File.OpenRead(filename);
2024-09-12 12:38:15 +00:00
try
{
var info = new FileInfo(filename);
var sw = System.Diagnostics.Stopwatch.StartNew();
var cid = await UploadStream(fileStream);
var time = sw.Elapsed;
app.Performance.UploadSuccessful(info.Length, time);
app.CidRepo.Add(nodeId, cid.Id, info.Length);
return cid;
}
catch (Exception exc)
{
app.Performance.UploadFailed(exc);
throw;
}
}
2024-04-01 18:40:03 +00:00
2024-09-12 12:38:15 +00:00
private async Task<ContentId> UploadStream(FileStream fileStream)
{
log.Debug($"Uploading file...");
var response = await codex.UploadAsync(fileStream, app.Cts.Token);
2024-04-01 18:40:03 +00:00
if (string.IsNullOrEmpty(response)) FrameworkAssert.Fail("Received empty response.");
if (response.StartsWith("Unable to store block")) FrameworkAssert.Fail("Node failed to store block.");
2024-09-12 12:38:15 +00:00
log.Debug($"Uploaded file. Received contentId: '{response}'.");
2024-04-01 18:40:03 +00:00
return new ContentId(response);
}
private async Task<string> RequestStorage(ContentId cid)
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
log.Debug("Requesting storage for " + cid.Id);
var result = await codex.CreateStorageRequestAsync(cid.Id, new StorageRequestCreation()
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
Collateral = app.Config.RequiredCollateral.ToString(),
Duration = (app.Config.ContractDurationMinutes * 60).ToString(),
Expiry = (app.Config.ContractExpiryMinutes * 60).ToString(),
Nodes = app.Config.NumHosts,
Reward = app.Config.Price.ToString(),
ProofProbability = "15",
2024-09-12 12:38:15 +00:00
Tolerance = app.Config.HostTolerance
}, app.Cts.Token);
log.Debug("Purchase ID: " + result);
2024-09-12 12:38:15 +00:00
var encoded = await GetEncodedCid(result);
app.CidRepo.AddEncoded(cid.Id, encoded);
return result;
}
2024-09-12 12:38:15 +00:00
private async Task<string> GetEncodedCid(string pid)
{
try
{
2024-09-23 08:52:12 +00:00
var sp = (await GetStoragePurchase(pid))!;
2024-09-12 12:38:15 +00:00
return sp.Request.Content.Cid;
}
2024-09-12 12:38:15 +00:00
catch (Exception ex)
{
2024-09-12 12:38:15 +00:00
log.Error(ex.ToString());
throw;
}
2024-04-01 18:40:03 +00:00
}
2024-09-12 12:38:15 +00:00
private async Task<StoragePurchase?> GetStoragePurchase(string pid)
{
// openapi still don't match code.
var str = await client.GetStringAsync($"{address.Host}:{address.Port}/api/codex/v1/storage/purchases/{pid}");
if (string.IsNullOrEmpty(str)) return null;
return JsonConvert.DeserializeObject<StoragePurchase>(str);
}
2024-06-28 06:47:09 +00:00
private async Task WaitTillFinished(string pid)
2024-04-01 18:40:03 +00:00
{
try
{
var emptyResponseTolerance = 10;
2024-09-12 12:38:15 +00:00
while (!app.Cts.Token.IsCancellationRequested)
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
var purchase = await GetStoragePurchase(pid);
if (purchase == null)
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
await FixedShortDelay();
emptyResponseTolerance--;
if (emptyResponseTolerance == 0)
{
2024-06-28 06:47:09 +00:00
log.Log("Received 10 empty responses. Stop tracking this purchase.");
await ExpiryTimeDelay();
return;
}
2024-09-12 12:38:15 +00:00
continue;
}
2024-09-12 12:38:15 +00:00
var status = purchase.State.ToLowerInvariant();
if (status.Contains("cancel"))
{
2024-09-12 12:38:15 +00:00
app.Performance.StorageContractCancelled();
return;
}
if (status.Contains("error"))
{
app.Performance.StorageContractErrored(purchase.Error);
return;
}
if (status.Contains("finished"))
{
app.Performance.StorageContractFinished();
return;
}
if (status.Contains("started"))
{
app.Performance.StorageContractStarted();
await FixedDurationDelay();
2024-04-01 18:40:03 +00:00
}
2024-06-28 06:47:09 +00:00
await FixedShortDelay();
2024-04-01 18:40:03 +00:00
}
}
catch (Exception ex)
{
log.Log($"Wait failed with exception: {ex}. Assume contract will expire: Wait expiry time.");
await ExpiryTimeDelay();
2024-04-01 18:40:03 +00:00
}
}
private async Task FixedDurationDelay()
{
2024-09-12 12:38:15 +00:00
await Task.Delay(app.Config.ContractDurationMinutes * 60 * 1000, app.Cts.Token);
}
private async Task ExpiryTimeDelay()
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
await Task.Delay(app.Config.ContractExpiryMinutes * 60 * 1000, app.Cts.Token);
2024-04-01 18:40:03 +00:00
}
private async Task FixedShortDelay()
2024-04-01 18:40:03 +00:00
{
2024-09-12 12:38:15 +00:00
await Task.Delay(15 * 1000, app.Cts.Token);
2024-04-01 18:40:03 +00:00
}
}
}