Files
servuo-plugins/overlay/Scripts/Custom/Bridge/BridgeBoot.cs
wtclaude 48d57e6278 feat(bridge): publish the player-vendor market index as vendor.listing
Protocol 3.0 §8. Every player vendor's shop name, owner, location and priced
inventory, so the website can offer the search the in-game Vendor Search gump
offers — from outside the game, and honouring the same per-player opt-out.

It cannot be an RPC. rpc.rs correlates a reply on the FIRST frame carrying a
matching reqId, so a chunked reply sharing one reqId would deliver chunk 1 to the
HTTP caller and leak chunks 2..N onto the broadcast feed; a whole-world snapshot
would not fit in one frame inside the 10 s timeout either. So it is a diff sweep
on the broadcast stream, one authoritative frame per vendor.

The one genuinely new pattern here is an amortized round-robin: every other sweep
walks its whole collection per tick, which is fine for tens of houses and is not
fine for a world of shops whose inventories recurse into containers.
MarketSweepBatch (25) vendors are inventoried per tick from a persistent cursor,
so per-tick cost is bounded by the batch rather than by world size.

VendorSearch.GetItemName is never called: it builds an ObjectPropertyList,
serialises it and byte-parses the packet per item. The frame carries itemId, hue,
amount, price, the plain item.Name field and item.LabelNumber; the website
resolves names against its own cliloc table. (It would not work anyway — every
current client ships its cliloc files compressed and ServUO's Ultima.StringList
cannot read them, so the in-game gump has the same gap.)

Measured on the live shard (27 vendors x 40 listings, 209k items / 43k mobiles):
15.4 ms for the first cold tick of 25 vendors, 3.4 ms for the next, 0.3 ms in
steady state. `[bridge status` now reports lastMs/maxMs and a tick over 50 ms
warns, naming the knob — the batch cap is a claim about that number and an
operator tuning it was otherwise tuning blind.

- location is ONE nested object, not flat map/x/y/region, so the website's single
  market.location visibility rule can hide a vendor's whereabouts on both the
  live frame and the stored read model. Flat keys would need five rules.
- Owner is flat ownerSerial/ownerName, never BridgeJson.Actor, which would add
  acct and webId. Same argument points.board makes.
- pv.VendorSearch is honoured, so a shop hidden in game is hidden on the site;
  the seen-set removal then emits vendor.listing.remove.
- Container-priced items carry child:true, exactly as DoSearch reports them.
- Over MarketMaxListings (250) the frame says truncated and carries the real
  total, so the site shows "250 of 3,104" rather than a partial shop as complete.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-29 09:51:00 -05:00

223 lines
8.9 KiB
C#

