Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# AGENTS.md — OttO

## Purpose
OttO is the core runtime/framework. Keep application-specific logic out of this repo.
Add tests and docs with minimal disruption to public APIs.

## Non-goals
- Do NOT add/require external services (no real MQTT broker, DB, HTTP server) for unit tests.
- Do NOT access hardware, GPIO, serial, or OS-specific devices in tests.
- Avoid broad refactors. Prefer small, additive changes that enable testing.
- Always ignore files and directories that begin with an underscore '_'.

## Go conventions
- Run `gofmt` on all changed files.
- Keep package boundaries clean; avoid circular deps.
- Prefer context-aware APIs for long-running work.
- Avoid goroutine leaks: every goroutine must have a deterministic shutdown path.

## Testing (required)
Use **testify**:
- Use `github.com/stretchr/testify/require` for must-pass assertions.
- Use `github.com/stretchr/testify/assert` for non-fatal checks.
- Use `github.com/stretchr/testify/mock` only when a small fake isn’t practical.

Test rules:
- Tests must be hermetic: no network, no filesystem writes outside `t.TempDir()`.
- Avoid `time.Sleep` for synchronization. Use channels, WaitGroups, or context cancellation.
- Any test that could block must use `context.WithTimeout` and fail fast.
- Prefer table-driven tests.
- Keep tests deterministic and non-flaky.

Commands:
- Run: `go test ./...`
- When adding new packages or helpers, keep them internal: `internal/testutil` is allowed.

## What to test first (priority)
1. Pure logic: parsing, validation, topic naming/handling, config processing.
2. Concurrency: cancellation, shutdown behavior, channel fan-in/out, race-prone areas.
3. Interface contracts: error propagation and edge cases.

## Review checklist (before proposing changes)
- Does this change keep OttO independent of app/device-specific logic?
- Are new tests hermetic and deterministic?
- Any new goroutines? Where do they stop?
- Any sleeps/time-based flakiness introduced? Remove it.

## Commit guidance (if committing)
Prefer small commits:
- `test: <pkg> baseline`
- `testutil: add <helper>`
- `docs: godoc for <pkg>`
14 changes: 1 addition & 13 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,6 @@ fmt:
vet:
go vet ./...

# ottoctl:
# go build -o ${OTTOCTL_BINARY} -ldflags "-X github.com/rustyeddy/otto/cmd.version=${VERSION}" ./cmd/ottoctl/ottoctl

# otto:
# go build -o ${OTTO_BINARY} -ldflags "-X github.com/rustyeddy/otto/cmd.version=${VERSION}" ./cmd/otto

build:
$(MAKE) -C cmd

run: build
./otto

test:
rm -f cover.out
go test -benchmem -coverprofile=cover.out -cover ./...
Expand Down Expand Up @@ -104,4 +92,4 @@ service-status:
service-logs:
sudo journalctl -u $(SERVICE_FILE) -f

.PHONY: all build cmd otto ottoctl clean ci fmt run test vet install install-service enable-service uninstall-service uninstall service-status service-logs $(SUBDIRS)
.PHONY: all build otto ottoctl clean ci fmt run test vet install install-service enable-service uninstall-service uninstall service-status service-logs $(SUBDIRS)
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion examples/logging/main.go → _examples/logging/main.go
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need to move this back into the live code.

Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"log/slog"
"os"

"github.com/rustyeddy/otto/utils"
"github.com/rustyeddy/otto/_utils"
)

