Compare commits

..

9 Commits

Author SHA1 Message Date
df75875491 Merge branch 'release/beta-1.1' 2025-12-10 11:23:27 +01:00
27609dba2b fixed logs and config locations, updated connection closure handling 2025-12-10 11:22:09 +01:00
709abb30fa updated docs, minor changes 2025-12-08 09:36:40 +01:00
0c7909a701 added docs 2025-12-08 07:30:40 +01:00
7c9a7eedf9 Merge tag 'beta-1.0' into develop
Tagging version beta-1.0 beta-1.0
2025-12-08 07:01:46 +01:00
63f54167c4 Merge branch 'release/beta-1.0' 2025-12-08 07:01:45 +01:00
e198fc4b3f updated .gitignore 2025-12-08 07:01:05 +01:00
8e84523d4b continuous send for simulators 2025-12-08 06:58:43 +01:00
786b217f05 quality of life, updated config structure 2025-12-08 06:57:54 +01:00
15 changed files with 808 additions and 273 deletions

4
.gitignore vendored
View File

@@ -1,3 +1,7 @@
*
!*/
!*.*
*.exe
*.exe~
*.dll

474
README.md
View File

@@ -2,14 +2,476 @@
Gateway between multiple HomesteadRelay's and the HomesteadToGo Bot.
---
## dev notes
## HomesteadGateway Developer Documentation
perhaps drop database, instead
## Overview
HomesteadGateway is a WebSocket-based message routing gateway that facilitates bidirectional communication between game server mods/plugins and external bots (e.g., Discord bots). It acts as a relay, routing messages based on channel identifiers and managing message queues when endpoints are offline.
**Key Features:**
- WebSocket-based real-time communication
- Channel-based message routing
- Automatic message queuing for offline recipients
- API key authentication
- Connection keep-alive via ping/pong
- Support for multiple concurrent mod connections per channel
---
## Quick Start
1. Start the gateway (build/run your application that embeds the WebSocket gateway).
2. Connect a client to the WebSocket endpoint:
- URL: `ws://<host>:<port>/sync?api_key=<your_api_key>`
3. Immediately send a handshake JSON with type `mod` or `bot`.
4. On success, youll receive `{"status":"connected","type":"mod|bot"}`.
5. Exchange messages as JSON.
See the full details below.
---
## Architecture
### Connection Types
The gateway supports two types of connections:
1. **Mod Connection** - Game server mods/plugins that send and receive player messages
2. **Bot Connection** - External bots (typically Discord) that bridge messages to/from other platforms
### Message Flow
```
Mod -> websocket /register { server_id, channel_id } // grabbed from mod config
Bot -> websocket /ready { channel_id } // ready if Mod with fitting channel_id has called /register
Gateway -> memory cache (server_id -> channel_id; channel_id -> server_id) // mem enough
Mod/Bot -> websocket /ws { ... } -> Bot/Mod // sync
Mod (Server) ←→ Gateway ←→ Bot (Discord)
Channel A Channel A
```
Messages are routed based on `channel_id`:
- **Mod → Bot**: Messages from a mod are forwarded to the bot
- **Bot → Mod**: Messages from a bot are forwarded to the mod registered for that channel
---
## Connection Setup
### Endpoint
```
ws://<host>:<port>/sync?api_key=<your_api_key>
```
**Default Port:** 3333 (configurable)
### Authentication
Authentication is performed via API key, which can be provided in two ways:
1. **Query Parameter** (recommended):
```
ws://localhost:3333/sync?api_key=gateway
```
2. **HTTP Header**:
```
X-API-Key: gateway
```
### Connection Timeout
After connecting, you **must** send a handshake message within **60 seconds** or the connection will be closed.
---
## Handshake Protocol
### Step 1: Establish WebSocket Connection
Connect to the `/sync` endpoint with your API key.
### Step 2: Send Handshake Message
Immediately after connecting, send a JSON handshake message:
```json
{
"type": "mod", // or "bot"
"data": { ... }
}
```
#### Mod Handshake
For game server mods/plugins:
```json
{
"type": "mod",
"data": {
"server_id": "minecraft-server-001",
"channel_id": "123456789"
}
}
```
**Fields:**
- `server_id` (string, required): Unique identifier for your server instance
- `channel_id` (string, required): The Discord channel ID (or equivalent) this mod serves
#### Bot Handshake
For bots (Discord bots, etc.):
```json
{
"type": "bot",
"data": {
"bot_id": "discord-bot-123"
}
}
```
**Fields:**
- `bot_id` (string, required): The bots ID
**Note:** Only **one bot connection** is allowed at a time. Trying to connect a new bot will result in an `409 Conflict` Error.
### Step 3: Receive Acknowledgment
After sending the handshake, wait for an acknowledgment:
**Success Response:**
```json
{
"status": "connected",
"type": "mod|bot"
}
```
**Error Responses:**
```json
{
"message": "Malformed handshake.",
"code": 400
}
```
```json
{
"message": "Bot already connected.",
"code": 409
}
```
### Step 4: Begin Message Exchange
Once acknowledged, the connection is established and you can start sending/receiving messages.
---
## Message Protocol
### Sending Messages
After handshake, send messages as JSON:
#### From Mod to Bot
```json
{
"msg_id": "msg-unique-123",
"id": "minecraft-server-001",
"destination": {
"channel_id": "123456789"
},
"author": {
"id": "player-uuid-abc",
"name": "PlayerName"
},
"content": "Hello from the game server!",
"meta": {
"server_name": "Survival Server",
"world": "overworld"
},
"ts": "2025-12-08T10:30:00Z"
}
```
**Required Fields:**
- `msg_id` (string): Unique message identifier (generate client-side)
- `id` (string): Server ID (must match your handshake `server_id`)
- `destination.channel_id` (string): Target channel ID
- `author.id` (string): User/player identifier
- `content` (string): Message content (non-empty)
**Optional Fields:**
- `author.name` (string): Display name for the author
- `meta` (object): Additional metadata (arbitrary key-value pairs)
- `ts` (RFC3339 timestamp): Message timestamp (defaults to server time if omitted)
#### From Bot to Mod
```json
{
"msg_id": "discord-msg-456",
"id": "123456789",
"author": {
"id": "discord-user-789",
"name": "DiscordUser"
},
"content": "Hello from Discord!",
"meta": {
"platform": "discord",
"roles": ["admin"]
},
"ts": "2025-12-08T10:31:00Z"
}
```
**Required Fields:**
- `msg_id` (string): Unique message identifier
- `id` (string): Channel ID (from which channel the message originates)
- `author.id` (string): User identifier
- `content` (string): Message content (non-empty)
**Optional Fields:**
- `author.name` (string): Display name
- `meta` (object): Additional metadata
- `ts` (RFC3339 timestamp): Message timestamp
**Note:** Bot messages do **not** include a `destination` field, as the channel ID in `id` determines routing.
### Receiving Messages
Messages are received as JSON in the same format they were sent:
#### Mod Receives (from Bot)
```json
{
"type": "bot",
"channel_id": "123456789",
"author": {
"id": "discord-user-789",
"name": "DiscordUser"
},
"content": "Hello from Discord!",
"meta": {
"platform": "discord"
},
"ts": "2025-12-08T10:31:00Z",
"received_at": "2025-12-08T10:31:00.123Z",
"forwarded_at": "2025-12-08T10:31:00.125Z"
}
```
#### Bot Receives (from Mod)
```json
{
"type": "mod",
"channel_id": "123456789",
"author": {
"id": "player-uuid-abc",
"name": "PlayerName"
},
"content": "Hello from the game server!",
"meta": {
"server_name": "Survival Server"
},
"ts": "2025-12-08T10:30:00Z",
"received_at": "2025-12-08T10:30:00.100Z",
"forwarded_at": "2025-12-08T10:30:00.102Z"
}
```
**Additional Fields in Received Messages:**
- `type` (string): Origin type ("mod" or "bot")
- `channel_id` (string): The channel this message belongs to
- `received_at` (RFC3339): When gateway received the message
- `forwarded_at` (RFC3339): When gateway forwarded the message
### Message Acknowledgments
After sending each message, you'll receive an acknowledgment:
```json
{
"status": "completed",
"type": "mod"
}
```
**Status Values:**
- `completed`: Message was delivered immediately to recipient
- `queued`: Recipient is offline; message queued for later delivery
- `failed`: Message could not be delivered or queued
---
## Message Queuing
When a recipient is offline, messages are automatically queued:
- **Queue Size:** Configurable (default: 8 messages per channel)
- **Queue Behavior:** Circular buffer (oldest messages are overwritten when full)
- **Flush Trigger:** When recipient reconnects, all queued messages are delivered
### Example Flow
1. Mod sends message while bot is offline → Message queued
2. Bot connects and completes handshake → All queued messages flushed to bot
3. Bot sends message while mod is offline → Message queued
4. Mod connects → Queued messages flushed to mod
---
## Keep-Alive & Ping/Pong
The gateway sends **WebSocket ping messages every 30 seconds** to maintain connections.
**Client Responsibilities:**
1. **Respond to pings**: Your WebSocket library should automatically handle pong responses
2. **Handle pongs**: Set a pong handler to reset read deadlines
3. **Read Deadline**: The gateway sets a 60-second read deadline, reset on each pong
### Example (Go)
```go
conn.SetPongHandler(func(appData string) error {
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
```
---
## Error Handling
### Connection Errors
**Handshake Errors:**
- `400` - Malformed handshake JSON
- `401` - Invalid or missing API key
- `409` - Bot already connected (only for bot handshakes)
- `500` - Internal server error
**Message Errors:**
- `400` - Malformed message (missing required fields)
Errors are sent as JSON:
```json
{
"message": "Malformed message.",
"code": 400
}
```
### Validation Rules
Messages are validated on receipt:
- `id` must not be empty
- `msg_id` must not be empty
- `author.id` must not be empty
- `content` must not be empty
- For mod messages: `destination.channel_id` must not be empty
### Websocket Closures
- `1000` - Normal closure
- `1001` - Going away
Handle other WebSocket closures as unexpected errors.
---
## Rate Limits & Restrictions
- **Message Size Limit:** 2 MB per message (configurable)
- **Read Limit:** Messages exceeding the limit will close the connection
- **Concurrent Mods:** Multiple mods *can* connect to the same channel ID (different server IDs)
- **Concurrent Bots:** Only **one bot connection** allowed globally
---
## Best Practices
### 1. Generate Unique Message IDs
Always generate unique `msg_id` values for each message. Consider using:
- UUID v4
- Timestamp + random suffix
- Sequential counter with prefix
### 2. Handle Reconnections
Implement automatic reconnection logic with exponential backoff:
```
1st retry: 1 second
2nd retry: 2 seconds
3rd retry: 4 seconds
Max: 30 seconds
```
### 3. Set Appropriate Timeouts
- Write timeout: 5 seconds (same as Gateway)
- Read timeout: 60 seconds (reset on pong)
### 4. Validate Before Sending
Check required fields locally before sending to avoid validation errors.
### 5. Monitor Acknowledgments
Track acknowledgment statuses:
- `completed`: Message delivered
- `queued`: Message queued
- `failed`: Log and potentially retry
### 6. Use Metadata
The `meta` field is used for:
- Server information (server name, region, version)
- User context (roles, permissions)
- Message context (reply-to, thread-id)
### 7. Thread-Safe Writes
Use mutex/locks when writing to WebSocket from multiple threads.
---
## API Reference
### Endpoints
#### `GET /sync`
WebSocket upgrade endpoint for mod/bot connections.
**Query Parameters:**
- `api_key` (required): Authentication token
#### `GET /health`
Health check endpoint.
**Response:**
```json
{
"status": "healthy"
}
```
---
## Configuration
Gateway configuration (`config.toml`):
```toml
[gateway]
http_port = 3333 # WebSocket port
websocket = "gateway" # API key
body_size = 1 # Max message size in MB
queue_max = 8 # Messages per channel queue
```
---

