Compare commits

...

7 Commits

Author SHA1 Message Date
968b526fac Merge pull request 'feat(bridge)!: Protocol 3.0 cutover — world.ruleset, points.board, vendor.listing' (#6) from edge into main
Reviewed-on: #6
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-08-01 06:33:27 +00:00
7215ae5fe1 Merge pull request 'feat(bridge): publish the player-vendor market index as vendor.listing' (#5) from feat/vendor-listing into edge
Reviewed-on: #5
2026-07-29 20:06:43 +00:00
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
a38afe4c90 Merge pull request 'feat(bridge): publish points/loyalty leaderboards as points.board' (#4) from feat/points-board into edge
Reviewed-on: #4
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-29 07:54:09 +00:00
ed8f568d94 feat(bridge): publish points/loyalty leaderboards as points.board
Protocol 3.0 §7 (docs/link/v3.md). ServUO carries ~25 separate point currencies
— Queen's Loyalty, Void Pool, Casino, Clean Up Britannia, the nine city
loyalties, the Doom/Khaldun/Kotl treasure systems — every one a standing players
build over months, and none of them visible outside an in-game gump until now.

BridgePoints.cs
  - A diff sweep shaped like BridgeHousing: ServerStarted arms the timer, a
    sidecar connect clears the diff state so a fresh sidecar gets every board,
    and each pass emits only the systems whose top N or participant count moved.
    One ~600 B frame per system rather than one 12 KB frame, matching
    champ.update / guild.update. No points.remove — the system set is fixed at
    startup by PointsSystem.Configure, the same argument city.update makes.
  - Selection is a single bounded pass into a fixed N-element array kept sorted
    by insertion, NOT OrderByDescending().Take(N). PlayerTable is a plain List
    and ten of the ~25 systems have AutoAdd = true, so they hold a row for every
    character ever created: the naive version is ~25 full sorts on the Core
    thread, which BRIDGE_PLUGIN_PLAN.md §1 measured as the second thing in the
    bridge capable of blowing a frame budget.
  - Which systems publish defaults to the shard's OWN answer — ShowOnLoyaltyGump
    — rather than a list here that would drift; Bridge.cfg PointsSystems=
    overrides it, and an unrecognised name is logged rather than dropped.
  - Entries are written inline as {serial, name}, never via BridgeJson.Actor. A
    board is the widest-audience surface the bridge has, so acct/webId
    deliberately do not cross the wire; the site resolves serial → user from its
    own link mirror.

char.profile gains a points block, the titles precedent from PROTOCOL_2.md §10.3
  - Never uses PointsSystem.GetEntry/GetPoints: both MUTATE THE WORLD, since
    GetEntry(create: false) still calls AddEntry when the system has AutoAdd
    (PointsSystem.cs:207). Using them would have appended up to ten rows to the
    points save file every time anyone opened a character sheet. Hand-rolled
    read-only scan instead.
  - rank is off by default (PointsProfileRank). A points lookup stops at the
    character's own row; a rank must count every row that beats them, in every
    system, on every profile build.

Verified by running it, not by reading it: the whole Scripts tree (6,207 files)
compiles clean against real ServUO 57.4 assemblies, and a boot against the local
shard with a 43,011-mobile world emitted five live boards. That run caught a bug
no fake shard could — ServUO's uncapped idiom is MaxPoints = double.MaxValue,
and (long) on it is an UNCHECKED conversion yielding long.MinValue, so the first
sweep published "maxPoints": -9223372036854775808 for three of the five boards.
Cap()/Score() now normalise anything unrepresentable, and maxPoints: 0 is the
documented "uncapped" value — which on a real shard is the common case, not an
edge case. Re-verified after the fix: 0 for the uncapped systems, 15000 and
10000 for the two that genuinely cap.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-28 21:04:08 -05:00
a7a383e6d9 Merge pull request 'feat(bridge): emit world.ruleset, the shard's published ruleset' (#3) from feat/bridge-ruleset into edge
Reviewed-on: #3
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-28 20:37:05 +00:00
3fb4b7dc9f feat(bridge): emit world.ruleset, the shard's published ruleset
Protocol 3.0 §5 (docs/link/v3.md). One frame describing how this shard is
actually configured — expansion, which optional systems are on, skill/stat
caps, account and house limits, champion scroll rules, the save/restart
schedule — so the website's rules page cannot drift from the server.

Modelled on BridgeBoot.EmitHello, not on the diff sweeps: the ruleset changes
only when an operator edits a .cfg, so there is nothing to poll. It subscribes
Connected_Core, so a sidecar that comes up second still learns the ruleset,
and `[bridge reload` re-emits for an operator who just edited a file.

The frame is built from an EXPLICIT ALLOWLIST of Config.Get calls. Config.Entries
is never enumerated — that would sweep in every key on the server, secrets
included — and Server.cfg, Staff.cfg, Email.cfg, DataPath.cfg, Bridge.cfg,
Compiler.cfg, Reports.cfg and Client.cfg are named as excluded both here and in
a code comment. The one connection detail published is Bridge.PublicConnectAddress,
blank by default, which an operator sets deliberately for this purpose.

`rev` is FNV-1a over the body so an unchanged reconnect is a site-side no-op.
String.GetHashCode() is deliberately not used: it is seeded per process, so it
would change on every restart and defeat the diff.

Verified by compiling the full ServUO Scripts tree (6,205 files, net48, EJ) with
this overlay substituted for the deployed Bridge copy — clean.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-28 11:14:36 -05:00
7 changed files with 1669 additions and 1 deletions

View File

@@ -48,6 +48,83 @@ PresenceSweepSeconds=30
# house.remove (owner, region, location, decay). Houses change slowly; a few minutes is fine. # house.remove (owner, region, location, decay). Houses change slowly; a few minutes is fine.
HousingSweepSeconds=300 HousingSweepSeconds=300
# Points / loyalty leaderboards (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §7). ServUO carries ~25 point
# currencies (Queen's Loyalty, Void Pool, Casino, Clean Up Britannia, the nine city loyalties,
# the Doom/Khaldun/Kotl treasure systems, …). Each is diffed on this interval and emitted as
# one points.board frame per system when its top N moves.
#
# Slow on purpose: these are month-scale standings, and ten of the systems keep a row for
# every character ever created, so the pass is the widest read in the bridge. It is still
# cheap — a single bounded pass, never a sort — but there is nothing to gain by hurrying it.
PointsSweepSeconds=300
# Master switch for the boards. Off leaves char.profile points alone (see below).
PointsLeaderboardEnabled=true
# How many players per board. Clamped to 1..100 — the frame is emitted PER SYSTEM, so a big
# N is multiplied by ~25.
PointsTopN=10
# Which systems to publish, as a comma-separated list of PointsType names, e.g.
# PointsSystems=QueensLoyalty,CleanUpBritannia,VoidPool
# Blank (the default) publishes whatever the shard itself shows on the in-game loyalty gump
# (ShowOnLoyaltyGump), so a subsystem you add later gets a board without an edit here.
# An unrecognized name is logged and ignored, never silently dropped.
PointsSystems=
# Include a per-character "points" block in char.profile (the website character sheet). This
# is a lookup across every published system's table, so it is the dominant cost of building a
# profile; turn it off on a very large shard that does not want the sheet paying for it.
PointsProfileEnabled=true
# Also compute each system's rank in that block. OFF by default and worth leaving off: a
# points lookup stops at the character's own row, but a rank must count every row that beats
# them, in every system, on every profile build. The website already derives rank from the
# board for anyone in the top N.
PointsProfileRank=false
# Player-vendor market index (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §8). Every player vendor's shop name,
# owner, location and priced inventory, published as one vendor.listing frame per vendor so the
# website can offer the search the in-game Vendor Search gump offers. Honours each player's own
# in-game opt-out (the vendor's VendorSearch flag) — hide your vendor in game and it is hidden
# on the site too.
MarketEnabled=true
# Sweep interval. UNLIKE every other sweep here, a tick does NOT walk the whole world: it
# inventories at most MarketSweepBatch vendors and a persistent cursor round-robins through the
# rest, so the per-tick cost is bounded by the batch rather than by how many vendors exist. Full
# coverage takes ceil(vendors / batch) x MarketSweepSeconds — 500 vendors at the defaults is one
# complete pass every 20 minutes, and the site labels the data with how stale it may be.
#
# Lower this (or raise the batch) for faster coverage; both trade directly against per-tick cost,
# and the expensive part is the item walk, which recurses into every container a vendor is selling.
MarketSweepSeconds=60
MarketSweepBatch=25
# Per-vendor listing cap, after which the frame carries "truncated": true. A commodity reseller
# with thousands of stacked resources is a real thing, and an uncapped frame for one is measured
# in megabytes. Clamped to 1..5000.
MarketMaxListings=250
# Shard ruleset (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §5). One world.ruleset frame — expansion, which
# systems are on, skill/stat caps, account and house limits, champion scroll rules —
# emitted on every sidecar connect (and on [bridge reload), so the website's rules page
# cannot drift from the server. Not a sweep: it changes only when you edit a .cfg.
#
# The frame is built from an explicit allowlist of keys in BridgeRuleset.cs. Server.cfg,
# Staff.cfg, Email.cfg, DataPath.cfg, Bridge.cfg, Compiler.cfg, Reports.cfg and Client.cfg
# are never read.
RulesetEnabled=true
# The one connection detail the bridge will publish, e.g. play.myshard.com,2593. Blank
# (the default) omits it entirely. Server.cfg's Address/Listen/Port are NEVER published —
# if you want a connect string on the site, put it here deliberately.
PublicConnectAddress=
# Include the save/restart schedule (AutoSave frequency, AutoRestart hour) in the frame.
# Turn off if you would rather not advertise a predictable restart window.
RulesetIncludeSchedule=true
# Shown to a player when they run [link. The website page where they enter the code. # Shown to a player when they run [link. The website page where they enter the code.
LinkUrl=https://yoursite/link LinkUrl=https://yoursite/link

View File

@@ -165,8 +165,13 @@ namespace Server.Custom.Bridge
BridgeGovernance.Rearm(); BridgeGovernance.Rearm();
BridgePresence.Rearm(); BridgePresence.Rearm();
BridgeHousing.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: {0}", BridgeConfig.Describe());
e.Mobile.SendMessage("Bridge: sweeps re-armed; endpoint changes take effect on reconnect."); e.Mobile.SendMessage("Bridge: sweeps re-armed; ruleset re-emitted; endpoint changes take effect on reconnect.");
break; break;
case "ping": case "ping":
@@ -181,6 +186,8 @@ namespace Server.Custom.Bridge
BridgeGovernance.SweepOnce(); BridgeGovernance.SweepOnce();
BridgePresence.SweepOnce(); BridgePresence.SweepOnce();
BridgeHousing.SweepOnce(); BridgeHousing.SweepOnce();
BridgePoints.SweepOnce();
BridgeMarket.SweepOnce();
e.Mobile.SendMessage("Bridge: ran one sweep of each stream."); e.Mobile.SendMessage("Bridge: ran one sweep of each stream.");
e.Mobile.SendMessage("Bridge: {0}", BridgeSweeps.Status()); e.Mobile.SendMessage("Bridge: {0}", BridgeSweeps.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeChamps.Status()); e.Mobile.SendMessage("Bridge: {0}", BridgeChamps.Status());
@@ -188,6 +195,8 @@ namespace Server.Custom.Bridge
e.Mobile.SendMessage("Bridge: {0}", BridgeGovernance.Status()); e.Mobile.SendMessage("Bridge: {0}", BridgeGovernance.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgePresence.Status()); e.Mobile.SendMessage("Bridge: {0}", BridgePresence.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeHousing.Status()); e.Mobile.SendMessage("Bridge: {0}", BridgeHousing.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgePoints.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeMarket.Status());
break; break;
default: default:
@@ -202,7 +211,10 @@ namespace Server.Custom.Bridge
e.Mobile.SendMessage("Bridge: {0}", BridgeGovernance.Status()); e.Mobile.SendMessage("Bridge: {0}", BridgeGovernance.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgePresence.Status()); e.Mobile.SendMessage("Bridge: {0}", BridgePresence.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeHousing.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}", BridgePages.Status());
e.Mobile.SendMessage("Bridge: {0}", BridgeRuleset.Status());
break; break;
} }
} }

