mirror of
https://github.com/cirruslabs/orchard.git
synced 2026-10-17 12:15:37 +02:00
Refactorings for simplify readability (#35)
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/cirruslabs/orchard/internal/concurrentmap"
|
||||
"net"
|
||||
)
|
||||
|
||||
var ErrInvalidToken = errors.New("invalid proxy token")
|
||||
|
||||
type Proxy struct {
|
||||
sessions *concurrentmap.ConcurrentMap[*TokenSlot]
|
||||
}
|
||||
|
||||
type TokenSlot struct {
|
||||
ctx context.Context
|
||||
ch chan net.Conn
|
||||
}
|
||||
|
||||
func NewProxy() *Proxy {
|
||||
return &Proxy{
|
||||
sessions: concurrentmap.NewConcurrentMap[*TokenSlot](),
|
||||
}
|
||||
}
|
||||
|
||||
func (proxy *Proxy) Request(ctx context.Context, session string) (chan net.Conn, func()) {
|
||||
tokenSlot := &TokenSlot{
|
||||
ctx: ctx,
|
||||
ch: make(chan net.Conn),
|
||||
}
|
||||
|
||||
proxy.sessions.Store(session, tokenSlot)
|
||||
|
||||
return tokenSlot.ch, func() {
|
||||
proxy.sessions.Delete(session)
|
||||
}
|
||||
}
|
||||
|
||||
func (proxy *Proxy) Respond(session string, conn net.Conn) (context.Context, error) {
|
||||
tokenSlot, ok := proxy.sessions.Load(session)
|
||||
if !ok {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
tokenSlot.ch <- conn
|
||||
|
||||
return tokenSlot.ctx, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package proxy_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/cirruslabs/orchard/internal/controller/proxy"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestProxy(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
expectedConn, _ := net.Pipe()
|
||||
|
||||
proxy := proxy.NewProxy()
|
||||
|
||||
token := uuid.New().String()
|
||||
|
||||
connCh, cancel := proxy.Request(ctx, token)
|
||||
defer cancel()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
_, err := proxy.Respond(token, expectedConn)
|
||||
require.NoError(t, err)
|
||||
|
||||
wg.Done()
|
||||
}()
|
||||
|
||||
actualConn := <-connCh
|
||||
require.Equal(t, expectedConn, actualConn)
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
Reference in New Issue
Block a user