Keeping logic within microservice boundaries
Deploy Promiscuity Auth API / deploy (push) Successful in 45s
Deploy Promiscuity Character API / deploy (push) Successful in 57s
Deploy Promiscuity Inventory API / deploy (push) Successful in 45s
Deploy Promiscuity Locations API / deploy (push) Successful in 58s
k8s smoke test / test (push) Successful in 8s

This commit is contained in:
2026-03-20 09:11:44 -05:00
parent 1320e0a0ac
commit 8ce6a05710
19 changed files with 720 additions and 531 deletions
@@ -9,6 +9,7 @@ public class LocationStore
private readonly IMongoCollection<Location> _col;
private readonly IMongoCollection<BsonDocument> _rawCol;
private readonly IMongoCollection<CharacterDocument> _characters;
private readonly IMongoCollection<BiomeDefinition> _biomeDefinitions;
private const string CoordIndexName = "coord_x_1_coord_y_1";
public LocationStore(IConfiguration cfg)
@@ -22,6 +23,7 @@ public class LocationStore
_col = db.GetCollection<Location>(collectionName);
_rawCol = db.GetCollection<BsonDocument>(collectionName);
_characters = db.GetCollection<CharacterDocument>("Characters");
_biomeDefinitions = db.GetCollection<BiomeDefinition>("BiomeDefinitions");
EnsureCoordIndexes();
@@ -232,6 +234,61 @@ public class LocationStore
await _col.UpdateOneAsync(filter, update);
}
public async Task<VisibleLocationWindowResponse> GetOrCreateVisibleLocationsAsync(int x, int y, int radius)
{
var generatedCount = await EnsureVisibleLocationsExistAsync(x, y, radius);
var locations = await GetVisibleLocationsAsync(x, y, radius, ensureMetadata: true);
return new VisibleLocationWindowResponse
{
GeneratedCount = generatedCount,
Locations = locations
};
}
public Task<List<BiomeDefinition>> GetBiomeDefinitionsAsync() =>
_biomeDefinitions.Find(Builders<BiomeDefinition>.Filter.Empty)
.SortBy(definition => definition.BiomeKey)
.ToListAsync();
public async Task<BiomeDefinition?> GetBiomeDefinitionAsync(string biomeKey)
{
var normalizedBiomeKey = NormalizeBiomeKey(biomeKey);
return await _biomeDefinitions.Find(definition => definition.BiomeKey == normalizedBiomeKey)
.FirstOrDefaultAsync();
}
public async Task<bool> CreateBiomeDefinitionAsync(BiomeDefinition definition)
{
definition.BiomeKey = NormalizeBiomeKey(definition.BiomeKey);
definition.TransitionWeights = NormalizeTransitionWeights(definition.TransitionWeights);
definition.ObjectSpawnRules = NormalizeObjectSpawnRules(definition.ObjectSpawnRules);
definition.UpdatedUtc = DateTime.UtcNow;
var existing = await GetBiomeDefinitionAsync(definition.BiomeKey);
if (existing is not null)
return false;
await _biomeDefinitions.InsertOneAsync(definition);
return true;
}
public async Task<BiomeDefinition> UpsertBiomeDefinitionAsync(string biomeKey, UpsertBiomeDefinitionRequest request)
{
var normalizedBiomeKey = NormalizeBiomeKey(biomeKey);
var definition = new BiomeDefinition
{
BiomeKey = normalizedBiomeKey,
ContinuationWeight = request.ContinuationWeight,
TransitionWeights = NormalizeTransitionWeights(request.TransitionWeights),
ObjectSpawnRules = NormalizeObjectSpawnRules(request.ObjectSpawnRules),
UpdatedUtc = DateTime.UtcNow
};
var filter = Builders<BiomeDefinition>.Filter.Eq(existing => existing.BiomeKey, normalizedBiomeKey);
await _biomeDefinitions.ReplaceOneAsync(filter, definition, new ReplaceOptions { IsUpsert = true });
return definition;
}
private void EnsureCoordIndexes()
{
var indexes = _rawCol.Indexes.List().ToList();
@@ -271,6 +328,13 @@ public class LocationStore
private void EnsureOriginLocation()
{
var biomeDefinitions = LoadBiomeDefinitions();
if (biomeDefinitions.Count == 0)
return;
var originBiomeKey = biomeDefinitions.Any(definition => definition.BiomeKey == "plains")
? "plains"
: biomeDefinitions[0].BiomeKey;
var filter = Builders<Location>.Filter.And(
Builders<Location>.Filter.Eq(l => l.Coord.X, 0),
Builders<Location>.Filter.Eq(l => l.Coord.Y, 0)
@@ -283,8 +347,8 @@ public class LocationStore
{
Name = "Origin",
Coord = new Coord { X = 0, Y = 0 },
BiomeKey = DetermineBiomeKey(0, 0),
LocationObject = CreateLocationObjectForBiome(DetermineBiomeKey(0, 0), 0, 0),
BiomeKey = originBiomeKey,
LocationObject = CreateLocationObjectForBiome(biomeDefinitions, originBiomeKey, 0, 0),
LocationObjectResolved = true,
CreatedUtc = DateTime.UtcNow
};
@@ -301,16 +365,97 @@ public class LocationStore
private static string NormalizeItemKey(string itemKey) => itemKey.Trim().ToLowerInvariant();
private async Task<List<VisibleLocationResponse>> GetVisibleLocationsAsync(int x, int y, int radius, bool ensureMetadata)
{
var minX = x - radius;
var maxX = x + radius;
var minY = y - radius;
var maxY = y + radius;
var filter = Builders<Location>.Filter.And(
Builders<Location>.Filter.Gte(location => location.Coord.X, minX),
Builders<Location>.Filter.Lte(location => location.Coord.X, maxX),
Builders<Location>.Filter.Gte(location => location.Coord.Y, minY),
Builders<Location>.Filter.Lte(location => location.Coord.Y, maxY)
);
var locations = await _col.Find(filter).ToListAsync();
if (ensureMetadata)
{
for (var index = 0; index < locations.Count; index++)
locations[index] = await EnsureLocationMetadataAsync(locations[index]);
}
return locations.Select(MapVisibleLocation).ToList();
}
private async Task<int> EnsureVisibleLocationsExistAsync(int x, int y, int radius)
{
var biomeDefinitions = await LoadBiomeDefinitionsAsync();
var generatedCount = 0;
for (var currentX = x - radius; currentX <= x + radius; currentX++)
{
for (var currentY = y - radius; currentY <= y + radius; currentY++)
{
if (await EnsureLocationStateAsync(currentX, currentY, biomeDefinitions))
generatedCount += 1;
}
}
return generatedCount;
}
private async Task<bool> EnsureLocationStateAsync(int x, int y, IReadOnlyList<BiomeDefinition> biomeDefinitions)
{
var filter = Builders<BsonDocument>.Filter.And(
Builders<BsonDocument>.Filter.Eq("coord.x", x),
Builders<BsonDocument>.Filter.Eq("coord.y", y)
);
var existing = await _rawCol.Find(filter).FirstOrDefaultAsync();
if (existing is not null)
{
var typedLocation = await _col.Find(location => location.Id == existing["_id"].AsObjectId.ToString()).FirstOrDefaultAsync();
if (typedLocation is not null)
await EnsureLocationMetadataAsync(typedLocation);
return false;
}
var biomeKey = await DetermineBiomeKeyAsync(x, y, biomeDefinitions);
var locationObject = CreateLocationObjectForBiome(biomeDefinitions, biomeKey, x, y);
BsonValue locationObjectValue = locationObject is null ? BsonNull.Value : locationObject.ToBsonDocument();
var update = Builders<BsonDocument>.Update
.SetOnInsert("_id", ObjectId.GenerateNewId())
.SetOnInsert("name", DefaultLocationName(x, y))
.SetOnInsert("coord", new BsonDocument { { "x", x }, { "y", y } })
.SetOnInsert("biomeKey", biomeKey)
.SetOnInsert("locationObject", locationObjectValue)
.SetOnInsert("locationObjectResolved", true)
.SetOnInsert("createdUtc", DateTime.UtcNow);
try
{
var result = await _rawCol.UpdateOneAsync(filter, update, new UpdateOptions { IsUpsert = true });
return result.UpsertedId is not null;
}
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
return false;
}
}
private async Task<Location> EnsureLocationMetadataAsync(Location location)
{
if (!string.IsNullOrWhiteSpace(location.BiomeKey) && location.LocationObjectResolved)
return location;
var biomeDefinitions = await LoadBiomeDefinitionsAsync();
var biomeKey = location.BiomeKey;
if (string.IsNullOrWhiteSpace(biomeKey))
biomeKey = DetermineBiomeKey(location.Coord.X, location.Coord.Y);
biomeKey = await DetermineBiomeKeyAsync(location.Coord.X, location.Coord.Y, biomeDefinitions);
var migratedObject = TryMigrateLegacyResources(location) ?? CreateLocationObjectForBiome(biomeKey, location.Coord.X, location.Coord.Y);
var migratedObject = TryMigrateLegacyResources(location) ?? CreateLocationObjectForBiome(biomeDefinitions, biomeKey, location.Coord.X, location.Coord.Y);
var filter = Builders<Location>.Filter.And(
Builders<Location>.Filter.Eq(l => l.Id, location.Id)
);
@@ -325,6 +470,38 @@ public class LocationStore
return location;
}
private static VisibleLocationResponse MapVisibleLocation(Location location)
{
return new VisibleLocationResponse
{
Id = location.Id,
Name = location.Name,
Coord = new Coord { X = location.Coord.X, Y = location.Coord.Y },
BiomeKey = location.BiomeKey,
LocationObject = MapVisibleLocationObject(location.LocationObject)
};
}
private static VisibleLocationObjectResponse? MapVisibleLocationObject(LocationObject? locationObject)
{
if (locationObject is null)
return null;
return new VisibleLocationObjectResponse
{
Id = locationObject.ObjectId,
ObjectType = locationObject.ObjectType,
ObjectKey = locationObject.ObjectKey,
Name = locationObject.Name,
State = new VisibleLocationObjectStateResponse
{
ItemKey = locationObject.State.ItemKey,
RemainingQuantity = locationObject.State.RemainingQuantity,
GatherQuantity = locationObject.State.GatherQuantity
}
};
}
private static LocationObject? TryMigrateLegacyResources(Location location)
{
var legacyResource = location.Resources.FirstOrDefault(r => r.RemainingQuantity > 0);
@@ -337,73 +514,105 @@ public class LocationStore
legacyResource.GatherQuantity);
}
private static string DetermineBiomeKey(int x, int y)
private async Task<string> DetermineBiomeKeyAsync(int x, int y, IReadOnlyList<BiomeDefinition> biomeDefinitions)
{
if (x == 0 && y == 0)
return "plains";
return biomeDefinitions.Any(definition => definition.BiomeKey == "plains")
? "plains"
: biomeDefinitions[0].BiomeKey;
var regionX = FloorDiv(x, 4);
var regionY = FloorDiv(y, 4);
var roll = Math.Abs(HashCode.Combine(regionX, regionY, 7919)) % 100;
if (roll < 35)
return "plains";
if (roll < 60)
return "forest";
if (roll < 80)
return "rocky";
if (roll < 92)
return "wetlands";
return "desert";
}
var neighbors = await LoadNeighborBiomeKeysAsync(x, y);
var baseBiome = DetermineBaseBiomeKey(x, y);
if (neighbors.Count == 0)
return biomeDefinitions.Any(definition => definition.BiomeKey == baseBiome)
? baseBiome
: biomeDefinitions[0].BiomeKey;
private static LocationObject? CreateLocationObjectForBiome(string biomeKey, int x, int y)
{
var roll = Math.Abs(HashCode.Combine(x, y, 1543)) % 100;
return biomeKey switch
var dominantNeighbor = neighbors
.GroupBy(key => key)
.OrderByDescending(group => group.Count())
.ThenBy(group => group.Key)
.First().Key;
var bestBiome = baseBiome;
var bestScore = double.NegativeInfinity;
foreach (var candidate in biomeDefinitions)
{
"forest" => roll switch
var score = candidate.BiomeKey == baseBiome ? 2.5 : 0.35;
if (candidate.BiomeKey == dominantNeighbor)
score += 1.8;
foreach (var neighbor in neighbors)
{
< 35 => null,
< 80 => CreateGatherableObject("wood", 60, 3),
< 95 => CreateGatherableObject("grass", 120, 10),
_ => CreateGatherableObject("stone", 40, 2)
},
"rocky" => roll switch
{
< 60 => null,
< 90 => CreateGatherableObject("stone", 40, 2),
_ => CreateGatherableObject("wood", 60, 3)
},
"wetlands" => roll switch
{
< 40 => null,
< 90 => CreateGatherableObject("grass", 120, 10),
_ => CreateGatherableObject("wood", 60, 3)
},
"desert" => roll switch
{
< 70 => null,
< 95 => CreateGatherableObject("stone", 40, 2),
_ => CreateGatherableObject("wood", 60, 3)
},
_ => roll switch
{
< 50 => null,
< 85 => CreateGatherableObject("grass", 120, 10),
_ => CreateGatherableObject("wood", 60, 3)
var neighborDefinition = biomeDefinitions.FirstOrDefault(definition => definition.BiomeKey == neighbor);
if (neighborDefinition is null)
continue;
if (candidate.BiomeKey == neighbor)
{
score += neighborDefinition.ContinuationWeight;
continue;
}
var transition = neighborDefinition.TransitionWeights
.FirstOrDefault(weight => weight.TargetBiomeKey == candidate.BiomeKey);
if (transition is not null)
score += transition.Weight;
}
};
score += StableNoise(x, y, StableHash(candidate.BiomeKey)) * 0.25;
if (score > bestScore)
{
bestScore = score;
bestBiome = candidate.BiomeKey;
}
}
return bestBiome;
}
private static LocationObject CreateGatherableObject(string itemKey, int remainingQuantity, int gatherQuantity)
private static LocationObject? CreateLocationObjectForBiome(IReadOnlyList<BiomeDefinition> biomeDefinitions, string biomeKey, int x, int y)
{
var biome = biomeDefinitions.FirstOrDefault(definition => definition.BiomeKey == biomeKey)
?? throw new InvalidOperationException($"Missing biome definition for '{biomeKey}'.");
var totalWeight = biome.ObjectSpawnRules.Sum(rule => rule.Weight);
if (totalWeight <= 0)
return null;
var roll = StableNoise(x, y, 401) * totalWeight;
var cumulative = 0.0;
foreach (var rule in biome.ObjectSpawnRules)
{
cumulative += rule.Weight;
if (roll > cumulative)
continue;
if (string.Equals(rule.ResultType, "none", StringComparison.OrdinalIgnoreCase))
return null;
if (!string.Equals(rule.ResultType, "gatherable", StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(rule.ItemKey))
return null;
return CreateGatherableObject(
rule.ItemKey,
Math.Max(0, rule.RemainingQuantity),
Math.Max(1, rule.GatherQuantity),
rule.ObjectKey,
rule.DisplayName);
}
return null;
}
private static LocationObject CreateGatherableObject(string itemKey, int remainingQuantity, int gatherQuantity, string? objectKey = null, string? displayName = null)
{
var normalizedItemKey = NormalizeItemKey(itemKey);
return new LocationObject
{
ObjectId = Guid.NewGuid().ToString("N"),
ObjectType = "gatherable",
ObjectKey = $"{normalizedItemKey}_node",
Name = HumanizeItemKey(normalizedItemKey),
ObjectKey = string.IsNullOrWhiteSpace(objectKey) ? $"{normalizedItemKey}_node" : objectKey,
Name = string.IsNullOrWhiteSpace(displayName) ? HumanizeItemKey(normalizedItemKey) : displayName,
State = new LocationObjectState
{
ItemKey = normalizedItemKey,
@@ -428,6 +637,110 @@ public class LocationStore
return quotient;
}
private async Task<List<string>> LoadNeighborBiomeKeysAsync(int x, int y)
{
var coords = new[] { (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1) };
var filters = coords.Select(coord =>
Builders<BsonDocument>.Filter.And(
Builders<BsonDocument>.Filter.Eq("coord.x", coord.Item1),
Builders<BsonDocument>.Filter.Eq("coord.y", coord.Item2)))
.ToList();
var filter = Builders<BsonDocument>.Filter.Or(filters);
var neighbors = await _rawCol.Find(filter).ToListAsync();
return neighbors
.Where(doc => doc.Contains("biomeKey"))
.Select(doc => doc.GetValue("biomeKey", "").AsString)
.Where(key => !string.IsNullOrWhiteSpace(key))
.ToList();
}
private List<BiomeDefinition> LoadBiomeDefinitions()
{
return _biomeDefinitions.Find(Builders<BiomeDefinition>.Filter.Empty)
.SortBy(definition => definition.BiomeKey)
.ToList();
}
private async Task<List<BiomeDefinition>> LoadBiomeDefinitionsAsync()
{
var definitions = await _biomeDefinitions.Find(Builders<BiomeDefinition>.Filter.Empty)
.SortBy(definition => definition.BiomeKey)
.ToListAsync();
if (definitions.Count == 0)
throw new InvalidOperationException("No biome definitions exist in the BiomeDefinitions collection.");
return definitions;
}
private static string DetermineBaseBiomeKey(int x, int y)
{
var temperature = StableNoise(x, y, 101);
var moisture = StableNoise(x, y, 202);
var ruggedness = StableNoise(x, y, 303);
if (ruggedness > 0.74)
return "rocky";
if (moisture > 0.72 && temperature < 0.75)
return "wetlands";
if (moisture > 0.56)
return "forest";
if (moisture < 0.22 && temperature > 0.58)
return "desert";
return "plains";
}
private static double StableNoise(int x, int y, int salt)
{
var value = Math.Sin((x * 12.9898) + (y * 78.233) + ((1729 + salt) * 0.1597)) * 43758.5453;
return value - Math.Floor(value);
}
private static int StableHash(string value)
{
unchecked
{
var hash = 17;
foreach (var ch in value)
hash = (hash * 31) + ch;
return hash;
}
}
private static string NormalizeBiomeKey(string biomeKey) => biomeKey.Trim().ToLowerInvariant();
private static List<BiomeTransitionWeight> NormalizeTransitionWeights(IEnumerable<BiomeTransitionWeight> transitionWeights)
{
return transitionWeights
.Where(weight => !string.IsNullOrWhiteSpace(weight.TargetBiomeKey))
.Select(weight => new BiomeTransitionWeight
{
TargetBiomeKey = NormalizeBiomeKey(weight.TargetBiomeKey),
Weight = weight.Weight
})
.ToList();
}
private static List<BiomeObjectSpawnRule> NormalizeObjectSpawnRules(IEnumerable<BiomeObjectSpawnRule> objectSpawnRules)
{
return objectSpawnRules.Select(rule => new BiomeObjectSpawnRule
{
ResultType = string.IsNullOrWhiteSpace(rule.ResultType) ? "none" : rule.ResultType.Trim().ToLowerInvariant(),
ItemKey = string.IsNullOrWhiteSpace(rule.ItemKey) ? null : NormalizeItemKey(rule.ItemKey),
ObjectKey = string.IsNullOrWhiteSpace(rule.ObjectKey) ? null : rule.ObjectKey.Trim(),
DisplayName = string.IsNullOrWhiteSpace(rule.DisplayName) ? null : rule.DisplayName.Trim(),
RemainingQuantity = rule.RemainingQuantity,
GatherQuantity = rule.GatherQuantity,
Weight = rule.Weight
}).ToList();
}
private static string DefaultLocationName(int x, int y)
{
if (x == 0 && y == 0)
return "Origin";
return $"Location {x},{y}";
}
private static LocationObject CloneLocationObject(LocationObject source)
{
return new LocationObject