Bridge Remote speech through bounded reader assembly
This commit is contained in:
1 parent
703d44029c
commit
393ff90f00
12 files changed
+890
-93
No files matched your search
@@ -20,7 +20,7 @@ import (
|
||||
)
|
||||
|
||||
// A test-only executable peer. The parent supplies synthetic approval over real
|
||||
// SDK process pipes; no production command can instantiate this workflow yet.
|
||||
// SDK process pipes. Production reader consent is tested separately.
|
||||
func TestConnectionWorkflowSDKPeer(t *testing.T) {
|
||||
if os.Args[len(os.Args)-1] != "remote-workflow-peer" {
|
||||
return
|
||||
@@ -85,9 +85,23 @@ func TestConnectionWorkflowSDKPeer(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
for _, role := range []string{"controller", "controlled"} {
|
||||
t.Run(role, func(t *testing.T) { testConnectionWorkflowPublicSDKProcess(t, role) })
|
||||
}
|
||||
}
|
||||
|
||||
func testConnectionWorkflowPublicSDKProcess(t *testing.T, role string) {
|
||||
wireRole, peerRole, grant := controller, "slave", "remote-present"
|
||||
if role == "controlled" {
|
||||
wireRole, peerRole, grant = controlled, "master", "output-observe"
|
||||
}
|
||||
certificate, _ := testCertificate(t, false)
|
||||
probed := make(chan struct{})
|
||||
joined := make(chan struct{})
|
||||
relaySpeech := make(chan message, 1)
|
||||
requestSpeech := make(chan struct{})
|
||||
var requestOnce sync.Once
|
||||
t.Cleanup(func() { requestOnce.Do(func() { close(requestSpeech) }) })
|
||||
var serverMu sync.Mutex
|
||||
connections := 0
|
||||
target := testRelay(t, certificate, func(connection net.Conn) {
|
||||
@@ -103,11 +117,27 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
close(probed)
|
||||
return
|
||||
}
|
||||
if relayHandshake(t, connection, controller) == nil {
|
||||
reader := relayHandshake(t, connection, wireRole)
|
||||
if reader == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
_, _ = io.WriteString(connection, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"`+peerRole+`"}]}`+"\n")
|
||||
close(joined)
|
||||
if role == "controller" {
|
||||
_, _ = io.WriteString(connection, "{\"type\":\"speak\",\"origin\":7,\"sequence\":[\" fixture speech \"],\"priority\":1}\n")
|
||||
} else {
|
||||
<-requestSpeech
|
||||
frame, err := readFrame(reader)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
value, err := decodeMessage(frame)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
relaySpeech <- value
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, connection)
|
||||
})
|
||||
testBinary, err := os.Executable()
|
||||
@@ -173,12 +203,18 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
result := any(struct{}{})
|
||||
if frame.Method == "remote.open" {
|
||||
var open sdk.RemoteOpen
|
||||
if json.Unmarshal(frame.Params, &open) != nil || open.Epoch != 1 || open.Role != "controller" {
|
||||
if json.Unmarshal(frame.Params, &open) != nil || open.Epoch != 1 || open.Role != role {
|
||||
t.Error("invalid SDK lease request")
|
||||
return
|
||||
}
|
||||
result = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: open.Epoch}
|
||||
}
|
||||
if frame.Method == "remote.present" {
|
||||
var presentation sdk.RemotePresentation
|
||||
if json.Unmarshal(frame.Params, &presentation) != nil || presentation.Lease != strings.Repeat("b", 32) || presentation.Epoch != 1 || presentation.Sequence == 0 || presentation.Speech.Priority != 1 || len(presentation.Speech.Parts) != 1 || presentation.Speech.Parts[0].Text != " fixture speech " {
|
||||
t.Error("SDK changed incoming speech")
|
||||
}
|
||||
}
|
||||
if send(map[string]any{"jsonrpc": "2.0", "id": frame.ID, "result": result}) != nil {
|
||||
return
|
||||
}
|
||||
@@ -200,7 +236,7 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "id": "1", "method": "initialize", "params": map[string]any{
|
||||
"protocol": map[string]int{"major": 1, "minor": 1}, "session": "fixture",
|
||||
"apis": []string{"commands", "presentation", "interaction", "session-events", "remote-access"},
|
||||
"capabilities": []string{"presentation", "interaction", "remote-present"},
|
||||
"capabilities": []string{"presentation", "interaction", grant},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -214,7 +250,7 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": sdk.SessionEvent{
|
||||
Kind: "remote.action", Sequence: 1, Epoch: 1, Action: strings.Repeat("a", 32), Role: "controller", Grants: []string{"remote-present"},
|
||||
Kind: "remote.action", Sequence: 1, Epoch: 1, Action: strings.Repeat("a", 32), Role: role, Grants: []string{grant},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -259,17 +295,73 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
}
|
||||
invoke("remote-connection", "connect", "")
|
||||
awaitDone(t, joined)
|
||||
invoke("remote-connection", "disconnect", "")
|
||||
for _, expected := range []string{"remote.open", "remote.close"} {
|
||||
expectedCalls := []string{"remote.open", "remote.present"}
|
||||
if role == "controlled" {
|
||||
expectedCalls = []string{"remote.open"}
|
||||
ready := false
|
||||
for !ready {
|
||||
status := invoke("remote-connection", "refresh", "")
|
||||
if status.Form == nil {
|
||||
t.Fatal("missing connection status")
|
||||
}
|
||||
for _, element := range status.Form.Elements {
|
||||
for _, item := range element.Items {
|
||||
if item.ID == "status" && item.Label == connection_status_text(connectionStatus{state: "ready"}) {
|
||||
ready = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
t.Fatal("connection never became ready")
|
||||
}
|
||||
}
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": sdk.SessionEvent{
|
||||
Kind: "remote.output", Sequence: 2, Epoch: 1, Lease: strings.Repeat("b", 32),
|
||||
Speech: &sdk.RemoteSpeech{Kind: "speak", Priority: 1, Parts: []sdk.RemoteSpeechPart{{Text: " fixture speech "}}},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requestOnce.Do(func() { close(requestSpeech) })
|
||||
select {
|
||||
case method := <-leaseCalls:
|
||||
if method != expected {
|
||||
t.Fatal("unexpected lease operation", method)
|
||||
case value := <-relaySpeech:
|
||||
if value.kind != "speak" || value.origin != 0 || value.payload.(speech).parts[0].text != " fixture speech " {
|
||||
t.Fatal("SDK changed observed speech")
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("missing lease operation", expected)
|
||||
t.Fatal("SDK did not forward observed speech")
|
||||
}
|
||||
}
|
||||
for _, expected := range expectedCalls {
|
||||
for {
|
||||
select {
|
||||
case method := <-leaseCalls:
|
||||
if method == "remote.heartbeat" {
|
||||
continue
|
||||
}
|
||||
if method != expected {
|
||||
t.Fatal("unexpected lease operation", method)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("missing lease operation", expected)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
invoke("remote-connection", "disconnect", "")
|
||||
for {
|
||||
select {
|
||||
case method := <-leaseCalls:
|
||||
if method == "remote.heartbeat" {
|
||||
continue
|
||||
}
|
||||
if method != "remote.close" {
|
||||
t.Fatal("missing ordered close", method)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("missing close")
|
||||
}
|
||||
break
|
||||
}
|
||||
if result := invoke("remote-connection", "cancel", ""); !result.Done {
|
||||
t.Fatal("SDK did not close the workflow")
|
||||
}
|
||||
|
||||
+45
-34
@@ -36,11 +36,12 @@ type connectionAttempt struct {
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
epoch uint64
|
||||
err error // Protected by coordinator.mu.
|
||||
err error // Protected by coordinator.mu.
|
||||
speech *speechStream // Protected by coordinator.mu; nil until open succeeds.
|
||||
}
|
||||
|
||||
// coordinator joins reader consent and relay lifetime; it performs no desktop
|
||||
// effects. A fresh core action AND an explicit connect call are required for
|
||||
// coordinator joins reader consent, typed speech IPC and relay lifetime.
|
||||
// A fresh core action AND an explicit connect call are required for
|
||||
// every attempt. It never loads credentials, saves trust, or retries a network.
|
||||
type coordinator struct {
|
||||
client sessionClient
|
||||
@@ -109,6 +110,8 @@ func (c *coordinator) read_events() {
|
||||
if c.active != nil && event.Epoch == c.active.epoch {
|
||||
c.stop_locked(errLease)
|
||||
}
|
||||
case "remote.output":
|
||||
c.observe_locked(event)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
@@ -183,6 +186,9 @@ func (c *coordinator) stop_locked(err error) {
|
||||
}
|
||||
c.active.cancel() // Socket cancellation never waits for reader RPC cleanup.
|
||||
c.status.state, c.status.peer = "stopping", 0
|
||||
if c.active.speech != nil {
|
||||
c.active.speech.drain()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,8 +253,8 @@ func (c *coordinator) call(method string, params, result any) error {
|
||||
func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e endpoint, key string) {
|
||||
var lease sdk.RemoteLease
|
||||
var conn *relayConn
|
||||
var sequence uint64
|
||||
var heartbeatDone chan struct{}
|
||||
var stream *speechStream
|
||||
var operationsDone, outputDone chan struct{}
|
||||
var failure error
|
||||
defer func() {
|
||||
// Stop relay and heartbeat admission before serializing the final close.
|
||||
@@ -258,12 +264,18 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
|
||||
if conn != nil {
|
||||
conn.close()
|
||||
}
|
||||
if heartbeatDone != nil {
|
||||
<-heartbeatDone
|
||||
if operationsDone != nil {
|
||||
<-operationsDone
|
||||
}
|
||||
if outputDone != nil {
|
||||
<-outputDone
|
||||
}
|
||||
closeFailed := false
|
||||
if lease.Lease != "" {
|
||||
sequence++
|
||||
sequence := uint64(1)
|
||||
if stream != nil {
|
||||
sequence = stream.sequence + 1
|
||||
}
|
||||
closeFailed = c.call("remote.close", sdk.RemoteOperation{Lease: lease.Lease, Epoch: a.epoch, Sequence: sequence}, nil) != nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
@@ -312,28 +324,14 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
|
||||
c.status.state = "connecting"
|
||||
}
|
||||
c.mu.Unlock()
|
||||
heartbeatDone = make(chan struct{})
|
||||
stream = newSpeechStream(lease, approval)
|
||||
c.mu.Lock()
|
||||
a.speech = stream
|
||||
c.mu.Unlock()
|
||||
operationsDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(heartbeatDone)
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-a.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if a.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
sequence++
|
||||
if c.call("remote.heartbeat", sdk.RemoteOperation{Lease: lease.Lease, Epoch: a.epoch, Sequence: sequence}, nil) != nil {
|
||||
c.mu.Lock()
|
||||
c.stop_locked(errLease)
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
defer close(operationsDone)
|
||||
c.speech_operations(a, stream)
|
||||
}()
|
||||
var joined message
|
||||
conn, joined, failure = connect(a.ctx, e, r, key)
|
||||
@@ -347,6 +345,11 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
|
||||
if _, failure = s.accept(a.epoch, joined); failure != nil || !c.update(a, s) {
|
||||
return
|
||||
}
|
||||
outputDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(outputDone)
|
||||
c.speech_output(a, stream, conn)
|
||||
}()
|
||||
for a.ctx.Err() == nil {
|
||||
m, err := conn.read()
|
||||
if err != nil {
|
||||
@@ -360,13 +363,21 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
|
||||
failure = err
|
||||
return
|
||||
}
|
||||
// Desktop services are not implemented. Retain no payload and expose no
|
||||
// effect queue which could be mistaken for delivery-time authorization.
|
||||
if accepted && s.ignored != ^uint64(0) {
|
||||
s.ignored++
|
||||
}
|
||||
if !c.update(a, s) {
|
||||
return
|
||||
}
|
||||
if accepted {
|
||||
handled, err := c.receive_speech(a, stream, m)
|
||||
if err != nil {
|
||||
failure = err
|
||||
return
|
||||
}
|
||||
if !handled && s.ignored != ^uint64(0) {
|
||||
s.ignored++
|
||||
if !c.update(a, s) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,7 +171,7 @@ func TestCoordinatorMembershipFailureAndExplicitReconnect(t *testing.T) {
|
||||
depart := make(chan struct{})
|
||||
var once sync.Once
|
||||
t.Cleanup(func() { once.Do(func() { close(depart) }) })
|
||||
r, peerRole, effect := controller, "slave", `{"type":"speak","origin":7,"sequence":["private fixture"]}`
|
||||
r, peerRole, effect := controller, "slave", `{"type":"display","origin":7,"cells":[0,255]}`
|
||||
if roleName == "controlled" {
|
||||
r, peerRole, effect = controlled, "master", `{"type":"key","origin":7,"vk_code":65,"extended":false,"pressed":true}`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
const maxSpeechItems = 64
|
||||
|
||||
type speechItem struct {
|
||||
speech sdk.RemoteSpeech
|
||||
bytes int
|
||||
batch bool
|
||||
first bool
|
||||
final bool
|
||||
}
|
||||
|
||||
// One stream belongs to one attempt and lease. The coordinator mutex owns
|
||||
// admission/accounting, including in-flight work. Only speech_operations owns
|
||||
// sequence; teardown reads it after that worker finishes.
|
||||
type speechStream struct {
|
||||
lease sdk.RemoteLease
|
||||
role string
|
||||
grants []string
|
||||
incoming chan speechItem
|
||||
outgoing chan []byte
|
||||
items int
|
||||
bytes int
|
||||
sequence uint64
|
||||
}
|
||||
|
||||
func newSpeechStream(lease sdk.RemoteLease, approval sdk.SessionEvent) *speechStream {
|
||||
return &speechStream{lease: lease, role: approval.Role, grants: slices.Clone(approval.Grants),
|
||||
incoming: make(chan speechItem, maxSpeechItems), outgoing: make(chan []byte, maxSpeechItems)}
|
||||
}
|
||||
|
||||
func (stream *speechStream) drain() {
|
||||
for {
|
||||
select {
|
||||
case item := <-stream.incoming:
|
||||
stream.items--
|
||||
stream.bytes -= item.bytes
|
||||
case frame := <-stream.outgoing:
|
||||
stream.items--
|
||||
stream.bytes -= len(frame)
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *coordinator) speech_ready_locked(a *connectionAttempt, stream *speechStream) bool {
|
||||
return c.active == a && a.ctx.Err() == nil && a.speech == stream && c.status.state == "ready" && c.status.peer != 0
|
||||
}
|
||||
|
||||
// SDK event ownership never waits for a relay write. Pre-peer output is dropped
|
||||
// rather than retained for a helper who joins later. Core supplies the origin;
|
||||
// only events matching this controlled lease can reach this queue.
|
||||
func (c *coordinator) observe_locked(event sdk.SessionEvent) {
|
||||
a := c.active
|
||||
if a == nil || a.speech == nil {
|
||||
return
|
||||
}
|
||||
stream := a.speech
|
||||
if !c.speech_ready_locked(a, stream) || stream.role != "controlled" || !slices.Contains(stream.grants, "output-observe") || event.Lease != stream.lease.Lease || event.Epoch != stream.lease.Epoch {
|
||||
return
|
||||
}
|
||||
if event.Speech == nil {
|
||||
c.stop_locked(errProtocol)
|
||||
return
|
||||
}
|
||||
frame, err := relay_speech(*event.Speech)
|
||||
if err != nil {
|
||||
c.stop_locked(errProtocol)
|
||||
return
|
||||
}
|
||||
if stream.items == maxSpeechItems || stream.bytes+len(frame) > maxQueuedBytes {
|
||||
c.stop_locked(errLimit)
|
||||
return
|
||||
}
|
||||
stream.items++
|
||||
stream.bytes += len(frame)
|
||||
stream.outgoing <- frame // Capacity reserved above, including in-flight work.
|
||||
}
|
||||
|
||||
// Membership/origin checks have already run in the relay reader. Admit all
|
||||
// converted frames together or none, retaining FIFO cancel/pause order. Split
|
||||
// utterances are also assembled by core before reaching its speech owner.
|
||||
func (c *coordinator) receive_speech(a *connectionAttempt, stream *speechStream, message message) (bool, error) {
|
||||
if message.kind != "speak" && message.kind != "cancel" && message.kind != "pause_speech" {
|
||||
return false, nil
|
||||
}
|
||||
if stream.role != "controller" || !slices.Contains(stream.grants, "remote-present") {
|
||||
return false, nil
|
||||
}
|
||||
frames, err := reader_speech(message)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
items := make([]speechItem, len(frames))
|
||||
bytes := 0
|
||||
for index, speech := range frames {
|
||||
data, err := json.Marshal(speech)
|
||||
if err != nil {
|
||||
return true, errProtocol
|
||||
}
|
||||
items[index] = speechItem{speech: speech, bytes: len(data), batch: len(frames) > 1, first: index == 0, final: index == len(frames)-1}
|
||||
bytes += len(data)
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !c.speech_ready_locked(a, stream) {
|
||||
return true, errLease
|
||||
}
|
||||
if stream.items+len(items) > maxSpeechItems || stream.bytes+bytes > maxQueuedBytes {
|
||||
return true, errLimit
|
||||
}
|
||||
stream.items += len(items)
|
||||
stream.bytes += bytes
|
||||
for _, item := range items {
|
||||
stream.incoming <- item
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (c *coordinator) speech_release(stream *speechStream, bytes int) {
|
||||
c.mu.Lock()
|
||||
stream.items--
|
||||
stream.bytes -= bytes
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// All heartbeat/present calls share this owner, including during dial/join.
|
||||
// Check a due heartbeat before every effect so a busy speech queue cannot
|
||||
// indefinitely postpone lease liveness. Calls retain their independent SDK
|
||||
// deadline: disconnect must not cancel a healthy process session.
|
||||
func (c *coordinator) speech_operations(a *connectionAttempt, stream *speechStream) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
var utterance uint64
|
||||
heartbeat := func() bool {
|
||||
if a.ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
stream.sequence++
|
||||
err := c.call("remote.heartbeat", sdk.RemoteOperation{Lease: stream.lease.Lease, Epoch: a.epoch, Sequence: stream.sequence}, nil)
|
||||
if err != nil {
|
||||
c.mu.Lock()
|
||||
c.stop_locked(errLease)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
return err == nil
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-a.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if !heartbeat() {
|
||||
return
|
||||
}
|
||||
case item := <-stream.incoming:
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if !heartbeat() {
|
||||
c.speech_release(stream, item.bytes)
|
||||
return
|
||||
}
|
||||
default:
|
||||
}
|
||||
c.mu.Lock()
|
||||
ready := c.speech_ready_locked(a, stream)
|
||||
c.mu.Unlock()
|
||||
if !ready {
|
||||
c.speech_release(stream, item.bytes)
|
||||
return
|
||||
}
|
||||
stream.sequence++
|
||||
request := sdk.RemotePresentation{RemoteOperation: sdk.RemoteOperation{Lease: stream.lease.Lease, Epoch: a.epoch, Sequence: stream.sequence}, Speech: item.speech}
|
||||
if item.batch {
|
||||
if item.first {
|
||||
utterance = stream.sequence
|
||||
}
|
||||
request.Utterance, request.Final = utterance, item.final
|
||||
}
|
||||
err := c.call("remote.present", request, nil)
|
||||
c.speech_release(stream, item.bytes)
|
||||
if err != nil {
|
||||
c.mu.Lock()
|
||||
c.stop_locked(errLease)
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *coordinator) speech_output(a *connectionAttempt, stream *speechStream, conn *relayConn) {
|
||||
for {
|
||||
select {
|
||||
case <-a.ctx.Done():
|
||||
return
|
||||
case frame := <-stream.outgoing:
|
||||
c.mu.Lock()
|
||||
ready := c.speech_ready_locked(a, stream)
|
||||
c.mu.Unlock()
|
||||
if !ready {
|
||||
c.speech_release(stream, len(frame))
|
||||
return
|
||||
}
|
||||
err := conn.write(a.ctx, frame)
|
||||
c.speech_release(stream, len(frame))
|
||||
if err != nil {
|
||||
c.mu.Lock()
|
||||
c.stop_locked(err)
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
func TestCoordinatorIncomingSpeechOrderAndSequence(t *testing.T) {
|
||||
c, client := fixtureCoordinator(t, nil)
|
||||
action := approve(t, c, client, 1, "controller")
|
||||
text := " " + strings.Repeat("é\x00", 3000) + " "
|
||||
speak, _ := json.Marshal(map[string]any{"type": "speak", "origin": 7, "priority": 2, "sequence": []any{
|
||||
[]any{"CharacterModeCommand", map[string]any{"state": true}},
|
||||
[]any{"LangChangeCommand", map[string]any{"lang": "fr"}}, text,
|
||||
[]any{"EndUtteranceCommand", map[string]any{}},
|
||||
}})
|
||||
decoded, err := decodeMessage(speak)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected, err := reader_speech(decoded)
|
||||
if err != nil || len(expected) < 2 {
|
||||
t.Fatal("fixture must split", err)
|
||||
}
|
||||
fragments := len(expected)
|
||||
paused := true
|
||||
expected = append(expected, sdk.RemoteSpeech{Kind: "cancel"}, sdk.RemoteSpeech{Kind: "pause", Paused: &paused})
|
||||
cert, roots := testCertificate(t, true)
|
||||
target := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"slave"}]}`+"\n")
|
||||
_, _ = conn.Write(append(speak, '\n'))
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"cancel\",\"origin\":7}\n{\"type\":\"pause_speech\",\"origin\":7,\"switch\":true}\n")
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
})
|
||||
target.roots = roots
|
||||
if err := c.connect(action, target, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, client, "remote.open")
|
||||
for index, speech := range expected {
|
||||
request := nextCall(t, client, "remote.present").params.(sdk.RemotePresentation)
|
||||
if request.Lease != strings.Repeat("b", 32) || request.Epoch != 1 || request.Sequence != uint64(index+1) || !reflect.DeepEqual(request.Speech, speech) {
|
||||
t.Fatal("speech changed or reordered")
|
||||
}
|
||||
if index < fragments {
|
||||
if request.Utterance != 1 || request.Final != (index == fragments-1) {
|
||||
t.Fatal("split speech lacked a single assembly/final marker")
|
||||
}
|
||||
} else if request.Utterance != 0 || request.Final {
|
||||
t.Fatal("cancel/pause joined the preceding utterance")
|
||||
}
|
||||
}
|
||||
heartbeat := nextCall(t, client, "remote.heartbeat").params.(sdk.RemoteOperation)
|
||||
if heartbeat.Sequence != uint64(len(expected)+1) {
|
||||
t.Fatal("heartbeat sequence interleaved incorrectly")
|
||||
}
|
||||
awaitDone(t, c.disconnect())
|
||||
closed := nextCall(t, client, "remote.close").params.(sdk.RemoteOperation)
|
||||
if closed.Sequence != heartbeat.Sequence+1 {
|
||||
t.Fatal("close sequence did not follow presentation/heartbeat")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorRevocationDuringPresentation(t *testing.T) {
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
c, client := fixtureCoordinator(t, func(ctx context.Context, method string, params, result any) error {
|
||||
if method == "remote.open" {
|
||||
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
|
||||
}
|
||||
if method == "remote.present" {
|
||||
close(started)
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
t.Error("revoke cancelled healthy SDK call")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
t.Cleanup(func() { once.Do(func() { close(release) }) })
|
||||
action := approve(t, c, client, 1, "controller")
|
||||
cert, roots := testCertificate(t, true)
|
||||
closed := make(chan struct{})
|
||||
target := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[{\"id\":7,\"connection_type\":\"slave\"}]}\n{\"type\":\"speak\",\"origin\":7,\"sequence\":[\"first\"]}\n{\"type\":\"cancel\",\"origin\":7}\n")
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
close(closed)
|
||||
})
|
||||
target.roots = roots
|
||||
if err := c.connect(action, target, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, client, "remote.open")
|
||||
awaitDone(t, started)
|
||||
nextCall(t, client, "remote.present")
|
||||
client.events <- sdk.SessionEvent{Kind: "remote.revoked", Epoch: 1}
|
||||
awaitDone(t, closed)
|
||||
once.Do(func() { close(release) })
|
||||
closeRequest := nextCall(t, client, "remote.close").params.(sdk.RemoteOperation)
|
||||
if closeRequest.Sequence != 2 {
|
||||
t.Fatal("revocation delivered queued speech or raced final close")
|
||||
}
|
||||
awaitStatus(t, c, func(status connectionStatus) bool { return status.state == "failed" })
|
||||
}
|
||||
|
||||
func TestCoordinatorUnavailableSpeechOwnerClosesLease(t *testing.T) {
|
||||
c, client := fixtureCoordinator(t, func(_ context.Context, method string, params, result any) error {
|
||||
if method == "remote.open" {
|
||||
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
|
||||
}
|
||||
if method == "remote.present" {
|
||||
return &sdk.SessionError{Code: -32601, Message: "private host diagnostic"}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
action := approve(t, c, client, 1, "controller")
|
||||
cert, roots := testCertificate(t, true)
|
||||
target := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[{\"id\":7,\"connection_type\":\"slave\"}]}\n{\"type\":\"cancel\",\"origin\":7}\n")
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
})
|
||||
target.roots = roots
|
||||
if err := c.connect(action, target, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, client, "remote.open")
|
||||
nextCall(t, client, "remote.present")
|
||||
nextCall(t, client, "remote.close")
|
||||
status := awaitStatus(t, c, func(status connectionStatus) bool { return status.state == "failed" })
|
||||
if status.err != errLease {
|
||||
t.Fatal("unavailable speech owner did not fail closed with a constant error")
|
||||
}
|
||||
}
|
||||
|
||||
type speechWriteProbe struct {
|
||||
net.Conn
|
||||
started chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (conn *speechWriteProbe) Write(data []byte) (int, error) {
|
||||
conn.once.Do(func() { close(conn.started) })
|
||||
return conn.Conn.Write(data)
|
||||
}
|
||||
|
||||
func TestSpeechStreamRevocationWhileRelayWriteStalls(t *testing.T) {
|
||||
client := &fixtureClient{events: make(chan sdk.SessionEvent, 8)}
|
||||
c := newCoordinator(t.Context(), client)
|
||||
ctx, cancel := context.WithCancel(c.ctx)
|
||||
stream := newSpeechStream(sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}, sdk.SessionEvent{Role: "controlled", Grants: []string{"output-observe"}})
|
||||
a := &connectionAttempt{ctx: ctx, cancel: cancel, epoch: 1, speech: stream}
|
||||
c.mu.Lock()
|
||||
c.active, c.status = a, connectionStatus{state: "ready", peer: 7}
|
||||
c.mu.Unlock()
|
||||
writer, reader := net.Pipe()
|
||||
probe := &speechWriteProbe{Conn: writer, started: make(chan struct{})}
|
||||
conn := newRelayConn(ctx, probe)
|
||||
workerDone := make(chan struct{})
|
||||
go func() { defer close(workerDone); c.speech_output(a, stream, conn) }()
|
||||
t.Cleanup(func() {
|
||||
c.close()
|
||||
conn.close()
|
||||
reader.Close()
|
||||
awaitDone(t, workerDone)
|
||||
awaitDone(t, c.done)
|
||||
})
|
||||
event := sdk.SessionEvent{Kind: "remote.output", Lease: stream.lease.Lease, Epoch: 1, Speech: &sdk.RemoteSpeech{Kind: "cancel"}}
|
||||
client.events <- event
|
||||
awaitDone(t, probe.started)
|
||||
// The write cannot complete: no one reads the other end of net.Pipe.
|
||||
client.events <- event
|
||||
client.events <- sdk.SessionEvent{Kind: "remote.revoked", Epoch: 1}
|
||||
awaitDone(t, workerDone)
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if a.ctx.Err() == nil || stream.items != 0 || stream.bytes != 0 || c.status.peer != 0 || a.err != errLease {
|
||||
t.Fatal("blocked relay prevented revoke/queue cleanup")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorObservedSpeechToRelay(t *testing.T) {
|
||||
c, client := fixtureCoordinator(t, nil)
|
||||
action := approve(t, c, client, 3, "controlled")
|
||||
cert, roots := testCertificate(t, true)
|
||||
joinPeer := make(chan struct{})
|
||||
var once sync.Once
|
||||
t.Cleanup(func() { once.Do(func() { close(joinPeer) }) })
|
||||
received := make(chan message, 4)
|
||||
target := testRelay(t, cert, func(conn net.Conn) {
|
||||
reader := relayHandshake(t, conn, controlled)
|
||||
if reader == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
<-joinPeer
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"client_joined\",\"client\":{\"id\":7,\"connection_type\":\"master\"}}\n")
|
||||
for {
|
||||
frame, err := readFrame(reader)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m, err := decodeMessage(frame)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
received <- m
|
||||
}
|
||||
})
|
||||
target.roots = roots
|
||||
if err := c.connect(action, target, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, client, "remote.open")
|
||||
awaitStatus(t, c, func(status connectionStatus) bool { return status.state == "waiting" })
|
||||
// Exercise pre-peer rejection synchronously to establish the ordering.
|
||||
event := sdk.SessionEvent{Kind: "remote.output", Lease: strings.Repeat("b", 32), Epoch: 3, Speech: &sdk.RemoteSpeech{Kind: "speak", Parts: []sdk.RemoteSpeechPart{{Text: "old"}}}}
|
||||
c.mu.Lock()
|
||||
c.observe_locked(event)
|
||||
if c.active.speech.items != 0 {
|
||||
t.Error("retained pre-peer output")
|
||||
}
|
||||
c.mu.Unlock()
|
||||
once.Do(func() { close(joinPeer) })
|
||||
awaitStatus(t, c, func(status connectionStatus) bool { return status.state == "ready" })
|
||||
stale := event
|
||||
stale.Epoch--
|
||||
client.events <- stale
|
||||
stale = event
|
||||
stale.Lease = strings.Repeat("c", 32)
|
||||
client.events <- stale
|
||||
paused := false
|
||||
for _, speech := range []sdk.RemoteSpeech{
|
||||
{Kind: "speak", Priority: 1, Parts: []sdk.RemoteSpeechPart{{Text: " bonjour ", Characters: true, Language: "fr"}, {End: true}}},
|
||||
{Kind: "cancel"}, {Kind: "pause", Paused: &paused},
|
||||
} {
|
||||
copy := speech
|
||||
event.Speech = ©
|
||||
client.events <- event
|
||||
}
|
||||
for _, kind := range []string{"speak", "cancel", "pause_speech"} {
|
||||
select {
|
||||
case actual := <-received:
|
||||
if actual.kind != kind || actual.origin != 0 {
|
||||
t.Fatal("stale output, reordered output or forged origin")
|
||||
}
|
||||
if kind == "speak" {
|
||||
converted, err := reader_speech(actual)
|
||||
if err != nil || len(converted) != 1 || converted[0].Priority != 1 || converted[0].Parts[0].Text != " bonjour " || !converted[0].Parts[0].Characters || converted[0].Parts[0].Language != "fr" {
|
||||
t.Fatal("observed speech lost semantics")
|
||||
}
|
||||
}
|
||||
case <-time.After(4 * time.Second):
|
||||
t.Fatal("missing observed speech")
|
||||
}
|
||||
}
|
||||
awaitDone(t, c.disconnect())
|
||||
nextCall(t, client, "remote.close")
|
||||
}
|
||||
|
||||
// An inert stream lets admission bounds and cleanup be checked without timing
|
||||
// a network buffer. No workers consume its queues.
|
||||
func inertSpeechStream(t *testing.T, role string, grants []string) (*coordinator, *connectionAttempt, *speechStream) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
t.Cleanup(cancel)
|
||||
stream := newSpeechStream(sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}, sdk.SessionEvent{Role: role, Grants: grants})
|
||||
a := &connectionAttempt{ctx: ctx, cancel: cancel, epoch: 1, speech: stream}
|
||||
c := &coordinator{active: a, status: connectionStatus{state: "ready", peer: 7}}
|
||||
return c, a, stream
|
||||
}
|
||||
|
||||
func TestSpeechStreamAdmissionBoundsAndGrants(t *testing.T) {
|
||||
for _, direction := range []string{"incoming", "outgoing"} {
|
||||
for _, limit := range []string{"items", "bytes"} {
|
||||
t.Run(direction+"-"+limit, func(t *testing.T) {
|
||||
role, grants := "controller", []string{"remote-present"}
|
||||
if direction == "outgoing" {
|
||||
role, grants = "controlled", []string{"output-observe"}
|
||||
}
|
||||
c, a, stream := inertSpeechStream(t, role, grants)
|
||||
text := "text"
|
||||
if limit == "bytes" {
|
||||
text = strings.Repeat("a", 5800)
|
||||
}
|
||||
m := message{kind: "speak", payload: speech{parts: []speechPart{{kind: "text", text: text}}}}
|
||||
value := sdk.RemoteSpeech{Kind: "speak", Parts: []sdk.RemoteSpeechPart{{Text: text}}}
|
||||
for a.ctx.Err() == nil {
|
||||
if direction == "incoming" {
|
||||
_, err := c.receive_speech(a, stream, m)
|
||||
if err != nil {
|
||||
if err != errLimit {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.stop_locked(err)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
} else {
|
||||
c.mu.Lock()
|
||||
c.observe_locked(sdk.SessionEvent{Kind: "remote.output", Lease: stream.lease.Lease, Epoch: 1, Speech: &value})
|
||||
c.mu.Unlock()
|
||||
}
|
||||
if stream.items > maxSpeechItems || stream.bytes > maxQueuedBytes {
|
||||
t.Fatal("queue exceeded its bounds")
|
||||
}
|
||||
}
|
||||
if stream.items != 0 || stream.bytes != 0 || len(stream.incoming) != 0 || len(stream.outgoing) != 0 || a.err != errLimit {
|
||||
t.Fatal("overflow did not clear queues")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
c, a, stream := inertSpeechStream(t, "controller", nil)
|
||||
handled, err := c.receive_speech(a, stream, message{kind: "cancel"})
|
||||
if handled || err != nil || stream.items != 0 {
|
||||
t.Fatal("missing grant admitted speech")
|
||||
}
|
||||
// An utterance too large for the whole bounded queue admits no prefix.
|
||||
stream.grants = []string{"remote-present"}
|
||||
_, err = c.receive_speech(a, stream, message{kind: "speak", payload: speech{parts: []speechPart{{kind: "text", text: strings.Repeat("\x00", 50000)}}}})
|
||||
if err != errLimit || stream.items != 0 || len(stream.incoming) != 0 {
|
||||
t.Fatal("oversized utterance admitted a prefix")
|
||||
}
|
||||
for _, role := range []string{"controlled", "controller"} {
|
||||
c, _, stream := inertSpeechStream(t, role, nil)
|
||||
c.observe_locked(sdk.SessionEvent{Kind: "remote.output", Lease: stream.lease.Lease, Epoch: 1, Speech: &sdk.RemoteSpeech{Kind: "cancel"}})
|
||||
if stream.items != 0 {
|
||||
t.Fatal("wrong role or missing output-observe admitted output")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user