78 lines
2.4 KiB
Go
78 lines
2.4 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"cloudipvalidator/internal/inbound"
|
|
)
|
|
|
|
// GetInboundChecks returns the singleton inbound-checks settings row.
|
|
// BootstrapFromConfig guarantees it exists before any other code path can
|
|
// observe it, so sql.ErrNoRows here would indicate a bootstrap bug, not a
|
|
// normal condition.
|
|
func (d *DB) GetInboundChecks(ctx context.Context) (InboundChecksSettings, error) {
|
|
var s InboundChecksSettings
|
|
var portsJSON, tlsJSON, createdAt, updatedAt string
|
|
err := d.QueryRowContext(ctx, `
|
|
SELECT ports, icmp, tls_checks, created_at, updated_at FROM inbound_checks_settings WHERE id=1
|
|
`).Scan(&portsJSON, &s.ICMP, &tlsJSON, &createdAt, &updatedAt)
|
|
if err != nil {
|
|
return InboundChecksSettings{}, err
|
|
}
|
|
if err := json.Unmarshal([]byte(portsJSON), &s.Ports); err != nil {
|
|
return InboundChecksSettings{}, fmt.Errorf("decode inbound check ports: %w", err)
|
|
}
|
|
if s.Ports == nil {
|
|
s.Ports = []int{}
|
|
}
|
|
if err := json.Unmarshal([]byte(tlsJSON), &s.TLSChecks); err != nil {
|
|
return InboundChecksSettings{}, fmt.Errorf("decode inbound TLS checks: %w", err)
|
|
}
|
|
if s.CreatedAt, err = dbToTime(createdAt); err != nil {
|
|
return InboundChecksSettings{}, err
|
|
}
|
|
if s.UpdatedAt, err = dbToTime(updatedAt); err != nil {
|
|
return InboundChecksSettings{}, err
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
// SetInboundChecks preserves the TLS configuration when tlsChecks is nil.
|
|
// A pointer to a nil slice selects automatic mode.
|
|
func (d *DB) SetInboundChecks(ctx context.Context, ports []int, icmp bool, tlsChecks *[]inbound.TLSCheck) error {
|
|
seen := make(map[int]bool, len(ports))
|
|
for _, p := range ports {
|
|
if p < 1 || p > 65535 {
|
|
return fmt.Errorf("port %d out of range 1..65535: %w", p, ErrValidation)
|
|
}
|
|
if seen[p] {
|
|
return fmt.Errorf("duplicate port %d: %w", p, ErrValidation)
|
|
}
|
|
seen[p] = true
|
|
}
|
|
if ports == nil {
|
|
ports = []int{}
|
|
}
|
|
payload, err := json.Marshal(ports)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var tlsJSON any
|
|
if tlsChecks != nil {
|
|
if err := inbound.ValidateTLSChecks(*tlsChecks); err != nil {
|
|
return fmt.Errorf("%v: %w", err, ErrValidation)
|
|
}
|
|
encoded, err := json.Marshal(*tlsChecks)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tlsJSON = string(encoded)
|
|
}
|
|
_, err = d.ExecContext(ctx, `
|
|
UPDATE inbound_checks_settings SET ports=?, icmp=?, tls_checks=COALESCE(?, tls_checks), updated_at=? WHERE id=1
|
|
`, string(payload), icmp, tlsJSON, timeToDB(Now()))
|
|
return err
|
|
}
|