View File

@@ -35,6 +35,25 @@ namespace Server.Custom.Bridge
public static int CitySweepSeconds { get; private set; } public static int CitySweepSeconds { get; private set; }
public static int PresenceSweepSeconds { get; private set; } public static int PresenceSweepSeconds { get; private set; }
public static int HousingSweepSeconds { get; private set; } public static int HousingSweepSeconds { get; private set; }
public static int PointsSweepSeconds { get; private set; }
public static int MarketSweepSeconds { get; private set; }
// ---- player-vendor market index (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §8) ----
public static bool MarketEnabled { get; private set; }
public static int MarketSweepBatch { get; private set; }
public static int MarketMaxListings { get; private set; }
// ---- points / loyalty leaderboards (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §7) ----
public static bool PointsLeaderboardEnabled { get; private set; }
public static int PointsTopN { get; private set; }
public static string PointsSystems { get; private set; }
public static bool PointsProfileEnabled { get; private set; }
public static bool PointsProfileRank { get; private set; }
// ---- shard ruleset (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §5) ----
public static bool RulesetEnabled { get; private set; }
public static string PublicConnectAddress { get; private set; }
public static bool RulesetIncludeSchedule { get; private set; }
public static string LinkUrl { get; private set; } public static string LinkUrl { get; private set; }
@@ -107,6 +126,73 @@ namespace Server.Custom.Bridge
if (HousingSweepSeconds < 1) if (HousingSweepSeconds < 1)
HousingSweepSeconds = 1; HousingSweepSeconds = 1;
// Points/loyalty boards. The sweep touches every point entry on the shard, and ten of
// the ~25 systems keep a row per character ever created, so the default interval is
// deliberately slow — these are month-scale standings, not live state.
PointsSweepSeconds = Config.Get("Bridge.PointsSweepSeconds", 300);
if (PointsSweepSeconds < 1)
PointsSweepSeconds = 1;
PointsLeaderboardEnabled = Config.Get("Bridge.PointsLeaderboardEnabled", true);
// Board size. Bounded below at 1 because the selection indexes the Nth slot directly,
// and above at 100 because the frame is emitted per system — a large N multiplied by
// ~25 systems is how a "board" turns into a bandwidth problem.
PointsTopN = Config.Get("Bridge.PointsTopN", 10);
if (PointsTopN < 1)
PointsTopN = 1;
if (PointsTopN > 100)
PointsTopN = 100;
// Blank (the default) means "publish whatever the shard itself shows on the loyalty
// gump", so a shard that adds a subsystem gets its board without an edit here.
PointsSystems = Config.Get("Bridge.PointsSystems", "");
PointsProfileEnabled = Config.Get("Bridge.PointsProfileEnabled", true);
// Off by default, and the default is the point: a rank cannot early-exit the way a
// points lookup can — it must count every row that beats the player, in every system,
// on every profile build. See BridgeProfile.WritePoints.
PointsProfileRank = Config.Get("Bridge.PointsProfileRank", false);
// Player-vendor market index. Unlike every other sweep, this one does NOT walk its whole
// collection per tick: MarketSweepBatch caps how many vendors are inventoried, and a
// persistent cursor round-robins through the rest, so the per-tick cost is bounded by
// the batch rather than by how many vendors the world holds.
MarketEnabled = Config.Get("Bridge.MarketEnabled", true);
MarketSweepSeconds = Config.Get("Bridge.MarketSweepSeconds", 60);
if (MarketSweepSeconds < 1)
MarketSweepSeconds = 1;
// Bounded below at 1 (a batch of 0 would advance the cursor nowhere and publish nothing,
// silently) and above at 500, past which the batch stops bounding anything on any
// realistic shard and the tick is a whole-world pass by another name.
MarketSweepBatch = Config.Get("Bridge.MarketSweepBatch", 25);
if (MarketSweepBatch < 1)
MarketSweepBatch = 1;
if (MarketSweepBatch > 500)
MarketSweepBatch = 500;
// Per-vendor listing cap. BridgeJson.Parse caps INBOUND frames at 1 MB; outbound is
// uncapped and the sidecar's read_line will allocate whatever arrives, so the cap here
// is what keeps one commodity reseller with 8,000 stacked resources from emitting a
// multi-megabyte frame. Over the cap the frame carries "truncated": true and the site
// says so.
MarketMaxListings = Config.Get("Bridge.MarketMaxListings", 250);
if (MarketMaxListings < 1)
MarketMaxListings = 1;
if (MarketMaxListings > 5000)
MarketMaxListings = 5000;
// The ruleset frame is not a sweep — it is emitted once per sidecar connect (and on
// `[bridge reload`), so it has no interval. PublicConnectAddress is the ONE connection
// detail the bridge will publish, and only because an operator typed it here for that
// purpose; Server.cfg's Address/Port are never read (see BridgeRuleset's allowlist note).
RulesetEnabled = Config.Get("Bridge.RulesetEnabled", true);
PublicConnectAddress = Config.Get("Bridge.PublicConnectAddress", "");
RulesetIncludeSchedule = Config.Get("Bridge.RulesetIncludeSchedule", true);
LinkUrl = Config.Get("Bridge.LinkUrl", "https://yoursite/link"); LinkUrl = Config.Get("Bridge.LinkUrl", "https://yoursite/link");
TownCrierMaxLines = Config.Get("Bridge.TownCrierMaxLines", 6); TownCrierMaxLines = Config.Get("Bridge.TownCrierMaxLines", 6);