func main() {
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
29 changes: 29 additions & 0 deletions messenger/codec/json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package codec

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestJSONRoundTrip(t *testing.T) {
t.Parallel()

c := JSON[int]{}

raw, err := c.Marshal(42)
require.NoError(t, err)

got, err := c.Unmarshal(raw)
require.NoError(t, err)
assert.Equal(t, 42, got)
}

func TestJSONUnmarshalInvalid(t *testing.T) {
t.Parallel()

c := JSON[int]{}
_, err := c.Unmarshal([]byte(`"not-an-int"`))
require.Error(t, err)
}
6 changes: 4 additions & 2 deletions messenger/messenger.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type subSpec struct {
handler func(Message)
}

// Messenger manages desired MQTT subscriptions.
type Messenger struct {
MQTT MQTT

Expand All @@ -20,6 +21,7 @@ type Messenger struct {
unsubs map[string]func() error
}

// New returns a Messenger for the provided MQTT client.
func New(mqtt MQTT) *Messenger {
return &Messenger{
MQTT: mqtt,
Expand All @@ -28,14 +30,14 @@ func New(mqtt MQTT) *Messenger {
}
}

// Register a subscription you want to always be active.
// WantSub registers a subscription that should always be active.
func (m *Messenger) WantSub(topic string, qos byte, handler func(Message)) {
m.mu.Lock()
defer m.mu.Unlock()
m.subscriptions[topic] = subSpec{topic: topic, qos: qos, handler: handler}
}

// Apply all desired subscriptions (call on first connect and on every reconnect).
// ResubscribeAll applies desired subscriptions on connect and reconnect.
func (m *Messenger) ResubscribeAll(ctx context.Context) {
slog.Info("MQTT connected; (re)subscribing", "count", len(m.subscriptions))

Expand Down
109 changes: 109 additions & 0 deletions messenger/messenger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package messenger

import (
"context"
"sync"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type fakeMQTT struct {
mu sync.Mutex
subs []subCall
subscribeCalls map[string]int
unsubCalls map[string]int
}

type subCall struct {
topic string
qos byte
handler func(Message)
}

func newFakeMQTT() *fakeMQTT {
return &fakeMQTT{
subscribeCalls: make(map[string]int),
unsubCalls: make(map[string]int),
}
}

func (f *fakeMQTT) Publish(ctx context.Context, topic string, payload []byte, retain bool, qos byte) error {
return nil
}

func (f *fakeMQTT) Subscribe(ctx context.Context, topic string, qos byte, handler func(Message)) (func() error, error) {
f.mu.Lock()
f.subs = append(f.subs, subCall{topic: topic, qos: qos, handler: handler})
f.subscribeCalls[topic]++
f.mu.Unlock()

return func() error {
f.mu.Lock()
f.unsubCalls[topic]++
f.mu.Unlock()
return nil
}, nil
}

func (f *fakeMQTT) SetWill(topic string, payload []byte, retain bool, qos byte) error {
return nil
}

func (f *fakeMQTT) snapshot() (subs []subCall, subscribeCalls map[string]int, unsubCalls map[string]int) {
f.mu.Lock()
defer f.mu.Unlock()

subs = append([]subCall(nil), f.subs...)
subscribeCalls = make(map[string]int, len(f.subscribeCalls))
for k, v := range f.subscribeCalls {
subscribeCalls[k] = v
}
unsubCalls = make(map[string]int, len(f.unsubCalls))
for k, v := range f.unsubCalls {
unsubCalls[k] = v
}
return subs, subscribeCalls, unsubCalls
}

func TestMessengerResubscribeAllSubscribes(t *testing.T) {
t.Parallel()

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
t.Cleanup(cancel)

mqtt := newFakeMQTT()
m := New(mqtt)
m.WantSub("otto/devices/lamp/set", 1, func(Message) {})
m.WantSub("otto/devices/lamp/state", 0, func(Message) {})

m.ResubscribeAll(ctx)

subs, calls, _ := mqtt.snapshot()
require.Len(t, subs, 2)
assert.Equal(t, 1, calls["otto/devices/lamp/set"])
assert.Equal(t, 1, calls["otto/devices/lamp/state"])
}

func TestMessengerResubscribeAllUnsubscribesPrevious(t *testing.T) {
t.Parallel()

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
t.Cleanup(cancel)

mqtt := newFakeMQTT()
m := New(mqtt)
m.WantSub("otto/devices/lamp/set", 1, func(Message) {})
m.WantSub("otto/devices/lamp/state", 0, func(Message) {})

m.ResubscribeAll(ctx)
m.ResubscribeAll(ctx)

_, calls, unsubs := mqtt.snapshot()
assert.Equal(t, 2, calls["otto/devices/lamp/set"])
assert.Equal(t, 2, calls["otto/devices/lamp/state"])
assert.Equal(t, 1, unsubs["otto/devices/lamp/set"])
assert.Equal(t, 1, unsubs["otto/devices/lamp/state"])
}
Loading
Loading