diff --git a/CHANGELOG.md b/CHANGELOG.md index ec7f1c1..4169788 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.3.0 + +- `HibiraAuctionHouse`: follows an auction house published by + `@hibira-io/auction` (`createAuctionHouse()` on a Node server), so Unity and + browser players share it: open listings, recent sales, countdowns on the + server's clock, sale prices per item type, and a fresh snapshot on every + subscription. Bids go to your server. + ## 0.2.1 - README: cover image and screenshots. diff --git a/README.md b/README.md index 988aa5b..f2e50d0 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,34 @@ times here are in seconds. Coming from Photon PUN 2? See [Moving from Photon PUN 2](Documentation~/moving-from-photon-pun-2.md). +## Auction house + +`HibiraAuctionHouse` follows an auction house run by +[`@hibira-io/auction`](https://github.com/hibira-io/auction-js) on your Node +server, so Unity and browser players trade in the same house. Listings, +bids, extensions and sales arrive live; the countdown follows the server's +clock. + +```csharp +var house = HibiraAuctionHouse.Open(hibira, "main", "https://api.your-game.example/auction"); +house.Changed += () => DrawListings(house.Listings); +house.Updated += (kind, listing) => +{ + if (kind == "sold" && listing.BidderId == myId) ShowWon(listing.Item["type"]); +}; + +void Update() +{ + foreach (var l in house.Listings) SetTimer(l.Id, house.TimeLeft(l)); // seconds +} +``` + +The URL is your server's `GET` returning `house.snapshot()`; it loads on +every subscription, including after a reconnect. Bids never go over the +socket: POST them to your own server, which checks them with `house.bid()` +and publishes the result to everyone. `listing.MinBid` is the next lowest +bid, and `house.Prices(type)` the recent sale prices of an item type. + ## WebGL WebGL builds use the browser's WebSocket and `fetch` (through @@ -264,6 +292,12 @@ events `Joined`, `Updated`, `Matched`, `TimedOut`, `JoinFailed`. `HibiraMatch`: `FindMatches(tickets, rules, nowMs)`, `AllowedRange`, `CriteriaFit`. +`HibiraAuctionHouse`: `Open(client, house, snapshotUrl)` (or a `load` +function), `Listings`, `Closed`, `Get(id)`, `TimeLeft(listing)`, +`Prices(type)`, `NowMs()`, `Reload()`, `Close()`, and the events `Ready`, +`Changed`, `Updated(kind, listing)`, `Failed`. `HibiraListing` carries the +listing's fields (`Price`, `MinBid`, `Buyout`, `EndsAt`, `Status`, `Item`, …). + Not supported yet: end-to-end encrypted channels (`private-encrypted-`) and user sign-in (`pusher:signin`). diff --git a/Runtime/HibiraAuctionHouse.cs b/Runtime/HibiraAuctionHouse.cs new file mode 100644 index 0000000..dca3bd4 --- /dev/null +++ b/Runtime/HibiraAuctionHouse.cs @@ -0,0 +1,307 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Hibira +{ + /// One listing of an auction house, as the server published it. + public sealed class HibiraListing + { + public string Id { get; } + public string House { get; } + public string SellerId { get; } + /// Public info about the seller (name...), as your server set it. + public Dictionary Seller { get; } + /// What is sold, as your server set it; Item["type"] groups sale prices. + public Dictionary Item { get; } + public long StartPrice { get; } + public long? Buyout { get; } + /// The highest bid, or the sale price once sold; null before the first bid. + public long? Price { get; } + public string BidderId { get; } + public Dictionary Bidder { get; } + public int Bids { get; } + /// The lowest bid the server accepts next. + public long MinBid { get; } + /// Server time, ms since epoch. + public double EndsAt { get; } + /// "open", "sold", "unsold" or "cancelled". + public string Status { get; } + public double? ClosedAt { get; } + public long Version { get; } + /// The listing as JSON values, for fields your server added. + public Dictionary Raw { get; } + + public bool IsOpen => Status == "open"; + /// Item["type"] as text, or null. + public string ItemType => Json.Get(Item, "type") is object t ? Json.ToText(t) : null; + + HibiraListing(Dictionary d) + { + Raw = d; + Id = Json.ToText(Json.Get(d, "id")); + House = Json.Get(d, "house") as string; + SellerId = Json.Get(d, "sellerId") is object s ? Json.ToText(s) : null; + Seller = Json.Get(d, "seller") as Dictionary ?? new Dictionary(); + Item = Json.Get(d, "item") as Dictionary ?? new Dictionary(); + StartPrice = (long)Json.ToDouble(Json.Get(d, "startPrice")); + Buyout = Long(Json.Get(d, "buyout")); + Price = Long(Json.Get(d, "price")); + BidderId = Json.Get(d, "bidderId") is object b ? Json.ToText(b) : null; + Bidder = Json.Get(d, "bidder") as Dictionary; + Bids = (int)Json.ToDouble(Json.Get(d, "bids")); + MinBid = (long)Json.ToDouble(Json.Get(d, "minBid")); + EndsAt = Json.ToDouble(Json.Get(d, "endsAt")); + Status = Json.Get(d, "status") as string ?? "open"; + ClosedAt = Json.IsNumber(Json.Get(d, "closedAt")) ? Json.ToDouble(Json.Get(d, "closedAt")) : (double?)null; + Version = (long)Json.ToDouble(Json.Get(d, "version")); + } + + /// Read a listing from parsed JSON; null when it has no id or version. + public static HibiraListing From(object value) + { + if (!(value is Dictionary d)) return null; + if (!(Json.Get(d, "id") is string id) || id.Length == 0 || !Json.IsNumber(Json.Get(d, "version"))) return null; + return new HibiraListing(d); + } + + static long? Long(object v) => Json.IsNumber(v) ? (long)Json.ToDouble(v) : (long?)null; + } + + /// A recent sale price of one item type. + public readonly struct HibiraPricePoint + { + public readonly long Price; + public readonly double At; + public readonly string ListingId; + + public HibiraPricePoint(long price, double at, string listingId) + { + Price = price; + At = at; + ListingId = listingId; + } + } + + /// + /// An auction house that follows a channel published by @hibira-io/auction's + /// server (createAuctionHouse in Node), so Unity and browser players share + /// the same house. The channel carries one event, auction-update, with the + /// whole listing and a version; the newest version of each listing wins. + /// On every subscription, including after a reconnect, it loads the + /// server's snapshot (house.snapshot()) so nothing is missed. + /// + /// Players never bid over the socket: send bids to your own server, which + /// checks them with house.bid(). + /// + public sealed class HibiraAuctionHouse + { + public const string EventUpdate = "auction-update"; + + /// The first snapshot has loaded. + public event Action Ready; + /// Something changed: a server event or a (re)load. + public event Action Changed; + /// One server event. Arguments: kind (listed, bid, extended, sold, unsold, cancelled) and the listing. + public event Action Updated; + /// Loading the snapshot or subscribing failed. Argument: a message. + public event Action Failed; + + public HibiraChannel Channel { get; } + public string Name { get; } + public bool IsReady { get; private set; } + /// Server clock minus this device's clock, in ms. + public double OffsetMs { get; private set; } + public int KeepClosed { get; set; } = 50; + public int HistoryPerType { get; set; } = 20; + + /// Wall clock in ms since epoch. + internal Func EpochMs = () => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + readonly Func> _load; + readonly Action _onUpdate; + readonly Action _onSubscribed; + readonly Action _onError; + Dictionary _open = new Dictionary(); + List _closed = new List(); + readonly Dictionary> _prices = new Dictionary>(); + int _loadSeq; + + /// + /// Subscribe to auction-<house> and load the snapshot from + /// (your server's GET returning house.snapshot()). + /// + public static HibiraAuctionHouse Open(HibiraClient client, string house, string snapshotUrl, string channel = null) => + Open(client, house, async () => + { + var res = await HibiraHttp.Get(snapshotUrl); + if (res.Status < 200 || res.Status >= 300) throw new Exception(res.Error ?? $"snapshot: HTTP {res.Status}"); + return res.Body; + }, channel); + + /// Subscribe to auction-<house>; returns the snapshot as JSON text. + public static HibiraAuctionHouse Open(HibiraClient client, string house, Func> load, string channel = null) + { + if (client == null) throw new ArgumentNullException(nameof(client)); + var name = channel ?? "auction-" + house; + if (name.StartsWith("presence-", StringComparison.Ordinal)) + throw new ArgumentException($"HibiraAuctionHouse: use a public or private- channel, not \"{name}\""); + return new HibiraAuctionHouse(client.Subscribe(name), house, load); + } + + /// Track a channel you subscribed to yourself. Create it right after subscribing. + public HibiraAuctionHouse(HibiraChannel channel, string house, Func> load) + { + Channel = channel ?? throw new ArgumentNullException(nameof(channel)); + _load = load ?? throw new ArgumentNullException(nameof(load)); + Name = house; + _onUpdate = ev => Apply(ev.Data); + _onSubscribed = _ => _ = Reload(); + _onError = (status, message) => Failed?.Invoke($"subscription failed ({status}): {message}"); + channel.Bind(EventUpdate, _onUpdate); + channel.Subscribed += _onSubscribed; + channel.SubscriptionError += _onError; + if (channel.IsSubscribed) _ = Reload(); + } + + /// Open listings, ending soonest first. + public IReadOnlyList Listings => + _open.Values.OrderBy(l => l.EndsAt).ThenBy(l => l.Id, StringComparer.Ordinal).ToList(); + + /// Recently closed listings, newest first. + public IReadOnlyList Closed => _closed.ToList(); + + public HibiraListing Get(string id) => + id != null && _open.TryGetValue(id, out var l) ? l : _closed.FirstOrDefault(c => c.Id == id); + + /// The server's clock in ms since epoch. + public double NowMs() => EpochMs() + OffsetMs; + + /// Seconds left on a listing (0 once ended), on the server's clock. + public double TimeLeft(HibiraListing listing) => + listing == null || !listing.IsOpen ? 0 : Math.Max(0, (listing.EndsAt - NowMs()) / 1000.0); + + /// Recent sale prices of an item type, oldest first. + public IReadOnlyList Prices(string type) => + type != null && _prices.TryGetValue(type, out var list) ? list.ToList() : new List(); + + /// Load the snapshot again (done for you on every subscription). + public async Task Reload() + { + var seq = ++_loadSeq; + string text; + try + { + text = await _load(); + } + catch (Exception e) + { + if (seq == _loadSeq) Failed?.Invoke(e.Message); + return; + } + if (seq != _loadSeq) return; + if (!Json.TryParse(text, out var parsed) || !(parsed is Dictionary snap)) + { + Failed?.Invoke("snapshot: not a JSON object"); + return; + } + Merge(snap); + var first = !IsReady; + IsReady = true; + if (first) Ready?.Invoke(); + Changed?.Invoke(); + } + + /// Stop listening and unsubscribe. + public void Close() + { + _loadSeq++; + Channel.Unbind(EventUpdate, _onUpdate); + Channel.Subscribed -= _onSubscribed; + Channel.SubscriptionError -= _onError; + Channel.Unsubscribe(); + } + + // ---- internals ------------------------------------------------------- + + void Merge(Dictionary snap) + { + if (Json.IsNumber(Json.Get(snap, "serverNow"))) OffsetMs = Json.ToDouble(Json.Get(snap, "serverNow")) - EpochMs(); + var all = new Dictionary(); + foreach (var l in _closed) all[l.Id] = l; + foreach (var l in _open.Values) all[l.Id] = l; + var listed = new HashSet(); + foreach (var key in new[] { "listings", "closed" }) + { + if (!(Json.Get(snap, key) is List list)) continue; + foreach (var item in list) + { + var l = HibiraListing.From(item); + if (l == null) continue; + listed.Add(l.Id); + if (!all.TryGetValue(l.Id, out var mine) || mine.Version < l.Version) all[l.Id] = l; + } + } + // An open listing the snapshot does not mention arrived after it, + // unless its time is up (closed and pruned on the server). + var now = NowMs(); + foreach (var id in all.Keys.ToList()) + { + var l = all[id]; + if (!listed.Contains(id) && l.IsOpen && l.EndsAt <= now) all.Remove(id); + } + _open = all.Values.Where(l => l.IsOpen).ToDictionary(l => l.Id); + _closed = all.Values.Where(l => !l.IsOpen).OrderByDescending(l => l.ClosedAt ?? 0).Take(KeepClosed).ToList(); + if (Json.Get(snap, "prices") is Dictionary prices) + { + foreach (var kv in prices) + { + if (!(kv.Value is List points)) continue; + foreach (var p in points.OfType>()) + AddPrice(kv.Key, new HibiraPricePoint((long)Json.ToDouble(Json.Get(p, "price")), Json.ToDouble(Json.Get(p, "at")), Json.ToText(Json.Get(p, "listingId")))); + } + } + foreach (var l in _closed) NotePrice(l); + } + + internal void Apply(object data) + { + var d = data as Dictionary; + var l = HibiraListing.From(Json.Get(d, "listing")); + if (l == null) return; + if (Json.IsNumber(Json.Get(d, "serverNow"))) OffsetMs = Json.ToDouble(Json.Get(d, "serverNow")) - EpochMs(); + var known = Get(l.Id); + if (known != null && known.Version >= l.Version) return; + if (l.IsOpen) + { + _open[l.Id] = l; + } + else + { + _open.Remove(l.Id); + _closed.RemoveAll(c => c.Id == l.Id); + _closed.Insert(0, l); + if (_closed.Count > KeepClosed) _closed.RemoveRange(KeepClosed, _closed.Count - KeepClosed); + NotePrice(l); + } + Updated?.Invoke(Json.Get(d, "kind") as string, l); + Changed?.Invoke(); + } + + void NotePrice(HibiraListing l) + { + if (l.Status != "sold" || l.ItemType == null || l.Price == null) return; + AddPrice(l.ItemType, new HibiraPricePoint(l.Price.Value, l.ClosedAt ?? 0, l.Id)); + } + + void AddPrice(string type, HibiraPricePoint point) + { + if (!_prices.TryGetValue(type, out var list)) _prices[type] = list = new List(); + if (list.Any(p => p.ListingId == point.ListingId)) return; + list.Add(point); + list.Sort((a, b) => a.At.CompareTo(b.At)); + if (list.Count > HistoryPerType) list.RemoveRange(0, list.Count - HistoryPerType); + } + } +} diff --git a/Runtime/HibiraAuctionHouse.cs.meta b/Runtime/HibiraAuctionHouse.cs.meta new file mode 100644 index 0000000..c8ab372 --- /dev/null +++ b/Runtime/HibiraAuctionHouse.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09d263b85344b77a3974f58f55422242 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/HibiraHttp.cs b/Runtime/HibiraHttp.cs index 24c6977..4e2911a 100644 --- a/Runtime/HibiraHttp.cs +++ b/Runtime/HibiraHttp.cs @@ -27,6 +27,31 @@ public static string Form(IEnumerable> fields) return sb.ToString(); } + /// A GET that expects JSON, e.g. an auction house snapshot. + public static Task Get(string url, IDictionary headers = null) + { + var tcs = new TaskCompletionSource(); +#if UNITY_5_3_OR_NEWER + var request = UnityEngine.Networking.UnityWebRequest.Get(url); + request.SetRequestHeader("Accept", "application/json"); + if (headers != null) foreach (var kv in headers) request.SetRequestHeader(kv.Key, kv.Value); + request.SendWebRequest().completed += _ => + { + var status = (int)request.responseCode; + tcs.SetResult(new Response + { + Status = status, + Body = request.downloadHandler?.text ?? "", + Error = status == 0 ? request.error ?? "no response" : null, + }); + request.Dispose(); + }; +#else + _ = SendGet(url, headers, tcs); +#endif + return tcs.Task; + } + public static Task PostForm(string url, IDictionary headers, string form) { var tcs = new TaskCompletionSource(); @@ -77,6 +102,22 @@ static async Task Send(string url, IDictionary headers, string f tcs.SetResult(new Response { Status = 0, Body = "", Error = e.Message }); } } + + static async Task SendGet(string url, IDictionary headers, TaskCompletionSource tcs) + { + try + { + var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url); + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + if (headers != null) foreach (var kv in headers) request.Headers.TryAddWithoutValidation(kv.Key, kv.Value); + var response = await Client.SendAsync(request).ConfigureAwait(false); + tcs.SetResult(new Response { Status = (int)response.StatusCode, Body = await response.Content.ReadAsStringAsync().ConfigureAwait(false) }); + } + catch (Exception e) + { + tcs.SetResult(new Response { Status = 0, Body = "", Error = e.Message }); + } + } #endif } -} +} \ No newline at end of file diff --git a/Tests~/Hibira.Tests/AuctionTests.cs b/Tests~/Hibira.Tests/AuctionTests.cs new file mode 100644 index 0000000..8ff7c71 --- /dev/null +++ b/Tests~/Hibira.Tests/AuctionTests.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Hibira.Tests +{ + static class AuctionTests + { + static Dictionary L(string id, long version, string status = "open", double endsIn = 60000, long? price = null, string type = "sword", double closedAt = 0) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var d = new Dictionary + { + ["id"] = id, + ["version"] = version, + ["status"] = status, + ["endsAt"] = now + endsIn, + ["startPrice"] = 10L, + ["minBid"] = (price ?? 10) + 1, + ["bids"] = price == null ? 0L : 1L, + ["sellerId"] = "s", + ["item"] = new Dictionary { ["type"] = type }, + }; + if (price != null) d["price"] = price.Value; + if (status != "open") d["closedAt"] = closedAt == 0 ? (double)now : closedAt; + return d; + } + + static Dictionary Update(string kind, Dictionary listing) => + new Dictionary { ["kind"] = kind, ["listing"] = listing }; + + static (HibiraAuctionHouse house, Func setSnap) Setup(string snapshot) + { + var snap = snapshot; + var channel = new HibiraChannel(new HibiraClient("key"), "auction-main"); + var house = new HibiraAuctionHouse(channel, "main", () => Task.FromResult(snap)); + return (house, () => snap); + } + + [Test] + static void LoadsTheSnapshotAndSortsByEnd() + { + var snap = Json.Serialize(new Dictionary + { + ["serverNow"] = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + ["listings"] = new List { L("a", 1, endsIn: 60000), L("b", 1, endsIn: 1000) }, + ["closed"] = new List { L("c", 3, "sold", price: 40) }, + ["prices"] = new Dictionary { ["sword"] = new List { new Dictionary { ["price"] = 30L, ["at"] = 1.0, ["listingId"] = "old" } } }, + }); + var (house, _) = Setup(snap); + var ready = 0; + house.Ready += () => ready++; + house.Reload().Wait(); + Assert.Equal(1, ready); + Assert.Equal("b,a", string.Join(",", house.Listings.Select(l => l.Id))); + Assert.Equal("c", house.Closed[0].Id); + Assert.Equal("30,40", string.Join(",", house.Prices("sword").Select(p => p.Price))); + Assert.Equal(11L, house.Get("a").MinBid); + Assert.Equal("sword", house.Get("a").ItemType); + } + + [Test] + static void KeepsTheNewestVersion() + { + var (house, _) = Setup("{\"listings\":[]}"); + house.Reload().Wait(); + var kinds = new List(); + house.Updated += (k, l) => kinds.Add(k); + house.Apply(Update("bid", L("a", 3, price: 50))); + house.Apply(Update("bid", L("a", 2, price: 40))); + Assert.Equal(50L, house.Get("a").Price); + Assert.Equal("bid", string.Join(",", kinds)); + house.Apply(Update("sold", L("a", 4, "sold", price: 60))); + Assert.Equal(0, house.Listings.Count); + Assert.Equal("sold", house.Closed[0].Status); + Assert.Equal("60", string.Join(",", house.Prices("sword").Select(p => p.Price))); + } + + [Test] + static void EventsDuringLoadingWinWhenNewer() + { + var tcs = new TaskCompletionSource(); + var channel = new HibiraChannel(new HibiraClient("key"), "auction-main"); + var house = new HibiraAuctionHouse(channel, "main", () => tcs.Task); + var loading = house.Reload(); + house.Apply(Update("bid", L("a", 5, price: 90))); + house.Apply(Update("listed", L("new", 1))); + tcs.SetResult(Json.Serialize(new Dictionary + { + ["listings"] = new List { L("a", 4, price: 80), L("b", 1) }, + })); + loading.Wait(); + Assert.Equal(90L, house.Get("a").Price); + Assert.Equal("a,b,new", string.Join(",", house.Listings.Select(l => l.Id).OrderBy(x => x))); + } + + [Test] + static void DropsEndedListingsTheSnapshotNoLongerHas() + { + var (house, _) = Setup("{\"listings\":[]}"); + house.Apply(Update("listed", L("gone", 1, endsIn: -1000))); + house.Reload().Wait(); + Assert.Equal(0, house.Listings.Count); + } + + [Test] + static void TimeLeftFollowsTheServerClock() + { + var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var l = L("a", 1); + l["endsAt"] = (double)(now + 15000); + var (house, _) = Setup(Json.Serialize(new Dictionary { ["serverNow"] = (double)(now + 10000), ["listings"] = new List { l } })); + house.Reload().Wait(); + var left = house.TimeLeft(house.Get("a")); + Assert.True(left > 4 && left <= 5, $"left {left}"); + } + + [Test] + static void ReportsLoadFailuresAndIgnoresMalformedEvents() + { + var channel = new HibiraChannel(new HibiraClient("key"), "auction-main"); + var house = new HibiraAuctionHouse(channel, "main", () => Task.FromException(new Exception("500"))); + var errors = new List(); + house.Failed += errors.Add; + house.Reload().Wait(); + Assert.Equal("500", string.Join(",", errors)); + house.Apply(null); + house.Apply(new Dictionary { ["listing"] = new Dictionary { ["id"] = 1L } }); + Assert.Equal(0, house.Listings.Count); + } + + [Test] + static void RefusesPresenceChannels() + { + Assert.Throws(() => HibiraAuctionHouse.Open(new HibiraClient("key"), "x", () => Task.FromResult("{}"), "presence-auction")); + } + } +} diff --git a/package.json b/package.json index f0fa210..793ae44 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "io.hibira.realtime", - "version": "0.2.1", + "version": "0.3.0", "displayName": "Hibira Realtime", - "description": "Realtime WebSocket channels for Unity on Hibira and other Pusher-compatible servers: public, private and presence channels, client events, game rooms (seats, host, ready, chat) and a matchmaking queue, shared with @hibira-io/lobby browser players. Works in WebGL builds.", + "description": "Realtime WebSocket channels for Unity on Hibira and other Pusher-compatible servers: public, private and presence channels, client events, game rooms (seats, host, ready, chat) and a matchmaking queue, shared with @hibira-io/lobby browser players, and an auction house that follows @hibira-io/auction. Works in WebGL builds.", "unity": "2021.3", "license": "MIT", - "keywords": ["hibira", "pusher", "websocket", "realtime", "multiplayer", "lobby", "matchmaking", "webgl"], + "keywords": ["hibira", "pusher", "websocket", "realtime", "multiplayer", "lobby", "matchmaking", "auction", "webgl"], "author": { "name": "Hibira", "url": "https://hibira.io"