View File

@@ -0,0 +1,591 @@
using System;
using System.Collections.Generic;
using System.Text;
using Server.Items;
using Server.Mobiles;
using Server.Multis;
using Server.Engines.VendorSearching;
namespace Server.Custom.Bridge
{
/// <summary>
/// The shard-wide player-vendor index (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §8). Every player vendor's
/// shop name, owner, location and priced inventory, published as one authoritative
/// <c>vendor.listing</c> frame per vendor, so the website can offer the search the in-game
/// Vendor Search gump offers — from outside the game.
///
/// ---- Why this is a sweep and not an RPC ----
///
/// The obvious shape is a <c>market.snapshot</c> request/reply like vendor.snapshot next
/// door. It cannot work: the sidecar's rpc router correlates on the FIRST frame carrying a
/// matching reqId and resolves a single oneshot, 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 in one frame is not an option either — the reply timeout is 10 s and
/// 40,000 listings do not serialize in time.
///
/// So it is a diff sweep on the broadcast stream, shaped like <see cref="BridgeHousing"/>:
/// one frame per vendor, authoritative for that vendor, plus vendor.listing.remove when one
/// goes away. The per-account <c>vendor.snapshot</c> RPC is untouched; the player portal
/// keeps using it.
///
/// ---- The two perf traps, and what this does about them ----
///
/// 1. **VendorSearch.GetItemName is a packet builder, not a field read.** It constructs an
/// ObjectPropertyList, calls GetProperties, serialises it and then byte-parses the
/// resulting packet — PER ITEM. Across a full pass that is a multi-hundred-millisecond
/// stall on the Core thread. It is never called here. The frame carries `itemId`, `hue`,
/// `amount`, `price`, the plain `item.Name` field (null for most items) and
/// `item.LabelNumber`; the website resolves display names against its own cliloc table,
/// exactly as char.profile.equipment already does.
///
/// (On any modern client the call would not even work: every current client ships its
/// Cliloc.* files compressed, ServUO's bundled Ultima.StringList reads only the old plain
/// layout, so VendorSearch.StringList is null and GetItemName returns item.Name anyway.
/// The in-game gump has the same gap.)
///
/// 2. **A full pass is unbounded in world size.** 500 vendors × 80 listings is ~40,000 item
/// reads, and the reusable public GetItems(Container, List&lt;Item&gt;) recurses into
/// sub-containers, so the real count runs ABOVE the top-level pack.Items a naive estimate
/// would use. So the sweep is amortized: a persistent round-robin cursor over
/// PlayerVendor.PlayerVendors advances at most MarketSweepBatch vendors per tick, which
/// makes the PER-TICK cost bounded independently of how many vendors exist. Full coverage
/// takes ceil(vendors / batch) × MarketSweepSeconds. This is the one genuinely new pattern
/// versus the other sweeps, which all walk their whole collection every tick.
///
/// ---- Privacy ----
///
/// `pv.VendorSearch` is ServUO's own per-vendor opt-out and DoSearch filters on it, so a
/// player who hid their vendor in game is hidden on the website too: an opted-out vendor is
/// skipped entirely and the seen-set removal then drops it from the board. Map.Internal and
/// a null Backpack are skipped for the same reason DoSearch skips them.
///
/// Owner is written as flat `ownerSerial`/`ownerName` — never through BridgeJson.Actor,
/// which would add `acct` and `webId`. Same argument BridgePoints makes: this is the widest-
/// audience surface the bridge has, and the site resolves serial → user from its own
/// shard_account_links mirror when staff need it.
/// </summary>
public static class BridgeMarket
{
private static Timer _timer;
// vendor serial -> last-emitted signature.
private static readonly Dictionary<Serial, string> _last = new Dictionary<Serial, string>();
// Round-robin cursor: an INDEX into PlayerVendor.PlayerVendors, not a serial. The list is
// mutated by placement/deletion between ticks, so the cursor is a hint, not a promise — it
// is wrapped and clamped every tick, and a shifted list at worst re-visits or defers a
// vendor by one cycle. Tracking a serial instead would cost a lookup to find "where was I"
// and buy nothing: the sweep is idempotent per vendor.
private static int _cursor;
private static long _sweeps, _emitted, _removed, _scanned, _skipped, _truncated;
// Per-tick cost, in milliseconds. Reported by `[bridge status` because the
// whole design of this sweep is a claim about that number — the batch cap is what makes it
// independent of world size — and an operator tuning MarketSweepBatch is otherwise tuning
// blind. `_maxMs` is the one that matters: the Core thread runs this between frames, so the
// worst tick is the budget, not the average.
private static double _lastMs, _maxMs;
private static readonly System.Diagnostics.Stopwatch _clock = new System.Diagnostics.Stopwatch();
// Reused across ticks. The item walk is single-threaded (Core thread) and the list is
// cleared before each vendor, so one buffer serves the whole sweep — the alternative is a
// fresh List<Item> per vendor per tick, which at 25 vendors × every 60 s is pure garbage.
private static readonly List<Item> _items = new List<Item>();
public static void Initialize()
{
if (!BridgeConfig.Enabled)
return;
EventSink.ServerStarted += OnServerStarted;
}
private static void OnServerStarted()
{
BridgeLink.Connected_Core += OnConnected;
Rearm();
}
private static void OnConnected()
{
// A new sidecar knows nothing, so drop the diff state and start the round-robin from
// the top. The re-emit of the whole world is self-throttled by the batch window — this
// is the one place the amortized sweep pays for itself twice, because a reconnect on a
// whole-world sweep would otherwise be the biggest burst the bridge ever produces.
_last.Clear();
_cursor = 0;
}
/// <summary>Stops and recreates the timer from current config. Called by `[bridge reload`.</summary>
public static void Rearm()
{
Stop();
_timer = Timer.DelayCall(
TimeSpan.FromSeconds(BridgeConfig.MarketSweepSeconds),
TimeSpan.FromSeconds(BridgeConfig.MarketSweepSeconds),
MarketSweep);
}
public static void Stop()
{
if (_timer != null) { _timer.Stop(); _timer = null; }
}
/// <summary>
/// A bare (key-less) string value, or JSON null.
///
/// <see cref="BridgeJson.Escape"/> takes a non-null string — it dereferences
/// <c>value.Length</c> immediately — and <see cref="BridgeJson.Str"/> writes the `,"key":`
/// prefix itself, so neither serves a value written inside a hand-built object. Most of
/// what this frame writes is legitimately null (an item's plain Name is null for nearly
/// every item, a vendor standing in the street has no house), so this is the common path
/// rather than an edge case.
/// </summary>
private static void Text(StringBuilder sb, string value)
{
if (value == null)
sb.Append("null");
else
BridgeJson.Escape(sb, value);
}
public static string Status()
{
var all = PlayerVendor.PlayerVendors;
return String.Format(
"market(enabled={0} sweeps={1} scanned={2} emitted={3} removed={4} skipped={5} truncated={6} tracked={7} vendors={8} cursor={9} batch={10} lastMs={11:F2} maxMs={12:F2})",
BridgeConfig.MarketEnabled, _sweeps, _scanned, _emitted, _removed, _skipped,
_truncated, _last.Count, all == null ? 0 : all.Count, _cursor,
BridgeConfig.MarketSweepBatch, _lastMs, _maxMs);
}
/// <summary>Runs one sweep now. Wired into `[bridge sweepnow`.</summary>
public static void SweepOnce()
{
MarketSweep();
}
/// <summary>
/// One tick: at most <c>MarketSweepBatch</c> vendors starting at the cursor, then the
/// removal pass.
///
/// The removal pass is the part the batching makes subtle. `_last` holds every vendor
/// seen in ANY previous tick, but this tick only visited a window — so "not in this
/// tick's seen set" does NOT mean gone. Removals are therefore decided against the
/// CURRENT vendor list (plus the opt-out/validity rules), not against the window, which
/// is a cheap pass over serials rather than a second inventory walk.
/// </summary>
private static void MarketSweep()
{
try
{
if (!BridgeConfig.MarketEnabled)
return;
_sweeps++;
if (!BridgeLink.Connected)
return; // nothing is listening; do not fill the queue with perishable snapshots
_clock.Restart();
var all = PlayerVendor.PlayerVendors;
if (all == null || all.Count == 0)
{
Reap(null);
return;
}
// A live set of every serial that SHOULD be on the board right now, built as the
// window is walked plus a cheap pass over the rest. Built here rather than reusing
// a field so a throwing vendor cannot leave a half-built set behind.
var present = new HashSet<Serial>();
var count = all.Count;
var batch = Math.Min(BridgeConfig.MarketSweepBatch, count);
if (_cursor >= count)
_cursor = 0;
for (int i = 0; i < count; i++)
{
var vendor = all[i];
if (Eligible(vendor))
present.Add(vendor.Serial);
}
for (int n = 0; n < batch; n++)
{
var index = (_cursor + n) % count;
var vendor = all[index];
if (!Eligible(vendor))
{
_skipped++;
continue;
}
// One bad vendor must not cost the rest of the window: the item walk touches
// arbitrary Item subclasses on a shard running modified scripts.
try
{
SweepVendor(vendor);
}
catch (Exception ex)
{
Console.WriteLine("[Bridge] market sweep threw for 0x{0:X}: {1}",
vendor.Serial.Value, ex.Message);
}
}
_cursor = count == 0 ? 0 : (_cursor + batch) % count;
Reap(present);
}
catch (Exception ex)
{
Console.WriteLine("[Bridge] market sweep threw: {0}", ex.Message);
}
finally
{
// In `finally` so a throwing tick still records what it cost — a sweep that blows
// the budget and then throws is exactly the one worth seeing in the status line.
if (_clock.IsRunning)
{
_clock.Stop();
_lastMs = _clock.Elapsed.TotalMilliseconds;
if (_lastMs > _maxMs)
_maxMs = _lastMs;
WarnIfSlow();
}
}
}
/// <summary>
/// Per-tick budget, milliseconds. The batch cap exists to hold a tick under this
/// regardless of world size, so exceeding it means MarketSweepBatch is too large for
/// this shard's shops — the one thing an operator needs told, and the one thing
/// `[bridge status` cannot tell them unprompted. Generous: a tick is off the frame
/// budget, and the alternative to a rare 50 ms tick is a permanently stale market.
/// </summary>
private const double SlowTickMs = 50.0;
// At most one warning a minute. A shard whose batch is genuinely too big would otherwise
// print every MarketSweepSeconds forever, and a log nobody can read is a log nobody reads.
private static DateTime _lastWarn = DateTime.MinValue;
private static void WarnIfSlow()
{
if (_lastMs <= SlowTickMs)
return;
var now = DateTime.UtcNow;
if (now - _lastWarn < TimeSpan.FromMinutes(1))
return;
_lastWarn = now;
Console.WriteLine(
// ASCII only. The ServUO console writes in the OS code page, so an em dash here
// renders as "???" in the log an operator would paste into an issue.
"[Bridge] market sweep took {0:F1} ms (budget {1:F0} ms) - lower Bridge.MarketSweepBatch (now {2}) if this persists",
_lastMs, SlowTickMs, BridgeConfig.MarketSweepBatch);
}
/// <summary>
/// The same filter DoSearch applies, so the website's index is the in-game index.
/// <c>VendorSearch</c> is the player's own opt-out toggle and is honoured first.
/// </summary>
private static bool Eligible(PlayerVendor vendor)
{
return vendor != null
&& !vendor.Deleted
&& vendor.VendorSearch
&& vendor.Map != null
&& vendor.Map != Map.Internal
&& vendor.Backpack != null;
}
/// <summary>
/// Drops from the board every tracked vendor that is no longer eligible.
/// <paramref name="present"/> null means "there are no vendors at all", which clears it.
/// </summary>
private static void Reap(HashSet<Serial> present)
{
if (_last.Count == 0)
return;
List<Serial> gone = null;
foreach (var serial in _last.Keys)
{
if (present != null && present.Contains(serial))
continue;
if (gone == null)
gone = new List<Serial>();
gone.Add(serial);
}
if (gone == null)
return;
for (int i = 0; i < gone.Count; i++)
{
_last.Remove(gone[i]);
BridgeLink.Emit(BridgeJson.Begin("vendor.listing.remove").Ser("serial", gone[i]).End());
_removed++;
}
}
private static void SweepVendor(PlayerVendor vendor)
{
_scanned++;
CollectItems(vendor);
var sig = Signature(vendor);
string prior;
if (_last.TryGetValue(vendor.Serial, out prior) && prior == sig)
return; // nothing about this shop changed since it was last published
_last[vendor.Serial] = sig;
BridgeLink.Emit(WriteVendor(vendor));
_emitted++;
}
/// <summary>
/// Every sellable item on one vendor, into the shared buffer.
///
/// Mirrors VendorSearch's own private GetItems(PlayerVendor): the vendor's own movable
/// equipment (minus the backpack itself and hair layers, which are not merchandise)
/// followed by a recursive walk of the backpack. The recursion uses the PUBLIC
/// GetItems(Container, List&lt;Item&gt;) rather than a hand-rolled one so that ServUO's
/// rule about which containers are sold whole (quivers, seed boxes, jewelry boxes, …)
/// stays ServUO's to define — the predicate that decides it is private, and a copy here
/// would silently diverge the first time that list changes.
/// </summary>
private static void CollectItems(PlayerVendor vendor)
{
_items.Clear();
var own = vendor.Items;
if (own != null)
{
for (int i = 0; i < own.Count; i++)
{
var item = own[i];
if (item == null || !item.Movable || item == vendor.Backpack)
continue;
if (item.Layer == Layer.Hair || item.Layer == Layer.FacialHair)
continue;
_items.Add(item);
}
}
if (vendor.Backpack != null)
VendorSearch.GetItems(vendor.Backpack, _items);
}
/// <summary>
/// A listing's price, and whether it was priced by an enclosing container.
///
/// ServUO prices a container as a unit: an item inside a priced bag has no VendorItem of
/// its own and inherits the bag's price, which DoSearch surfaces as `isChild`. Reproduced
/// exactly, because a website that priced every item in a 40k bag at 40k would be lying
/// about the shard.
/// </summary>
private static int PriceOf(PlayerVendor vendor, Item item, out bool child)
{
child = false;
var vi = vendor.GetVendorItem(item);
if (vi != null)
return vi.Price;
var parent = item.Parent as Container;
while (parent != null)
{
vi = vendor.GetVendorItem(parent);
if (vi != null)
{
child = true;
return vi.Price;
}
parent = parent.Parent as Container;
}
return 0;
}
/// <summary>
/// The diff key. Location, shop name and owner are in it because they move a vendor's
/// row on the site; every listing's serial, price and amount are in it because those are
/// what a shopper searches on.
///
/// Built over the SAME buffer the frame is written from, in the same order, so a
/// signature match really does mean an identical frame — a cheaper hash (count + a sum
/// of serial^price, as §8.3 first proposed) collides on the common case of two items
/// swapping prices, which is exactly what re-pricing a shop looks like.
/// </summary>
private static string Signature(PlayerVendor vendor)
{
var sb = new StringBuilder(256);
sb.Append(vendor.ShopName ?? "").Append('|');
sb.Append(vendor.Owner == null ? 0 : vendor.Owner.Serial.Value).Append('|');
sb.Append(vendor.Map == null ? "" : vendor.Map.Name).Append('|');
sb.Append(vendor.X).Append(',').Append(vendor.Y).Append('|');
var limit = Math.Min(_items.Count, BridgeConfig.MarketMaxListings);
sb.Append(_items.Count).Append('|');
for (int i = 0; i < limit; i++)
{
var item = _items[i];
if (item == null || item.Deleted)
continue;
bool child;
var price = PriceOf(vendor, item, out child);
if (price <= 0)
continue;
sb.Append(item.Serial.Value.ToString("X")).Append(':')
.Append(price).Append(':')
.Append(item.Amount).Append(';');
}
return sb.ToString();
}
/// <summary>
/// One vendor frame — authoritative for that vendor, so the website replaces its whole
/// listing set from it rather than merging.
///
/// `location` is one nested object rather than flat map/x/y/region because it is ONE
/// admin-configurable field on the site (`market.location`): the visibility projection
/// matches literal JSON keys, so a nested object is what lets a single rule hide a
/// vendor's whereabouts on both the live frame and the stored read model. Flat keys
/// would need five rules that could drift apart.
///
/// `count` is the number of listings PUBLISHED, and `truncated` says the shop holds
/// more. A shop over the cap is a real thing (commodity resellers run thousands of
/// stacks) and the site says so rather than quietly showing a partial shop as complete.
/// </summary>
private static string WriteVendor(PlayerVendor vendor)
{
var sb = BridgeJson.Begin("vendor.listing")
.Ser("serial", vendor.Serial)
.Str("shopName", vendor.ShopName);
var owner = vendor.Owner;
if (owner != null)
{
sb.Ser("ownerSerial", owner.Serial);
sb.Str("ownerName", owner.Name);
}
sb.Append(",\"location\":{\"map\":");
Text(sb, vendor.Map == null ? null : vendor.Map.Name);
sb.Append(",\"x\":").Append(vendor.X);
sb.Append(",\"y\":").Append(vendor.Y);
sb.Append(",\"z\":").Append(vendor.Z);
var region = vendor.Region;
sb.Append(",\"region\":");
Text(sb, region == null ? null : region.Name);
// The house name is the sign's, which is what a player would be told to look for
// ("Bob's Villa"), not the house type. Null for a vendor standing outside one.
var house = vendor.House;
var sign = house == null ? null : house.Sign;
sb.Append(",\"house\":");
Text(sb, sign == null ? null : sign.GetName());
sb.Append('}');
var max = BridgeConfig.MarketMaxListings;
var published = 0;
var considered = 0;
var items = new StringBuilder(512);
for (int i = 0; i < _items.Count; i++)
{
var item = _items[i];
if (item == null || item.Deleted)
continue;
bool child;
var price = PriceOf(vendor, item, out child);
// Unpriced items are inventory, not listings — DoSearch drops them the same way.
if (price <= 0)
continue;
considered++;
if (published >= max)
continue;
if (published > 0)
items.Append(',');
items.Append("{\"serial\":\"0x").Append(item.Serial.Value.ToString("X")).Append('"');
items.Append(",\"itemId\":").Append(item.ItemID);
items.Append(",\"hue\":").Append(item.Hue);
items.Append(",\"amount\":").Append(item.Amount);
items.Append(",\"price\":").Append(price);
// The PLAIN Name field, which is null for most items — never GetItemName, which
// builds and parses a property packet per item. LabelNumber is the cliloc the
// website resolves against its own table.
items.Append(",\"name\":");
Text(items, item.Name);
items.Append(",\"cliloc\":").Append(item.LabelNumber);
if (child)
items.Append(",\"child\":true");
items.Append('}');
published++;
}
sb.Num("count", published);
sb.Num("total", considered);
sb.Bool("truncated", considered > published);
if (considered > published)
_truncated++;
sb.Append(",\"items\":[").Append(items).Append(']');
return sb.End();
}
}
}

