server/browser_stream_registry.go (2759B)
1 package main 2 3 import "net" 4 5 // This owner contains transport identities only. Commands never acquire 6 // simulation ownership or wait for a stream's network close handshake. 7 type browserStreamRegistry struct { 8 commands chan browserStreamCommand 9 stopping chan struct{} 10 done chan struct{} 11 } 12 13 type browserStreamCommand struct { 14 run func(map[string]*browserStream) 15 done chan struct{} 16 } 17 18 func (server *server) browserStreams() *browserStreamRegistry { 19 server.browserStreamsOnce.Do(func() { 20 registry := &browserStreamRegistry{commands: make(chan browserStreamCommand), stopping: make(chan struct{}), done: make(chan struct{})} 21 server.browserStreamService = registry 22 go func() { 23 defer close(registry.done) 24 streams := make(map[string]*browserStream) 25 for { 26 select { 27 case command := <-registry.commands: 28 command.run(streams) 29 close(command.done) 30 case <-registry.stopping: 31 return 32 } 33 } 34 }() 35 }) 36 return server.browserStreamService 37 } 38 39 func (registry *browserStreamRegistry) call(run func(map[string]*browserStream)) error { 40 command := browserStreamCommand{run: run, done: make(chan struct{})} 41 select { 42 case registry.commands <- command: 43 <-command.done 44 return nil 45 case <-registry.done: 46 return net.ErrClosed 47 } 48 } 49 50 // Producers and stream cleanup finish before the registry stops. 51 func (registry *browserStreamRegistry) stop() { 52 select { 53 case registry.stopping <- struct{}{}: 54 case <-registry.done: 55 } 56 <-registry.done 57 } 58 59 func (server *server) replaceBrowserStreams(players ...uint32) { 60 server.browserStreams().call(func(streams map[string]*browserStream) { 61 for _, stream := range streams { 62 for _, player := range players { 63 if stream.character == player { 64 stream.stop(browserSessionReplaced) 65 break 66 } 67 } 68 } 69 }) 70 } 71 72 func (stream *browserStream) remove() { 73 stream.server.browserStreams().call(func(streams map[string]*browserStream) { 74 if streams[stream.id] == stream { 75 delete(streams, stream.id) 76 } 77 }) 78 } 79 80 // Query the current simulation owner only when an absent stream needs a precise 81 // reconnect refusal. Normal transport admission does not depend on this query. 82 func (server *server) browserSessionConnected(player uint32, chat bool) (bool, error) { 83 if chat { 84 query := &chatConnectionQuery{player: player} 85 err := server.chatService.call(query) 86 return query.connected, err 87 } 88 zone, err := server.world.owner(player) 89 if err != nil { 90 return false, err 91 } 92 query := &zoneConnectionQuery{player: player} 93 err = zone.call(query) 94 return query.connected, err 95 } 96 97 type zoneConnectionQuery struct { 98 player uint32 99 connected bool 100 } 101 102 func (query *zoneConnectionQuery) execute(state *server) error { 103 query.connected = state.clients[query.player] != nil 104 return nil 105 }