fix(config): enforce the service context at registration

ServiceSpec.Context documented which addresses a service must end up with, but
nothing read it, so a typo'd context was accepted and meant nothing. Review
caught it as scaffolding that looked load-bearing.

RegisterService now validates it: an unknown context, or a hosted (server/both)
service registered with no default listen address, panics. Registrations come
from this repository's own init(), never from operator input, so an invalid one
is a programming error with no caller positioned to handle an error return, and
failing at process start beats a service binding where nobody dials.

Services.RequireTarget replaces the same check and message hand-written in
composeStateStoreClient and composeChatContract. An empty registered default
target is what declares a target operator-supplied, so the requirement belongs
to the registry rather than to each consumer. It stays a lazy check at
composition time rather than becoming load-time validation: a process that
never dials a service must still load a configuration that omits it.

The review's stated failure mode does not occur. A hosted service with an empty
listen does not reach net.Listen as an ephemeral port; resolveServiceListen
returns "no listen address" and archied refuses to start. The defect was the
inert field, not a silent bind.

Refs: archie-core-u23g
This commit is contained in:
sam committed 2026-09-19 01:50:25 +10:00
1 parent 5aedc28aae
commit 42bfd35514
6 files changed
+149 -15

No files matched your search

+5 -2
View File
@@ -60,8 +60,11 @@ Positional, five strings, as the story specifies. Each argument is data the curr
states in prose or in a branch:
- `context` is `client`, `server`, or `both`, and decides which fields must resolve
non-empty. A `server` or `both` service must end with a `listen`; a `client` or `both`
service must end with a `target`.
non-empty. `RegisterService` enforces it: an unknown context, or a hosted service with
no default `listen`, panics at registration. Registrations come from this repository's
own `init()`, never from operator input, so an invalid one is a programming error with
no caller positioned to handle an error return. A documented-but-unread `Context` would
be worse than no field at all.
- `target` is the **default**, and an empty default means the operator must supply one.
That single convention replaces the `state.target` required / `gateway.target` defaulted
asymmetry with no branch: `state` registers `""`, `gateway` registers an address.
+4 -7
View File
@@ -1,9 +1,6 @@
package archied
import (
"fmt"
"strings"
"google.golang.org/grpc"
"github.com/samcharles93/archie-core/internal/config"
@@ -18,14 +15,14 @@ import (
// itself and the fail-closed non-loopback rule belong to the transport, so
// they come from gatewayrpc.Dial.
func composeChatContract(services config.Services, secrets *secret.Registry, options ...grpc.DialOption) (gateway.ChatContract, func(), error) {
settings := services.Get(config.ServiceNameGateway)
if strings.TrimSpace(settings.Target) == "" {
return nil, nil, fmt.Errorf("services.gateway.target is required")
target, err := services.RequireTarget(config.ServiceNameGateway)
if err != nil {
return nil, nil, err
}
// Assigned through a typed variable rather than returned directly: a
// direct forward would hand a failed dial's nil *Client back as a
// non-nil ChatContract interface.
client, cleanup, err := gatewayrpc.Dial(settings.Target, services.ResolvedToken(config.ServiceNameGateway, secrets.Getenv), options...)
client, cleanup, err := gatewayrpc.Dial(target, services.ResolvedToken(config.ServiceNameGateway, secrets.Getenv), options...)
if err != nil {
return nil, nil, err
}
+3 -6
View File
@@ -1,9 +1,6 @@
package archied
import (
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/secret"
@@ -15,9 +12,9 @@ import (
// fail-closed non-loopback rule (§9) belong to the transport, so they come
// from staterpc.Dial.
func composeStateStoreClient(services config.Services, secrets *secret.Registry) (*staterpc.Client, func(), error) {
target := strings.TrimSpace(services.Get(config.ServiceNameState).Target)
if target == "" {
return nil, nil, fmt.Errorf("services.state.target is required")
target, err := services.RequireTarget(config.ServiceNameState)
if err != nil {
return nil, nil, err
}
return staterpc.Dial(target, services.ResolvedToken(config.ServiceNameState, secrets.Getenv))
}
+21
View File
@@ -1,5 +1,10 @@
package config
import (
"fmt"
"strings"
)
// Services maps a registered service name to its connection settings, keyed by
// the [services.<name>] section it was decoded from.
//
@@ -35,6 +40,22 @@ func (s Services) ResolvedToken(name string, getenv func(string) string) string
return getenv(spec.TokenEnv)
}
// RequireTarget returns the dial address for name, or an error naming the
// config key when the operator has not supplied one.
//
// A service registered with an empty default target is one the operator must
// configure, so this is the registry's own contract rather than a consumer's
// private rule. It stays a lazy check at composition time, not a load-time
// validation: a process that never dials a given service must still be able to
// load a configuration that omits it.
func (s Services) RequireTarget(name string) (string, error) {
target := strings.TrimSpace(s[name].Target)
if target == "" {
return "", fmt.Errorf("services.%s.target is required", name)
}
return target, nil
}
// ServiceConnection is a service's gRPC addresses plus the bearer token a
// client presents when the target is non-loopback. A client reads only Target
// and TargetToken; Listen belongs to the process that owns the service. The
+92
View File
@@ -1,6 +1,8 @@
package config_test
import (
"fmt"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/config"
@@ -131,3 +133,93 @@ func TestResolvedTokenOfUnregisteredServiceHasNoEnvFallback(t *testing.T) {
t.Errorf("ResolvedToken = %q, want empty", got)
}
}
// mustPanic runs fn and returns the recovered value, or fails if fn returned
// normally. Registration errors are programming errors in this repository's
// own init(), not operator input, so they abort the process rather than
// returning an error nobody is positioned to handle.
func mustPanic(t *testing.T, fn func()) (recovered any) {
t.Helper()
defer func() { recovered = recover() }()
fn()
t.Fatal("RegisterService returned normally, want a panic")
return nil
}
// TestRegisterServiceRejectsAnUnknownContext makes Context load-bearing. It
// documented which addresses a service must end up with, but nothing read it,
// so a typo'd context was accepted and silently meant nothing.
func TestRegisterServiceRejectsAnUnknownContext(t *testing.T) {
got := mustPanic(t, func() {
config.RegisterService("clientt", "widget-badcontext", "", "127.0.0.1:7005", "T")
})
if !strings.Contains(fmt.Sprint(got), "clientt") {
t.Errorf("panic = %v, want it to name the invalid context", got)
}
}
// TestRegisterServiceRejectsAHostedServiceWithNoListen pins the requirement
// Context exists to express: a service this repository hosts must have a
// default bind address, because an empty one reaches net.Listen as "any free
// port".
func TestRegisterServiceRejectsAHostedServiceWithNoListen(t *testing.T) {
for _, hosted := range []string{config.ServiceServer, config.ServiceBoth} {
t.Run(hosted, func(t *testing.T) {
got := mustPanic(t, func() {
config.RegisterService(hosted, "widget-nolisten-"+hosted, "127.0.0.1:1", "", "T")
})
if !strings.Contains(fmt.Sprint(got), "listen") {
t.Errorf("panic = %v, want it to name the missing listen address", got)
}
})
}
}
// TestRegisterServiceAcceptsAClientWithNoTargetDefault keeps the State Store's
// own shape legal: a dialled-only service may register an empty target, which
// is how "the operator must supply this" is stated.
func TestRegisterServiceAcceptsAClientWithNoTargetDefault(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Fatalf("RegisterService panicked on a legal client registration: %v", r)
}
}()
config.RegisterService(config.ServiceClient, "widget-clientok", "", "127.0.0.1:7006", "T")
}
// TestRequireTargetReportsAnAbsentOperatorSuppliedTarget moves the "target is
// required" check off two hand-written consumer copies and onto the registry,
// which is what declared the target operator-supplied in the first place.
func TestRequireTargetReportsAnAbsentOperatorSuppliedTarget(t *testing.T) {
for _, tt := range []struct {
name string
target string
want string
wantErr bool
}{
{name: "absent", wantErr: true},
{name: "blank", target: " \t\n", wantErr: true},
{name: "set", target: "10.0.0.1:9090", want: "10.0.0.1:9090"},
{name: "set with padding", target: " 10.0.0.1:9090 ", want: "10.0.0.1:9090"},
} {
t.Run(tt.name, func(t *testing.T) {
services := config.Services{config.ServiceNameState: {Target: tt.target}}
got, err := services.RequireTarget(config.ServiceNameState)
if tt.wantErr {
if err == nil {
t.Fatal("RequireTarget returned no error for an empty target")
}
if !strings.Contains(err.Error(), "services.state.target") {
t.Errorf("error = %v, want it to name the config key", err)
}
return
}
if err != nil {
t.Fatalf("RequireTarget: %v", err)
}
if got != tt.want {
t.Errorf("RequireTarget = %q, want %q", got, tt.want)
}
})
}
}
+24
View File
@@ -1,7 +1,9 @@
package config
import (
"fmt"
"sort"
"strings"
"sync"
)
@@ -60,7 +62,29 @@ var (
//
// Re-registering a name replaces the previous spec, so a test can install a
// throwaway service without disturbing the built-ins.
//
// It panics on a registration that cannot be honoured. Registrations come from
// this repository's own init(), never from operator input, so an invalid one is
// a programming error: there is no caller positioned to handle an error return,
// and failing at process start is better than a service that binds somewhere
// nobody dials. Context is enforced here rather than merely documented, so
// "hosted" genuinely implies a bind address.
func RegisterService(context, name, target, listen, tokenEnv string) {
switch context {
case ServiceClient, ServiceServer, ServiceBoth:
default:
panic(fmt.Sprintf(
"config.RegisterService(%q): unknown context %q, want %q, %q or %q",
name, context, ServiceClient, ServiceServer, ServiceBoth,
))
}
if context != ServiceClient && strings.TrimSpace(listen) == "" {
panic(fmt.Sprintf(
"config.RegisterService(%q): a %q service needs a default listen address; "+
"an empty one reaches net.Listen as \"any free port\"",
name, context,
))
}
serviceRegistryMu.Lock()
defer serviceRegistryMu.Unlock()
serviceRegistry[name] = ServiceSpec{