View File

@@ -0,0 +1,404 @@
using System;
using System.Collections.Generic;
using System.Text;
using Server.Engines.Points;
namespace Server.Custom.Bridge
{
/// <summary>
/// Points / loyalty leaderboards (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §7). ServUO carries ~25 separate point
/// currencies (Queen's Loyalty, Void Pool, Casino, Clean Up Britannia, the nine city
/// loyalties, Blackthorn, the Doom/Khaldun/Kotl treasure systems, …), every one of them a
/// standing a player accumulates over months — and none of them has ever been visible
/// anywhere but an in-game gump. This is the diff sweep that publishes them as boards.
///
/// Shaped like <see cref="BridgeHousing"/>: ServerStarted arms a timer, a sidecar connect
/// clears the diff state so a fresh sidecar gets every board, and each pass emits only the
/// systems whose top N actually moved. One frame per system (~600 B) rather than one 12 KB
/// frame, matching champ.update / guild.update.
///
/// **There is no `points.remove`.** The set of systems is fixed at Configure() time by
/// PointsSystem.Configure — a system cannot disappear at runtime — which is the same
/// argument city.update already makes for cities.
///
/// ---- The perf trap, and why the selection looks like this ----
///
/// `PlayerTable` is a plain List&lt;PointsEntry&gt;, and QueensLoyalty has AutoAdd = true, so it
/// holds an entry for every PlayerMobile that has ever logged in — zero-point rows included.
/// The obvious `.OrderByDescending(e =&gt; e.Points).Take(N)` is a full sort PER SYSTEM: at
/// 20,000 historical characters that is ~25 sorts and ~7.5 M comparisons on the Core thread,
/// tens of milliseconds, which BRIDGE_PLUGIN_PLAN.md §1 measured as the second thing in the
/// whole bridge capable of blowing a frame budget (bulk profile generation being the first).
///
/// So: a single pass per system into a fixed N-element array kept sorted by insertion.
/// O(n·N) with tiny constants, one allocation for the whole sweep, and the common case is a
/// single comparison against the running Nth place before the row is rejected. ~500 k cheap
/// iterations per pass at the default 300 s interval.
/// </summary>
public static class BridgePoints
{
private static Timer _timer;
// PointsType name -> last-emitted signature.
private static readonly Dictionary<string, string> _last =
new Dictionary<string, string>(StringComparer.Ordinal);
private static long _sweeps, _emitted;
// Reused across systems and across sweeps: the selection is single-threaded (Core thread)
// and fully overwritten each time, so there is nothing to allocate per pass.
private static PointsEntry[] _top = new PointsEntry[0];
public static void Initialize()
{
if (!BridgeConfig.Enabled)
return;
EventSink.ServerStarted += OnServerStarted;
}
private static void OnServerStarted()
{
BridgeLink.Connected_Core += OnConnected;
Rearm();
}
private static void OnConnected()
{
// A new sidecar knows nothing; drop the diff state so the next pass re-emits every board.
_last.Clear();
}
/// <summary>Stops and recreates the timer from current config. Called by `[bridge reload`.</summary>
public static void Rearm()
{
Stop();
_timer = Timer.DelayCall(
TimeSpan.FromSeconds(BridgeConfig.PointsSweepSeconds),
TimeSpan.FromSeconds(BridgeConfig.PointsSweepSeconds),
PointsSweep);
}
public static void Stop()
{
if (_timer != null) { _timer.Stop(); _timer = null; }
}
public static string Status()
{
return String.Format("points(enabled={0} sweeps={1} emitted={2} tracked={3} topN={4})",
BridgeConfig.PointsLeaderboardEnabled, _sweeps, _emitted, _last.Count,
BridgeConfig.PointsTopN);
}
/// <summary>Runs one sweep now. Wired into `[bridge sweepnow`.</summary>
public static void SweepOnce()
{
PointsSweep();
}
private static void PointsSweep()
{
try
{
if (!BridgeConfig.PointsLeaderboardEnabled)
return;
_sweeps++;
if (!BridgeLink.Connected)
return; // nothing is listening; do not fill the queue with perishable snapshots
// Systems is a mutable static populated by ~25 separate subsystem constructors in
// PointsSystem.Configure(). It is null before that runs and could in principle hold
// a null element, so neither is assumed.
var systems = PointsSystem.Systems;
if (systems == null)
return;
var selected = SelectedSystems();
var n = BridgeConfig.PointsTopN;
if (_top.Length != n)
_top = new PointsEntry[n];
for (int i = 0; i < systems.Count; i++)
{
var sys = systems[i];
if (sys == null)
continue;
// One bad system must not cost the rest of the sweep: Name/MaxPoints are
// abstract members implemented by 25 unrelated subsystems, any of which could
// throw on a shard running modified scripts.
try
{
SweepSystem(sys, selected);
}
catch (Exception ex)
{
Console.WriteLine("[Bridge] points sweep threw for {0}: {1}",
sys.Loyalty, ex.Message);
}
}
}
catch (Exception ex)
{
Console.WriteLine("[Bridge] points sweep threw: {0}", ex.Message);
}
}
private static void SweepSystem(PointsSystem sys, HashSet<string> selected)
{
var key = sys.Loyalty.ToString();
if (!IsPublished(sys, key, selected))
return;
int ranked;
var count = SelectTop(sys, out ranked);
var sig = Signature(count, ranked);
string prior;
if (_last.TryGetValue(key, out prior) && prior == sig)
return; // top N and participant count both unchanged since last emit
_last[key] = sig;
BridgeLink.Emit(WriteBoard(sys, key, count, ranked));
_emitted++;
}
/// <summary>
/// Which systems are published. The default is the shard's OWN answer to "is this
/// player-facing?" — ShowOnLoyaltyGump, the flag that decides whether a system appears
/// on the in-game loyalty gump — rather than a list invented here that would drift from
/// the server every time a subsystem is added. `Bridge.cfg PointsSystems=` overrides it
/// with an explicit comma-separated list of PointsType names.
/// </summary>
private static bool IsPublished(PointsSystem sys, string key, HashSet<string> selected)
{
if (selected != null)
return selected.Contains(key);
return sys.ShowOnLoyaltyGump;
}
// Parsed form of BridgeConfig.PointsSystems, rebuilt when the raw string changes so
// `[bridge reload` picks up an edit without a restart. null == "no override, use
// ShowOnLoyaltyGump".
private static string _selectedRaw;
private static HashSet<string> _selected;
private static HashSet<string> SelectedSystems()
{
var raw = BridgeConfig.PointsSystems ?? "";
if (raw == _selectedRaw)
return _selected;
_selectedRaw = raw;
_selected = null;
if (raw.Trim().Length == 0)
return null;
var set = new HashSet<string>(StringComparer.Ordinal);
foreach (var part in raw.Split(','))
{
var name = part.Trim();
if (name.Length == 0)
continue;
// Resolve through the enum so a typo is reported loudly rather than silently
// publishing one board fewer than the operator asked for.
PointsType parsed;
if (Enum.TryParse(name, true, out parsed) && Enum.IsDefined(typeof(PointsType), parsed))
set.Add(parsed.ToString());
else
Console.WriteLine("[Bridge] unknown PointsSystems entry '{0}', ignoring", name);
}
_selected = set;
return _selected;
}
/// <summary>
/// Single pass over one system's PlayerTable, keeping the best <c>_top.Length</c> entries
/// in descending order. Returns how many slots were filled; <paramref name="ranked"/>
/// receives the number of players actually holding points.
///
/// Ties do not displace (the shift test is strict, and the reject test is inclusive), so
/// an unchanged table produces an unchanged board — which is what makes the diff
/// signature meaningful rather than a source of spurious re-emits.
/// </summary>
private static int SelectTop(PointsSystem sys, out int ranked)
{
ranked = 0;
var table = sys.PlayerTable;
var top = _top;
if (table == null || top.Length == 0)
return 0;
var count = 0;
for (int i = 0; i < table.Count; i++)
{
var entry = table[i];
if (entry == null)
continue;
var player = entry.Player;
// A deleted character keeps its row until the next save/load cycle, and AutoAdd
// systems are mostly zero-point rows. Neither belongs on a leaderboard.
if (player == null || player.Deleted || entry.Points <= 0)
continue;
ranked++;
var points = entry.Points;
// The common case for a big table: worse than the running Nth place, one compare.
if (count == top.Length && points <= top[count - 1].Points)
continue;
var pos = count < top.Length ? count : top.Length - 1;
while (pos > 0 && top[pos - 1].Points < points)
{
top[pos] = top[pos - 1];
pos--;
}
top[pos] = entry;
if (count < top.Length)
count++;
}
return count;
}
/// <summary>
/// A system's point ceiling as a whole number, or **0 meaning "uncapped"**.
///
/// `MaxPoints` is a double, and ServUO's idiom for "no cap" is `double.MaxValue`
/// (DespiseCrystals, ShameCrystals and VoidPool all do this). A plain `(long)` cast of
/// that is an UNCHECKED conversion — it does not throw, it produces `long.MinValue` —
/// which is exactly what the first sweep against a real shard published:
/// `"maxPoints": -9223372036854775808`. Anything not representable as a positive long
/// therefore becomes 0, which the website already renders as "no maximum".
/// </summary>
internal static long Cap(double value)
{
// NaN first: every comparison against NaN is false, so it would otherwise fall through
// to the same unchecked cast.
if (Double.IsNaN(value) || value <= 0 || value >= 9.2233720368547758E18)
return 0;
return (long)value;
}
/// <summary>
/// A score as a whole number. Same unchecked-cast hazard as <see cref="Cap"/>, but the
/// saturating direction is the opposite: an implausibly large score is still a large
/// score, so it clamps to long.MaxValue rather than collapsing to 0.
/// </summary>
internal static long Score(double value)
{
if (Double.IsNaN(value) || value <= 0)
return 0;
if (value >= 9.2233720368547758E18)
return Int64.MaxValue;
return (long)value;
}
/// <summary>
/// The diff key: every published serial and its whole-point score, plus the participant
/// count. Points are compared exactly as they are emitted, so a fractional award that
/// does not move the displayed number does not cost a frame either.
/// </summary>
private static string Signature(int count, int ranked)
{
var sb = new StringBuilder(64);
sb.Append(ranked).Append('|');
for (int i = 0; i < count; i++)
{
var entry = _top[i];
sb.Append(entry.Player.Serial.Value.ToString("X"))
.Append(':')
.Append(Score(entry.Points))
.Append(';');
}
return sb.ToString();
}
/// <summary>
/// One board frame.
///
/// `nameString` AND `nameNumber` are both emitted because Name is a TextDefinition, which
/// may carry either a literal or a cliloc id — the same contract titles.reward already
/// documents at BridgeProfile.cs:107-110. Resolving clilocs is the website's job.
///
/// **Entries are written inline as {serial, name} — never through BridgeJson.Actor.**
/// That is deliberate even though the website can now reveal fields by audience rung:
/// Actor would add `acct` and `webId`, and neither is needed here, because the site
/// resolves serial → user from its own shard_account_links mirror for staff views. A
/// board is the widest-audience surface the bridge has; the account name of every ranked
/// player has no business crossing the wire to reach it.
/// </summary>
private static string WriteBoard(PointsSystem sys, string key, int count, int ranked)
{
var name = sys.Name;
var sb = BridgeJson.Begin("points.board")
.Str("system", key)
.Str("nameString", name == null ? null : name.String)
.Num("nameNumber", name == null ? 0 : name.Number)
.Num("maxPoints", Cap(sys.MaxPoints))
.Bool("showOnGump", sys.ShowOnLoyaltyGump)
// Players actually HOLDING points, not PlayerTable.Count: an AutoAdd system has a
// zero-point row for every character that ever logged in, so the raw count would
// report the shard's whole character census as this system's participants.
.Num("players", ranked);
sb.Append(",\"top\":[");
for (int i = 0; i < count; i++)
{
var entry = _top[i];
if (i > 0)
sb.Append(',');
sb.Append("{\"rank\":").Append(i + 1);
sb.Append(",\"serial\":\"0x").Append(entry.Player.Serial.Value.ToString("X")).Append('"');
sb.Append(",\"name\":");
BridgeJson.Escape(sb, entry.Player.Name ?? "");
// Whole points: every one of these systems awards and displays integers in game,
// and a board that renders 29500.00000000001 would be a bug report.
sb.Append(",\"points\":").Append(Score(entry.Points));
sb.Append('}');
}
sb.Append(']');
return sb.End();
}
}
}

