458 lines
16 KiB
Python
Executable File
458 lines
16 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Generate protobuf venue enums from the canonical venue registry."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
REGISTRY = ROOT / "src/lib_spark/spark/domain_model/venues.json"
|
|
LEGACY_PROTO = ROOT / "src/lib_spark/spark/domain_model/Security.proto"
|
|
DOMAIN_PROTO = ROOT / "src/lib_spark/spark/api/domain/Venue.proto"
|
|
MARKET_DATA_CONFIG = ROOT / "src/lib_spark/spark/api/md/MarketDataConfig.proto"
|
|
ADMIN_TYPES = ROOT / "src/Spark.Admin.WebApp/src/Accounts/Types.fs"
|
|
RAKURAI_REGISTRY = ROOT / "src/app_sparkd/sparkd/rakurai/RakuraiVenueRegistry.h"
|
|
RAKURAI_VENUES = ROOT / "src/lib_spark/spark/domain_model/RakuraiVenues.h"
|
|
BEGIN = "// BEGIN GENERATED VENUE ENUM"
|
|
END = "// END GENERATED VENUE ENUM"
|
|
ADMIN_BEGIN = "// BEGIN GENERATED ADMIN VENUES"
|
|
ADMIN_END = "// END GENERATED ADMIN VENUES"
|
|
CONFIG_IMPORT_BEGIN = "// BEGIN GENERATED VENUE CONFIG IMPORTS"
|
|
CONFIG_IMPORT_END = "// END GENERATED VENUE CONFIG IMPORTS"
|
|
CONFIG_FIELD_BEGIN = " // BEGIN GENERATED VENUE CONFIG FIELDS"
|
|
CONFIG_FIELD_END = " // END GENERATED VENUE CONFIG FIELDS"
|
|
|
|
|
|
def load_venues() -> list[dict[str, object]]:
|
|
data = json.loads(REGISTRY.read_text(encoding="utf-8"))
|
|
venues = data.get("venues")
|
|
if not isinstance(venues, list) or not venues:
|
|
raise ValueError("venues.json must contain a non-empty 'venues' array")
|
|
|
|
names: set[str] = set()
|
|
ids: dict[str, set[int]] = {"legacy_id": set(), "domain_id": set()}
|
|
config_ids: set[int] = set()
|
|
rakurai_ids: set[str] = set()
|
|
for venue in venues:
|
|
if not isinstance(venue, dict):
|
|
raise ValueError("each venue must be an object")
|
|
name = venue.get("name")
|
|
if not isinstance(name, str) or not re.fullmatch(r"[A-Z][A-Z0-9_]*", name):
|
|
raise ValueError(f"invalid venue name: {name!r}")
|
|
if name in names:
|
|
raise ValueError(f"duplicate venue name: {name}")
|
|
names.add(name)
|
|
scope = venue.get("scope", "both")
|
|
if scope not in ("both", "legacy", "domain"):
|
|
raise ValueError(f"{name}.scope must be 'both', 'legacy', or 'domain'")
|
|
if scope in ("both", "legacy") and "legacy_id" not in venue:
|
|
raise ValueError(f"{name} is missing legacy_id")
|
|
if scope in ("both", "domain") and "domain_id" not in venue:
|
|
raise ValueError(f"{name} is missing domain_id")
|
|
if scope == "legacy" and "domain_id" in venue:
|
|
raise ValueError(f"{name} is legacy-only but has domain_id")
|
|
if scope == "domain" and "legacy_id" in venue:
|
|
raise ValueError(f"{name} is domain-only but has legacy_id")
|
|
for key in ids:
|
|
value = venue.get(key)
|
|
if value is None:
|
|
continue
|
|
if not isinstance(value, int) or value < 0:
|
|
raise ValueError(f"{name}.{key} must be a non-negative integer")
|
|
if value in ids[key]:
|
|
raise ValueError(f"duplicate {key}: {value}")
|
|
ids[key].add(value)
|
|
config = venue.get("market_data_config")
|
|
if config is not None:
|
|
if not isinstance(config, dict):
|
|
raise ValueError(f"{name}.market_data_config must be an object")
|
|
config_type = config.get("type")
|
|
field_id = config.get("field_id")
|
|
if not isinstance(config_type, str) or not re.fullmatch(
|
|
r"[A-Z][A-Za-z0-9]*", config_type
|
|
):
|
|
raise ValueError(f"invalid config type for {name}: {config_type!r}")
|
|
if not isinstance(field_id, int) or field_id <= 0:
|
|
raise ValueError(f"{name} config field_id must be a positive integer")
|
|
if field_id in config_ids:
|
|
raise ValueError(f"duplicate market-data config field_id: {field_id}")
|
|
config_ids.add(field_id)
|
|
rakurai = venue.get("rakurai")
|
|
if rakurai is not None:
|
|
if not isinstance(rakurai, list) or not rakurai:
|
|
raise ValueError(f"{name}.rakurai must be a non-empty array")
|
|
if "legacy_id" not in venue or "domain_id" not in venue:
|
|
raise ValueError(f"{name}.rakurai requires both venue IDs")
|
|
for connector in rakurai:
|
|
if not isinstance(connector, dict):
|
|
raise ValueError(f"each {name}.rakurai entry must be an object")
|
|
connector_id = connector.get("id")
|
|
pool_type = connector.get("pool_type")
|
|
quote_currency = connector.get("quote_currency")
|
|
if not isinstance(connector_id, str) or not re.fullmatch(
|
|
r"[a-z][a-z0-9_]*", connector_id
|
|
):
|
|
raise ValueError(
|
|
f"invalid Rakurai connector ID for {name}: {connector_id!r}"
|
|
)
|
|
if connector_id in rakurai_ids:
|
|
raise ValueError(f"duplicate Rakurai connector ID: {connector_id}")
|
|
rakurai_ids.add(connector_id)
|
|
if not isinstance(pool_type, str) or not re.fullmatch(
|
|
r"[a-z][a-z0-9_]*", pool_type
|
|
):
|
|
raise ValueError(
|
|
f"invalid Rakurai pool type for {name}: {pool_type!r}"
|
|
)
|
|
if quote_currency is not None and (
|
|
not isinstance(quote_currency, str)
|
|
or not re.fullmatch(r"[A-Z][A-Z0-9]*", quote_currency)
|
|
):
|
|
raise ValueError(
|
|
f"invalid Rakurai quote currency for {name}: "
|
|
f"{quote_currency!r}"
|
|
)
|
|
|
|
unset = next((v for v in venues if v["name"] == "UNSET"), None)
|
|
if unset is None or unset.get("legacy_id") != 0 or unset.get("domain_id") != 0:
|
|
raise ValueError("UNSET must retain legacy_id 0 and domain_id 0")
|
|
return venues
|
|
|
|
|
|
def enum_block(venues: list[dict[str, object]], kind: str) -> str:
|
|
id_key = f"{kind}_id"
|
|
selected = sorted((v for v in venues if id_key in v), key=lambda v: int(v[id_key]))
|
|
lines = [BEGIN, "enum Venue {"]
|
|
for venue in selected:
|
|
name = venue.get("domain_name", venue["name"]) if kind == "domain" else venue["name"]
|
|
lines.append(f" VENUE_{name} = {venue[id_key]};")
|
|
lines.extend(["}", END])
|
|
return "\n".join(lines)
|
|
|
|
|
|
def validate_published_ids(
|
|
venues: list[dict[str, object]], path: Path, kind: str
|
|
) -> None:
|
|
with path.open("r", encoding="utf-8", newline="") as source:
|
|
existing_source = source.read()
|
|
generated = re.search(
|
|
rf"{re.escape(BEGIN)}(.*?){re.escape(END)}", existing_source, re.DOTALL
|
|
)
|
|
if generated is None:
|
|
raise ValueError(f"generated venue markers missing from {path}")
|
|
existing = {
|
|
name: int(value)
|
|
for name, value in re.findall(r"VENUE_([A-Z0-9_]+)\s*=\s*(\d+)", generated.group(1))
|
|
}
|
|
id_key = f"{kind}_id"
|
|
expected = {}
|
|
for venue in venues:
|
|
if id_key not in venue:
|
|
continue
|
|
name = venue.get("domain_name", venue["name"]) if kind == "domain" else venue["name"]
|
|
expected[str(name)] = int(venue[id_key])
|
|
for name, published_id in existing.items():
|
|
if name not in expected:
|
|
raise ValueError(f"published {kind} venue VENUE_{name} cannot be removed")
|
|
if expected[name] != published_id:
|
|
raise ValueError(
|
|
f"published {kind} ID for VENUE_{name} cannot change "
|
|
f"from {published_id} to {expected[name]}"
|
|
)
|
|
|
|
|
|
def admin_block(venues: list[dict[str, object]]) -> str:
|
|
selected = sorted(
|
|
(v for v in venues if "legacy_id" in v and v.get("admin_selectable", True)),
|
|
key=lambda v: str(v["name"]),
|
|
)
|
|
def csharp_enum_name(name: str) -> str:
|
|
parts = name.split("_")
|
|
return name if len(parts) == 1 else "".join(part.title() for part in parts)
|
|
|
|
values = "; ".join(f"Venue.{csharp_enum_name(str(v['name']))}" for v in selected)
|
|
return f"{ADMIN_BEGIN}\nlet venues = [| {values}; |]\n{ADMIN_END}"
|
|
|
|
|
|
def config_import_block(venues: list[dict[str, object]]) -> str:
|
|
configs = sorted(
|
|
(v["market_data_config"] for v in venues if "market_data_config" in v),
|
|
key=lambda config: int(config["field_id"]),
|
|
)
|
|
imports = "\n".join(
|
|
f'import "spark/api/md/{config["type"]}.proto";' for config in configs
|
|
)
|
|
return f"{CONFIG_IMPORT_BEGIN}\n{imports}\n{CONFIG_IMPORT_END}"
|
|
|
|
|
|
def config_field_block(venues: list[dict[str, object]]) -> str:
|
|
selected = sorted(
|
|
(v for v in venues if "market_data_config" in v),
|
|
key=lambda v: int(v["market_data_config"]["field_id"]),
|
|
)
|
|
fields = []
|
|
for venue in selected:
|
|
config = venue["market_data_config"]
|
|
field_name = str(venue["name"]).lower()
|
|
fields.append(
|
|
f' repeated {config["type"]} {field_name} = {config["field_id"]};'
|
|
)
|
|
return f"{CONFIG_FIELD_BEGIN}\n" + "\n".join(fields) + f"\n{CONFIG_FIELD_END}"
|
|
|
|
|
|
def rakurai_registry(venues: list[dict[str, object]]) -> str:
|
|
mappings = [
|
|
(str(venue["name"]), connector)
|
|
for venue in venues
|
|
for connector in venue.get("rakurai", [])
|
|
]
|
|
supported = sorted({name for name, _ in mappings})
|
|
|
|
connector_names = "\n".join(
|
|
f" case ConnectorVenue::{connector['id']}:\n"
|
|
f" return \"{connector['id']}\";"
|
|
for _, connector in mappings
|
|
)
|
|
domain_matches = "\n".join(
|
|
f" case api::domain::VENUE_{name}:\n"
|
|
+ " return "
|
|
+ " ||\n ".join(
|
|
f"connector_venue == ConnectorVenue::{connector['id']}"
|
|
for mapping_name, connector in mappings
|
|
if mapping_name == name
|
|
)
|
|
+ ";"
|
|
for name in supported
|
|
)
|
|
legacy_matches = "\n".join(
|
|
f" case api::VENUE_{name}:\n"
|
|
+ " return "
|
|
+ " ||\n ".join(
|
|
f"connector_venue == ConnectorVenue::{connector['id']}"
|
|
for mapping_name, connector in mappings
|
|
if mapping_name == name
|
|
)
|
|
+ ";"
|
|
for name in supported
|
|
)
|
|
supported_cases = "\n".join(
|
|
f" case api::domain::VENUE_{name}:" for name in supported
|
|
)
|
|
security_type_cases = "\n".join(
|
|
f" case ConnectorVenue::{connector['id']}:\n"
|
|
f" return api::domain::SECURITY_TYPE_"
|
|
f"{'FUTURE' if connector['pool_type'] == 'perp' else 'SPOT'};"
|
|
for _, connector in mappings
|
|
)
|
|
quote_currency_cases = "\n".join(
|
|
f" case ConnectorVenue::{connector['id']}:\n"
|
|
f" return \"{connector['quote_currency']}\";"
|
|
for _, connector in mappings
|
|
if "quote_currency" in connector
|
|
)
|
|
config_cases = "\n".join(
|
|
f''' if (id == "{connector['id']}") {{
|
|
if (venue_filter.has_value() &&
|
|
*venue_filter != api::domain::VENUE_{name}) {{
|
|
return std::nullopt;
|
|
}}
|
|
ConnectorDexConfig config;
|
|
config.dex_name = ConnectorVenue::{connector['id']};
|
|
config.pool_typ = ConnectorPoolType::{connector['pool_type']};
|
|
return config;
|
|
}}'''
|
|
for name, connector in mappings
|
|
)
|
|
|
|
return f'''// Generated by tools/generate_venues.py. Do not edit.
|
|
#pragma once
|
|
|
|
#include "spark/api/domain/SecurityType.pb.h"
|
|
#include "spark/api/domain/Venue.pb.h"
|
|
#include "spark/domain_model/Security.pb.h"
|
|
|
|
#include <dex_utils.h>
|
|
|
|
#include <optional>
|
|
#include <string_view>
|
|
|
|
namespace bts::rakurai {{
|
|
|
|
using ConnectorDexConfig = ::rakurai::dex_connector::configuration::dex_config;
|
|
using ConnectorPoolType = ::rakurai::dex_connector::data_types::pool_type;
|
|
using ConnectorVenue = ::rakurai::dex_connector::data_types::venue;
|
|
|
|
inline std::string_view connector_venue_name(ConnectorVenue venue) {{
|
|
switch (venue) {{
|
|
{connector_names}
|
|
default:
|
|
return "invalid";
|
|
}}
|
|
}}
|
|
|
|
inline bool venue_matches(
|
|
api::domain::Venue spark_venue, ConnectorVenue connector_venue) {{
|
|
switch (spark_venue) {{
|
|
{domain_matches}
|
|
default:
|
|
return false;
|
|
}}
|
|
}}
|
|
|
|
inline bool venue_matches(
|
|
api::Venue spark_venue, ConnectorVenue connector_venue) {{
|
|
switch (spark_venue) {{
|
|
{legacy_matches}
|
|
default:
|
|
return false;
|
|
}}
|
|
}}
|
|
|
|
inline bool is_rakurai_venue(api::domain::Venue venue) {{
|
|
switch (venue) {{
|
|
{supported_cases}
|
|
return true;
|
|
default:
|
|
return false;
|
|
}}
|
|
}}
|
|
|
|
inline api::domain::SecurityType connector_security_type(
|
|
ConnectorVenue venue) {{
|
|
switch (venue) {{
|
|
{security_type_cases}
|
|
default:
|
|
return api::domain::SECURITY_TYPE_UNSPECIFIED;
|
|
}}
|
|
}}
|
|
|
|
inline std::string_view connector_quote_currency(ConnectorVenue venue) {{
|
|
switch (venue) {{
|
|
{quote_currency_cases}
|
|
default:
|
|
return {{}};
|
|
}}
|
|
}}
|
|
|
|
inline std::optional<ConnectorDexConfig> make_connector_dex_config(
|
|
std::string_view id,
|
|
std::optional<api::domain::Venue> venue_filter = std::nullopt) {{
|
|
{config_cases}
|
|
return std::nullopt;
|
|
}}
|
|
|
|
}} // namespace bts::rakurai
|
|
'''
|
|
|
|
|
|
def rakurai_venues(venues: list[dict[str, object]]) -> str:
|
|
cases = "\n".join(
|
|
f" case api::VENUE_{venue['name']}:"
|
|
for venue in venues if venue.get("rakurai")
|
|
)
|
|
return f'''// Generated by tools/generate_venues.py. Do not edit.
|
|
#pragma once
|
|
|
|
#include "spark/domain_model/Security.pb.h"
|
|
|
|
namespace bts::domain {{
|
|
|
|
// Shared execution metadata must not depend on the Rakurai connector library.
|
|
inline bool is_rakurai_venue(api::Venue venue) {{
|
|
switch (venue) {{
|
|
{cases}
|
|
return true;
|
|
default:
|
|
return false;
|
|
}}
|
|
}}
|
|
|
|
}} // namespace bts::domain
|
|
'''
|
|
|
|
|
|
def write_generated_file(path: Path, content: str, check: bool) -> bool:
|
|
if path.exists() and path.read_text(encoding="utf-8") == content:
|
|
return True
|
|
if check:
|
|
print(f"out of date: {path.relative_to(ROOT)}", file=sys.stderr)
|
|
return False
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(content, encoding="utf-8")
|
|
print(f"updated {path.relative_to(ROOT)}")
|
|
return True
|
|
|
|
|
|
def replace_block(
|
|
path: Path, block: str, check: bool, begin: str = BEGIN, end: str = END
|
|
) -> bool:
|
|
with path.open("r", encoding="utf-8", newline="") as source:
|
|
original = source.read()
|
|
newline = "\r\n" if "\r\n" in original else "\n"
|
|
block = block.replace("\n", newline)
|
|
pattern = re.compile(rf"{re.escape(begin)}.*?{re.escape(end)}", re.DOTALL)
|
|
if not pattern.search(original):
|
|
raise ValueError(f"generated venue markers missing from {path}")
|
|
updated = pattern.sub(block, original, count=1)
|
|
if updated == original:
|
|
return True
|
|
if check:
|
|
print(f"out of date: {path.relative_to(ROOT)}", file=sys.stderr)
|
|
return False
|
|
with path.open("w", encoding="utf-8", newline="") as destination:
|
|
destination.write(updated)
|
|
print(f"updated {path.relative_to(ROOT)}")
|
|
return True
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--check", action="store_true", help="fail instead of updating generated files")
|
|
args = parser.parse_args()
|
|
try:
|
|
venues = load_venues()
|
|
validate_published_ids(venues, LEGACY_PROTO, "legacy")
|
|
validate_published_ids(venues, DOMAIN_PROTO, "domain")
|
|
ok = replace_block(LEGACY_PROTO, enum_block(venues, "legacy"), args.check)
|
|
ok = replace_block(DOMAIN_PROTO, enum_block(venues, "domain"), args.check) and ok
|
|
ok = replace_block(
|
|
ADMIN_TYPES,
|
|
admin_block(venues),
|
|
args.check,
|
|
ADMIN_BEGIN,
|
|
ADMIN_END,
|
|
) and ok
|
|
ok = replace_block(
|
|
MARKET_DATA_CONFIG,
|
|
config_import_block(venues),
|
|
args.check,
|
|
CONFIG_IMPORT_BEGIN,
|
|
CONFIG_IMPORT_END,
|
|
) and ok
|
|
ok = replace_block(
|
|
MARKET_DATA_CONFIG,
|
|
config_field_block(venues),
|
|
args.check,
|
|
CONFIG_FIELD_BEGIN,
|
|
CONFIG_FIELD_END,
|
|
) and ok
|
|
ok = write_generated_file(
|
|
RAKURAI_REGISTRY, rakurai_registry(venues), args.check
|
|
) and ok
|
|
ok = write_generated_file(
|
|
RAKURAI_VENUES, rakurai_venues(venues), args.check
|
|
) and ok
|
|
return 0 if ok else 1
|
|
except (OSError, ValueError, json.JSONDecodeError) as error:
|
|
print(f"venue generation failed: {error}", file=sys.stderr)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|