using System;
using System.Collections.Generic;
using Server.Commands;
namespace Server.Custom.Bridge
{
/// <summary>
/// Lifecycle wiring. Boot order (Server/Main.cs:544-562, all on the Core thread):
///
/// Configure() -> World.Load() -> Initialize() -> EventSink.ServerStarted
///
/// Config is read in Configure. Handlers are attached in Initialize. The socket opens on
/// ServerStarted, once the world is actually there to describe.
///
/// EventSink.Shutdown does NOT fire on a crash (Server/Main.cs:198,313), so the sidecar
/// must treat socket EOF as normal and re-handshake rather than waiting for a goodbye.
/// </summary>
public static class BridgeBoot
{
private static readonly Dictionary<string, Action<Dictionary<string, object>>> _handlers =
new Dictionary<string, Action<Dictionary<string, object>>>(StringComparer.Ordinal);
/// <summary>
/// Identifies this run of the shard. It is stable across sidecar reconnects and changes
/// on every shard restart, which is how the sidecar tells "I reconnected" (keep my
/// cached state) from "the shard restarted" (discard it).
/// </summary>
private static string _bootId;
public static void Configure()
{
BridgeConfig.Configure();
}
public static void Initialize()
{
if (!BridgeConfig.Enabled)
{
Console.WriteLine("[Bridge] disabled by config");
return;
}
CommandSystem.Register("bridge", AccessLevel.Administrator, Bridge_OnCommand);
RegisterHandler("ping", OnPing);
BridgeLink.InboundLine += OnInboundLine;
BridgeLink.Connected_Core += EmitHello;
EventSink.ServerStarted += OnServerStarted;
EventSink.Shutdown += OnShutdown;
EventSink.Crashed += OnCrashed;
Console.WriteLine("[Bridge] {0}", BridgeConfig.Describe());
}
/// <summary>Handlers run on the Core thread. They may touch the world freely.</summary>
public static void RegisterHandler(string kind, Action<Dictionary<string, object>> handler)
{
_handlers[kind] = handler;
}
private static void OnServerStarted()
{
_bootId = Guid.NewGuid().ToString("N");
BridgeLink.Start();
}
/// <summary>
/// Core thread, once per connection. The sidecar restarts independently of the shard,
/// so this is sent on every connect rather than once at boot — otherwise a sidecar that
/// came up second would never learn which shard it is talking to.
/// </summary>
private static void EmitHello()
{
BridgeLink.Emit(BridgeJson.Begin("server.hello")
.Str("shard", Server.Misc.ServerList.ServerName)
.Str("bootId", _bootId)
.Num("connects", BridgeLink.Connects)
.Num("items", World.Items.Count)
.Num("mobiles", World.Mobiles.Count)
.Num("accounts", Accounting.Accounts.Count)
.End());
}
private static void OnShutdown(ShutdownEventArgs e)
{
BridgeLink.Emit(BridgeJson.Begin("server.shutdown").End());
// Stop() joins the link thread for up to 2s, which gives the writer a chance to drain
// the goodbye. Best effort: the sidecar must not depend on receiving it.
BridgeLink.Stop();
}
private static void OnCrashed(CrashedEventArgs e)
{
try
{
BridgeLink.Emit(BridgeJson.Begin("server.crashed")
.Str("error", e.Exception == null ? null : e.Exception.Message)
.End());
BridgeLink.Stop();
}
catch
{
// The process is already going down. Never make a crash worse.
}
}
/// <summary>Core thread, one call per inbound line.</summary>
private static void OnInboundLine(string line)
{
var obj = BridgeJson.Parse(line);
if (obj == null)
{
Console.WriteLine("[Bridge] malformed inbound line, ignoring");
return;
}
var kind = BridgeJson.GetString(obj, "kind");
if (kind == null)
return;
Action<Dictionary<string, object>> handler;
if (!_handlers.TryGetValue(kind, out handler))
{
Console.WriteLine("[Bridge] no handler for inbound kind '{0}'", kind);
return;
}
handler(obj);
}
private static void OnPing(Dictionary<string, object> o)
{
var sb = BridgeJson.Begin("pong");
var id = BridgeJson.GetString(o, "id");
if (id != null)
sb.Str("id", id);
BridgeLink.Emit(sb.End());
}
[Usage("bridge [status | reload | ping | sweepnow]")]
[Description("Inspects and controls the sidecar link.")]
private static void Bridge_OnCommand(CommandEventArgs e)
{
var arg = e.Length > 0 ? e.GetString(0).ToLowerInvariant() : "status";
switch (arg)
{
case "reload":
BridgeConfig.Load();
BridgeSweeps.Rearm();
BridgePages.Rearm();
BridgeChamps.Rearm();
BridgeSocial.Rearm();
BridgeGovernance.Rearm();
BridgePresence.Rearm();
BridgeHousing.Rearm();
BridgePoints.Rearm();
BridgeMarket.Rearm();
// Not a sweep, so it has nothing to re-arm — but an operator who just edited a
// .cfg wants the change on the site now, not after a shard restart.
BridgeRuleset.Emit();
e.Mobile.SendMessage("Bridge: {0}", BridgeConfig.Describe());
e.Mobile.SendMessage("Bridge: sweeps re-armed; ruleset re-emitted; endpoint changes take effect on reconnect.");
break;
case "ping":
BridgeLink.Emit(BridgeJson.Begin("ping").End());
e.Mobile.SendMessage("Bridge: ping queued.");
break;
case "sweepnow":
BridgeSweeps.SweepOnce();
BridgeChamps.SweepOnce();
BridgeSocial.SweepOnce();
BridgeGovernance.SweepOnce();
BridgePresence.SweepOnce();
BridgeHousing.SweepOnce();
BridgePoints.SweepOnce();
BridgeMarket.SweepOnce();
e.Mobile.SendMessage("Bridge: ran one sweep of each stream.");
e.Mobile.SendMessage("Bridge: {0}", BridgeSweeps.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeChamps.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeSocial.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeGovernance.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgePresence.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeHousing.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgePoints.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeMarket.Status());
break;
default:
e.Mobile.SendMessage("Bridge: {0}", BridgeConfig.Describe());
e.Mobile.SendMessage(
"Bridge: connected={0} depth={1} sent={2} dropped={3} received={4} connects={5} writeErrors={6}",
BridgeLink.Connected, BridgeLink.Depth, BridgeLink.Sent, BridgeLink.Dropped,
BridgeLink.Received, BridgeLink.Connects, BridgeLink.WriteErrors);
e.Mobile.SendMessage("Bridge: {0}", BridgeSweeps.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeChamps.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeSocial.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeGovernance.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgePresence.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeHousing.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgePoints.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeMarket.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgePages.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeRuleset.Status());
break;
}
}
}
}