feat: ✨ initial commit
This commit is contained in:
@@ -0,0 +1,44 @@
|
|||||||
|
name: tx-sync build
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: build-htz-01
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- goos: linux
|
||||||
|
goarch: amd64
|
||||||
|
artifact: tx-sync-linux-amd64
|
||||||
|
- goos: windows
|
||||||
|
goarch: amd64
|
||||||
|
artifact: tx-sync-windows-amd64.exe
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: go test ./...
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
env:
|
||||||
|
GOOS: ${{ matrix.goos }}
|
||||||
|
GOARCH: ${{ matrix.goarch }}
|
||||||
|
GOAMD64: v1
|
||||||
|
CGO_ENABLED: "0"
|
||||||
|
run: go build -trimpath -ldflags="-s -w" -o "${{ matrix.artifact }}" .
|
||||||
|
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ${{ matrix.artifact }}
|
||||||
|
path: ${{ matrix.artifact }}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Binaries
|
||||||
|
tx-sync
|
||||||
|
tx-sync.exe
|
||||||
|
tx-sync-linux-amd64
|
||||||
|
tx-sync-windows-amd64.exe
|
||||||
|
|
||||||
|
# Local operator config (beside binary)
|
||||||
|
/config.json
|
||||||
@@ -1,2 +1,50 @@
|
|||||||
# tx-sync
|
# tx-sync
|
||||||
|
|
||||||
|
Small utility that POSTs txAdmin `playersDB.json` to your FiveM dashboard on a timer. It does not parse the file; your server ingests the raw JSON.
|
||||||
|
|
||||||
|
## Server contract (dashboard ingest)
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
|------|--------|
|
||||||
|
| Method | `POST` |
|
||||||
|
| Header | `X-API-Key: <secret>` |
|
||||||
|
| Header | `Content-Type: application/json` |
|
||||||
|
| Body | Raw bytes of `playersDB.json` |
|
||||||
|
| URL | Whatever you configure (full URL) |
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
1. Run the binary once from a **console** (TTY). If `config.json` is missing, an interactive wizard creates it next to the executable, then exits.
|
||||||
|
2. Run again: it uploads immediately, then every `sync_interval` (default `5m`).
|
||||||
|
|
||||||
|
```text
|
||||||
|
tx-sync [-config path/to/config.json] [-setup]
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`-setup`**: run the wizard and exit (overwrites or creates `config.json`).
|
||||||
|
|
||||||
|
## Configuration (`config.json`)
|
||||||
|
|
||||||
|
Lives beside the binary by default (see `-config`).
|
||||||
|
|
||||||
|
| Field | Description |
|
||||||
|
|-------|-------------|
|
||||||
|
| `endpoint` | Full POST URL |
|
||||||
|
| `api_key` | Sent as `X-API-Key` |
|
||||||
|
| `players_db_path` | Path to `playersDB.json` on disk |
|
||||||
|
| `sync_interval` | Go duration string (e.g. `5m`, `10m30s`) |
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -trimpath -ldflags="-s -w" -o tx-sync .
|
||||||
|
```
|
||||||
|
|
||||||
|
Cross-compile (example):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
GOOS=linux GOARCH=amd64 GOAMD64=v1 CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o tx-sync-linux-amd64 .
|
||||||
|
GOOS=windows GOARCH=amd64 GOAMD64=v1 CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o tx-sync.exe .
|
||||||
|
```
|
||||||
|
|
||||||
|
CI builds Linux and Windows binaries via `.gitea/workflows/build.yml`.
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
module github.com/jdbnet/tx-sync
|
||||||
|
|
||||||
|
go 1.22
|
||||||
|
|
||||||
|
require golang.org/x/term v0.27.0
|
||||||
|
|
||||||
|
require golang.org/x/sys v0.28.0 // indirect
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||||
|
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
|
||||||
|
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/term"
|
||||||
|
)
|
||||||
|
|
||||||
|
const DefaultSyncInterval = "5m"
|
||||||
|
|
||||||
|
// Config holds runtime settings. JSON field names are stable for operators editing by hand.
|
||||||
|
type Config struct {
|
||||||
|
Endpoint string `json:"endpoint"`
|
||||||
|
APIKey string `json:"api_key"`
|
||||||
|
PlayersDBPath string `json:"players_db_path"`
|
||||||
|
SyncInterval string `json:"sync_interval"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultPath returns config.json next to the executable.
|
||||||
|
func DefaultPath() (string, error) {
|
||||||
|
exe, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
exe, err = filepath.EvalSymlinks(exe)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(filepath.Dir(exe), "config.json"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) Validate() error {
|
||||||
|
if strings.TrimSpace(c.Endpoint) == "" {
|
||||||
|
return errors.New("endpoint is required")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(c.APIKey) == "" {
|
||||||
|
return errors.New("api_key is required")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(c.PlayersDBPath) == "" {
|
||||||
|
return errors.New("players_db_path is required")
|
||||||
|
}
|
||||||
|
interval := strings.TrimSpace(c.SyncInterval)
|
||||||
|
if interval == "" {
|
||||||
|
interval = DefaultSyncInterval
|
||||||
|
}
|
||||||
|
if _, err := time.ParseDuration(interval); err != nil {
|
||||||
|
return fmt.Errorf("sync_interval: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) IntervalDuration() (time.Duration, error) {
|
||||||
|
s := strings.TrimSpace(c.SyncInterval)
|
||||||
|
if s == "" {
|
||||||
|
s = DefaultSyncInterval
|
||||||
|
}
|
||||||
|
return time.ParseDuration(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Load(path string) (*Config, error) {
|
||||||
|
b, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var c Config
|
||||||
|
if err := json.Unmarshal(b, &c); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Save(path string, c *Config) error {
|
||||||
|
b, err := json.MarshalIndent(c, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.WriteFile(path, b, 0600)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunWizard interactively collects settings and writes config to path. Requires a TTY on stdin.
|
||||||
|
func RunWizard(path string) error {
|
||||||
|
if !term.IsTerminal(int(os.Stdin.Fd())) {
|
||||||
|
return errors.New("stdin is not a terminal: run this program from a console to create config.json, or create the file by hand")
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintln(os.Stderr, "tx-sync: first-time setup — values are saved to:", path)
|
||||||
|
fmt.Fprintln(os.Stderr)
|
||||||
|
|
||||||
|
endpoint := promptLine("HTTPS endpoint URL (POST, full URL): ")
|
||||||
|
apiKey, err := promptPassword("API key (X-API-Key, hidden): ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
dbPath := promptLine("Path to playersDB.json: ")
|
||||||
|
interval := promptLine(fmt.Sprintf("Sync interval [%s]: ", DefaultSyncInterval))
|
||||||
|
if strings.TrimSpace(interval) == "" {
|
||||||
|
interval = DefaultSyncInterval
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := Config{
|
||||||
|
Endpoint: strings.TrimSpace(endpoint),
|
||||||
|
APIKey: strings.TrimSpace(apiKey),
|
||||||
|
PlayersDBPath: strings.TrimSpace(dbPath),
|
||||||
|
SyncInterval: strings.TrimSpace(interval),
|
||||||
|
}
|
||||||
|
if err := cfg.Validate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := Save(path, &cfg); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Fprintln(os.Stderr)
|
||||||
|
fmt.Fprintln(os.Stderr, "Configuration saved. Run tx-sync again to start syncing (immediate upload, then on the timer).")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func promptLine(label string) string {
|
||||||
|
fmt.Fprint(os.Stderr, label)
|
||||||
|
s := bufio.NewScanner(os.Stdin)
|
||||||
|
if !s.Scan() {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return s.Text()
|
||||||
|
}
|
||||||
|
|
||||||
|
func promptPassword(label string) (string, error) {
|
||||||
|
fmt.Fprint(os.Stderr, label)
|
||||||
|
b, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||||
|
fmt.Fprintln(os.Stderr)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(b), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConfigValidate(t *testing.T) {
|
||||||
|
c := Config{
|
||||||
|
Endpoint: "https://example.com/api/ingest",
|
||||||
|
APIKey: "k",
|
||||||
|
PlayersDBPath: "/data/playersDB.json",
|
||||||
|
SyncInterval: "5m",
|
||||||
|
}
|
||||||
|
if err := c.Validate(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
d, err := c.IntervalDuration()
|
||||||
|
if err != nil || d != 5*time.Minute {
|
||||||
|
t.Fatalf("interval: %v %v", d, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigValidateEmpty(t *testing.T) {
|
||||||
|
var c Config
|
||||||
|
if err := c.Validate(); err == nil {
|
||||||
|
t.Fatal("expected error")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package sync
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Upload posts the raw playersDB.json bytes to endpoint with X-API-Key and Content-Type: application/json.
|
||||||
|
func Upload(ctx context.Context, client *http.Client, endpoint, apiKey string, body []byte) error {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("X-API-Key", apiKey)
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
|
||||||
|
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, bytes.TrimSpace(snippet))
|
||||||
|
}
|
||||||
|
_, _ = io.Copy(io.Discard, resp.Body)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadPlayersDB reads the file from disk.
|
||||||
|
func ReadPlayersDB(path string) ([]byte, error) {
|
||||||
|
return os.ReadFile(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHTTPClient returns a client suitable for large JSON uploads.
|
||||||
|
func NewHTTPClient() *http.Client {
|
||||||
|
return &http.Client{
|
||||||
|
Timeout: 90 * time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package sync
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUpload(t *testing.T) {
|
||||||
|
const wantKey = "secret"
|
||||||
|
var gotBody []byte
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
t.Errorf("method %s", r.Method)
|
||||||
|
}
|
||||||
|
if r.Header.Get("X-API-Key") != wantKey {
|
||||||
|
t.Errorf("X-API-Key")
|
||||||
|
}
|
||||||
|
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||||
|
t.Errorf("Content-Type %q", ct)
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
gotBody, err = io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
client := srv.Client()
|
||||||
|
body := []byte(`{"ok":true}`)
|
||||||
|
if err := Upload(context.Background(), client, srv.URL, wantKey, body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(gotBody) != string(body) {
|
||||||
|
t.Fatalf("body %q", gotBody)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadNon2xx(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Error(w, "nope", http.StatusTeapot)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
err := Upload(context.Background(), srv.Client(), srv.URL, "k", []byte("{}"))
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jdbnet/tx-sync/internal/config"
|
||||||
|
"github.com/jdbnet/tx-sync/internal/sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
/*
|
||||||
|
tx-sync uploads txAdmin playersDB.json to an HTTP(S) endpoint on a schedule.
|
||||||
|
|
||||||
|
Expected server contract (for your dashboard ingest implementation):
|
||||||
|
- Method: POST
|
||||||
|
- Header: X-API-Key: <secret>
|
||||||
|
- Header: Content-Type: application/json
|
||||||
|
- Body: raw bytes of playersDB.json
|
||||||
|
- URL: full URL from config (no fixed path in this client)
|
||||||
|
*/
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
log.SetFlags(log.LstdFlags | log.Lmsgprefix)
|
||||||
|
log.SetPrefix("tx-sync: ")
|
||||||
|
|
||||||
|
defaultPath, err := config.DefaultPath()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("resolve config path: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
configPath := flag.String("config", defaultPath, "path to config.json")
|
||||||
|
setup := flag.Bool("setup", false, "run interactive configuration wizard and exit")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if *setup {
|
||||||
|
if err := config.RunWizard(*configPath); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, statErr := os.Stat(*configPath); statErr != nil {
|
||||||
|
if errors.Is(statErr, os.ErrNotExist) {
|
||||||
|
if err := config.RunWizard(*configPath); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
log.Fatalf("config file: %v", statErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.Load(*configPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("load config: %v", err)
|
||||||
|
}
|
||||||
|
if err := cfg.Validate(); err != nil {
|
||||||
|
log.Fatalf("invalid config: %v (run with -setup to reconfigure)", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
interval, err := cfg.IntervalDuration()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("sync interval: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
client := sync.NewHTTPClient()
|
||||||
|
|
||||||
|
if err := pushOnce(ctx, client, cfg); err != nil {
|
||||||
|
log.Printf("upload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ticker := time.NewTicker(interval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("shutting down")
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
if err := pushOnce(ctx, client, cfg); err != nil {
|
||||||
|
log.Printf("upload: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func pushOnce(ctx context.Context, client *http.Client, cfg *config.Config) error {
|
||||||
|
body, err := sync.ReadPlayersDB(cfg.PlayersDBPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read %q: %w", cfg.PlayersDBPath, err)
|
||||||
|
}
|
||||||
|
if err := sync.Upload(ctx, client, cfg.Endpoint, cfg.APIKey, body); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
log.Printf("upload ok (%d bytes)", len(body))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user