Make Brokkr editor commands multiprocess safe

This commit is contained in:
Meta Vens 2026-07-18 18:37:02 +01:00
commit 821f9d32e2
9 changed files with 152 additions and 166 deletions

View file

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<CultLibRoot Condition="'$(CultLibRoot)' == ''">..\..\CultLib-codex-cultmesh-reliability</CultLibRoot>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\brokkr-contracts\Brokkr.Contracts.csproj" />
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching\GameCult.Caching.csproj" />
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching.MessagePack\GameCult.Caching.MessagePack.csproj" />
<PackageReference Include="MessagePack" Version="3.1.7" />
</ItemGroup>
</Project>

94
brokkr-command/Program.cs Normal file
View file

@ -0,0 +1,94 @@
using GameCult.Brokkr;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
var options = Options.Parse(args);
using var cache = await CultCacheMessagePack.OpenAsync(options.CachePath, new CultCacheOpenOptions
{
UseDirectoryStore = true
});
var command = new BrokkrUnityCommand
{
commandId = options.CommandId,
action = options.Action,
value = options.Value,
viewKind = options.ViewKind,
outputPath = options.OutputPath,
width = options.Width,
height = options.Height
};
var commandKey = new CultRecordKey($"unity/commands/{command.commandId}");
await cache.AddAsync(command, new CultRecordHandle<BrokkrUnityCommand>(commandKey));
await cache.FlushAsync();
if (options.WaitMilliseconds <= 0)
{
Console.WriteLine(command.commandId);
return;
}
var receiptKey = new CultRecordKey($"unity/receipts/{command.commandId}");
var deadline = DateTimeOffset.UtcNow.AddMilliseconds(options.WaitMilliseconds);
while (DateTimeOffset.UtcNow < deadline)
{
await Task.Delay(100);
await cache.PullAllBackingStoresAsync();
if (!cache.TryGet(receiptKey, out BrokkrUnityCommandReceipt? receipt) || receipt == null)
{
continue;
}
Console.WriteLine($"{receipt.status}: {receipt.message}");
if (!string.IsNullOrWhiteSpace(receipt.objectId))
{
Console.WriteLine(receipt.objectId);
}
Environment.ExitCode = string.Equals(receipt.status, "accepted", StringComparison.Ordinal) ? 0 : 1;
return;
}
throw new TimeoutException($"Timed out waiting for Brokkr receipt '{receiptKey.Value}'.");
internal sealed record Options(
string CachePath,
string Action,
string Value,
string ViewKind,
string OutputPath,
int Width,
int Height,
string CommandId,
int WaitMilliseconds)
{
internal static Options Parse(string[] args)
{
var values = new Dictionary<string, string>(StringComparer.Ordinal);
for (var index = 0; index < args.Length; index += 2)
{
if (index + 1 >= args.Length || !args[index].StartsWith("--", StringComparison.Ordinal))
{
throw new ArgumentException("Arguments must be --name value pairs.");
}
values[args[index]] = args[index + 1];
}
string Required(string name) => values.TryGetValue(name, out var value) && !string.IsNullOrWhiteSpace(value)
? value
: throw new ArgumentException($"{name} is required.");
string Optional(string name) => values.TryGetValue(name, out var value) ? value : "";
int Integer(string name, int fallback) => values.TryGetValue(name, out var value)
? int.Parse(value, System.Globalization.CultureInfo.InvariantCulture)
: fallback;
return new Options(
Path.GetFullPath(Required("--unity-cache")),
Required("--action"),
Optional("--value"),
Optional("--view"),
Optional("--output"),
Integer("--width", 0),
Integer("--height", 0),
values.TryGetValue("--command-id", out var commandId) ? commandId : Guid.NewGuid().ToString("N"),
Integer("--wait-ms", 10000));
}
}

View file

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<CultLibRoot Condition="'$(CultLibRoot)' == ''">..\..\CultLib-codex-cultmesh-reliability</CultLibRoot>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\surfaces\unity\Packages\com.gamecult.brokkr\Runtime\*.cs" />
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching\GameCult.Caching.csproj" />
<PackageReference Include="MessagePack" Version="3.1.7" />
</ItemGroup>
</Project>

View file