View File

@@ -2,6 +2,7 @@ using System;
using System.Text; using System.Text;
using Server.Accounting; using Server.Accounting;
using Server.Engines.Points;
using Server.Items; using Server.Items;
using Server.Mobiles; using Server.Mobiles;
@@ -99,6 +100,7 @@ namespace Server.Custom.Bridge
sb.Append(']'); sb.Append(']');
WriteTitles(sb, m); WriteTitles(sb, m);
WritePoints(sb, m);
return sb.End(); return sb.End();
} }
@@ -147,6 +149,147 @@ namespace Server.Custom.Bridge
sb.Append("]}"); sb.Append("]}");
} }
/// <summary>
/// The point/loyalty standings this character holds (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §7.3). Read-model
/// enrichment on an existing kind, exactly like <see cref="WriteTitles"/> — there is no
/// request kind for "one character's points", because the profile is already the place
/// the website asks for everything about one character.
///
/// Systems with no entry, or an entry at zero, are omitted: ten of the ~25 systems have
/// AutoAdd = true and therefore hold a zero-point row for every character that has ever
/// logged in, so emitting them all would be ~25 lines of noise on every sheet.
///
/// **Never call PointsSystem.GetEntry / GetPoints here.** Both look benign and both
/// MUTATE THE WORLD: `GetEntry(from, create: false)` still calls AddEntry when the system
/// has AutoAdd (PointsSystem.cs:207), which appends a row to PlayerTable and fires
/// OnPlayerAdded. A read model that used them would silently grow the points save file by
/// up to ten rows every time anyone viewed a character sheet. Hence the manual scan.
///
/// Cost: one early-exiting pass over each published system's PlayerTable. The AutoAdd
/// tables are census-sized, so this is the dominant term in the profile — roughly 10 × n
/// comparisons, against the ~0.069 ms/2.4 KB the rest of the profile measures at. That is
/// acceptable because profiles are built on demand at human rates and never in a sweep;
/// PointsProfileEnabled turns it off for a shard where it isn't.
///
/// **Deliberately no `rank`.** Rank cannot early-exit — it must count every row that
/// beats the player, in every system, every time — and the website can derive it from
/// the points.board frame for anyone who is actually on a board. See PointsProfileRank.
/// </summary>
private static void WritePoints(StringBuilder sb, PlayerMobile m)
{
if (!BridgeConfig.PointsProfileEnabled)
return;
sb.Append(",\"points\":[");
try
{
var systems = PointsSystem.Systems;
if (systems != null)
{
bool first = true;
for (int i = 0; i < systems.Count; i++)
{
var sys = systems[i];
if (sys == null || !sys.ShowOnLoyaltyGump)
continue;
var points = LookupPoints(sys, m);
if (points <= 0)
continue;
if (!first) sb.Append(',');
first = false;
var name = sys.Name;
sb.Append("{\"system\":\"").Append(sys.Loyalty).Append('"');
sb.Append(",\"nameString\":");
if (name == null || name.String == null)
sb.Append("null");
else
BridgeJson.Escape(sb, name.String);
sb.Append(",\"nameNumber\":").Append(name == null ? 0 : name.Number);
sb.Append(",\"points\":").Append(BridgePoints.Score(points));
sb.Append(",\"maxPoints\":").Append(BridgePoints.Cap(sys.MaxPoints));
// Off by default. The field is absent rather than null when disabled, so a
// consumer can tell "this shard does not compute rank" from "unranked".
if (BridgeConfig.PointsProfileRank)
sb.Append(",\"rank\":").Append(RankOf(sys, points));
sb.Append('}');
}
}
}
catch (Exception ex)
{
// A profile is worth more than its points block; never fail the sheet over one.
Console.WriteLine("[Bridge] profile points threw: {0}", ex.Message);
}
sb.Append(']');
}
/// <summary>
/// This character's score in one system, or 0 if it has no entry. A hand-rolled scan
/// rather than GetEntry/GetPoints for the mutation reason above; it stops at the match,
/// which the rank computation could not.
/// </summary>
private static double LookupPoints(PointsSystem sys, PlayerMobile m)
{
var table = sys.PlayerTable;
if (table == null)
return 0;
for (int i = 0; i < table.Count; i++)
{
var entry = table[i];
if (entry != null && entry.Player == m)
return entry.Points;
}
return 0;
}
/// <summary>
/// 1-based standing in one system: how many live characters hold strictly more points,
/// plus one. Ties share a rank, which is what a player expects to see.
///
/// Only reachable with PointsProfileRank=true, and off by default for the reason stated
/// in <see cref="WritePoints"/>: unlike the points lookup, this visits every row of the
/// table every time, so it turns a bounded early-exiting scan into a guaranteed full one
/// per published system per profile.
/// </summary>
private static int RankOf(PointsSystem sys, double points)
{
var table = sys.PlayerTable;
if (table == null)
return 1;
var better = 0;
for (int i = 0; i < table.Count; i++)
{
var entry = table[i];
if (entry == null || entry.Player == null || entry.Player.Deleted)
continue;
if (entry.Points > points)
better++;
}
return better + 1;
}
private static bool IsGearLayer(Layer layer) private static bool IsGearLayer(Layer layer)
{ {
switch (layer) switch (layer)

View File

@@ -0,0 +1,355 @@
using System;
using System.Text;
using Server.Engines.CityLoyalty;
using Server.Engines.VvV;
using Server.Multis;
namespace Server.Custom.Bridge
{
/// <summary>
/// The shard ruleset (https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/v3.md §5). One `world.ruleset` frame describing how
/// this shard is actually configured: expansion, which systems are on, skill/stat caps, house
/// and account limits, champion scroll rules, and the save/restart schedule. It is what turns
/// the website's "Rules" page from hand-maintained prose into something that cannot drift from
/// the server.
///
/// Modelled on <see cref="BridgeBoot.EmitHello"/>, NOT on the diff sweeps: the ruleset changes
/// only when an operator edits Config/*.cfg and restarts (or runs `[bridge reload`), so there is
/// nothing to poll. It subscribes Connected_Core so a sidecar that comes up second still learns
/// the ruleset, exactly as server.hello does.
///
/// **The one hard rule: this is an explicit allowlist of Config.Get calls.** Never enumerate
/// Config.Entries (Server/Config.cs) — that would sweep in every key on the server, secrets
/// included. Files deliberately never read here, in addition to anything not named below:
///
/// Server.cfg — Address / Listen / Port. Only Bridge.PublicConnectAddress is published,
/// and only because an operator typed it there for exactly this purpose.
/// Staff.cfg — staff account names.
/// Email.cfg — SMTP credentials.
/// DataPath.cfg — filesystem layout.
/// Bridge.cfg — the sidecar host/port and our own caps.
/// Compiler.cfg — build flags.
/// Reports.cfg — report upload credentials.
/// Client.cfg — client-version enforcement (not player-facing rules).
///
/// `rev` is an FNV-1a hash of the emitted body, so a reconnect that carries an unchanged ruleset
/// is a no-op site-side. String.GetHashCode() is deliberately NOT used: it is randomized per
/// process on modern .NET, so it would change on every shard restart and defeat the whole point.
/// </summary>
public static class BridgeRuleset
{
private static long _emitted;
private static string _rev = "";
private static int _bytes;
public static void Initialize()
{
if (!BridgeConfig.Enabled)
return;
BridgeLink.Connected_Core += Emit;
}
public static string Status()
{
return String.Format("ruleset(enabled={0} emitted={1} rev={2} bytes={3})",
BridgeConfig.RulesetEnabled, _emitted, _rev.Length == 0 ? "-" : _rev, _bytes);
}
/// <summary>
/// Core thread. Builds and queues one `world.ruleset` frame. Called on every sidecar
/// connect and by `[bridge reload` (an operator who just edited a .cfg wants to see the
/// change on the site without restarting the shard).
/// </summary>
public static void Emit()
{
if (!BridgeConfig.RulesetEnabled)
return;
try
{
var body = BuildBody();
_rev = Fnv1a(body);
_bytes = body.Length;
_emitted++;
// rev goes first so a reader can short-circuit on an unchanged frame before parsing
// the rest of it.
BridgeLink.Emit(BridgeJson.Begin("world.ruleset")
.Str("rev", _rev)
.Append(body)
.End());
}
catch (Exception ex)
{
Console.WriteLine("[Bridge] ruleset emit threw: {0}", ex.Message);
}
}
/// <summary>
/// The allowlist. Every block is optional and omitted when its system is off, so a shard
/// that does not run (say) VvV publishes no `vvv` block rather than a block of zeroes.
/// </summary>
private static string BuildBody()
{
var sb = new StringBuilder(2048);
sb.Str("shard", Server.Misc.ServerList.ServerName);
sb.Str("expansion", Core.Expansion.ToString());
// The ONLY thing published from a connection-address setting, and only because the
// operator put it in Bridge.cfg specifically to be shown. Server.cfg is never read.
var connect = BridgeConfig.PublicConnectAddress;
if (!String.IsNullOrEmpty(connect))
sb.Str("connect", connect);
WriteSystems(sb);
WriteCaps(sb);
sb.Append(",\"housing\":{\"accountHouseLimit\":")
.Append(BaseHouse.AccountHouseLimit).Append('}');
WriteAccounts(sb);
WriteVetRewards(sb);
WriteLoot(sb);
WriteVendors(sb);
WriteChampions(sb);
WriteTreasureMaps(sb);
WriteVvV(sb);
WriteStore(sb);
if (BridgeConfig.RulesetIncludeSchedule)
WriteSchedule(sb);
return sb.ToString();
}
/// <summary>
/// Which optional systems this shard runs. Read from each system's own static rather than
/// re-parsing its .cfg, so a system that derives its state (Factions is on exactly when VvV
/// is off — Services/Factions/Core/Faction.cs) is reported the way the server actually sees
/// it. This block subsumes the `world.systems` capability frame PROTOCOL_2.md §10.4
/// sketched but never implemented.
/// </summary>
private static void WriteSystems(StringBuilder sb)
{
sb.Append(",\"systems\":{");
sb.Append("\"cityLoyalty\":").Append(Json(CityLoyaltySystem.Enabled));
sb.Append(",\"vvv\":").Append(Json(ViceVsVirtueSystem.Enabled));
sb.Append(",\"factions\":").Append(Json(Server.Factions.Settings.Enabled));
sb.Append(",\"siege\":").Append(Json(Siege.SiegeShard));
sb.Append(",\"chat\":").Append(Json(Config.Get("Chat.Enabled", true)));
sb.Append(",\"store\":").Append(Json(Config.Get("Store.Enabled", true)));
sb.Append(",\"dailyRares\":").Append(Json(Config.Get("DailyRares.Enabled", true)));
sb.Append(",\"honesty\":").Append(Json(Config.Get("Honesty.Enabled", true)));
sb.Append(",\"shadowguard\":").Append(Json(Core.TOL));
sb.Append(",\"treasureMaps\":").Append(Json(Config.Get("TreasureMaps.Enabled", true)));
sb.Append(",\"vetRewards\":").Append(Json(Config.Get("VetRewards.Enabled", true)));
sb.Append(",\"testCenter\":").Append(Json(Config.Get("TestCenter.Enabled", false)));
sb.Append('}');
}
/// <summary>
/// Skill and stat caps — the single most-asked "what are the rules here?" question, and the
/// one most often wrong on a hand-written page. SkillCap is in tenths (1000 = 100.0).
/// </summary>
private static void WriteCaps(StringBuilder sb)
{
sb.Append(",\"caps\":{");
sb.Append("\"skill\":").Append(Config.Get("PlayerCaps.SkillCap", 1000));
sb.Append(",\"totalSkill\":").Append(Config.Get("PlayerCaps.TotalSkillCap", 7000));
sb.Append(",\"stat\":").Append(Config.Get("PlayerCaps.TotalStatCap", 225));
sb.Append(",\"str\":").Append(Config.Get("PlayerCaps.StrCap", 125));
sb.Append(",\"dex\":").Append(Config.Get("PlayerCaps.DexCap", 125));
sb.Append(",\"int\":").Append(Config.Get("PlayerCaps.IntCap", 125));
sb.Append(",\"strMax\":").Append(Config.Get("PlayerCaps.StrMaxCap", 150));
sb.Append(",\"dexMax\":").Append(Config.Get("PlayerCaps.DexMaxCap", 150));
sb.Append(",\"intMax\":").Append(Config.Get("PlayerCaps.IntMaxCap", 150));
sb.Append('}');
}
/// <summary>
/// Account limits. `autoCreate` is the in-game first-login auto-create switch, which pairs
/// with the bridge's own SignupMode (BridgeConfig.WarnOnSignupMismatch) — publishing it
/// lets the site's signup page tell a visitor the truth about how to get an account.
/// Character slots come from Siege.cfg, which is where ServUO keeps them regardless of
/// whether the shard is actually Siege.
/// </summary>
private static void WriteAccounts(StringBuilder sb)
{
sb.Append(",\"accounts\":{");
sb.Append("\"perIp\":").Append(Config.Get("Accounts.AccountsPerIp", 1));
sb.Append(",\"charSlots\":").Append(Siege.CharacterSlots);
sb.Append(",\"autoCreate\":").Append(Json(Config.Get("Accounts.AutoCreateAccounts", true)));
sb.Append('}');
}
private static void WriteVetRewards(StringBuilder sb)
{
var enabled = Config.Get("VetRewards.Enabled", true);
sb.Append(",\"vetRewards\":{\"enabled\":").Append(Json(enabled));
if (enabled)
{
var interval = Config.Get("VetRewards.RewardInterval", TimeSpan.FromDays(30.0));
sb.Append(",\"rewardIntervalDays\":").Append((int)interval.TotalDays);
}
sb.Append('}');
}
/// <summary>The Felucca risk-vs-reward numbers — the reason players choose a facet.</summary>
private static void WriteLoot(StringBuilder sb)
{
sb.Append(",\"loot\":{");
sb.Append("\"feluccaLuckBonus\":").Append(Config.Get("Loot.FeluccaLuckBonus", 0));
sb.Append(",\"feluccaBudgetBonus\":").Append(Config.Get("Loot.FeluccaBudgetBonus", 0));
sb.Append(",\"feluccaMaxProps\":").Append(Config.Get("Loot.MaxProps", 5));
sb.Append('}');
}
private static void WriteVendors(StringBuilder sb)
{
sb.Append(",\"vendors\":{");
sb.Append("\"restockDelayMinutes\":").Append(Config.Get("Vendors.RestockDelay", 60));
sb.Append(",\"maxSell\":").Append(Config.Get("Vendors.MaxSell", 500));
sb.Append(",\"economyStockAmount\":").Append(Config.Get("Vendors.EconomyStockAmount", 500));
sb.Append('}');
}
/// <summary>
/// Champion spawn rewards. `rankThresholds` is the red-skull count at which each rank is
/// reached, which is what a player actually wants to know before committing to a spawn.
/// </summary>
private static void WriteChampions(StringBuilder sb)
{
if (!Config.Get("Champions.Enabled", true))
return;
sb.Append(",\"champions\":{");
sb.Append("\"powerScrolls\":").Append(Config.Get("Champions.PowerScrolls", 6));
sb.Append(",\"statScrolls\":").Append(Config.Get("Champions.StatScrolls", 16));
sb.Append(",\"scrollChance\":").Append(Json(Config.Get("Champions.ScrollChance", 0.1)));
sb.Append(",\"transcendenceChance\":")
.Append(Json(Config.Get("Champions.TranscendenceChance", 50.0)));
sb.Append(",\"rankThresholds\":[")
.Append(Config.Get("Champions.Rank2RedSkulls", 5)).Append(',')
.Append(Config.Get("Champions.Rank3RedSkulls", 10)).Append(',')
.Append(Config.Get("Champions.Rank4RedSkulls", 13))
.Append(']');
sb.Append('}');
}
private static void WriteTreasureMaps(StringBuilder sb)
{
var enabled = Config.Get("TreasureMaps.Enabled", true);
sb.Append(",\"treasureMaps\":{\"enabled\":").Append(Json(enabled));
if (enabled)
{
sb.Append(",\"lootChance\":").Append(Json(Config.Get("TreasureMaps.LootChance", 0.01)));
sb.Append(",\"resetDays\":").Append(Json(Config.Get("TreasureMaps.ResetTime", 30.0)));
}
sb.Append('}');
}
private static void WriteVvV(StringBuilder sb)
{
if (!ViceVsVirtueSystem.Enabled)
return;
sb.Append(",\"vvv\":{");
sb.Append("\"enabled\":true");
sb.Append(",\"startSilver\":").Append(ViceVsVirtueSystem.StartSilver);
sb.Append(",\"enhancedRules\":").Append(Json(ViceVsVirtueSystem.EnhancedRules));
sb.Append('}');
}
/// <summary>
/// The Ultima Store. Only `enabled` and the currency's display name — never the store's
/// price table or any payment configuration, neither of which lives in Config anyway.
/// </summary>
private static void WriteStore(StringBuilder sb)
{
var enabled = Config.Get("Store.Enabled", true);
sb.Append(",\"store\":{\"enabled\":").Append(Json(enabled));
if (enabled)
sb.Str("currencyName", Config.Get("Store.CurrencyName", "Sovereigns"));
sb.Append('}');
}
/// <summary>
/// Save and restart schedule — "when does the shard hiccup?", the other question a live
/// status page is asked. Off behind RulesetIncludeSchedule for an operator who would rather
/// not advertise a predictable restart window.
/// </summary>
private static void WriteSchedule(StringBuilder sb)
{
sb.Append(",\"schedule\":{");
var saves = Config.Get("AutoSave.Enabled", true);
sb.Append("\"autoSaveEnabled\":").Append(Json(saves));
if (saves)
{
var freq = Config.Get("AutoSave.Frequency", TimeSpan.FromMinutes(5.0));
sb.Append(",\"autoSaveFrequencyMinutes\":").Append((int)freq.TotalMinutes);
}
var restart = Config.Get("AutoRestart.Enabled", false);
sb.Append(",\"autoRestartEnabled\":").Append(Json(restart));
if (restart)
{
sb.Append(",\"autoRestartHour\":").Append(Config.Get("AutoRestart.Hour", 12));
sb.Append(",\"autoRestartMinute\":").Append(Config.Get("AutoRestart.Minute", 0));
sb.Append(",\"autoRestartFrequencyHours\":").Append(Config.Get("AutoRestart.Frequency", 24));
}
sb.Append('}');
}
// ---- helpers ----
private static string Json(bool value)
{
return value ? "true" : "false";
}
private static string Json(double value)
{
return value.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>
/// FNV-1a over the UTF-16 code units of the body, as 8 lowercase hex digits. Any stable
/// hash would do; what matters is that it is stable ACROSS PROCESSES, which
/// String.GetHashCode() is not (it is seeded randomly per process), so using that would
/// produce a different rev after every restart and make the whole diff pointless.
/// </summary>
private static string Fnv1a(string s)
{
const uint offset = 2166136261;
const uint prime = 16777619;
uint hash = offset;
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
hash = (hash ^ (byte)(c & 0xFF)) * prime;
hash = (hash ^ (byte)(c >> 8)) * prime;
}
return hash.ToString("x8");
}
}
}