Route icon results through UI events (T-607)
This commit is contained in:
@@ -17,6 +17,8 @@ const (
|
||||
EventAppStarted EventType = "AppStarted"
|
||||
EventAppExited EventType = "AppExited"
|
||||
EventLicenseChanged EventType = "LicenseChanged"
|
||||
EventIconReady EventType = "IconReady"
|
||||
EventIconFailed EventType = "IconFailed"
|
||||
)
|
||||
|
||||
var validEventTypes = map[EventType]struct{}{
|
||||
@@ -33,6 +35,8 @@ var validEventTypes = map[EventType]struct{}{
|
||||
EventAppStarted: {},
|
||||
EventAppExited: {},
|
||||
EventLicenseChanged: {},
|
||||
EventIconReady: {},
|
||||
EventIconFailed: {},
|
||||
}
|
||||
|
||||
// Valid reports whether eventType is part of the documented event contract.
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrEventRelayClosed = errors.New("application event relay closed")
|
||||
ErrEventRelayInvalid = errors.New("application event relay is invalid")
|
||||
)
|
||||
|
||||
// EventRelay is a bounded FIFO between background event pumps and the UI frame.
|
||||
// Submit applies lossless backpressure; Drain must only run on the UI goroutine.
|
||||
type EventRelay struct {
|
||||
events chan Event
|
||||
slots chan struct{}
|
||||
done chan struct{}
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
// NewEventRelay creates a relay with a strictly positive bounded capacity.
|
||||
func NewEventRelay(capacity int) (*EventRelay, error) {
|
||||
if capacity <= 0 {
|
||||
return nil, fmt.Errorf(
|
||||
"%w: capacity must be positive",
|
||||
ErrEventRelayInvalid,
|
||||
)
|
||||
}
|
||||
relay := &EventRelay{
|
||||
events: make(chan Event, capacity),
|
||||
slots: make(chan struct{}, capacity),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
for index := 0; index < capacity; index++ {
|
||||
relay.slots <- struct{}{}
|
||||
}
|
||||
return relay, nil
|
||||
}
|
||||
|
||||
// Submit queues one event or returns when the context/relay closes.
|
||||
func (relay *EventRelay) Submit(ctx context.Context, event Event) error {
|
||||
if relay == nil {
|
||||
return fmt.Errorf("%w: nil relay", ErrEventRelayInvalid)
|
||||
}
|
||||
if !event.Type.Valid() {
|
||||
return fmt.Errorf(
|
||||
"%w: unknown type %q",
|
||||
ErrInvalidEvent,
|
||||
event.Type,
|
||||
)
|
||||
}
|
||||
select {
|
||||
case <-relay.done:
|
||||
return ErrEventRelayClosed
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-relay.slots:
|
||||
}
|
||||
|
||||
relay.mu.Lock()
|
||||
defer relay.mu.Unlock()
|
||||
if relay.closed {
|
||||
relay.slots <- struct{}{}
|
||||
return ErrEventRelayClosed
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
relay.slots <- struct{}{}
|
||||
return err
|
||||
}
|
||||
relay.events <- event
|
||||
return nil
|
||||
}
|
||||
|
||||
// Drain applies the events present at entry without extending a UI frame forever.
|
||||
func (relay *EventRelay) Drain(apply func(Event) error) error {
|
||||
if relay == nil || apply == nil {
|
||||
return fmt.Errorf("%w: nil relay or apply function", ErrEventRelayInvalid)
|
||||
}
|
||||
limit := len(relay.events)
|
||||
var applyErrors []error
|
||||
for index := 0; index < limit; index++ {
|
||||
select {
|
||||
case event := <-relay.events:
|
||||
relay.slots <- struct{}{}
|
||||
if err := apply(event); err != nil {
|
||||
applyErrors = append(applyErrors, err)
|
||||
}
|
||||
default:
|
||||
return errors.Join(applyErrors...)
|
||||
}
|
||||
}
|
||||
return errors.Join(applyErrors...)
|
||||
}
|
||||
|
||||
// Close unblocks pending submissions. Queued events remain available to Drain.
|
||||
func (relay *EventRelay) Close() {
|
||||
if relay == nil {
|
||||
return
|
||||
}
|
||||
relay.closeOnce.Do(func() {
|
||||
relay.mu.Lock()
|
||||
relay.closed = true
|
||||
close(relay.done)
|
||||
relay.mu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
// PumpEvents forwards application events to a relay and requests a UI frame.
|
||||
// invalidate may be called concurrently; no UI state may be mutated here.
|
||||
func PumpEvents(
|
||||
ctx context.Context,
|
||||
events <-chan Event,
|
||||
relay *EventRelay,
|
||||
invalidate func(),
|
||||
) error {
|
||||
if events == nil || relay == nil || invalidate == nil {
|
||||
return fmt.Errorf("%w: incomplete event pump", ErrEventRelayInvalid)
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case event, open := <-events:
|
||||
if !open {
|
||||
return nil
|
||||
}
|
||||
if err := relay.Submit(ctx, event); err != nil {
|
||||
return err
|
||||
}
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEventRelayUsesBoundedFIFOBackpressure(t *testing.T) {
|
||||
relay, err := NewEventRelay(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := Event{Type: EventCatalogRefreshed, RequestID: "first"}
|
||||
second := Event{Type: EventCatalogRejected, RequestID: "second"}
|
||||
if err := relay.Submit(context.Background(), first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
started := make(chan struct{})
|
||||
secondResult := make(chan error, 1)
|
||||
go func() {
|
||||
close(started)
|
||||
secondResult <- relay.Submit(context.Background(), second)
|
||||
}()
|
||||
<-started
|
||||
select {
|
||||
case err := <-secondResult:
|
||||
t.Fatalf("second Submit() completed while relay was full: %v", err)
|
||||
default:
|
||||
}
|
||||
|
||||
var received []string
|
||||
if err := relay.Drain(func(event Event) error {
|
||||
received = append(received, event.RequestID)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitRelayResult(secondResult); err != nil {
|
||||
t.Fatalf("second Submit() error = %v", err)
|
||||
}
|
||||
if err := relay.Drain(func(event Event) error {
|
||||
received = append(received, event.RequestID)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(received, []string{"first", "second"}) {
|
||||
t.Fatalf("received order = %v", received)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventRelayCloseAndContextUnblockFullSubmit(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
unblock func(*EventRelay, context.CancelFunc)
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "close",
|
||||
unblock: func(relay *EventRelay, _ context.CancelFunc) {
|
||||
relay.Close()
|
||||
},
|
||||
wantErr: ErrEventRelayClosed,
|
||||
},
|
||||
{
|
||||
name: "cancel",
|
||||
unblock: func(_ *EventRelay, cancel context.CancelFunc) {
|
||||
cancel()
|
||||
},
|
||||
wantErr: context.Canceled,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
relay, err := NewEventRelay(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := relay.Submit(
|
||||
context.Background(),
|
||||
Event{Type: EventCatalogRefreshed},
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
started := make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
close(started)
|
||||
result <- relay.Submit(ctx, Event{Type: EventCatalogRejected})
|
||||
}()
|
||||
<-started
|
||||
test.unblock(relay, cancel)
|
||||
if err := waitRelayResult(result); !errors.Is(err, test.wantErr) {
|
||||
t.Fatalf("Submit() error = %v, want %v", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPumpEventsInvalidatesBeforeUIDrainAndStops(t *testing.T) {
|
||||
relay, err := NewEventRelay(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := make(chan Event, 2)
|
||||
invalidated := make(chan struct{}, 2)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
pumpResult := make(chan error, 1)
|
||||
go func() {
|
||||
pumpResult <- PumpEvents(ctx, source, relay, func() {
|
||||
invalidated <- struct{}{}
|
||||
})
|
||||
}()
|
||||
|
||||
first := Event{Type: EventCatalogRefreshed, RequestID: "first"}
|
||||
second := Event{Type: EventCatalogRejected, RequestID: "second"}
|
||||
source <- first
|
||||
source <- second
|
||||
waitSignal(t, invalidated)
|
||||
|
||||
var received []string
|
||||
if len(received) != 0 {
|
||||
t.Fatal("background pump applied an event before UI drain")
|
||||
}
|
||||
if err := relay.Drain(func(event Event) error {
|
||||
received = append(received, event.RequestID)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitSignal(t, invalidated)
|
||||
if err := relay.Drain(func(event Event) error {
|
||||
received = append(received, event.RequestID)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(received, []string{"first", "second"}) {
|
||||
t.Fatalf("received order = %v", received)
|
||||
}
|
||||
|
||||
cancel()
|
||||
if err := waitRelayResult(pumpResult); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("PumpEvents() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventRelayDrainReportsErrorsAndContinues(t *testing.T) {
|
||||
relay, err := NewEventRelay(2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, eventType := range []EventType{EventCatalogRefreshed, EventCatalogRejected} {
|
||||
if err := relay.Submit(context.Background(), Event{Type: eventType}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
wantErr := errors.New("apply failed")
|
||||
applied := 0
|
||||
err = relay.Drain(func(Event) error {
|
||||
applied++
|
||||
return wantErr
|
||||
})
|
||||
if !errors.Is(err, wantErr) || applied != 2 {
|
||||
t.Fatalf("Drain() = (%d applies, %v)", applied, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEventRelayRejectsInvalidCapacity(t *testing.T) {
|
||||
if _, err := NewEventRelay(0); !errors.Is(err, ErrEventRelayInvalid) {
|
||||
t.Fatalf("NewEventRelay(0) error = %v", err)
|
||||
}
|
||||
relay, err := NewEventRelay(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
relay.Close()
|
||||
if err := relay.Submit(
|
||||
context.Background(),
|
||||
Event{Type: EventCatalogRefreshed},
|
||||
); !errors.Is(err, ErrEventRelayClosed) {
|
||||
t.Fatalf("Submit(after Close) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func waitRelayResult(result <-chan error) error {
|
||||
select {
|
||||
case err := <-result:
|
||||
return err
|
||||
case <-time.After(2 * time.Second):
|
||||
return errors.New("timed out waiting for relay")
|
||||
}
|
||||
}
|
||||
|
||||
func waitSignal(t *testing.T, signal <-chan struct{}) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-signal:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for signal")
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ func TestEventTypeValid(t *testing.T) {
|
||||
EventAppStarted,
|
||||
EventAppExited,
|
||||
EventLicenseChanged,
|
||||
EventIconReady,
|
||||
EventIconFailed,
|
||||
}
|
||||
|
||||
for _, eventType := range eventTypes {
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
MinIconDPI = 48
|
||||
MaxIconDPI = 768
|
||||
)
|
||||
|
||||
var ErrInvalidIconEvent = errors.New("invalid icon application event")
|
||||
|
||||
// IconFailureCode is a stable, non-sensitive reason exposed to UI adapters.
|
||||
type IconFailureCode string
|
||||
|
||||
const (
|
||||
IconFailureUnavailable IconFailureCode = "unavailable"
|
||||
IconFailureInvalid IconFailureCode = "invalid_content"
|
||||
IconFailureUnsafe IconFailureCode = "unsafe_cache"
|
||||
)
|
||||
|
||||
// Valid reports whether code is part of the documented icon event contract.
|
||||
func (code IconFailureCode) Valid() bool {
|
||||
switch code {
|
||||
case IconFailureUnavailable, IconFailureInvalid, IconFailureUnsafe:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// IconEventIdentity correlates one background request with one catalog icon.
|
||||
type IconEventIdentity struct {
|
||||
RequestID string
|
||||
AppID string
|
||||
Reference string
|
||||
DPI int
|
||||
}
|
||||
|
||||
// NewIconEventIdentity validates and canonicalizes an icon event identity.
|
||||
func NewIconEventIdentity(
|
||||
requestID string,
|
||||
appID string,
|
||||
reference string,
|
||||
dpi int,
|
||||
) (IconEventIdentity, error) {
|
||||
if strings.TrimSpace(requestID) == "" {
|
||||
return IconEventIdentity{}, fmt.Errorf(
|
||||
"%w: empty request ID",
|
||||
ErrInvalidIconEvent,
|
||||
)
|
||||
}
|
||||
if strings.TrimSpace(appID) == "" {
|
||||
return IconEventIdentity{}, fmt.Errorf(
|
||||
"%w: empty app ID",
|
||||
ErrInvalidIconEvent,
|
||||
)
|
||||
}
|
||||
canonicalReference, err := NormalizeIconReference(reference)
|
||||
if err != nil {
|
||||
return IconEventIdentity{}, err
|
||||
}
|
||||
if dpi < MinIconDPI || dpi > MaxIconDPI {
|
||||
return IconEventIdentity{}, fmt.Errorf(
|
||||
"%w: DPI %d outside %d..%d",
|
||||
ErrInvalidIconEvent,
|
||||
dpi,
|
||||
MinIconDPI,
|
||||
MaxIconDPI,
|
||||
)
|
||||
}
|
||||
return IconEventIdentity{
|
||||
RequestID: requestID,
|
||||
AppID: appID,
|
||||
Reference: canonicalReference,
|
||||
DPI: dpi,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NormalizeIconReference returns the canonical sha256:<lower-hex> form.
|
||||
func NormalizeIconReference(reference string) (string, error) {
|
||||
const prefix = "sha256:"
|
||||
if !strings.HasPrefix(reference, prefix) {
|
||||
return "", fmt.Errorf(
|
||||
"%w: icon reference must use sha256",
|
||||
ErrInvalidIconEvent,
|
||||
)
|
||||
}
|
||||
digest := strings.ToLower(strings.TrimPrefix(reference, prefix))
|
||||
decoded, err := hex.DecodeString(digest)
|
||||
if err != nil || len(decoded) != sha256.Size || len(digest) != sha256.Size*2 {
|
||||
return "", fmt.Errorf(
|
||||
"%w: malformed icon digest",
|
||||
ErrInvalidIconEvent,
|
||||
)
|
||||
}
|
||||
return prefix + digest, nil
|
||||
}
|
||||
|
||||
// IconReadyPayload contains an image decoded outside the Gio UI goroutine.
|
||||
type IconReadyPayload struct {
|
||||
Reference string
|
||||
DPI int
|
||||
Image image.Image
|
||||
}
|
||||
|
||||
// IconFailedPayload contains a stable failure classification, never a raw URL.
|
||||
type IconFailedPayload struct {
|
||||
Reference string
|
||||
DPI int
|
||||
ErrorCode IconFailureCode
|
||||
}
|
||||
|
||||
// IconEvent is the validated representation consumed by UI adapters.
|
||||
type IconEvent struct {
|
||||
Type EventType
|
||||
Identity IconEventIdentity
|
||||
Image image.Image
|
||||
ErrorCode IconFailureCode
|
||||
}
|
||||
|
||||
// NewIconReadyEvent builds a validated ready event.
|
||||
func NewIconReadyEvent(
|
||||
identity IconEventIdentity,
|
||||
icon image.Image,
|
||||
) (Event, error) {
|
||||
validated, err := NewIconEventIdentity(
|
||||
identity.RequestID,
|
||||
identity.AppID,
|
||||
identity.Reference,
|
||||
identity.DPI,
|
||||
)
|
||||
if err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
if isNilImage(icon) {
|
||||
return Event{}, fmt.Errorf("%w: nil ready image", ErrInvalidIconEvent)
|
||||
}
|
||||
return Event{
|
||||
Type: EventIconReady,
|
||||
RequestID: validated.RequestID,
|
||||
AppID: validated.AppID,
|
||||
Payload: IconReadyPayload{
|
||||
Reference: validated.Reference,
|
||||
DPI: validated.DPI,
|
||||
Image: icon,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NewIconFailedEvent builds a validated failure event.
|
||||
func NewIconFailedEvent(
|
||||
identity IconEventIdentity,
|
||||
code IconFailureCode,
|
||||
) (Event, error) {
|
||||
validated, err := NewIconEventIdentity(
|
||||
identity.RequestID,
|
||||
identity.AppID,
|
||||
identity.Reference,
|
||||
identity.DPI,
|
||||
)
|
||||
if err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
if !code.Valid() {
|
||||
return Event{}, fmt.Errorf(
|
||||
"%w: unknown failure code %q",
|
||||
ErrInvalidIconEvent,
|
||||
code,
|
||||
)
|
||||
}
|
||||
return Event{
|
||||
Type: EventIconFailed,
|
||||
RequestID: validated.RequestID,
|
||||
AppID: validated.AppID,
|
||||
Payload: IconFailedPayload{
|
||||
Reference: validated.Reference,
|
||||
DPI: validated.DPI,
|
||||
ErrorCode: code,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ParseIconEvent validates an icon envelope. Non-icon events return handled=false.
|
||||
func ParseIconEvent(event Event) (parsed IconEvent, handled bool, err error) {
|
||||
switch event.Type {
|
||||
case EventIconReady:
|
||||
payload, ok := event.Payload.(IconReadyPayload)
|
||||
if !ok {
|
||||
return IconEvent{}, true, fmt.Errorf(
|
||||
"%w: ready payload has type %T",
|
||||
ErrInvalidIconEvent,
|
||||
event.Payload,
|
||||
)
|
||||
}
|
||||
identity, identityErr := NewIconEventIdentity(
|
||||
event.RequestID,
|
||||
event.AppID,
|
||||
payload.Reference,
|
||||
payload.DPI,
|
||||
)
|
||||
if identityErr != nil {
|
||||
return IconEvent{}, true, identityErr
|
||||
}
|
||||
if isNilImage(payload.Image) {
|
||||
return IconEvent{}, true, fmt.Errorf(
|
||||
"%w: nil ready image",
|
||||
ErrInvalidIconEvent,
|
||||
)
|
||||
}
|
||||
return IconEvent{
|
||||
Type: event.Type,
|
||||
Identity: identity,
|
||||
Image: payload.Image,
|
||||
}, true, nil
|
||||
case EventIconFailed:
|
||||
payload, ok := event.Payload.(IconFailedPayload)
|
||||
if !ok {
|
||||
return IconEvent{}, true, fmt.Errorf(
|
||||
"%w: failed payload has type %T",
|
||||
ErrInvalidIconEvent,
|
||||
event.Payload,
|
||||
)
|
||||
}
|
||||
identity, identityErr := NewIconEventIdentity(
|
||||
event.RequestID,
|
||||
event.AppID,
|
||||
payload.Reference,
|
||||
payload.DPI,
|
||||
)
|
||||
if identityErr != nil {
|
||||
return IconEvent{}, true, identityErr
|
||||
}
|
||||
if !payload.ErrorCode.Valid() {
|
||||
return IconEvent{}, true, fmt.Errorf(
|
||||
"%w: unknown failure code %q",
|
||||
ErrInvalidIconEvent,
|
||||
payload.ErrorCode,
|
||||
)
|
||||
}
|
||||
return IconEvent{
|
||||
Type: event.Type,
|
||||
Identity: identity,
|
||||
ErrorCode: payload.ErrorCode,
|
||||
}, true, nil
|
||||
default:
|
||||
return IconEvent{}, false, nil
|
||||
}
|
||||
}
|
||||
|
||||
func isNilImage(icon image.Image) bool {
|
||||
if icon == nil {
|
||||
return true
|
||||
}
|
||||
value := reflect.ValueOf(icon)
|
||||
switch value.Kind() {
|
||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
|
||||
reflect.Ptr, reflect.Slice:
|
||||
return value.IsNil()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"image"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIconEventRoundTrip(t *testing.T) {
|
||||
reference := "sha256:" + strings.Repeat("A1", 32)
|
||||
identity, err := NewIconEventIdentity("request-1", "app-one", reference, 144)
|
||||
if err != nil {
|
||||
t.Fatalf("NewIconEventIdentity() error = %v", err)
|
||||
}
|
||||
if identity.Reference != strings.ToLower(reference) {
|
||||
t.Fatalf("canonical reference = %q", identity.Reference)
|
||||
}
|
||||
|
||||
icon := image.NewNRGBA(image.Rect(0, 0, 24, 24))
|
||||
ready, err := NewIconReadyEvent(identity, icon)
|
||||
if err != nil {
|
||||
t.Fatalf("NewIconReadyEvent() error = %v", err)
|
||||
}
|
||||
parsed, handled, err := ParseIconEvent(ready)
|
||||
if err != nil || !handled {
|
||||
t.Fatalf("ParseIconEvent(ready) = (%+v, %t, %v)", parsed, handled, err)
|
||||
}
|
||||
if parsed.Type != EventIconReady || parsed.Identity != identity || parsed.Image != icon {
|
||||
t.Fatalf("parsed ready event = %+v", parsed)
|
||||
}
|
||||
|
||||
failed, err := NewIconFailedEvent(identity, IconFailureUnsafe)
|
||||
if err != nil {
|
||||
t.Fatalf("NewIconFailedEvent() error = %v", err)
|
||||
}
|
||||
parsed, handled, err = ParseIconEvent(failed)
|
||||
if err != nil || !handled {
|
||||
t.Fatalf("ParseIconEvent(failed) = (%+v, %t, %v)", parsed, handled, err)
|
||||
}
|
||||
if parsed.Type != EventIconFailed ||
|
||||
parsed.Identity != identity ||
|
||||
parsed.ErrorCode != IconFailureUnsafe {
|
||||
t.Fatalf("parsed failed event = %+v", parsed)
|
||||
}
|
||||
|
||||
parsed, handled, err = ParseIconEvent(Event{Type: EventCatalogRefreshed})
|
||||
if err != nil || handled {
|
||||
t.Fatalf("ParseIconEvent(non-icon) = (%+v, %t, %v)", parsed, handled, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIconEventRejectsInvalidIdentityAndPayload(t *testing.T) {
|
||||
validReference := "sha256:" + strings.Repeat("0a", 32)
|
||||
tests := []struct {
|
||||
name string
|
||||
requestID string
|
||||
appID string
|
||||
reference string
|
||||
dpi int
|
||||
}{
|
||||
{name: "empty request", appID: "app", reference: validReference, dpi: 96},
|
||||
{name: "empty app", requestID: "request", reference: validReference, dpi: 96},
|
||||
{name: "bad reference", requestID: "request", appID: "app", reference: "md5:00", dpi: 96},
|
||||
{name: "low DPI", requestID: "request", appID: "app", reference: validReference, dpi: 47},
|
||||
{name: "high DPI", requestID: "request", appID: "app", reference: validReference, dpi: 769},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, err := NewIconEventIdentity(
|
||||
test.requestID,
|
||||
test.appID,
|
||||
test.reference,
|
||||
test.dpi,
|
||||
)
|
||||
if !errors.Is(err, ErrInvalidIconEvent) {
|
||||
t.Fatalf("NewIconEventIdentity() error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
identity, err := NewIconEventIdentity("request", "app", validReference, 96)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := NewIconReadyEvent(identity, nil); !errors.Is(err, ErrInvalidIconEvent) {
|
||||
t.Fatalf("NewIconReadyEvent(nil) error = %v", err)
|
||||
}
|
||||
var typedNil *image.NRGBA
|
||||
if _, err := NewIconReadyEvent(identity, typedNil); !errors.Is(err, ErrInvalidIconEvent) {
|
||||
t.Fatalf("NewIconReadyEvent(typed nil) error = %v", err)
|
||||
}
|
||||
if _, err := NewIconFailedEvent(identity, IconFailureCode("raw-http-error")); !errors.Is(err, ErrInvalidIconEvent) {
|
||||
t.Fatalf("NewIconFailedEvent(invalid code) error = %v", err)
|
||||
}
|
||||
|
||||
invalidPayloads := []Event{
|
||||
{Type: EventIconReady, RequestID: "request", AppID: "app", Payload: "wrong"},
|
||||
{Type: EventIconFailed, RequestID: "request", AppID: "app", Payload: "wrong"},
|
||||
{
|
||||
Type: EventIconReady,
|
||||
RequestID: "request",
|
||||
AppID: "app",
|
||||
Payload: IconReadyPayload{
|
||||
Reference: validReference,
|
||||
DPI: 96,
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: EventIconFailed,
|
||||
RequestID: "request",
|
||||
AppID: "app",
|
||||
Payload: IconFailedPayload{
|
||||
Reference: validReference,
|
||||
DPI: 96,
|
||||
ErrorCode: IconFailureCode("raw"),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, event := range invalidPayloads {
|
||||
_, handled, err := ParseIconEvent(event)
|
||||
if !handled || !errors.Is(err, ErrInvalidIconEvent) {
|
||||
t.Fatalf("ParseIconEvent(%+v) handled=%t error=%v", event, handled, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"softbox.local/core/application"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrIconDeliveryInvalid = errors.New("icon event delivery is invalid")
|
||||
ErrIconEventPublish = errors.New("publish icon application event")
|
||||
)
|
||||
|
||||
// IconLoader is the narrow cache contract used by background delivery.
|
||||
type IconLoader interface {
|
||||
Load(context.Context, IconRequest) (IconResult, error)
|
||||
}
|
||||
|
||||
// IconLoaderFunc adapts a function to IconLoader.
|
||||
type IconLoaderFunc func(context.Context, IconRequest) (IconResult, error)
|
||||
|
||||
func (function IconLoaderFunc) Load(
|
||||
ctx context.Context,
|
||||
request IconRequest,
|
||||
) (IconResult, error) {
|
||||
return function(ctx, request)
|
||||
}
|
||||
|
||||
// IconEventPublisher queues application events for UI adapters.
|
||||
type IconEventPublisher interface {
|
||||
Publish(context.Context, application.Event) error
|
||||
}
|
||||
|
||||
// IconEventPublisherFunc adapts a function to IconEventPublisher.
|
||||
type IconEventPublisherFunc func(context.Context, application.Event) error
|
||||
|
||||
func (function IconEventPublisherFunc) Publish(
|
||||
ctx context.Context,
|
||||
event application.Event,
|
||||
) error {
|
||||
return function(ctx, event)
|
||||
}
|
||||
|
||||
// IconEventDelivery loads and decodes an icon in a caller-owned background task.
|
||||
// It never creates goroutines and never imports or mutates Gio state.
|
||||
type IconEventDelivery struct {
|
||||
Loader IconLoader
|
||||
Publisher IconEventPublisher
|
||||
}
|
||||
|
||||
// LoadAndPublish emits one ready or failed application event.
|
||||
// Cancellation ends silently so an obsolete request cannot publish a stale failure.
|
||||
func (delivery IconEventDelivery) LoadAndPublish(
|
||||
ctx context.Context,
|
||||
identity application.IconEventIdentity,
|
||||
) error {
|
||||
validated, err := application.NewIconEventIdentity(
|
||||
identity.RequestID,
|
||||
identity.AppID,
|
||||
identity.Reference,
|
||||
identity.DPI,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrIconDeliveryInvalid, err)
|
||||
}
|
||||
if isNilIconDeliveryDependency(delivery.Loader) ||
|
||||
isNilIconDeliveryDependency(delivery.Publisher) {
|
||||
return fmt.Errorf(
|
||||
"%w: loader and publisher are required",
|
||||
ErrIconDeliveryInvalid,
|
||||
)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
result, loadErr := delivery.Loader.Load(ctx, IconRequest{
|
||||
Reference: validated.Reference,
|
||||
DPI: validated.DPI,
|
||||
})
|
||||
if loadErr != nil {
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
return ctxErr
|
||||
}
|
||||
if isIconDeliveryCancellation(loadErr) {
|
||||
return loadErr
|
||||
}
|
||||
return delivery.publishFailure(ctx, validated, loadErr)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
icon, decodeErr := DecodeIcon(result.Bytes)
|
||||
if decodeErr != nil {
|
||||
return delivery.publishFailure(ctx, validated, decodeErr)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
ready, eventErr := application.NewIconReadyEvent(validated, icon)
|
||||
if eventErr != nil {
|
||||
return fmt.Errorf("%w: %v", ErrIconDeliveryInvalid, eventErr)
|
||||
}
|
||||
if publishErr := delivery.Publisher.Publish(ctx, ready); publishErr != nil {
|
||||
if isIconDeliveryCancellation(publishErr) {
|
||||
return publishErr
|
||||
}
|
||||
return errors.Join(ErrIconEventPublish, publishErr)
|
||||
}
|
||||
return result.Warning
|
||||
}
|
||||
|
||||
func (delivery IconEventDelivery) publishFailure(
|
||||
ctx context.Context,
|
||||
identity application.IconEventIdentity,
|
||||
cause error,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
failed, eventErr := application.NewIconFailedEvent(
|
||||
identity,
|
||||
classifyIconFailure(cause),
|
||||
)
|
||||
if eventErr != nil {
|
||||
return errors.Join(
|
||||
fmt.Errorf("load or decode icon: %w", cause),
|
||||
fmt.Errorf("%w: %v", ErrIconDeliveryInvalid, eventErr),
|
||||
)
|
||||
}
|
||||
publishErr := delivery.Publisher.Publish(ctx, failed)
|
||||
operationErr := fmt.Errorf("load or decode icon: %w", cause)
|
||||
if publishErr != nil {
|
||||
if isIconDeliveryCancellation(publishErr) {
|
||||
return publishErr
|
||||
}
|
||||
return errors.Join(operationErr, ErrIconEventPublish, publishErr)
|
||||
}
|
||||
return operationErr
|
||||
}
|
||||
|
||||
func classifyIconFailure(err error) application.IconFailureCode {
|
||||
switch {
|
||||
case errors.Is(err, ErrIconCacheUnsafe):
|
||||
return application.IconFailureUnsafe
|
||||
case errors.Is(err, ErrIconReferenceInvalid),
|
||||
errors.Is(err, ErrIconDPIInvalid),
|
||||
errors.Is(err, ErrIconHashMismatch),
|
||||
errors.Is(err, ErrIconTooLarge),
|
||||
errors.Is(err, ErrIconImageInvalid),
|
||||
errors.Is(err, ErrIconResponseInvalid):
|
||||
return application.IconFailureInvalid
|
||||
default:
|
||||
return application.IconFailureUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
func isIconDeliveryCancellation(err error) bool {
|
||||
return errors.Is(err, context.Canceled) ||
|
||||
errors.Is(err, context.DeadlineExceeded)
|
||||
}
|
||||
|
||||
func isNilIconDeliveryDependency(dependency any) bool {
|
||||
if dependency == nil {
|
||||
return true
|
||||
}
|
||||
value := reflect.ValueOf(dependency)
|
||||
switch value.Kind() {
|
||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
|
||||
reflect.Ptr, reflect.Slice:
|
||||
return value.IsNil()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"softbox.local/core/application"
|
||||
)
|
||||
|
||||
func TestIconEventDeliveryPublishesDecodedReadyEvent(t *testing.T) {
|
||||
document := testPNG(t, 24, 24)
|
||||
identity := iconEventIdentity(t, document, "request-ready")
|
||||
var gotRequest IconRequest
|
||||
var events []application.Event
|
||||
delivery := IconEventDelivery{
|
||||
Loader: IconLoaderFunc(func(
|
||||
_ context.Context,
|
||||
request IconRequest,
|
||||
) (IconResult, error) {
|
||||
gotRequest = request
|
||||
return IconResult{Bytes: document, Source: IconSourceMemory}, nil
|
||||
}),
|
||||
Publisher: IconEventPublisherFunc(func(
|
||||
_ context.Context,
|
||||
event application.Event,
|
||||
) error {
|
||||
events = append(events, event)
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
|
||||
if err := delivery.LoadAndPublish(context.Background(), identity); err != nil {
|
||||
t.Fatalf("LoadAndPublish() error = %v", err)
|
||||
}
|
||||
if gotRequest.Reference != identity.Reference || gotRequest.DPI != identity.DPI {
|
||||
t.Fatalf("loader request = %+v", gotRequest)
|
||||
}
|
||||
if len(events) != 1 {
|
||||
t.Fatalf("published events = %d", len(events))
|
||||
}
|
||||
parsed, handled, err := application.ParseIconEvent(events[0])
|
||||
if err != nil || !handled {
|
||||
t.Fatalf("ParseIconEvent() = (%+v, %t, %v)", parsed, handled, err)
|
||||
}
|
||||
if parsed.Type != application.EventIconReady || parsed.Identity != identity {
|
||||
t.Fatalf("ready event = %+v", parsed)
|
||||
}
|
||||
if bounds := parsed.Image.Bounds(); bounds.Dx() != 24 || bounds.Dy() != 24 {
|
||||
t.Fatalf("decoded bounds = %v", bounds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIconEventDeliveryClassifiesFailuresWithoutRawErrorPayload(t *testing.T) {
|
||||
document := testPNG(t, 8, 8)
|
||||
identity := iconEventIdentity(t, document, "request-failed")
|
||||
tests := []struct {
|
||||
name string
|
||||
loadErr error
|
||||
bytes []byte
|
||||
wantCode application.IconFailureCode
|
||||
}{
|
||||
{name: "unsafe", loadErr: ErrIconCacheUnsafe, wantCode: application.IconFailureUnsafe},
|
||||
{name: "invalid", loadErr: ErrIconHashMismatch, wantCode: application.IconFailureInvalid},
|
||||
{
|
||||
name: "unavailable",
|
||||
loadErr: errors.New("GET https://secret.invalid/icon?token=hidden failed"),
|
||||
wantCode: application.IconFailureUnavailable,
|
||||
},
|
||||
{name: "decode", bytes: []byte("not an image"), wantCode: application.IconFailureInvalid},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var published application.Event
|
||||
delivery := IconEventDelivery{
|
||||
Loader: IconLoaderFunc(func(
|
||||
context.Context,
|
||||
IconRequest,
|
||||
) (IconResult, error) {
|
||||
return IconResult{Bytes: test.bytes}, test.loadErr
|
||||
}),
|
||||
Publisher: IconEventPublisherFunc(func(
|
||||
_ context.Context,
|
||||
event application.Event,
|
||||
) error {
|
||||
published = event
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
|
||||
err := delivery.LoadAndPublish(context.Background(), identity)
|
||||
if err == nil {
|
||||
t.Fatal("LoadAndPublish() unexpectedly succeeded")
|
||||
}
|
||||
parsed, handled, parseErr := application.ParseIconEvent(published)
|
||||
if parseErr != nil || !handled {
|
||||
t.Fatalf("ParseIconEvent() = (%+v, %t, %v)", parsed, handled, parseErr)
|
||||
}
|
||||
if parsed.Type != application.EventIconFailed || parsed.ErrorCode != test.wantCode {
|
||||
t.Fatalf("failed event = %+v", parsed)
|
||||
}
|
||||
payload := published.Payload.(application.IconFailedPayload)
|
||||
if strings.Contains(string(payload.ErrorCode), "secret") ||
|
||||
strings.Contains(string(payload.ErrorCode), "token") {
|
||||
t.Fatalf("failure payload leaked raw error: %+v", payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIconEventDeliveryReportsPublishFailureAndCacheWarning(t *testing.T) {
|
||||
document := testPNG(t, 12, 12)
|
||||
identity := iconEventIdentity(t, document, "request-publish")
|
||||
publishErr := errors.New("event queue closed")
|
||||
delivery := IconEventDelivery{
|
||||
Loader: IconLoaderFunc(func(
|
||||
context.Context,
|
||||
IconRequest,
|
||||
) (IconResult, error) {
|
||||
return IconResult{Bytes: document}, nil
|
||||
}),
|
||||
Publisher: IconEventPublisherFunc(func(
|
||||
context.Context,
|
||||
application.Event,
|
||||
) error {
|
||||
return publishErr
|
||||
}),
|
||||
}
|
||||
if err := delivery.LoadAndPublish(context.Background(), identity); !errors.Is(err, ErrIconEventPublish) || !errors.Is(err, publishErr) {
|
||||
t.Fatalf("LoadAndPublish() error = %v", err)
|
||||
}
|
||||
|
||||
warning := errors.New("disk store warning")
|
||||
delivery.Loader = IconLoaderFunc(func(
|
||||
context.Context,
|
||||
IconRequest,
|
||||
) (IconResult, error) {
|
||||
return IconResult{Bytes: document, Warning: warning}, nil
|
||||
})
|
||||
delivery.Publisher = IconEventPublisherFunc(func(
|
||||
context.Context,
|
||||
application.Event,
|
||||
) error {
|
||||
return nil
|
||||
})
|
||||
if err := delivery.LoadAndPublish(context.Background(), identity); !errors.Is(err, warning) {
|
||||
t.Fatalf("LoadAndPublish() warning = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIconEventDeliveryCancellationPublishesNothing(t *testing.T) {
|
||||
document := testPNG(t, 10, 10)
|
||||
identity := iconEventIdentity(t, document, "request-canceled")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
loaderCalled := false
|
||||
publisherCalled := false
|
||||
delivery := IconEventDelivery{
|
||||
Loader: IconLoaderFunc(func(
|
||||
context.Context,
|
||||
IconRequest,
|
||||
) (IconResult, error) {
|
||||
loaderCalled = true
|
||||
return IconResult{}, nil
|
||||
}),
|
||||
Publisher: IconEventPublisherFunc(func(
|
||||
context.Context,
|
||||
application.Event,
|
||||
) error {
|
||||
publisherCalled = true
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
if err := delivery.LoadAndPublish(ctx, identity); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("LoadAndPublish() error = %v", err)
|
||||
}
|
||||
if loaderCalled || publisherCalled {
|
||||
t.Fatalf("canceled delivery called loader=%t publisher=%t", loaderCalled, publisherCalled)
|
||||
}
|
||||
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
loaderCalled = false
|
||||
publisherCalled = false
|
||||
delivery.Loader = IconLoaderFunc(func(
|
||||
context.Context,
|
||||
IconRequest,
|
||||
) (IconResult, error) {
|
||||
loaderCalled = true
|
||||
cancel()
|
||||
return IconResult{Bytes: document}, nil
|
||||
})
|
||||
if err := delivery.LoadAndPublish(ctx, identity); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("LoadAndPublish(cancel during load) error = %v", err)
|
||||
}
|
||||
if !loaderCalled || publisherCalled {
|
||||
t.Fatalf(
|
||||
"cancel-during-load called loader=%t publisher=%t",
|
||||
loaderCalled,
|
||||
publisherCalled,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIconEventDeliveryRejectsIncompleteDependencies(t *testing.T) {
|
||||
document := testPNG(t, 4, 4)
|
||||
identity := iconEventIdentity(t, document, "request-invalid")
|
||||
tests := []IconEventDelivery{
|
||||
{},
|
||||
{Loader: IconLoaderFunc(nil), Publisher: IconEventPublisherFunc(nil)},
|
||||
}
|
||||
for _, delivery := range tests {
|
||||
if err := delivery.LoadAndPublish(context.Background(), identity); !errors.Is(err, ErrIconDeliveryInvalid) {
|
||||
t.Fatalf("LoadAndPublish() error = %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func iconEventIdentity(
|
||||
t *testing.T,
|
||||
document []byte,
|
||||
requestID string,
|
||||
) application.IconEventIdentity {
|
||||
t.Helper()
|
||||
request := iconRequest(document, 96)
|
||||
identity, err := application.NewIconEventIdentity(
|
||||
requestID,
|
||||
"app-one",
|
||||
request.Reference,
|
||||
request.DPI,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return identity
|
||||
}
|
||||
Reference in New Issue
Block a user