@ -131,12 +131,11 @@ fn main() -> Result<()> {
match command.as_str() {
"provider" | "smoke" => print_provider(),
"sync-contract" => print_sync_contract(),
"unity-command" => unity_command(UnityCommandArgs::parse(args.collect())?),
"sync-once" => sync_once(SyncArgs::parse(args.collect())?),
"sync-loop" => sync_loop(SyncLoopArgs::parse(args.collect())?),
_ => {
eprintln!(
"usage: brokkr-daemon [provider|smoke|sync-contract|unity-command --unity-cache PATH --action ACTION [--value VALUE] [--view game|scene] [--output PATH] [--width N] [--height N] [--command-id ID]|sync-once --unity-cache PATH --blender-cache PATH [--dry-run]|sync-loop --unity-cache PATH --blender-cache PATH [--interval-ms N] [--max-passes N] [--dry-run]]"
"usage: brokkr-daemon [provider|smoke|sync-contract|sync-once --unity-cache PATH --blender-cache PATH [--dry-run]|sync-loop --unity-cache PATH --blender-cache PATH [--interval-ms N] [--max-passes N] [--dry-run]]"
);
std::process::exit(2);
}
@ -181,42 +180,6 @@ fn sync_loop(args: SyncLoopArgs) -> Result<()> {
}
}
fn unity_command(args: UnityCommandArgs) -> Result<()> {
let command_id = args
.command_id
.unwrap_or_else(|| stable_id(["unity-command", &args.action, &chrono_like_timestamp_id()]));
let command = json!([
"brokkr.unity.command_intent.v0",
command_id,
args.action,
"",
"",
"",
"",
args.value,
"",
"",
"",
"",
"",
args.view_kind,
args.output_path,
args.width,
args.height
]);
let mut store = MirrorStore::open(&args.unity_cache)?;
let command_id = command[1]
.as_str()
.ok_or_else(|| anyhow!("generated Unity command has no command id"))?;
store.put_messagepack_document(
"brokkr.unity.command_intent.v0",
&format!("unity/commands/{command_id}"),
&command,
)?;
println!("{command_id}");
Ok(())
}
fn build_provider_advertisement() -> ProviderAdvertisement {
ProviderAdvertisement {
schema: PROVIDER_SCHEMA,
@ -541,76 +504,6 @@ struct SyncArgs {
dry_run: bool,
}
#[derive(Debug, Clone)]
struct UnityCommandArgs {
unity_cache: PathBuf,
action: String,
value: String,
view_kind: String,
output_path: String,
width: i64,
height: i64,
command_id: Option<String>,
}
impl UnityCommandArgs {
fn parse(args: Vec<String>) -> Result<Self> {
let mut unity_cache = None;
let mut action = None;
let mut value = String::new();
let mut view_kind = String::new();
let mut output_path = String::new();
let mut width = 0;
let mut height = 0;
let mut command_id = None;
let mut index = 0;
while index < args.len() {
let option = args[index].as_str();
index += 1;
let required_value = |index: usize| {
args.get(index)
.cloned()
.ok_or_else(|| anyhow!("{option} requires a value"))
};
match option {
"--unity-cache" => unity_cache = Some(PathBuf::from(required_value(index)?)),
"--action" => action = Some(required_value(index)?),
"--value" => value = required_value(index)?,
"--view" => view_kind = required_value(index)?,
"--output" => output_path = required_value(index)?,
"--width" => {
let raw = required_value(index)?;
width = raw
.parse()
.with_context(|| format!("invalid --width value: {raw}"))?;
}
"--height" => {
let raw = required_value(index)?;
height = raw
.parse()
.with_context(|| format!("invalid --height value: {raw}"))?;
}
"--command-id" => command_id = Some(required_value(index)?),
other => return Err(anyhow!("unknown unity-command argument: {other}")),
}
index += 1;
}
Ok(Self {
unity_cache: unity_cache
.ok_or_else(|| anyhow!("unity-command requires --unity-cache"))?,
action: action.ok_or_else(|| anyhow!("unity-command requires --action"))?,
value,
view_kind,
output_path,
width,
height,
command_id,
})
}
}
impl SyncArgs {
fn parse(args: Vec<String>) -> Result<Self> {
let parsed = ParsedSyncCli::parse(args, false)?;
@ -2102,52 +1995,6 @@ fn chrono_like_timestamp_id() -> String {
mod tests {
use super::*;
#[test]
fn unity_command_writes_typed_editor_lifecycle_intent() -> Result<()> {
let temp = tempfile::tempdir()?;
let cache = temp.path().join("unity-editor.ccmp");
let args = UnityCommandArgs::parse(vec![
"--unity-cache".into(),
cache.display().to_string(),
"--action".into(),
"captureEditorView".into(),
"--view".into(),
"scene".into(),
"--output".into(),
"artifacts/scene.png".into(),
"--width".into(),
"1280".into(),
"--height".into(),
"720".into(),
"--command-id".into(),
"capture-scene-test".into(),
])?;
unity_command(args)?;
let mut store = MirrorStore::open(&cache)?;
let document = store
.documents()?
.into_iter()
.find(|item| item.key == "unity/commands/capture-scene-test")
.expect("Unity editor command should be written");
assert_eq!(
field_string(&document.value, 2, "action").as_deref(),
Some("captureEditorView")
);
assert_eq!(
field_string(&document.value, 13, "viewKind").as_deref(),
Some("scene")
);
assert_eq!(
field_string(&document.value, 14, "outputPath").as_deref(),
Some("artifacts/scene.png")
);
assert_eq!(field_i64(&document.value, 15, "width"), Some(1280));
assert_eq!(field_i64(&document.value, 16, "height"), Some(720));
Ok(())
}
#[test]
fn provider_advertises_muninn_owned_quest_routes_for_unity() {
let provider = build_provider_advertisement();

View file

@ -75,10 +75,10 @@ Primary sync documents:
Operational commands:
- `brokkr-daemon unity-command --unity-cache .brokkr/unity-editor.ccmp --action setEditorPlayState --value true`
- `brokkr-daemon unity-command --unity-cache .brokkr/unity-editor.ccmp --action setEditorPaused --value true`
- `brokkr-daemon unity-command --unity-cache .brokkr/unity-editor.ccmp --action refreshAssets`
- `brokkr-daemon unity-command --unity-cache .brokkr/unity-editor.ccmp --action captureEditorView --view scene --output artifacts/scene.png`
- `dotnet run --project brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action setEditorPlayState --value true`
- `dotnet run --project brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action setEditorPaused --value true`
- `dotnet run --project brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action refreshAssets`
- `dotnet run --project brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action captureEditorView --view scene --output artifacts/scene.png`
- `brokkr-daemon sync-once --unity-cache .brokkr/unity-editor.ccmp --blender-cache .brokkr/blender-editor.ccmp`
- `brokkr-daemon sync-loop --unity-cache .brokkr/unity-editor.ccmp --blender-cache .brokkr/blender-editor.ccmp --interval-ms 500`

View file

@ -4,6 +4,7 @@ using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using GameCult.Mesh;
using GameCult.Networking;
using R3;
@ -33,8 +34,13 @@ namespace GameCult.Brokkr.Editor
CachePath = cachePath;
Directory.CreateDirectory(Path.GetDirectoryName(cachePath) ?? ".");
node = await CultMesh.StartNodeAsync(cachePath, new CultMeshNodeOptions
node = await CultMesh.CreateNodeAsync(cachePath, new CultMeshNodeOptions
{
StartServer = false,
CacheOptions = new CultCacheOpenOptions
{
UseDirectoryStore = true
},
EnableDurableShardLogs = true,
DatabaseOptions = new CultNetDatabaseOptions
{
@ -69,6 +75,12 @@ namespace GameCult.Brokkr.Editor
await node.FlushAsync(soft: true);
}
internal Task PullExternalUpdatesAsync()
{
RequireRunning();
return node.Cache.PullAllBackingStoresAsync();
}
internal async Task PublishPrefabMirrorSnapshotAsync(BrokkrUnityPrefabMirrorSnapshot snapshot)
{
RequireRunning();

View file

@ -6,7 +6,7 @@ namespace GameCult.Brokkr.Editor
[InitializeOnLoad]
public static class BrokkrEditorDaemonBridge
{
private const string AutoStartKey = "GameCult.Brokkr.AutoStartMirror";
private static string AutoStartKey => $"GameCult.Brokkr.AutoStartMirror.{UnityEngine.Application.dataPath}";
private static readonly BrokkrCultMeshMirror Mirror = new();
private static double nextPollAt;
private static bool startQueued;
@ -37,14 +37,14 @@ namespace GameCult.Brokkr.Editor
}
[MenuItem("GameCult/Brokkr/Start Daemon Bridge")]
private static void StartDaemonBridge()
public static void StartDaemonBridge()
{
AutoStart = true;
EnsureStarted();
}
[MenuItem("GameCult/Brokkr/Stop Daemon Bridge")]
private static void StopDaemonBridge()
public static void StopDaemonBridge()
{
AutoStart = false;
Mirror.Dispose();
@ -104,6 +104,7 @@ namespace GameCult.Brokkr.Editor
}
nextPollAt = EditorApplication.timeSinceStartup + 1.0;
Mirror.PullExternalUpdatesAsync().GetAwaiter().GetResult();
DrainCommands();
DrainSyncReceipts();
}

View file

@ -173,7 +173,7 @@ namespace GameCult.Brokkr
[Serializable]
public sealed class BrokkrUnityCommandEnvelope
{
[Key(0)] public BrokkrUnityCommand command;
[Key(0)] public BrokkrUnityCommand command = new();
}
[CultDocument("brokkr.unity.command_receipt", "brokkr.unity.command_receipt.v0")]

View file

@ -40,9 +40,9 @@ same CultCache mirror. Common lifecycle commands can be issued without UI
automation:
```powershell
cargo run --manifest-path E:/Projects/Brokkr/brokkr-daemon/Cargo.toml -- unity-command --unity-cache .brokkr/unity-editor.ccmp --action setEditorPlayState --value true
cargo run --manifest-path E:/Projects/Brokkr/brokkr-daemon/Cargo.toml -- unity-command --unity-cache .brokkr/unity-editor.ccmp --action setEditorPaused --value true
cargo run --manifest-path E:/Projects/Brokkr/brokkr-daemon/Cargo.toml -- unity-command --unity-cache .brokkr/unity-editor.ccmp --action captureEditorView --view scene --output artifacts/scene.png
dotnet run --project E:/Projects/Brokkr/brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action setEditorPlayState --value true
dotnet run --project E:/Projects/Brokkr/brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action setEditorPaused --value true
dotnet run --project E:/Projects/Brokkr/brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action captureEditorView --view scene --output artifacts/scene.png
```
6. Click `Publish Mirror`.
7. To create a ScriptableObject through the mirror, fill `ScriptableObject Type`,