From 28f7c83b64f5d0e7a2c5463ee4e1a2212645ab45 Mon Sep 17 00:00:00 2001 From: dingo Date: Fri, 7 Nov 2025 09:03:02 -0500 Subject: [PATCH] Working on Networking --- ...251105224215_InitialGameSchema.Designer.cs | 470 ++++++++++++++++++ .../20251105224215_InitialGameSchema.cs | 327 ++++++++++++ Migrations/GameDbContextModelSnapshot.cs | 467 +++++++++++++++++ Program.cs | 22 + SystemRevivalServer.csproj | 9 + appsettings.json | 18 +- data/ConnectionStringFactory.cs | 44 ++ data/DatabaseHealthCheck.cs | 31 ++ data/DatabaseManager.cs | 176 +++++++ data/DatabaseOptions.cs | 11 + data/DesignTimeDbContextFactory.cs | 33 ++ data/GameDbContext.cs | 22 + data/IDatabaseManager.cs | 30 ++ data/ServiceCollectionExtensions.cs | 25 + data/entities/Account.cs | 39 ++ data/entities/Character.cs | 64 +++ data/entities/EquipmentSlot.cs | 34 ++ data/entities/InventoryItem.cs | 36 ++ data/entities/ItemTemplate.cs | 33 ++ data/entities/Session.cs | 30 ++ data/entities/Zone.cs | 33 ++ k8s/deployment.yaml | 49 +- k8s/ingress.yaml | 15 +- k8s/service.yaml | 25 +- 24 files changed, 2023 insertions(+), 20 deletions(-) create mode 100644 Migrations/20251105224215_InitialGameSchema.Designer.cs create mode 100644 Migrations/20251105224215_InitialGameSchema.cs create mode 100644 Migrations/GameDbContextModelSnapshot.cs create mode 100644 data/ConnectionStringFactory.cs create mode 100644 data/DatabaseHealthCheck.cs create mode 100644 data/DatabaseManager.cs create mode 100644 data/DatabaseOptions.cs create mode 100644 data/DesignTimeDbContextFactory.cs create mode 100644 data/GameDbContext.cs create mode 100644 data/IDatabaseManager.cs create mode 100644 data/ServiceCollectionExtensions.cs create mode 100644 data/entities/Account.cs create mode 100644 data/entities/Character.cs create mode 100644 data/entities/EquipmentSlot.cs create mode 100644 data/entities/InventoryItem.cs create mode 100644 data/entities/ItemTemplate.cs create mode 100644 data/entities/Session.cs create mode 100644 data/entities/Zone.cs diff --git a/Migrations/20251105224215_InitialGameSchema.Designer.cs b/Migrations/20251105224215_InitialGameSchema.Designer.cs new file mode 100644 index 0000000..95c82bf --- /dev/null +++ b/Migrations/20251105224215_InitialGameSchema.Designer.cs @@ -0,0 +1,470 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Server.Data; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + [DbContext(typeof(GameDbContext))] + [Migration("20251105224215_InitialGameSchema")] + partial class InitialGameSchema + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("BannedUntil") + .HasColumnType("datetime(6)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Email") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsBanned") + .HasColumnType("tinyint(1)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("varbinary(64)"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("varbinary(32)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("accounts", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("AppearanceJson") + .HasColumnType("json"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("FacingDeg") + .HasColumnType("float"); + + b.Property("HpCurrent") + .HasColumnType("int unsigned"); + + b.Property("HpMax") + .HasColumnType("int unsigned"); + + b.Property("Level") + .HasColumnType("int unsigned"); + + b.Property("MpCurrent") + .HasColumnType("int unsigned"); + + b.Property("MpMax") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("PosX") + .HasColumnType("double"); + + b.Property("PosY") + .HasColumnType("double"); + + b.Property("PosZ") + .HasColumnType("double"); + + b.Property("StaminaCurrent") + .HasColumnType("int unsigned"); + + b.Property("StaminaMax") + .HasColumnType("int unsigned"); + + b.Property("StatDexterity") + .HasColumnType("int unsigned"); + + b.Property("StatEndurance") + .HasColumnType("int unsigned"); + + b.Property("StatIntelligence") + .HasColumnType("int unsigned"); + + b.Property("StatStrength") + .HasColumnType("int unsigned"); + + b.Property("StatWisdom") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Xp") + .HasColumnType("bigint unsigned"); + + b.Property("ZoneId") + .HasColumnType("bigint unsigned"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.HasIndex("ZoneId"); + + b.ToTable("characters", (string)null); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("SlotCode") + .HasColumnType("tinyint unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotCode") + .IsUnique(); + + b.ToTable("equipment", (string)null); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("Quantity") + .HasColumnType("int unsigned"); + + b.Property("SlotIndex") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotIndex") + .IsUnique(); + + b.ToTable("inventories", (string)null); + }); + + modelBuilder.Entity("Server.Data.ItemTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemType") + .HasColumnType("tinyint unsigned"); + + b.Property("MaxStack") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Rarity") + .HasColumnType("tinyint unsigned"); + + b.Property("StatsJson") + .HasColumnType("json"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Weight") + .HasColumnType("int unsigned"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("item_templates", (string)null); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ExpiresAt") + .HasColumnType("datetime(6)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("Token") + .IsUnique(); + + b.ToTable("sessions", (string)null); + }); + + modelBuilder.Entity("Server.Data.Zone", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("MaxX") + .HasColumnType("double"); + + b.Property("MaxY") + .HasColumnType("double"); + + b.Property("MaxZ") + .HasColumnType("double"); + + b.Property("MinX") + .HasColumnType("double"); + + b.Property("MinY") + .HasColumnType("double"); + + b.Property("MinZ") + .HasColumnType("double"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("zones", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Characters") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Zone", "Zone") + .WithMany() + .HasForeignKey("ZoneId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Account"); + + b.Navigation("Zone"); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Sessions") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Navigation("Characters"); + + b.Navigation("Sessions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Migrations/20251105224215_InitialGameSchema.cs b/Migrations/20251105224215_InitialGameSchema.cs new file mode 100644 index 0000000..51cce05 --- /dev/null +++ b/Migrations/20251105224215_InitialGameSchema.cs @@ -0,0 +1,327 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + /// + public partial class InitialGameSchema : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterDatabase() + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "accounts", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Username = table.Column(type: "varchar(32)", maxLength: 32, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Email = table.Column(type: "varchar(255)", maxLength: 255, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + PasswordHash = table.Column(type: "varbinary(64)", nullable: false), + PasswordSalt = table.Column(type: "varbinary(32)", nullable: false), + IsBanned = table.Column(type: "tinyint(1)", nullable: false), + BannedUntil = table.Column(type: "datetime(6)", nullable: true), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn) + }, + constraints: table => + { + table.PrimaryKey("PK_accounts", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "item_templates", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ItemType = table.Column(type: "tinyint unsigned", nullable: false), + Rarity = table.Column(type: "tinyint unsigned", nullable: false), + MaxStack = table.Column(type: "int unsigned", nullable: false), + Weight = table.Column(type: "int unsigned", nullable: false), + StatsJson = table.Column(type: "json", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn) + }, + constraints: table => + { + table.PrimaryKey("PK_item_templates", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "zones", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + MinX = table.Column(type: "double", nullable: false), + MinY = table.Column(type: "double", nullable: false), + MinZ = table.Column(type: "double", nullable: false), + MaxX = table.Column(type: "double", nullable: false), + MaxY = table.Column(type: "double", nullable: false), + MaxZ = table.Column(type: "double", nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn) + }, + constraints: table => + { + table.PrimaryKey("PK_zones", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "sessions", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + AccountId = table.Column(type: "bigint unsigned", nullable: false), + Token = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ExpiresAt = table.Column(type: "datetime(6)", nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + }, + constraints: table => + { + table.PrimaryKey("PK_sessions", x => x.Id); + table.ForeignKey( + name: "FK_sessions_accounts_AccountId", + column: x => x.AccountId, + principalTable: "accounts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "characters", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + AccountId = table.Column(type: "bigint unsigned", nullable: false), + Name = table.Column(type: "varchar(32)", maxLength: 32, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Level = table.Column(type: "int unsigned", nullable: false), + Xp = table.Column(type: "bigint unsigned", nullable: false), + StatStrength = table.Column(type: "int unsigned", nullable: false), + StatDexterity = table.Column(type: "int unsigned", nullable: false), + StatWisdom = table.Column(type: "int unsigned", nullable: false), + StatIntelligence = table.Column(type: "int unsigned", nullable: false), + StatEndurance = table.Column(type: "int unsigned", nullable: false), + HpCurrent = table.Column(type: "int unsigned", nullable: false), + HpMax = table.Column(type: "int unsigned", nullable: false), + MpCurrent = table.Column(type: "int unsigned", nullable: false), + MpMax = table.Column(type: "int unsigned", nullable: false), + StaminaCurrent = table.Column(type: "int unsigned", nullable: false), + StaminaMax = table.Column(type: "int unsigned", nullable: false), + ZoneId = table.Column(type: "bigint unsigned", nullable: false), + PosX = table.Column(type: "double", nullable: false), + PosY = table.Column(type: "double", nullable: false), + PosZ = table.Column(type: "double", nullable: false), + FacingDeg = table.Column(type: "float", nullable: false), + AppearanceJson = table.Column(type: "json", nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn) + }, + constraints: table => + { + table.PrimaryKey("PK_characters", x => x.Id); + table.ForeignKey( + name: "FK_characters_accounts_AccountId", + column: x => x.AccountId, + principalTable: "accounts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_characters_zones_ZoneId", + column: x => x.ZoneId, + principalTable: "zones", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "equipment", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + CharacterId = table.Column(type: "bigint unsigned", nullable: false), + SlotCode = table.Column(type: "tinyint unsigned", nullable: false), + ItemTemplateId = table.Column(type: "bigint unsigned", nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn) + }, + constraints: table => + { + table.PrimaryKey("PK_equipment", x => x.Id); + table.ForeignKey( + name: "FK_equipment_characters_CharacterId", + column: x => x.CharacterId, + principalTable: "characters", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_equipment_item_templates_ItemTemplateId", + column: x => x.ItemTemplateId, + principalTable: "item_templates", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "inventories", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + CharacterId = table.Column(type: "bigint unsigned", nullable: false), + SlotIndex = table.Column(type: "int unsigned", nullable: false), + ItemTemplateId = table.Column(type: "bigint unsigned", nullable: false), + Quantity = table.Column(type: "int unsigned", nullable: false), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn) + }, + constraints: table => + { + table.PrimaryKey("PK_inventories", x => x.Id); + table.ForeignKey( + name: "FK_inventories_characters_CharacterId", + column: x => x.CharacterId, + principalTable: "characters", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_inventories_item_templates_ItemTemplateId", + column: x => x.ItemTemplateId, + principalTable: "item_templates", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_accounts_Email", + table: "accounts", + column: "Email", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_accounts_Username", + table: "accounts", + column: "Username", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_characters_AccountId", + table: "characters", + column: "AccountId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_characters_ZoneId", + table: "characters", + column: "ZoneId"); + + migrationBuilder.CreateIndex( + name: "IX_equipment_CharacterId_SlotCode", + table: "equipment", + columns: new[] { "CharacterId", "SlotCode" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_equipment_ItemTemplateId", + table: "equipment", + column: "ItemTemplateId"); + + migrationBuilder.CreateIndex( + name: "IX_inventories_CharacterId", + table: "inventories", + column: "CharacterId"); + + migrationBuilder.CreateIndex( + name: "IX_inventories_CharacterId_SlotIndex", + table: "inventories", + columns: new[] { "CharacterId", "SlotIndex" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_inventories_ItemTemplateId", + table: "inventories", + column: "ItemTemplateId"); + + migrationBuilder.CreateIndex( + name: "IX_item_templates_Name", + table: "item_templates", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_sessions_AccountId", + table: "sessions", + column: "AccountId"); + + migrationBuilder.CreateIndex( + name: "IX_sessions_Token", + table: "sessions", + column: "Token", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_zones_Name", + table: "zones", + column: "Name", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "equipment"); + + migrationBuilder.DropTable( + name: "inventories"); + + migrationBuilder.DropTable( + name: "sessions"); + + migrationBuilder.DropTable( + name: "characters"); + + migrationBuilder.DropTable( + name: "item_templates"); + + migrationBuilder.DropTable( + name: "accounts"); + + migrationBuilder.DropTable( + name: "zones"); + } + } +} diff --git a/Migrations/GameDbContextModelSnapshot.cs b/Migrations/GameDbContextModelSnapshot.cs new file mode 100644 index 0000000..ac14ff7 --- /dev/null +++ b/Migrations/GameDbContextModelSnapshot.cs @@ -0,0 +1,467 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Server.Data; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + [DbContext(typeof(GameDbContext))] + partial class GameDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("BannedUntil") + .HasColumnType("datetime(6)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Email") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsBanned") + .HasColumnType("tinyint(1)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("varbinary(64)"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("varbinary(32)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("accounts", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("AppearanceJson") + .HasColumnType("json"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("FacingDeg") + .HasColumnType("float"); + + b.Property("HpCurrent") + .HasColumnType("int unsigned"); + + b.Property("HpMax") + .HasColumnType("int unsigned"); + + b.Property("Level") + .HasColumnType("int unsigned"); + + b.Property("MpCurrent") + .HasColumnType("int unsigned"); + + b.Property("MpMax") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("PosX") + .HasColumnType("double"); + + b.Property("PosY") + .HasColumnType("double"); + + b.Property("PosZ") + .HasColumnType("double"); + + b.Property("StaminaCurrent") + .HasColumnType("int unsigned"); + + b.Property("StaminaMax") + .HasColumnType("int unsigned"); + + b.Property("StatDexterity") + .HasColumnType("int unsigned"); + + b.Property("StatEndurance") + .HasColumnType("int unsigned"); + + b.Property("StatIntelligence") + .HasColumnType("int unsigned"); + + b.Property("StatStrength") + .HasColumnType("int unsigned"); + + b.Property("StatWisdom") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Xp") + .HasColumnType("bigint unsigned"); + + b.Property("ZoneId") + .HasColumnType("bigint unsigned"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.HasIndex("ZoneId"); + + b.ToTable("characters", (string)null); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("SlotCode") + .HasColumnType("tinyint unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotCode") + .IsUnique(); + + b.ToTable("equipment", (string)null); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("Quantity") + .HasColumnType("int unsigned"); + + b.Property("SlotIndex") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotIndex") + .IsUnique(); + + b.ToTable("inventories", (string)null); + }); + + modelBuilder.Entity("Server.Data.ItemTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemType") + .HasColumnType("tinyint unsigned"); + + b.Property("MaxStack") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Rarity") + .HasColumnType("tinyint unsigned"); + + b.Property("StatsJson") + .HasColumnType("json"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Weight") + .HasColumnType("int unsigned"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("item_templates", (string)null); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ExpiresAt") + .HasColumnType("datetime(6)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("Token") + .IsUnique(); + + b.ToTable("sessions", (string)null); + }); + + modelBuilder.Entity("Server.Data.Zone", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("MaxX") + .HasColumnType("double"); + + b.Property("MaxY") + .HasColumnType("double"); + + b.Property("MaxZ") + .HasColumnType("double"); + + b.Property("MinX") + .HasColumnType("double"); + + b.Property("MinY") + .HasColumnType("double"); + + b.Property("MinZ") + .HasColumnType("double"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("zones", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Characters") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Zone", "Zone") + .WithMany() + .HasForeignKey("ZoneId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Account"); + + b.Navigation("Zone"); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Sessions") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Navigation("Characters"); + + b.Navigation("Sessions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Program.cs b/Program.cs index d88dee2..56060c0 100644 --- a/Program.cs +++ b/Program.cs @@ -1,11 +1,19 @@ using System.Net; using System.Net.Sockets; using Server.Networking; +using Microsoft.EntityFrameworkCore; +using Server.Data; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(); builder.Services.AddSingleton(); var app = builder.Build(); +var cs = builder.Configuration.GetConnectionString("PrimaryMySql") + ?? builder.Configuration.GetSection("Database")["ConnectionString"]; +var mysqlConnectionString = ConnectionStringFactory.BuildMySqlFromEnv(); +builder.Services.AddDbContext(options => + options.UseMySql(cs, ServerVersion.AutoDetect(cs))); + app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(20), @@ -23,6 +31,20 @@ app.Map("/ws", async (HttpContext httpContext, NetworkManager networkManager) => var acceptedWebSocket = await httpContext.WebSockets.AcceptWebSocketAsync(); await networkManager.AcceptWebSocketAsync(httpContext, acceptedWebSocket); }); +// EF Core +builder.Services.AddDbContext(options => + options.UseMySql(mysqlConnectionString, ServerVersion.AutoDetect(mysqlConnectionString))); + +builder.Services.AddOptions() + .Configure(o => + { + o.ConnectionString = mysqlConnectionString; + o.CommandTimeoutSeconds = int.TryParse(Environment.GetEnvironmentVariable("DB_COMMAND_TIMEOUT_S"), out var t) ? t : 30; + o.MaxRetryCount = int.TryParse(Environment.GetEnvironmentVariable("DB_MAX_RETRY"), out var r) ? r : 3; + o.RetryBaseDelayMs = int.TryParse(Environment.GetEnvironmentVariable("DB_RETRY_BASE_MS"), out var d) ? d : 100; + }) + .Validate(o => !string.IsNullOrWhiteSpace(o.ConnectionString), "DB connection string required") + .ValidateOnStart(); // Start TCP listener int tcpPort = int.TryParse(Environment.GetEnvironmentVariable("TCP_PORT"), out var parsed) ? parsed : 40000; diff --git a/SystemRevivalServer.csproj b/SystemRevivalServer.csproj index 9ff70ae..156ed45 100644 --- a/SystemRevivalServer.csproj +++ b/SystemRevivalServer.csproj @@ -10,7 +10,16 @@ + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + diff --git a/appsettings.json b/appsettings.json index 10f68b8..2a44ce7 100644 --- a/appsettings.json +++ b/appsettings.json @@ -1,9 +1,15 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Database": { + "ConnectionString": "Server=a2nlmysql45plsk.secureserver.net;Port=3306;Database=Theraborn;User ID=tbadmin;Password=8N10ml9x?;Pooling=true;Minimum Pool Size=0;Maximum Pool Size=50;", + "CommandTimeoutSeconds": 30, + "MaxRetryCount": 3, + "RetryBaseDelayMs": 100 } - }, - "AllowedHosts": "*" } diff --git a/data/ConnectionStringFactory.cs b/data/ConnectionStringFactory.cs new file mode 100644 index 0000000..5d410ec --- /dev/null +++ b/data/ConnectionStringFactory.cs @@ -0,0 +1,44 @@ +using System; +using MySqlConnector; + +namespace Server.Data; + +public static class ConnectionStringFactory +{ + public static string BuildMySqlFromEnv() + { + // Prefer a full connection string if present + var full = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING"); + if (!string.IsNullOrWhiteSpace(full)) return full; + + string host = Get("DB_HOST", required: true); + int port = int.TryParse(Environment.GetEnvironmentVariable("DB_PORT"), out var p) ? p : 3306; + string db = Get("DB_NAME", required: true); + string user = Get("DB_USER", required: true); + string pass = Get("DB_PASSWORD", required: true); + + var b = new MySqlConnectionStringBuilder + { + Server = host, + Port = (uint)port, + Database = db, + UserID = user, + Password = pass, + Pooling = true, + MinimumPoolSize = 0, + MaximumPoolSize = (uint)(int.TryParse(Environment.GetEnvironmentVariable("DB_MAX_POOL"), out var max) ? Math.Max(1, max) : 50), + // Optional: + // DefaultCommandTimeout = (uint)(int.TryParse(Environment.GetEnvironmentVariable("DB_COMMAND_TIMEOUT_S"), out var t) ? t : 30) + }; + + return b.ConnectionString; + + static string Get(string name, bool required) + { + var v = Environment.GetEnvironmentVariable(name); + if (required && string.IsNullOrWhiteSpace(v)) + throw new InvalidOperationException($"Missing required environment variable: {name}"); + return v ?? ""; + } + } +} diff --git a/data/DatabaseHealthCheck.cs b/data/DatabaseHealthCheck.cs new file mode 100644 index 0000000..6d51ca3 --- /dev/null +++ b/data/DatabaseHealthCheck.cs @@ -0,0 +1,31 @@ +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using MySqlConnector; + +namespace Server.Data; + +public sealed class DatabaseHealthCheck : IHealthCheck +{ + private readonly DatabaseOptions _options; + + public DatabaseHealthCheck(Microsoft.Extensions.Options.IOptions options) + => _options = options.Value; + + public async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) + { + try + { + await using var conn = new MySqlConnection(_options.ConnectionString); + await conn.OpenAsync(cancellationToken); + + await using var cmd = new MySqlCommand("SELECT 1;", conn); + var result = await cmd.ExecuteScalarAsync(cancellationToken); + return result is not null ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy("SELECT 1 returned null"); + } + catch (System.Exception ex) + { + return new HealthCheckResult(HealthStatus.Unhealthy, "DB connection failed", ex); + } + } +} diff --git a/data/DatabaseManager.cs b/data/DatabaseManager.cs new file mode 100644 index 0000000..099367b --- /dev/null +++ b/data/DatabaseManager.cs @@ -0,0 +1,176 @@ +using System; +using System.Data; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using MySqlConnector; + +namespace Server.Data; + +public sealed class DatabaseManager : IDatabaseManager, IAsyncDisposable +{ + private readonly DatabaseOptions _options; + private readonly ILogger _logger; + + public DatabaseManager(IOptions options, ILogger logger) + { + _options = options.Value; + _logger = logger; + } + + // --------------------------- + // Public API + // --------------------------- + + public async Task ExecuteAsync( + Func> operation, + CancellationToken cancellationToken = default) + { + return await RetryAsync(async ct => + { + await using MySqlConnection mysqlConnection = await OpenNewConnectionAsync(ct); + return await operation(mysqlConnection); + }, cancellationToken); + } + + public async Task ExecuteAsync( + Func operation, + CancellationToken cancellationToken = default) + { + await RetryAsync(async ct => + { + await using MySqlConnection mysqlConnection = await OpenNewConnectionAsync(ct); + await operation(mysqlConnection); + return true; // dummy value for non-generic path + }, cancellationToken); + } + + public async Task WithTransactionAsync( + Func> operation, + IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, + CancellationToken cancellationToken = default) + { + return await RetryAsync(async ct => + { + await using MySqlConnection mysqlConnection = await OpenNewConnectionAsync(ct); + var transaction = await mysqlConnection.BeginTransactionAsync(isolationLevel, ct); + + try + { + T result = await operation(mysqlConnection, transaction); + await transaction.CommitAsync(ct); + await DisposeTransactionAsync(transaction); + return result; + } + catch + { + await SafeRollbackAsync(transaction, ct); + await DisposeTransactionAsync(transaction); + throw; + } + }, cancellationToken); + } + + public async Task WithTransactionAsync( + Func operation, + IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, + CancellationToken cancellationToken = default) + { + await RetryAsync(async ct => + { + await using MySqlConnection mysqlConnection = await OpenNewConnectionAsync(ct); + var transaction = await mysqlConnection.BeginTransactionAsync(isolationLevel, ct); + + try + { + await operation(mysqlConnection, transaction); + await transaction.CommitAsync(ct); + await DisposeTransactionAsync(transaction); + return true; + } + catch + { + await SafeRollbackAsync(transaction, ct); + await DisposeTransactionAsync(transaction); + throw; + } + }, cancellationToken); + } + + // --------------------------- + // Internals + // --------------------------- + + private async Task OpenNewConnectionAsync(CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(_options.ConnectionString)) + throw new InvalidOperationException("Database connection string is not configured."); + + var connection = new MySqlConnection(_options.ConnectionString); + await connection.OpenAsync(cancellationToken); + return connection; + } + + private static async Task SafeRollbackAsync(IDbTransaction transaction, CancellationToken cancellationToken) + { + try + { + if (transaction is MySqlTransaction mySqlTx) + await mySqlTx.RollbackAsync(cancellationToken); + else + transaction.Rollback(); + } + catch + { + // swallow rollback exceptions + } + } + + private static async Task DisposeTransactionAsync(IDbTransaction transaction) + { + if (transaction is IAsyncDisposable asyncDisposableTx) + await asyncDisposableTx.DisposeAsync(); + else + transaction.Dispose(); + } + + // Simple, robust retry with jittered backoff (replaces Polly to avoid API mismatch) + private async Task RetryAsync(Func> operation, CancellationToken cancellationToken) + { + int maxAttempts = Math.Max(1, _options.MaxRetryCount + 1); // attempts = retries + initial try + int baseDelayMs = Math.Max(10, _options.RetryBaseDelayMs); + + for (int attempt = 1; attempt <= maxAttempts; attempt++) + { + try + { + cancellationToken.ThrowIfCancellationRequested(); + return await operation(cancellationToken); + } + catch (Exception ex) when (IsTransient(ex) && attempt < maxAttempts) + { + var backoff = TimeSpan.FromMilliseconds(baseDelayMs * Math.Pow(2, attempt - 1)); + var jitter = TimeSpan.FromMilliseconds(Random.Shared.Next(0, 50)); + var delay = backoff + jitter; + + _logger.LogWarning(ex, "DB transient error, attempt {Attempt}/{Max}. Retrying in {Delay} ms", + attempt, maxAttempts, (int)delay.TotalMilliseconds); + + try { await Task.Delay(delay, cancellationToken); } + catch (OperationCanceledException) { throw; } + } + } + + // Should never reach; loop either returns or throws. + throw new InvalidOperationException("Retry loop exited unexpectedly."); + } + + private static bool IsTransient(Exception ex) + { + // Expand as needed with specific MySQL transient codes. + return ex is MySqlException or TimeoutException or InvalidOperationException; + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} diff --git a/data/DatabaseOptions.cs b/data/DatabaseOptions.cs new file mode 100644 index 0000000..a8e2309 --- /dev/null +++ b/data/DatabaseOptions.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace Server.Data; + +public sealed class DatabaseOptions +{ + [Required] public string ConnectionString { get; set; } = string.Empty; + public int CommandTimeoutSeconds { get; set; } = 30; + public int MaxRetryCount { get; set; } = 3; + public int RetryBaseDelayMs { get; set; } = 100; // jittered backoff base +} diff --git a/data/DesignTimeDbContextFactory.cs b/data/DesignTimeDbContextFactory.cs new file mode 100644 index 0000000..970b4ce --- /dev/null +++ b/data/DesignTimeDbContextFactory.cs @@ -0,0 +1,33 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.Extensions.Configuration; + +namespace Server.Data; + +public sealed class DesignTimeDbContextFactory : IDesignTimeDbContextFactory +{ + public GameDbContext CreateDbContext(string[] args) + { + string cs; + try { cs = ConnectionStringFactory.BuildMySqlFromEnv(); } + catch + { + var cfg = new ConfigurationBuilder() + .AddJsonFile("appsettings.json", optional: true) + .AddUserSecrets(optional: true) + .AddEnvironmentVariables() + .Build(); + + cs = cfg.GetConnectionString("PrimaryMySql") + ?? cfg["Database:ConnectionString"] + ?? "Server=localhost;Port=3306;Database=systemrevival;User Id=root;Password=pass;"; + } + + var opts = new DbContextOptionsBuilder() + .UseMySql(cs, ServerVersion.AutoDetect(cs)) + .Options; + + return new GameDbContext(opts); + } +} + diff --git a/data/GameDbContext.cs b/data/GameDbContext.cs new file mode 100644 index 0000000..b44abab --- /dev/null +++ b/data/GameDbContext.cs @@ -0,0 +1,22 @@ +using System.Security.Principal; +using Microsoft.EntityFrameworkCore; + +namespace Server.Data; + +public sealed class GameDbContext : DbContext +{ + public GameDbContext(DbContextOptions options) : base(options) { } + + public DbSet Accounts => Set(); + public DbSet Sessions => Set(); + public DbSet Characters => Set(); + public DbSet Zones => Set(); + public DbSet ItemTemplates => Set(); + public DbSet Inventory => Set(); + public DbSet Equipment => Set(); + + protected override void OnModelCreating(ModelBuilder b) + { + b.ApplyConfigurationsFromAssembly(typeof(GameDbContext).Assembly); + } +} diff --git a/data/IDatabaseManager.cs b/data/IDatabaseManager.cs new file mode 100644 index 0000000..a7ae254 --- /dev/null +++ b/data/IDatabaseManager.cs @@ -0,0 +1,30 @@ +using System.Data; +using System.Threading; +using System.Threading.Tasks; + +namespace Server.Data; + +/// +/// Central entry for DB access: resilient connections, optional transactions, and utility helpers. +/// Works great for Dapper or ADO.NET; EF Core can reuse the same connection string. +/// +public interface IDatabaseManager +{ + Task ExecuteAsync( + Func> operation, + CancellationToken cancellationToken = default); + + Task ExecuteAsync( + Func operation, + CancellationToken cancellationToken = default); + + Task WithTransactionAsync( + Func> operation, + IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, + CancellationToken cancellationToken = default); + + Task WithTransactionAsync( + Func operation, + IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, + CancellationToken cancellationToken = default); +} diff --git a/data/ServiceCollectionExtensions.cs b/data/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..2e5a0fc --- /dev/null +++ b/data/ServiceCollectionExtensions.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Server.Data; + +namespace Server; + +public static class ServiceCollectionExtensions +{ + public static IServiceCollection AddDatabaseManager(this IServiceCollection services, IConfiguration configuration) + { + services.AddOptions() + .Bind(configuration.GetSection("Database")) + .ValidateDataAnnotations() + .Validate(o => !string.IsNullOrWhiteSpace(o.ConnectionString), "Database:ConnectionString is required") + .ValidateOnStart(); + + services.AddSingleton(); + + services.AddHealthChecks() + .AddCheck("mysql", failureStatus: HealthStatus.Unhealthy, tags: new[] { "ready" }); + + return services; + } +} diff --git a/data/entities/Account.cs b/data/entities/Account.cs new file mode 100644 index 0000000..7771c75 --- /dev/null +++ b/data/entities/Account.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +public sealed class Account +{ + public ulong Id { get; set; } + public string Username { get; set; } = ""; + public string? Email { get; set; } + public byte[] PasswordHash { get; set; } = Array.Empty(); + public byte[] PasswordSalt { get; set; } = Array.Empty(); + public bool IsBanned { get; set; } + public DateTime? BannedUntil { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + public ICollection Sessions { get; set; } = new List(); + public ICollection Characters { get; set; } = new List(); +} + +public sealed class AccountConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("accounts"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + e.Property(x => x.Username).HasMaxLength(32).IsRequired(); + e.Property(x => x.Email).HasMaxLength(255); + e.HasIndex(x => x.Username).IsUnique(); + e.HasIndex(x => x.Email).IsUnique(); + e.Property(x => x.PasswordHash).HasColumnType("varbinary(64)"); + e.Property(x => x.PasswordSalt).HasColumnType("varbinary(32)"); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + } +} diff --git a/data/entities/Character.cs b/data/entities/Character.cs new file mode 100644 index 0000000..75712ae --- /dev/null +++ b/data/entities/Character.cs @@ -0,0 +1,64 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +public sealed class Character +{ + public ulong Id { get; set; } + public ulong AccountId { get; set; } + public string Name { get; set; } = ""; + + public uint Level { get; set; } = 1; + public ulong Xp { get; set; } = 0; + + public uint StatStrength { get; set; } = 1; + public uint StatDexterity { get; set; } = 1; + public uint StatWisdom { get; set; } = 1; + public uint StatIntelligence { get; set; } = 1; + public uint StatEndurance { get; set; } = 1; + + public uint HpCurrent { get; set; } = 10; + public uint HpMax { get; set; } = 10; + public uint MpCurrent { get; set; } = 0; + public uint MpMax { get; set; } = 0; + public uint StaminaCurrent { get; set; } = 0; + public uint StaminaMax { get; set; } = 0; + + public ulong ZoneId { get; set; } + public double PosX { get; set; } + public double PosY { get; set; } + public double PosZ { get; set; } + public float FacingDeg { get; set; } + + // store as JSON in MySQL 8 + public string? AppearanceJson { get; set; } + + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + public Account? Account { get; set; } + public Zone? Zone { get; set; } +} + +public sealed class CharacterConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("characters"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + e.Property(x => x.Name).HasMaxLength(32).IsRequired(); + + e.HasIndex(x => x.AccountId).IsUnique(); // 1 character per account (change later if needed) + e.HasIndex(x => x.ZoneId); + + e.Property(x => x.AppearanceJson).HasColumnType("json"); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + + e.HasOne(x => x.Account).WithMany(a => a.Characters).HasForeignKey(x => x.AccountId).OnDelete(DeleteBehavior.Cascade); + e.HasOne(x => x.Zone).WithMany().HasForeignKey(x => x.ZoneId).OnDelete(DeleteBehavior.Restrict); + } +} diff --git a/data/entities/EquipmentSlot.cs b/data/entities/EquipmentSlot.cs new file mode 100644 index 0000000..938330c --- /dev/null +++ b/data/entities/EquipmentSlot.cs @@ -0,0 +1,34 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +public sealed class EquipmentSlot +{ + public ulong Id { get; set; } + public ulong CharacterId { get; set; } + public byte SlotCode { get; set; } // 1=head,2=chest,... + public ulong ItemTemplateId { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + public Character? Character { get; set; } + public ItemTemplate? ItemTemplate { get; set; } +} + +public sealed class EquipmentSlotConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("equipment"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + e.HasIndex(x => new { x.CharacterId, x.SlotCode }).IsUnique(); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + + e.HasOne(x => x.Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade); + e.HasOne(x => x.ItemTemplate).WithMany().HasForeignKey(x => x.ItemTemplateId).OnDelete(DeleteBehavior.Restrict); + } +} diff --git a/data/entities/InventoryItem.cs b/data/entities/InventoryItem.cs new file mode 100644 index 0000000..abd9d20 --- /dev/null +++ b/data/entities/InventoryItem.cs @@ -0,0 +1,36 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +public sealed class InventoryItem +{ + public ulong Id { get; set; } + public ulong CharacterId { get; set; } + public uint SlotIndex { get; set; } + public ulong ItemTemplateId { get; set; } + public uint Quantity { get; set; } = 1; + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + public Character? Character { get; set; } + public ItemTemplate? ItemTemplate { get; set; } +} + +public sealed class InventoryItemConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("inventories"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + e.HasIndex(x => new { x.CharacterId, x.SlotIndex }).IsUnique(); + e.HasIndex(x => x.CharacterId); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + + e.HasOne(x => x.Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade); + e.HasOne(x => x.ItemTemplate).WithMany().HasForeignKey(x => x.ItemTemplateId).OnDelete(DeleteBehavior.Restrict); + } +} diff --git a/data/entities/ItemTemplate.cs b/data/entities/ItemTemplate.cs new file mode 100644 index 0000000..1fb605b --- /dev/null +++ b/data/entities/ItemTemplate.cs @@ -0,0 +1,33 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +public sealed class ItemTemplate +{ + public ulong Id { get; set; } + public string Name { get; set; } = ""; + public byte ItemType { get; set; } = 1; + public byte Rarity { get; set; } = 1; + public uint MaxStack { get; set; } = 1; + public uint Weight { get; set; } = 0; + public string? StatsJson { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } +} + +public sealed class ItemTemplateConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("item_templates"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + e.Property(x => x.Name).HasMaxLength(64).IsRequired(); + e.HasIndex(x => x.Name).IsUnique(); + e.Property(x => x.StatsJson).HasColumnType("json"); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + } +} diff --git a/data/entities/Session.cs b/data/entities/Session.cs new file mode 100644 index 0000000..dce6f05 --- /dev/null +++ b/data/entities/Session.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +public sealed class Session +{ + public ulong Id { get; set; } + public ulong AccountId { get; set; } + public string Token { get; set; } = ""; // 64-char base64url/hex + public DateTime ExpiresAt { get; set; } + public DateTime CreatedAt { get; set; } + + public Account? Account { get; set; } +} + +public sealed class SessionConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("sessions"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + e.HasIndex(x => x.Token).IsUnique(); + e.HasIndex(x => x.AccountId); + e.Property(x => x.Token).HasMaxLength(64).IsRequired(); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.HasOne(x => x.Account).WithMany(a => a.Sessions).HasForeignKey(x => x.AccountId).OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/data/entities/Zone.cs b/data/entities/Zone.cs new file mode 100644 index 0000000..dce0ee2 --- /dev/null +++ b/data/entities/Zone.cs @@ -0,0 +1,33 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +public sealed class Zone +{ + public ulong Id { get; set; } + public string Name { get; set; } = ""; + public double MinX { get; set; } + public double MinY { get; set; } + public double MinZ { get; set; } + public double MaxX { get; set; } + public double MaxY { get; set; } + public double MaxZ { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } +} + +public sealed class ZoneConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("zones"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + e.Property(x => x.Name).HasMaxLength(64).IsRequired(); + e.HasIndex(x => x.Name).IsUnique(); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + } +} diff --git a/k8s/deployment.yaml b/k8s/deployment.yaml index b69540b..2b002d1 100644 --- a/k8s/deployment.yaml +++ b/k8s/deployment.yaml @@ -20,6 +20,53 @@ spec: image: registry.aeternalisgames.com/systemrevivalserver/systemrevivalserver:latest imagePullPolicy: Always ports: - - containerPort: 8080 + - containerPort: 8080 # HTTP/WS + - containerPort: 40000 # TCP game + env: + # Server runtime + - name: HTTP_PORT + value: "8080" + - name: TCP_PORT + value: "40000" + - name: ASPNETCORE_URLS + value: "http://0.0.0.0:8080" + - name: TICK_RATE_HZ + value: "20" + - name: IDLE_TIMEOUT_S + value: "45" + - name: MAX_CONN + value: "10000" + + # MySQL + - name: DB_HOST + valueFrom: { secretKeyRef: { name: mysql-secret, key: DB_HOST } } + - name: DB_PORT + valueFrom: { secretKeyRef: { name: mysql-secret, key: DB_PORT } } + - name: DB_NAME + valueFrom: { secretKeyRef: { name: mysql-secret, key: DB_NAME } } + - name: DB_USER + valueFrom: { secretKeyRef: { name: mysql-secret, key: DB_USER } } + - name: DB_PASSWORD + valueFrom: { secretKeyRef: { name: mysql-secret, key: DB_PASSWORD } } + + + # Redis + - name: REDIS_HOST + valueFrom: { secretKeyRef: { name: redis-secret, key: REDIS_HOST } } + - name: REDIS_PORT + valueFrom: { secretKeyRef: { name: redis-secret, key: REDIS_PORT } } + - name: REDIS_PASSWORD + valueFrom: { secretKeyRef: { name: redis-secret, key: REDIS_PASSWORD } } + + + livenessProbe: + tcpSocket: { port: 8080 } + initialDelaySeconds: 10 + periodSeconds: 15 + readinessProbe: + httpGet: { path: /health/ready, port: 8080 } + initialDelaySeconds: 10 + periodSeconds: 10 + imagePullSecrets: - name: aeternalis-regcred diff --git a/k8s/ingress.yaml b/k8s/ingress.yaml index 8f97d8a..da281cc 100644 --- a/k8s/ingress.yaml +++ b/k8s/ingress.yaml @@ -1,29 +1,24 @@ apiVersion: networking.k8s.io/v1 kind: Ingress metadata: - name: systemrevival-server + name: systemrevival-ws namespace: systemrevival-server annotations: - # use your cluster issuer cert-manager.io/cluster-issuer: letsencrypt-godaddy - # good nginx defaults; remove if you don't need them nginx.ingress.kubernetes.io/ssl-redirect: "true" - nginx.ingress.kubernetes.io/proxy-body-size: "20m" spec: - # make sure this matches your ingress class ingressClassName: nginx tls: - - hosts: - - srs.aeternalisgames.com + - hosts: [ "srs.aeternalisgames.com" ] secretName: srs-tls rules: - host: srs.aeternalisgames.com http: paths: - - path: / + - path: /ws pathType: Prefix backend: service: - name: systemrevival-server + name: systemrevival-ws port: - number: 80 + number: 8080 diff --git a/k8s/service.yaml b/k8s/service.yaml index 71c6b0a..3323f2c 100644 --- a/k8s/service.yaml +++ b/k8s/service.yaml @@ -1,7 +1,8 @@ -apiVersion: v1 +# HTTP/WS for ingress +apiVersion: v1 kind: Service metadata: - name: systemrevival-server + name: systemrevival-ws namespace: systemrevival-server labels: app: systemrevival-server @@ -10,6 +11,24 @@ spec: app: systemrevival-server ports: - name: http - port: 80 + port: 8080 targetPort: 8080 type: ClusterIP +--- +# Raw TCP game port (public) +apiVersion: v1 +kind: Service +metadata: + name: systemrevival-tcp + namespace: systemrevival-server + labels: + app: systemrevival-server +spec: + selector: + app: systemrevival-server + type: LoadBalancer + externalTrafficPolicy: Local + ports: + - name: tcp-game + port: 40000 + targetPort: 40000