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

feat: return non cached avatar with get state. #51

Merged
merged 6 commits into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Mimir.Worker/BlockPoller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ public async Task RunAsync(CancellationToken cancellationToken)
var stateGetter = new StateGetter(stateService);
while (!cancellationToken.IsCancellationRequested)
{
var syncedBlockIndex = await mongoDbStore.GetLatestBlockIndex();
var currentBlockIndex = await stateService.GetLatestIndex();
var syncedBlockIndex = await mongoDbStore.GetLatestBlockIndex() ?? currentBlockIndex - 1;
moreal marked this conversation as resolved.
Show resolved Hide resolved
var processBlockIndex = syncedBlockIndex + 1;
if (processBlockIndex >= currentBlockIndex)
if (processBlockIndex > currentBlockIndex)
{
await Task.Delay(TimeSpan.FromMilliseconds(3000), cancellationToken);
continue;
Expand Down
14 changes: 11 additions & 3 deletions Mimir.Worker/Services/MongoDbStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,19 @@ public async Task UpdateLatestBlockIndex(long blockIndex)
await MetadataCollection.BulkWriteAsync(new[] { updateModel });
}

public async Task<long> GetLatestBlockIndex()
public async Task<long?> GetLatestBlockIndex()
{
var filter = Builders<BsonDocument>.Filter.Eq("_id", "SyncContext");
var doc = await MetadataCollection.FindSync(filter).FirstAsync();
return doc.GetValue("LatestBlockIndex").AsInt64;
try
{
var doc = await MetadataCollection.FindSync(filter).FirstAsync();
return doc.GetValue("LatestBlockIndex").AsInt64;
}
catch (InvalidOperationException e)
{
Console.WriteLine(e);
moreal marked this conversation as resolved.
Show resolved Hide resolved
return null;
}
}

public async Task BulkUpsertArenaDataAsync(List<ArenaData> arenaDatas)
Expand Down
117 changes: 115 additions & 2 deletions Mimir/Controllers/AvatarController.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,136 @@
using System.Numerics;
using Bencodex;
using Libplanet.Common;
using Libplanet.Crypto;
using Microsoft.AspNetCore.Mvc;
using Mimir.Models.Avatar;
using Mimir.Repositories;
using Mimir.Services;
using Mimir.Util;
using MongoDB.Bson;
using Nekoyume.Model.State;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mimir.Controllers;

[ApiController]
[Route("{network}/avatars")]
public class AvatarController(AvatarRepository avatarRepository) : ControllerBase
{
#region temporary snippets

// This is a snippet from Mimir/Util/BigIntegerToStringConverter.cs
moreal marked this conversation as resolved.
Show resolved Hide resolved
private class BigIntegerToStringConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(BigInteger);
}

public override object ReadJson(JsonReader reader, Type objectType, object? existingValue,
JsonSerializer serializer)
{
throw new NotImplementedException();
}

public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
writer.WriteValue(value?.ToString());
}
}

// This is a snippet from Mimir/Util/StateJsonConverter.cs
private class StateJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IState).IsAssignableFrom(objectType);
}

public override object ReadJson(
JsonReader reader,
Type objectType,
object? existingValue,
JsonSerializer serializer)
{
throw new NotImplementedException();
}

public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value is null)
{
return;
}

var jo = JObject.FromObject(value, JsonSerializer.CreateDefault(new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Converters = new List<JsonConverter> { new BigIntegerToStringConverter() },
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
}));

var iValue = value switch
{
AvatarState avatarState => avatarState.SerializeList(),
IState state => state.Serialize(),
_ => null
};

if (iValue != null)
{
var rawValue = ByteUtil.Hex(new Codec().Encode(iValue));
jo.Add("Raw", rawValue);
}

jo.WriteTo(writer);
}
}

// This is a snippet from Mimir.Worker/Models/State/BaseData.cs
private static JsonSerializerSettings JsonSerializerSettings => new()
{
Converters = { new StateJsonConverter() },
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
};

#endregion snippets

[HttpGet("{avatarAddress}/inventory")]
public Inventory? GetInventory(string network, string avatarAddress)
public async Task<Inventory?> GetInventory(
string network,
string avatarAddress,
IStateService stateService)
{
var inventory = avatarRepository.GetInventory(network, avatarAddress);
if (inventory is null)
if (inventory is not null)
{
return inventory;
}

var stateGetter = new StateGetter(stateService);
var inventoryState = await stateGetter.GetInventoryStateAsync(new Address(avatarAddress));
if (inventoryState is null)
{
Response.StatusCode = StatusCodes.Status404NotFound;
return null;
}

try
{
var jsonString = JsonConvert.SerializeObject(inventoryState, JsonSerializerSettings);
var bsonDocument = BsonDocument.Parse(jsonString);
inventory = new Inventory(bsonDocument);
moreal marked this conversation as resolved.
Show resolved Hide resolved
}
catch
{
Response.StatusCode = StatusCodes.Status500InternalServerError;
return null;
}

return inventory;
}
}