aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/world_runtime.go (8288B)


      1 package main
      2 
      3 import (
      4 	"fmt"
      5 	"net"
      6 	"slices"
      7 )
      8 
      9 // The directory owns routing and detached metadata. Entity state belongs to a
     10 // zone; an arrival barrier keeps reconnects behind an in-flight ownership move.
     11 type worldRuntime struct {
     12 	browserVisitors *browserVisitors
     13 
     14 	snapshots           chan chan worldSnapshot
     15 	environment         chan worldEnvironmentUpdate
     16 	operations          chan worldOperation
     17 	playerCreations     chan playerCreation
     18 	admissions          chan worldLookup
     19 	lookups             chan worldLookup
     20 	transfers           chan worldTransfer
     21 	ownership           chan worldOwnership
     22 	messages            chan worldMessage
     23 	presence            chan presenceUpdate
     24 	people              chan presenceQuery
     25 	missionLookups      chan missionLookup
     26 	missionChanges      chan missionChange
     27 	missionCreations    chan missionCreation
     28 	missionOperations   chan missionOperation
     29 	missionParticipants chan missionParticipantsQuery
     30 	stopping            chan struct{}
     31 	done                chan struct{}
     32 	stopError           error
     33 }
     34 
     35 type worldRoute struct {
     36 	zone  *zoneRuntime
     37 	ready chan struct{}
     38 	err   error // Written before ready closes.
     39 }
     40 
     41 type worldLookup struct {
     42 	player uint32
     43 	reply  chan *worldRoute
     44 }
     45 
     46 type worldTransfer struct {
     47 	source  *zoneRuntime
     48 	arrival playerTransfer
     49 	reply   chan error
     50 }
     51 
     52 func newWorldRuntime(configuration *server, states map[uint32]*server) (*worldRuntime, error) {
     53 	// Validate the complete initial ownership graph before starting any workers.
     54 	owners := make(map[uint32]uint32)
     55 	if configuration.populationDormant() {
     56 		for id, playfield := range configuration.npcOwners {
     57 			owners[id] = playfield
     58 		}
     59 	}
     60 	presence := make(map[uint32]playerPresence)
     61 	teams := make(map[uint32]*playerTeam)
     62 	chatPeople := make(map[uint32]*chatPerson)
     63 	for playfield, state := range states {
     64 		for id, person := range state.chatPeople() {
     65 			chatPeople[id] = person
     66 		}
     67 		for id, character := range state.characters {
     68 			if character.playfield != playfield {
     69 				return nil, fmt.Errorf("character %d belongs to playfield %d, not %d", id, character.playfield, playfield)
     70 			}
     71 			if previous, exists := owners[id]; exists && previous != playfield {
     72 				return nil, fmt.Errorf("character %d has multiple zone owners", id)
     73 			}
     74 			owners[id] = playfield
     75 			if !character.npc {
     76 				if character.team != nil {
     77 					team := *character.team
     78 					team.members = slices.Clone(team.members)
     79 					teams[team.id] = &team
     80 				}
     81 				presence[id] = playerPresence{id: id, name: character.name, side: character.appearance >> 9 & 3,
     82 					combat: state.characterInCombat(character)}
     83 			}
     84 		}
     85 	}
     86 	world := &worldRuntime{browserVisitors: configuration.browserVisitors, snapshots: make(chan chan worldSnapshot), environment: make(chan worldEnvironmentUpdate), operations: make(chan worldOperation), playerCreations: make(chan playerCreation), admissions: make(chan worldLookup), lookups: make(chan worldLookup), transfers: make(chan worldTransfer),
     87 		ownership: make(chan worldOwnership), messages: make(chan worldMessage),
     88 		presence: make(chan presenceUpdate), people: make(chan presenceQuery),
     89 		stopping: make(chan struct{}), done: make(chan struct{}),
     90 		missionLookups: make(chan missionLookup), missionChanges: make(chan missionChange), missionCreations: make(chan missionCreation),
     91 		missionOperations: make(chan missionOperation), missionParticipants: make(chan missionParticipantsQuery)}
     92 	missions := newMissionCatalog(configuration.missionExpiry)
     93 	if configuration.chatService == nil {
     94 		var err error
     95 		configuration.chatService, err = newChatRuntime(configuration.db, configuration.databaseWriter, chatPeople)
     96 		if err != nil {
     97 			return nil, err
     98 		}
     99 	}
    100 	if configuration.teamService == nil {
    101 		configuration.teamService = newTeamDirectory(configuration.databaseWriter, teams)
    102 	}
    103 	services := configuration.services()
    104 	coordinator := &worldCoordinator{worldServices: services, browserCreations: configuration.browserCreations}
    105 	configuration.browserCreations = nil
    106 	environment := worldEnvironment{configuration.gameSeconds, configuration.clockStarted, configuration.weather, configuration.weatherUntil}
    107 	zones := make(map[uint32]*zoneRuntime)
    108 	for playfield, state := range states {
    109 		state.world, state.playfield, state.identities = world, playfield, configuration.identities
    110 		state.teamService, state.chatService = configuration.teamService, configuration.chatService
    111 		zones[playfield] = newZoneRuntime(state)
    112 	}
    113 	ready := make(chan struct{})
    114 	close(ready)
    115 	routes := make(map[uint32]*worldRoute)
    116 	for player, playfield := range owners {
    117 		routes[player] = &worldRoute{zone: zones[playfield], ready: ready}
    118 	}
    119 	directory := &worldDirectory{world: world, services: services, environment: environment, coordinator: coordinator,
    120 		zones: zones, routes: routes, presence: presence, missions: missions, stopping: world.stopping,
    121 		arrived: make(chan struct{}), quiesced: make(chan struct{})}
    122 	go directory.run()
    123 	return world, nil
    124 }
    125 
    126 func (world *worldRuntime) lookup(player uint32) (*worldRoute, error) {
    127 	return world.lookupOn(world.lookups, player)
    128 }
    129 
    130 func (world *worldRuntime) lookupOn(requests chan worldLookup, player uint32) (*worldRoute, error) {
    131 	for {
    132 		lookup := worldLookup{player: player, reply: make(chan *worldRoute, 1)}
    133 		select {
    134 		case requests <- lookup:
    135 		case <-world.done:
    136 			return nil, net.ErrClosed
    137 		}
    138 		route := <-lookup.reply
    139 		if route == nil {
    140 			return nil, nil
    141 		}
    142 		<-route.ready
    143 		if route.err == errZoneOwnerChanged {
    144 			continue
    145 		}
    146 		return route, route.err
    147 	}
    148 }
    149 
    150 func (world *worldRuntime) owner(player uint32) (*zoneRuntime, error) {
    151 	route, err := world.lookup(player)
    152 	if err != nil {
    153 		return nil, err
    154 	}
    155 	if route == nil {
    156 		return nil, fmt.Errorf("unknown world character %d", player)
    157 	}
    158 	return route.zone, nil
    159 }
    160 
    161 func (world *worldRuntime) transfer(source *zoneRuntime, arrival playerTransfer) error {
    162 	request := worldTransfer{source: source, arrival: arrival, reply: make(chan error, 1)}
    163 	select {
    164 	case world.transfers <- request:
    165 		return <-request.reply
    166 	case <-world.done:
    167 		return net.ErrClosed
    168 	}
    169 }
    170 
    171 func (world *worldRuntime) stop() error {
    172 	close(world.stopping)
    173 	<-world.done
    174 	return world.stopError
    175 }
    176 
    177 // Each connection keeps its admitted owner, even after the directory changes.
    178 type routedWorldSession struct {
    179 	world *worldRuntime
    180 	zone  *zoneRuntime
    181 }
    182 
    183 func (session *routedWorldSession) joinWorldClient(client *worldClient, player uint32) error {
    184 	// Native authentication has validated the requested ID before admission.
    185 	if client.browserTokenHash != "" && session.world.browserVisitors.lookup(client.browserTokenHash) != 0 {
    186 		if err := session.world.operate(func(coordinator *worldCoordinator) error {
    187 			if coordinator.browserVisitors.lookup(client.browserTokenHash) != player {
    188 				return nil
    189 			}
    190 			if !coordinator.playerLimit.admit(client) {
    191 				return fmt.Errorf("Server full. Please try again later.")
    192 			}
    193 			visitor, err := coordinator.completeBrowserLaunch(player, client.browserTokenHash, client.conn.RemoteAddr().String())
    194 			if err != nil || visitor == nil {
    195 				coordinator.playerLimit.release(client)
    196 				return err
    197 			}
    198 			err = session.world.createPlayer(visitor)
    199 			if err != nil {
    200 				coordinator.playerLimit.release(client)
    201 			}
    202 			return err
    203 		}); err != nil {
    204 			return err
    205 		}
    206 	}
    207 	for {
    208 		route, err := session.world.lookupOn(session.world.admissions, player)
    209 		if err != nil {
    210 			return err
    211 		}
    212 		if route == nil {
    213 			return fmt.Errorf("unknown world character %d", player)
    214 		}
    215 		zone := route.zone
    216 		// A departure can finish between directory lookup and command admission.
    217 		// Only this pre-admission rejection is retryable; an admitted session stays.
    218 		err = zone.joinWorldClient(client, player)
    219 		if err == errZoneOwnerChanged {
    220 			continue
    221 		}
    222 		session.zone = zone
    223 		return err
    224 	}
    225 }
    226 
    227 func (session *routedWorldSession) leaveWorldClient(client *worldClient) {
    228 	if session.zone != nil {
    229 		session.zone.leaveWorldClient(client)
    230 	}
    231 }
    232 
    233 func (session *routedWorldSession) handleWorldMessage(client *worldClient, body []byte) error {
    234 	return session.zone.handleWorldMessage(client, body)
    235 }
    236 
    237 func (session *routedWorldSession) sendVicinity(client *worldClient, kind uint32, message string, metadata []byte) {
    238 	session.zone.sendVicinity(client, kind, message, metadata)
    239 }