orleans
Microsoft Orleans patterns for distributed game servers, Grains, Silos, persistence, and multiplayer game architecture
What this skill does
# Microsoft Orleans Game Server Skill
## Engine Detection
Look for: `.sln` with Orleans NuGet packages, `*Grain*.cs`, `*Silo*.cs`, `Microsoft.Orleans.*` in `.csproj`, `ISiloBuilder`, `IClusterClient`
## Project Structure
```
GameServer/
GameServer.sln
src/
GameServer.Grains.Interfaces/ # Grain interfaces (shared)
IPlayerGrain.cs
IRoomGrain.cs
IMatchGrain.cs
ILeaderboardGrain.cs
GameServer.Grains/ # Grain implementations
PlayerGrain.cs
RoomGrain.cs
MatchGrain.cs
LeaderboardGrain.cs
GameServer.Silo/ # Silo host configuration
Program.cs
SiloConfig.cs
GameServer.Client/ # Client SDK / API gateway
Program.cs
Controllers/
GameController.cs
GameServer.Shared/ # Shared types and DTOs
Models/
PlayerState.cs
MatchState.cs
GameAction.cs
tests/
GameServer.Tests/
PlayerGrainTests.cs
MatchGrainTests.cs
```
## Grain Pattern (Virtual Actor)
Grains are the core abstraction. Each grain has a unique identity and is single-threaded:
```csharp
// Interface - GameServer.Grains.Interfaces/IPlayerGrain.cs
public interface IPlayerGrain : IGrainWithStringKey
{
Task<PlayerState> GetState();
Task JoinRoom(string roomId);
Task LeaveRoom();
Task<bool> TakeDamage(float amount, string attackerId);
Task UpdatePosition(Vector3 position, Quaternion rotation);
}
// Implementation - GameServer.Grains/PlayerGrain.cs
public class PlayerGrain : Grain, IPlayerGrain
{
private readonly IPersistentState<PlayerState> _state;
private readonly ILogger<PlayerGrain> _logger;
private IDisposable? _heartbeatTimer;
public PlayerGrain(
[PersistentState("player", "gameStore")]
IPersistentState<PlayerState> state,
ILogger<PlayerGrain> logger)
{
_state = state;
_logger = logger;
}
public override async Task OnActivateAsync(CancellationToken ct)
{
_logger.LogInformation("Player {Id} activated", this.GetPrimaryKeyString());
_heartbeatTimer = this.RegisterGrainTimer(
Heartbeat, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30));
await base.OnActivateAsync(ct);
}
public override async Task OnDeactivateAsync(DeactivationReason reason, CancellationToken ct)
{
_heartbeatTimer?.Dispose();
await _state.WriteStateAsync();
await base.OnDeactivateAsync(reason, ct);
}
public Task<PlayerState> GetState() => Task.FromResult(_state.State);
public async Task JoinRoom(string roomId)
{
var room = GrainFactory.GetGrain<IRoomGrain>(roomId);
await room.AddPlayer(this.GetPrimaryKeyString());
_state.State.CurrentRoomId = roomId;
await _state.WriteStateAsync();
}
public async Task<bool> TakeDamage(float amount, string attackerId)
{
_state.State.Health -= amount;
if (_state.State.Health <= 0)
{
_state.State.Health = 0;
_state.State.IsAlive = false;
await _state.WriteStateAsync();
// Notify the room
if (_state.State.CurrentRoomId is not null)
{
var room = GrainFactory.GetGrain<IRoomGrain>(_state.State.CurrentRoomId);
await room.OnPlayerDeath(this.GetPrimaryKeyString(), attackerId);
}
return true; // Player died
}
await _state.WriteStateAsync();
return false;
}
private Task Heartbeat()
{
_state.State.LastHeartbeat = DateTime.UtcNow;
return _state.WriteStateAsync();
}
}
```
## Room/Match Grain (Game Session)
```csharp
public interface IRoomGrain : IGrainWithStringKey
{
Task AddPlayer(string playerId);
Task RemovePlayer(string playerId);
Task<RoomState> GetState();
Task BroadcastAction(GameAction action);
Task OnPlayerDeath(string playerId, string killerId);
}
public class RoomGrain : Grain, IRoomGrain
{
private readonly IPersistentState<RoomState> _state;
private readonly HashSet<string> _activePlayers = new();
public RoomGrain(
[PersistentState("room", "gameStore")]
IPersistentState<RoomState> state)
{
_state = state;
}
public async Task AddPlayer(string playerId)
{
if (_activePlayers.Count >= _state.State.MaxPlayers)
throw new InvalidOperationException("Room is full");
_activePlayers.Add(playerId);
_state.State.PlayerIds = _activePlayers.ToList();
await _state.WriteStateAsync();
// Notify all players
await BroadcastAction(new GameAction
{
Type = "player_joined",
PlayerId = playerId,
Timestamp = DateTime.UtcNow
});
}
public async Task BroadcastAction(GameAction action)
{
var tasks = _activePlayers.Select(async id =>
{
var player = GrainFactory.GetGrain<IPlayerGrain>(id);
// Push via stream or polling
});
await Task.WhenAll(tasks);
}
}
```
## Orleans Streams (Real-Time Updates)
```csharp
// Producer (in RoomGrain)
public async Task BroadcastGameState()
{
var streamProvider = this.GetStreamProvider("GameStream");
var stream = streamProvider.GetStream<GameStateUpdate>(
StreamId.Create("room", this.GetPrimaryKeyString()));
await stream.OnNextAsync(new GameStateUpdate
{
RoomId = this.GetPrimaryKeyString(),
Players = _state.State.PlayerIds,
Timestamp = DateTime.UtcNow
});
}
// Consumer (in client or another grain)
var stream = streamProvider.GetStream<GameStateUpdate>(
StreamId.Create("room", roomId));
await stream.SubscribeAsync((update, token) =>
{
// Handle real-time game state update
return Task.CompletedTask;
});
```
## Silo Configuration
```csharp
// Program.cs - Silo Host
var builder = Host.CreateDefaultBuilder(args)
.UseOrleans((context, siloBuilder) =>
{
if (context.HostingEnvironment.IsDevelopment())
{
siloBuilder.UseLocalhostClustering();
siloBuilder.AddMemoryGrainStorage("gameStore");
}
else
{
siloBuilder.UseAzureStorageClustering(options =>
options.ConfigureTableServiceClient(connectionString));
siloBuilder.AddAzureTableGrainStorage("gameStore", options =>
options.ConfigureTableServiceClient(connectionString));
}
siloBuilder.AddMemoryStreams("GameStream");
siloBuilder.UseDashboard(); // Orleans Dashboard for monitoring
});
```
## Persistence Patterns
```csharp
// State class
[GenerateSerializer]
public class PlayerState
{
[Id(0)] public string PlayerId { get; set; } = "";
[Id(1)] public float Health { get; set; } = 100f;
[Id(2)] public bool IsAlive { get; set; } = true;
[Id(3)] public string? CurrentRoomId { get; set; }
[Id(4)] public DateTime LastHeartbeat { get; set; }
[Id(5)] public Dictionary<string, int> Inventory { get; set; } = new();
}
// Use [GenerateSerializer] and [Id(n)] for Orleans serialization
// Write state explicitly after mutations: await _state.WriteStateAsync()
// State is automatically loaded on grain activation
```
## Key Rules
1. **Grains are single-threaded** - No locks needed, but avoid blocking calls
2. **Use Task/async everywhere** - Never block with .Result or .Wait()
3. **Keep grain state small** - Large state = slow activation/persistence
4. **Use grain timers, not Task.Delay** - Timers are grain-lifecycle aware
5. **Dispose timers in OnDeactivateAsync** - Prevent leaks
6. **Use streams for real-time communication** - Not polling
7. **Persist state explicitly** - Call WriteStateAsync after mutations
8. **Use [GenerateSerializer]** - Not JSON serialization for grain state
9. **Design for grain deactivation** - Grains can deactivate at anyRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.