122
bot.go
View File

@@ -5,10 +5,14 @@ package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"math/rand"
"net/url"
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
@@ -18,8 +22,12 @@ import (
const (
gatewayURL = "ws://localhost:3333/sync"
apiKey = "gateway"
// must match the mod's channel id used by your mod simulator
channelID = "123456789"
channelID = "123456789"
)
var (
minInterval = 500 * time.Millisecond
maxInterval = 5 * time.Second
)
type Handshake struct {
@@ -28,7 +36,7 @@ type Handshake struct {
}
type BotHandshake struct {
ChannelId string `json:"channel_id"` // match gateway field exactly
BotID string `json:"bot_id"`
}
type GatewayAck struct {
@@ -56,12 +64,21 @@ type GatewayMessageIn struct {
ReceivedAt time.Time `json:"-"`
}
func randomDuration(min, max time.Duration) time.Duration {
if max <= min {
return min
}
diff := int64(max - min)
n := rand.Int63n(diff)
return min + time.Duration(n)
}
func main() {
var (
botID = flag.String("bot", "sim-bot-1", "bot id")
sendAfter = flag.Duration("send-after", 0, "optional: send a bot->mod message after this delay (e.g. 2s)")
sendMsg = flag.String("msg", "Hello from bot!", "optional bot->mod test message content")
)
rand.Seed(time.Now().UnixNano())
botID := flag.String("bot", "sim-bot-1", "bot id")
sendAfter := flag.Duration("send-after", 0, "optional: send a bot->mod message after this delay (e.g. 2s)")
sendMsg := flag.String("msg", "Hello from bot!", "optional bot->mod test message content")
flag.Parse()
interrupt := make(chan os.Signal, 1)
@@ -75,43 +92,48 @@ func main() {
q.Set("api_key", apiKey)
u.RawQuery = q.Encode()
log.Printf("Connecting to %s", u.String())
conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatalf("Failed to connect: %v", err)
}
// we intentionally don't defer conn.Close() here immediately; we'll do on shutdown
log.Println("Connected to gateway")
defer conn.Close()
var writeMu sync.Mutex
// handle server pings by replying a Pong (safe)
conn.SetPingHandler(func(appData string) error {
log.Println("Received ping from server, sending pong")
return conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(5*time.Second))
writeMu.Lock()
err := conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(5*time.Second))
writeMu.Unlock()
if err != nil {
log.Printf("Failed to send pong: %v", err)
return err
}
return nil
})
// send bot handshake (must at least include bot_id)
bhs := BotHandshake{ChannelId: channelID}
bhs := BotHandshake{BotID: "discord-bot"}
data, err := json.Marshal(bhs)
if err != nil {
_ = conn.Close()
log.Fatalf("Failed to marshal bot handshake: %v", err)
}
hs := Handshake{Type: "bot", Data: data}
writeMu.Lock()
if err := conn.WriteJSON(hs); err != nil {
writeMu.Unlock()
_ = conn.Close()
log.Fatalf("Failed to send handshake: %v", err)
}
log.Println("Handshake sent (bot)")
writeMu.Unlock()
// Instead of ReadJSON, read raw message so we can see whatever the server returns (or why it closes).
// This avoids a silent parsing failure if server returns non-JSON or closes immediately.
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
msgType, raw, err := conn.ReadMessage()
if err != nil {
_ = conn.Close()
log.Fatalf("Failed to read handshake response: %v", err)
}
_ = conn.SetReadDeadline(time.Time{}) // clear deadline
_ = conn.SetReadDeadline(time.Time{})
if msgType == websocket.TextMessage || msgType == websocket.BinaryMessage {
log.Printf("Raw handshake reply: %s", string(raw))
@@ -122,11 +144,11 @@ func main() {
log.Printf("Parsed ack: status=%q, type=%q", ack.Status, ack.Type)
}
} else {
log.Printf("Handshake reply was control frame or unexpected type=%d", msgType)
log.Printf("Handshake reply type=%d", msgType)
}
// From here, start the normal read loop.
done := make(chan struct{})
go func() {
defer close(done)
for {
@@ -139,20 +161,20 @@ func main() {
}
return
}
if msgType == websocket.TextMessage || msgType == websocket.BinaryMessage {
log.Printf("Received from gateway: %s", string(message))
}
}
}()
// optionally send a bot->mod message after a delay
var msgCounter uint64 = 1
if *sendAfter > 0 {
go func() {
time.Sleep(*sendAfter)
msg := GatewayMessageIn{
MsgID: "bot-msg-001",
ID: channelID, // bot reports channel id as ID
MsgID: fmt.Sprintf("bot-msg-%06d", atomic.AddUint64(&msgCounter, 1)),
ID: channelID,
Author: User{
ID: *botID,
Name: "SimBot",
@@ -160,20 +182,55 @@ func main() {
Content: *sendMsg,
Ts: time.Now().UTC(),
}
// set a write deadline
writeMu.Lock()
_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
if err := conn.WriteJSON(msg); err != nil {
log.Printf("Failed to send bot->mod test message: %v", err)
return
} else {
log.Printf("Sent bot->mod test message (channel=%s)", channelID)
}
log.Printf("Sent bot->mod test message (channel=%s)", channelID)
_ = conn.SetWriteDeadline(time.Time{})
writeMu.Unlock()
}()
}
log.Println("Bot simulator running. Press Ctrl+C to exit.")
go func() {
for {
select {
case <-done:
return
default:
}
d := randomDuration(minInterval, maxInterval)
select {
case <-done:
return
case <-time.After(d):
msgNum := atomic.AddUint64(&msgCounter, 1)
msg := GatewayMessageIn{
MsgID: fmt.Sprintf("sim-bot-msg-%06d", msgNum),
ID: channelID,
Author: User{
ID: fmt.Sprintf("%s-%d", *botID, msgNum%1000),
Name: fmt.Sprintf("SimBot%d", msgNum%1000),
},
Content: fmt.Sprintf("Automated bot message #%d (delay %s)", msgNum, d),
Ts: time.Now().UTC(),
}
writeMu.Lock()
_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
if err := conn.WriteJSON(msg); err != nil {
writeMu.Unlock()
log.Printf("Failed to send automated bot message: %v", err)
return
}
_ = conn.SetWriteDeadline(time.Time{})
writeMu.Unlock()
log.Printf("Sent automated bot message %s", msg.MsgID)
}
}
}()
// Wait for interrupt or read loop done
for {
select {
case <-done:
@@ -182,8 +239,9 @@ func main() {
return
case <-interrupt:
log.Println("Interrupt received, closing connection...")
// politely close
writeMu.Lock()
_ = conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
writeMu.Unlock()
select {
case <-done:
case <-time.After(time.Second):

View File

@@ -7,10 +7,4 @@ rotation = 3 # in days
http_port = 3333
websocket = "gateway"
body_size = 2 # in MB
queue_max = 8192
[database]
host_dsn = ""
username = ""
password = ""
database = ""
queue_max = 8

View File

@@ -1,8 +1,6 @@
package controller
import (
"homestead/homestead_gateway/ws"
)
import "homestead/homestead_gateway/ws"
type GatewayController struct {
Websocket *ws.WebsocketGateway

13
main.go
View File

@@ -3,11 +3,20 @@ package main
import (
"flag"
"homestead/homestead_gateway/controller"
"homestead/homestead_gateway/util"
"homestead/homestead_gateway/util/config"
"os"
"path"
)
func main() {
cfgPath := flag.String("config", "config.toml", "configuration file")
dir := util.GetPath()
if dir == "" {
dir, _ = os.Getwd()
}
file := path.Join(dir, "config.toml")
cfgPath := flag.String("config", file, "configuration file")
cfg, err := config.LoadConfig(*cfgPath)
if err != nil {
panic(err)
@@ -19,3 +28,5 @@ func main() {
panic(err)
}
}
// todo logs from exe not cwd

133
sim.go
View File

@@ -4,10 +4,14 @@ package main
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/url"
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
@@ -19,7 +23,13 @@ const (
apiKey = "gateway"
serverID = "test-server-001"
// THE CHANNEL ID the mod says it serves. Must match gateway expectation.
channelID = "123456789"
channelID = "1444253682777587804"
)
// send interval range (random between minInterval and maxInterval)
var (
minInterval = 500 * time.Millisecond
maxInterval = 5 * time.Second
)
type Handshake struct {
@@ -59,6 +69,8 @@ type GatewayMessageIn struct {
}
func main() {
rand.Seed(time.Now().UnixNano())
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
@@ -80,19 +92,19 @@ func main() {
log.Println("Connected to gateway")
// respond to pings (server ping -> client must pong). Using SetPingHandler is fine,
// but WriteControl for Pong is acceptable too.
var writeMu sync.Mutex
conn.SetPingHandler(func(appData string) error {
log.Println("Received ping from server, sending pong")
err := conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(5*time.Second))
if err != nil {
writeMu.Lock()
defer writeMu.Unlock()
if err := conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(5*time.Second)); err != nil {
log.Printf("Failed to send pong: %v", err)
return err
}
return nil
})
// Build and send handshake including channel id
modHS := ModHandshake{
ServerID: serverID,
ChannelID: channelID,
@@ -107,12 +119,14 @@ func main() {
Data: modHSData,
}
writeMu.Lock()
if err := conn.WriteJSON(handshake); err != nil {
writeMu.Unlock()
log.Fatalf("Failed to send handshake: %v", err)
}
writeMu.Unlock()
log.Println("Handshake sent")
// Read acknowledgment (some servers might not reply with JSON; handle errors)
var ack GatewayAck
if err := conn.ReadJSON(&ack); err != nil {
log.Fatalf("Failed to read acknowledgment: %v", err)
@@ -129,62 +143,115 @@ func main() {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
log.Printf("WebSocket error: %v", err)
} else {
log.Printf("Connection closed: %v", err)
log.Printf("Connection closed/read error: %v", err)
}
return
}
if messageType == websocket.TextMessage || messageType == websocket.BinaryMessage {
switch messageType {
case websocket.TextMessage, websocket.BinaryMessage:
log.Printf("Received from server: %s", string(message))
default:
}
}
}()
// Optional: send a test message after connecting
time.Sleep(1 * time.Second)
testMsg := GatewayMessageIn{
MsgID: "test-msg-001",
ID: serverID,
Destination: Destination{
ID: channelID,
},
Author: User{
ID: "player-uuid-123",
Name: "TestPlayer",
},
Content: "Hello from simulated mod!",
Ts: time.Now().UTC(),
}
var msgCounter uint64 = 1
if err := conn.WriteJSON(testMsg); err != nil {
log.Printf("Failed to send test message: %v", err)
} else {
log.Println("Sent test message to gateway")
}
func() {
testMsg := GatewayMessageIn{
MsgID: fmt.Sprintf("test-msg-%06d", atomic.AddUint64(&msgCounter, 1)),
ID: serverID,
Destination: Destination{
ID: channelID,
},
Author: User{
ID: "player-uuid-123",
Name: "TestPlayer",
},
Content: "Hello from simulated mod!",
Ts: time.Now().UTC(),
}
log.Println("Connection established. Responding to pings. Press Ctrl+C to disconnect.")
writeMu.Lock()
if err := conn.WriteJSON(testMsg); err != nil {
log.Printf("Failed to send test message: %v", err)
} else {
log.Println("Sent initial test message to gateway")
}
writeMu.Unlock()
}()
go func() {
for {
d := randomDuration(minInterval, maxInterval)
select {
case <-done:
return
case <-time.After(d):
// build message
msgNum := atomic.AddUint64(&msgCounter, 1)
msg := GatewayMessageIn{
MsgID: fmt.Sprintf("sim-msg-%06d", msgNum),
ID: serverID,
Destination: Destination{
ID: channelID,
},
Author: User{
ID: fmt.Sprintf("sim-user-%d", msgNum%1000),
Name: fmt.Sprintf("SimUser%d", msgNum%1000),
},
Content: fmt.Sprintf("Random interval message #%d (delay %s)", msgNum, d),
Ts: time.Now().UTC(),
}
writeMu.Lock()
if err := conn.WriteJSON(msg); err != nil {
log.Printf("Failed to send simulated message: %v", err)
writeMu.Unlock()
return
}
writeMu.Unlock()
log.Printf("Sent simulated message %s (next wait up to %s)", msg.MsgID, maxInterval)
}
}
}()
log.Println("Connection established. Sending simulated messages at random intervals. Press Ctrl+C to disconnect.")
for {
select {
case <-done:
log.Println("Connection closed")
log.Println("Connection read loop closed, exiting")
return
case <-interrupt:
log.Println("Interrupt received, closing connection...")
writeMu.Lock()
err := conn.WriteMessage(
websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
)
writeMu.Unlock()
if err != nil {
log.Printf("Write close error: %v", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
case <-time.After(1 * time.Second):
}
return
}
}
}
func randomDuration(min, max time.Duration) time.Duration {
if max <= min {
return min
}
diff := int64(max - min)
n := rand.Int63n(diff)
return min + time.Duration(n)
}

View File

@@ -3,9 +3,8 @@ package config
import "log/slog"
type Config struct {
Log LogConfig `toml:"log"`
Gateway GatewayConfig `toml:"gateway"`
Database DatabaseConfig `toml:"database"`
Log LogConfig `toml:"log"`
Gateway GatewayConfig `toml:"gateway"`
}
type GatewayConfig struct {
@@ -20,10 +19,3 @@ type LogConfig struct {
Directory string `toml:"directory"`
Rotation int `toml:"rotation"`
}
type DatabaseConfig struct {
HostDSN string `toml:"host_dsn"`
Username string `toml:"username"`
Password string `toml:"password"`
Database string `toml:"database"`
}

View File

@@ -3,6 +3,7 @@ package logger
import (
"context"
"fmt"
"homestead/homestead_gateway/util"
"homestead/homestead_gateway/util/config"
"log/slog"
"os"
@@ -23,6 +24,7 @@ func New(id string, cfg config.LogConfig) (*slog.Logger, func() error, error) {
cfg.Rotation = 7
}
cfg.Directory = util.NormalizeLogPath(cfg.Directory)
console := slog.NewTextHandler(&prefixWriter{inner: os.Stderr, prefix: []byte("[" + id + "] "), startLine: true}, &slog.HandlerOptions{AddSource: true, Level: cfg.Level})
router := newFileRouter(cfg.Directory, cfg.Rotation, id)
root := slogmulti.Fanout(console, router)

51
util/util.go Normal file
View File

@@ -0,0 +1,51 @@
package util
import (
"os"
"path/filepath"
"time"
"github.com/gorilla/websocket"
)
func GetPath() string {
exe, err := os.Executable()
if err != nil {
return ""
}
exe, err = filepath.EvalSymlinks(exe)
if err != nil {
}
return filepath.Dir(exe)
}
func NormalizePath(path string) string {
return filepath.Clean(filepath.FromSlash(path))
}
func NormalizeLogPath(path string) string {
if filepath.IsAbs(path) {
return path
}
return NormalizePath(filepath.Join(GetPath(), path))
}
//
func CloseConnWithControlMessage(conn *websocket.Conn, typ int, text string) {
_ = conn.SetWriteDeadline(time.Now().Add(time.Second))
_ = conn.WriteControl(
typ, websocket.FormatCloseMessage(typ, text), time.Now().Add(time.Second),
)
_ = conn.Close()
}
func CloseConn(conn *websocket.Conn) {
CloseConnWithControlMessage(
conn, websocket.CloseNormalClosure,
"Disconnecting.",
)
}

View File

@@ -68,7 +68,7 @@ func (wsg *WebsocketGateway) handleSync(w http.ResponseWriter, r *http.Request)
_ = wsg.sendWebsocketResponse(conn, GatewayAck{Status: "connected", Type: "mod"})
wsg.registry.FlushChannelWithSender(mhs.ChannelID, wsg.flush)
wsg.logger.Info("Mod connected via Websocket.", "remote", conn.RemoteAddr().String())
wsg.logger.Info("Mod connected via Websocket.", "remote", conn.RemoteAddr().String(), "id", mhs.ServerID)
go wsg.read(conn, "mod", mhs.ChannelID)
case "bot":
@@ -78,12 +78,12 @@ func (wsg *WebsocketGateway) handleSync(w http.ResponseWriter, r *http.Request)
return
}
if bhs.ChannelId == "" {
if bhs.BotID == "" {
wsg.sendWebsocketError(conn, "Malformed bot handshake.", 400, true)
return
}
if !wsg.registerConn(conn, "bot", bhs.ChannelId, "") {
if !wsg.registerConn(conn, "bot", "", "") {
wsg.sendWebsocketError(conn, "Bot already connected.", 409, true)
return
}
@@ -91,8 +91,8 @@ func (wsg *WebsocketGateway) handleSync(w http.ResponseWriter, r *http.Request)
_ = wsg.sendWebsocketResponse(conn, GatewayAck{Status: "connected", Type: "bot"})
wsg.registry.FlushAllToBotWithSender(wsg.flush)
wsg.logger.Info("Bot connected via Websocket.", "remote", conn.RemoteAddr().String())
go wsg.read(conn, "bot", bhs.ChannelId)
wsg.logger.Info("Bot connected via Websocket.", "remote", conn.RemoteAddr().String(), "id", bhs.BotID)
go wsg.read(conn, "bot", "")
default:
wsg.sendWebsocketError(conn, "Unknown handshake.", 400, true)

View File

@@ -2,6 +2,7 @@ package ws
import (
"fmt"
"homestead/homestead_gateway/util"
"time"
"github.com/gorilla/websocket"
@@ -13,14 +14,17 @@ func (q *BoundedQueue) Enqueue(m GatewayMessageOut) bool {
if q.capacity == 0 {
return false
}
if q.length < q.capacity {
q.buf[(q.start+q.length)%q.capacity] = m
q.length++
return true
}
// overwrite oldest
q.buf[q.start] = m
q.start = (q.start + 1) % q.capacity
return true
}
@@ -30,12 +34,15 @@ func (q *BoundedQueue) PopAll() []GatewayMessageOut {
if q.length == 0 {
return nil
}
out := make([]GatewayMessageOut, 0, q.length)
for i := 0; i < q.length; i++ {
out = append(out, q.buf[(q.start+i)%q.capacity])
}
q.start = 0
q.length = 0
return out
}
@@ -64,6 +71,19 @@ func (r *Registry) getOrCreate(channel string) *ChannelEntry {
return e
}
func (r *Registry) ForEach(cb func(channelID string)) {
r.mu.RLock()
ids := make([]string, 0, len(r.entries))
for id := range r.entries {
ids = append(ids, id)
}
r.mu.RUnlock()
for _, id := range ids {
cb(id)
}
}
//
// RegisterMod : map channel_id -> mod conn (serverID)
@@ -71,9 +91,11 @@ func (r *Registry) RegisterMod(channelID, serverID string, conn *websocket.Conn)
e := r.getOrCreate(channelID)
e.mu.Lock()
defer e.mu.Unlock()
if e.Mod != nil && e.Mod.Conn != nil {
_ = e.Mod.Conn.Close()
util.CloseConn(e.Mod.Conn)
}
e.Mod = &ConnWrapper{Conn: conn, ServerID: serverID, LastSeen: time.Now()}
// flush queued bot->mod messages for this channel
// caller should use FlushChannelWithSender to perform actual sends
@@ -82,9 +104,11 @@ func (r *Registry) RegisterMod(channelID, serverID string, conn *websocket.Conn)
// RegisterBot : single connection for bot. after registration call FlushAllToBotWithSender
func (r *Registry) RegisterBot(conn *websocket.Conn) {
r.botMu.Lock()
if r.bot != nil && r.bot.Conn != nil {
_ = r.bot.Conn.Close()
r.UnregisterBot()
}
r.bot = &ConnWrapper{Conn: conn, LastSeen: time.Now()}
r.botMu.Unlock()
}
@@ -103,13 +127,7 @@ func (r *Registry) UnregisterMod(channelID string) {
e.mu.Unlock()
if modConn != nil && modConn.Conn != nil {
_ = modConn.Conn.SetWriteDeadline(time.Now().Add(time.Second))
_ = modConn.Conn.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, "Disconnecting."),
time.Now().Add(time.Second),
)
_ = modConn.Conn.Close()
util.CloseConn(modConn.Conn)
}
}
@@ -120,13 +138,7 @@ func (r *Registry) UnregisterBot() {
r.botMu.Unlock()
if botConn != nil && botConn.Conn != nil {
_ = botConn.Conn.SetWriteDeadline(time.Now().Add(time.Second))
_ = botConn.Conn.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, "Disconnecting."),
time.Now().Add(time.Second),
)
_ = botConn.Conn.Close()
util.CloseConn(botConn.Conn)
}
}
@@ -135,11 +147,11 @@ func (r *Registry) Send(channelID string, out GatewayMessageOut, sendOverConn fu
r.botMu.Lock()
b := r.bot
r.botMu.Unlock()
if b != nil && b.Conn != nil {
if err := sendOverConn(b.Conn, out); err == nil {
return true, false, nil
}
_ = b.Conn.Close()
r.UnregisterBot()
}
@@ -147,6 +159,7 @@ func (r *Registry) Send(channelID string, out GatewayMessageOut, sendOverConn fu
e.mu.Lock()
enq := e.Queue.Enqueue(out)
e.mu.Unlock()
if !enq {
return false, false, fmt.Errorf("queue disabled")
}
@@ -157,17 +170,18 @@ func (r *Registry) Send(channelID string, out GatewayMessageOut, sendOverConn fu
e.mu.Lock()
mod := e.Mod
e.mu.Unlock()
if mod != nil && mod.Conn != nil {
if err := sendOverConn(mod.Conn, out); err == nil {
return true, false, nil
}
_ = mod.Conn.Close()
r.UnregisterMod(channelID)
}
e.mu.Lock()
enq := e.Queue.Enqueue(out)
e.mu.Unlock()
if !enq {
return false, false, fmt.Errorf("queue disabled")
}
@@ -183,11 +197,13 @@ func (r *Registry) FlushChannelWithSender(channelID string, sendOverConn func(*w
if e == nil {
return
}
e.mu.Lock()
if e.Mod == nil || e.Mod.Conn == nil {
e.mu.Unlock()
return
}
msgs := e.Queue.PopAll()
modConn := e.Mod.Conn
e.mu.Unlock()
@@ -221,6 +237,7 @@ func (r *Registry) FlushAllToBotWithSender(sendOverConn func(*websocket.Conn, Ga
e.mu.Lock()
msgs := e.Queue.PopAll()
e.mu.Unlock()
if len(msgs) == 0 {
continue
}

View File

@@ -67,19 +67,19 @@ type Destination struct {
type GatewayMessageIn struct {
Type string
ID string `json:"id"` // where am I from (channel_id or server_id)
MsgID string `json:"msg_id"` // msg id
Destination Destination `json:"destination,omitempty"` // where do I wanna go (channel_id or empty if from Bot)
Author User `json:"author"` // who sent the message
Content string `json:"content"` // message content
Meta map[string]interface{} `json:"meta,omitempty"` // additional metadata
Ts time.Time `json:"ts,omitempty"` // timestamp
ReceivedAt time.Time `json:"-"` // ReceivedAt is populated by gateway (not from mod)
ID string `json:"id"`
MsgID string `json:"msg_id"`
Destination Destination `json:"destination,omitempty"`
Author User `json:"author"`
Content string `json:"content"`
Meta map[string]interface{} `json:"meta,omitempty"`
Ts time.Time `json:"ts,omitempty"`
ReceivedAt time.Time `json:"-"`
}
type GatewayMessageOut struct {
Type string `json:"type"` // "mod"|"bot"
ID string `json:"channel_id,omitempty"` // message.Destination.ID
Type string `json:"type"`
ID string `json:"channel_id,omitempty"`
Author User `json:"author"`
Content string `json:"content"`
Meta map[string]interface{} `json:"meta,omitempty"`
@@ -106,5 +106,5 @@ type ModHandshake struct {
}
type BotHandshake struct {
ChannelId string `json:"channel_id"`
BotID string `json:"bot_id"`
}

View File

@@ -4,7 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"log/slog"
"homestead/homestead_gateway/util"
"net/http"
"strings"
"time"
@@ -56,7 +56,7 @@ func (wsg *WebsocketGateway) sendWebsocketError(conn *websocket.Conn, message st
_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
_ = conn.WriteJSON(map[string]interface{}{"message": message, "code": code})
if close {
_ = conn.Close()
util.CloseConn(conn)
}
}
@@ -65,7 +65,7 @@ func (wsg *WebsocketGateway) sendWebsocketResponse(conn *websocket.Conn, content
if err := conn.WriteJSON(content); err != nil {
wsg.logger.Error("Failed to respond to connection.", "remote", conn.RemoteAddr().String(), "err", err)
_ = conn.Close()
util.CloseConnWithControlMessage(conn, websocket.CloseAbnormalClosure, "Connection error.")
return err
}
@@ -99,11 +99,11 @@ func (wsg *WebsocketGateway) validateApiKey(r *http.Request) bool {
return !(apiKey == "" || apiKey != wsg.apiKey)
}
func loggingMiddleware(logger *slog.Logger, next http.Handler) http.Handler {
func (wsg *WebsocketGateway) loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
logger.Info("Incoming HTTP request.", "remote", r.RemoteAddr, "path", r.URL.Path, "duration", time.Since(start))
wsg.logger.Info("Incoming HTTP request.", "remote", r.RemoteAddr, "path", r.URL.Path, "duration", time.Since(start))
})
}
@@ -140,20 +140,23 @@ func (wsg *WebsocketGateway) closeAll() {
wsg.registry.UnregisterBot()
wsg.registry.mu.RLock()
channelIDs := make([]string, 0, len(wsg.registry.entries))
for channelID := range wsg.registry.entries {
channelIDs = append(channelIDs, channelID)
}
wsg.registry.mu.RUnlock()
for _, channelID := range channelIDs {
wsg.registry.ForEach(func(channelID string) {
wsg.registry.UnregisterMod(channelID)
}
})
}
//
func NewUpgrader() websocket.Upgrader {
return websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true // local by default; change for production
},
}
}
func NewRegistry(queueCap int) *Registry {
return &Registry{
entries: make(map[string]*ChannelEntry),

View File

@@ -17,18 +17,12 @@ import (
func NewWebsocketGateway(cfg config.GatewayConfig, logger *slog.Logger, closefn func() error) *WebsocketGateway {
return &WebsocketGateway{
logger: logger,
closeFn: closefn,
port: cfg.HttpPort,
apiKey: cfg.Websocket,
registry: NewRegistry(32),
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true // local by default; change for production
},
},
logger: logger,
closeFn: closefn,
port: cfg.HttpPort,
apiKey: cfg.Websocket,
upgrader: NewUpgrader(),
registry: NewRegistry(cfg.QueueSize),
bodySizeBytes: int64(cfg.BodySize) * 1024 * 1024,
}
}
@@ -47,7 +41,7 @@ func (wsg *WebsocketGateway) Serve(ctx context.Context, listenAddr string) error
srv := &http.Server{
Addr: listenAddr,
Handler: loggingMiddleware(wsg.logger, mux),
Handler: wsg.loggingMiddleware(mux),
BaseContext: func(l net.Listener) context.Context { return ctx },
}
errCh := make(chan error, 1)
@@ -65,121 +59,6 @@ func (wsg *WebsocketGateway) Serve(ctx context.Context, listenAddr string) error
//
//func (wsg *WebsocketGateway) modReadLoop(conn *websocket.Conn, meta cache.ConnectionMetaData) {
// defer func() {
// wsg.unregisterConn(conn, meta, "mod")
// wsg.logger.Info("Client disconnected.", "remote", conn.RemoteAddr().String(), "server_id", meta.ID)
// }()
//
// ticker := time.NewTicker(30 * time.Second)
// defer ticker.Stop()
//
// go func() {
// for range ticker.C {
// wsg.sendWebsocketPing(conn)
// }
// }()
//
// for {
// typ, data, err := conn.ReadMessage()
//
// if err != nil {
// if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
// wsg.logger.Warn("Mod-Client unexpectedly closed the connection.", "err", err)
// }
// return
// }
//
// if typ != websocket.TextMessage && typ != websocket.BinaryMessage {
// continue
// }
//
// var msg GatewayModMessageIn
// if err := json.Unmarshal(data, &msg); err != nil {
// _ = writeJSONSafe(conn, map[string]string{"error": "invalid json: " + err.Error()})
// wsg.logger.Warn("invalid json from mod", "server_id", meta.ID, "remote", conn.RemoteAddr().String(), "err", err)
// continue
// }
//
// msg.ReceivedAt = time.Now().UTC()
// if err := msg.Validate(); err != nil {
// _ = writeJSONSafe(conn, map[string]string{"error": err.Error()})
// wsg.logger.Warn("mod message validation failed", "server_id", meta.ID, "remote", conn.RemoteAddr().String(), "err", err)
// continue
// }
//
// // Handle the message (forward to bot, enrich, etc.)
// if err := wsg.modHandler.Handle(conn, msg); err != nil {
// _ = writeJSONSafe(conn, map[string]string{"error": "handler error: " + err.Error()})
// wsg.logger.Error("mod handler error", "server_id", meta.ID, "err", err)
// continue
// }
//
// _ = writeJSONSafe(conn, map[string]string{"status": "completed"}) // or "queued"
// }
//}
//
//func (wsg *WebsocketGateway) botReadLoop(conn *websocket.Conn, meta cache.ConnectionMetaData) {
// defer func() {
// wsg.unregisterConn(conn, meta, "bot")
// wsg.logger.Info("bot disconnected", "bot_id", meta.ID, "remote", conn.RemoteAddr().String())
// }()
//
// pingTicker := time.NewTicker(30 * time.Second)
// defer pingTicker.Stop()
//
// // Send pings in a separate goroutine
// go func() {
// for range pingTicker.C {
// _ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
// if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
// wsg.logger.Debug("write ping failed", "bot_id", meta.ID, "err", err)
// return
// }
// wsg.logger.Debug("sent ping to bot", "bot_id", meta.ID)
// }
// }()
//
// for {
// typ, data, err := conn.ReadMessage()
// if err != nil {
// if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
// wsg.logger.Warn("unexpected bot close", "bot_id", meta.ID, "err", err)
// } else {
// wsg.logger.Debug("bot read error", "bot_id", meta.ID, "err", err)
// }
// return
// }
//
// if typ != websocket.TextMessage && typ != websocket.BinaryMessage {
// continue
// }
//
// var msg GatewayBotMessageIn
// if err := json.Unmarshal(data, &msg); err != nil {
// _ = writeJSONSafe(conn, map[string]string{"error": "invalid json: " + err.Error()})
// wsg.logger.Warn("invalid json from bot", "bot_id", meta.ID, "remote", conn.RemoteAddr().String(), "err", err)
// continue
// }
//
// msg.ReceivedAt = time.Now().UTC()
// if err := msg.Validate(); err != nil {
// _ = writeJSONSafe(conn, map[string]string{"error": err.Error()})
// wsg.logger.Warn("bot message validation failed", "bot_id", meta.ID, "remote", conn.RemoteAddr().String(), "err", err)
// continue
// }
//
// // Handle the message (forward to mod, enrich, etc.)
// if err := wsg.botHandler.Handle(conn, msg); err != nil {
// _ = writeJSONSafe(conn, map[string]string{"error": "handler error: " + err.Error()})
// wsg.logger.Error("bot handler error", "bot_id", meta.ID, "err", err)
// continue
// }
//
// _ = writeJSONSafe(conn, map[string]string{"status": "ok"})
// }
//}
func (wsg *WebsocketGateway) read(conn *websocket.Conn, _type, channelId string) {
defer func() {
wsg.unregisterConn(_type, channelId)
@@ -249,13 +128,10 @@ func (wsg *WebsocketGateway) read(conn *websocket.Conn, _type, channelId string)
ForwardedAt: time.Now().UTC(),
}
delivered, queued, err := wsg.registry.Send(out.ID, out, func(c *websocket.Conn, m GatewayMessageOut) error {
_ = c.SetWriteDeadline(time.Now().Add(5 * time.Second))
return c.WriteJSON(m)
})
delivered, queued, err := wsg.registry.Send(outID, out, wsg.flush)
if err != nil {
wsg.logger.Error("registry send error", "err", err)
wsg.logger.Error("Registry queue/delivery error.", "remote", conn.RemoteAddr().String(), "err", err)
_ = wsg.sendWebsocketResponse(conn, GatewayAck{Status: "failed", Type: message.Type})
continue
}