nmdc-telegramfrontend/upstreamWorker.go

45 lines
980 B
Go

package main
import (
"context"
"code.ivysaur.me/libnmdc"
)
// upstreamWorker handles an NMDC connection.
// It blocks on the current thread, caller can background it with 'go'.
func upstreamWorker(ctx context.Context, hubAddress, username string, responseChan chan<- libnmdc.HubEvent) {
interiorChan := make(chan libnmdc.HubEvent, 0)
conn := libnmdc.ConnectAsync(
&libnmdc.HubConnectionOptions{
Address: libnmdc.HubAddress(hubAddress),
Self: &libnmdc.UserInfo{
Nick: username,
ClientTag: AppName,
ClientVersion: AppVersion,
},
},
interiorChan,
)
for {
select {
case <-ctx.Done():
conn.Disconnect()
ctx = nil // prevent hitting this case again repeatedly - closed channel reads immediately, nil channel blocks forever
case evt := <-interiorChan:
responseChan <- evt // forward
if evt.StateChange == libnmdc.CONNECTIONSTATE_DISCONNECTED && ctx.Err() != nil {
// We're done here
return
}
}
}
}