Private
Public Access
1
0

chg: dev: replace the legacy gos/web-socket-bundle & replace it with Mercure protocol #4

This commit is contained in:
2026-04-09 22:00:53 +02:00
parent b55c223d8a
commit 7219471a86
33 changed files with 1198 additions and 2324 deletions

View File

@@ -6,7 +6,6 @@ ReactDOM.render(
<MineSeeker
env={document.getElementById("mine-wrapper").dataset.env}
gameId={document.getElementById("mine-wrapper").dataset.gameId}
ssl={document.getElementById("mine-wrapper").dataset.ssl}
/>,
document.getElementById("mine-wrapper"),
);

View File

@@ -11,16 +11,22 @@ class MineSeeker extends React.Component {
this.state = {
env: props.env,
ssl: props.ssl,
gameInherited: '' !== props.gameId,
gameAssoc: gameAssoc,
channel: channel,
session: null,
createGrid: false,
stepCache: [],
connectionLost: false,
end: false,
};
/** SSE connection (not React state — no re-render needed) */
this.eventSource = null;
/**
* Users from GET /api/game/connect (inherited game).
* Passed to wSubscribe so it can determine the local player's colour.
*/
this.rpcUsers = null;
}
currectGridSize() {
@@ -37,9 +43,6 @@ class MineSeeker extends React.Component {
/**
* STEP
*
* @param coords
* @returns {{red: *, blue: *}}
*/
makePointsCalcAndStep(coords) {
let users = this.refs.gridControl.refs.userControl,
@@ -63,14 +66,10 @@ class MineSeeker extends React.Component {
/**
* START
*
* @param payload
*/
makeGameStart(payload) {
/** every time the blue starts */
this.refs.gridControl.refs.userControl.setState({ activePlayer: 1 });
/** Set up player names w/ server data */
this.refs.gridControl.refs.userControl.refs.red.setState({
name: '' !== payload.users.red ? payload.users.red : payload.users.redAnon,
});
@@ -88,10 +87,6 @@ class MineSeeker extends React.Component {
/**
* THE END
*
* @param bluePoints
* @param redPoints
* @param resign
*/
makeGameEndIfItEnds(bluePoints, redPoints, resign = false) {
let redWins = 25 < redPoints,
@@ -109,7 +104,6 @@ class MineSeeker extends React.Component {
}
this.refs.gridControl.showLeftMines();
this.refs.gridControl.refs.userControl.setState({ activePlayer: false });
this.refs.gridControl.refs.userControl.refs.red.setState({ desc: '' });
this.refs.gridControl.refs.userControl.refs.blue.setState({ desc: '' });
@@ -128,25 +122,19 @@ class MineSeeker extends React.Component {
});
this.setState({ end: true });
this.makeGameEndIfItEnds(0, 0, true);
}
clickResign() {
/** PUBLISH */
this.state.session.publish(this.state.channel, {
'resign': this.refs.gridControl.refs.userControl.state.activePlayer ? 'blue' : 'red',
});
let resignColor = this.refs.gridControl.refs.userControl.state.activePlayer ? 'blue' : 'red';
this.publishStep({ resign: resignColor });
this.resignProcess(this.refs.gridControl.state.webPlayer);
}
clickResignCancel() {
this.refs.gridControl.setState({
overlay: false,
});
this.refs.gridControl.setState({ overlay: false });
}
/** RESIGN */
resign() {
let users = this.refs.gridControl.refs.userControl,
activePlayer = users.state.activePlayer ? 'blue' : 'red';
@@ -165,11 +153,133 @@ class MineSeeker extends React.Component {
}
}
wInit(session, gridServer, gridClient) {
this.setState({ session: session });
// ------------------------------------------------------------------ //
// Mercure message handlers (same logic as former WAMP callbacks)
// ------------------------------------------------------------------ //
/** save session to GridControl */
/** render grid fields - @see #12 */
wSubscribe(payload, rpcUsers = null) {
'dev' === this.state.env && console.info(
('undefined' !== typeof payload.user ? payload.user : 'user') + ' has been subscribed to the channel!',
);
let firstUser = !rpcUsers;
null === this.refs.gridControl.state.webPlayer && this.refs.gridControl.setState({
webPlayer: payload.user === payload.users.blue
|| (
firstUser && '' !== payload.users.blueAnon
|| !firstUser && ('' === rpcUsers.blueAnon && '' === rpcUsers.blue)
)
? 'blue' : 'red',
});
(900 > $(document).width()) && this.currectGridSize();
if (
2 === payload.userCnt
&& (
!this.state.connectionLost
|| this.state.connectionLost && false === this.refs.gridControl.refs.userControl.state.activePlayer && !this.state.end
)
) {
this.makeGameStart(payload);
}
}
wUnsubscribe(payload) {
'dev' === this.state.env && console.info(payload.msg);
this.refs.gridControl.setState({
overlay: true,
overlayTitle: 'The connection has been lost w/ your friend...',
overlaySubTitle: 'Please, restart the game!',
});
}
wTopic(payload) {
if (this.refs.gridControl.state.webPlayer !== payload.data.player) {
if (null === payload.data.resign) {
'dev' === this.state.env && console.warn(payload.user + ' has been stepped to coords: ' + payload.data.coords[0] + ', ' + payload.data.coords[1]);
'dev' === this.state.env && console.warn('Opponent stepped: Auto-Step process');
this.refs.gridControl.refs.userControl.setState({ bombSelected: payload.data.bomb });
let points = this.makePointsCalcAndStep(payload.data.coords);
this.makeGameEndIfItEnds(points.blue, points.red);
} else {
this.resignProcess(payload.data.resign);
}
}
}
// ------------------------------------------------------------------ //
// Mercure / SSE connection
// ------------------------------------------------------------------ //
/**
* Dispatches every incoming SSE message.
* Distinguishes subscription events, game-step events, and disconnect events
* using the same payload shape as the former WAMP broadcast.
*/
handleMercureMessage(payload) {
let isTopicEvent = 'undefined' !== typeof payload.data;
let isNotUnsubscribe = 'undefined' === typeof payload.msg;
if (isTopicEvent) {
this.wTopic(payload);
} else if (isNotUnsubscribe) {
this.wSubscribe(payload, this.rpcUsers);
} else {
this.wUnsubscribe(payload);
}
/** Reconnection: replay cached steps once both players are back */
if (2 === payload.userCnt && this.state.connectionLost) {
'dev' === this.state.env && console.info('Reconnection process');
let cache = this.state.stepCache;
cache.forEach(item => this.publishStep(item));
this.setState({ connectionLost: false, stepCache: [] });
}
}
openEventSource() {
const wrapper = document.getElementById('mine-wrapper');
const hubUrl = wrapper.dataset.mercureHubUrl;
const subscriberJwt = wrapper.dataset.mercureSubscriberJwt;
const url = new URL(hubUrl, window.location.origin);
url.searchParams.append('topic', this.state.channel);
if (subscriberJwt) {
url.searchParams.append('authorization', subscriberJwt);
}
if (this.eventSource) {
this.eventSource.close();
}
this.eventSource = new EventSource(url.toString());
this.eventSource.onmessage = event => {
this.handleMercureMessage(JSON.parse(event.data));
};
this.eventSource.onopen = () => {
'dev' === this.state.env && console.info('SSE connection opened');
if (this.state.connectionLost) {
'dev' === this.state.env && console.info('SSE reconnected — rejoining channel');
this.joinGame();
}
};
this.eventSource.onerror = () => {
'dev' === this.state.env && console.error('SSE connection error / lost');
this.setState({ connectionLost: true });
};
}
wInit(gridServer, gridClient) {
this.refs.gridControl.setState({
grid: this.state.gameInherited ? gridServer : gridClient,
channel: this.state.channel,
@@ -207,177 +317,86 @@ class MineSeeker extends React.Component {
});
}
wSubscribe(payload, rpcUsers = null) {
'dev' === this.state.env && console.info(
('undefined' !== typeof payload.user ? payload.user : 'user') + ' has been subscribed to the channel!',
);
let firstUser = !rpcUsers;
null === this.refs.gridControl.state.webPlayer && this.refs.gridControl.setState({
webPlayer: payload.user === payload.users.blue
|| (
firstUser && '' !== payload.users.blueAnon
|| !firstUser && ('' === rpcUsers.blueAnon && '' === rpcUsers.blue)
)
? 'blue' : 'red',
});
/** rwd */
(900 > $(document).width()) && this.currectGridSize();
/** every user has been came */
if (
2 === payload.userCnt
&& (
!this.state.connectionLost
|| this.state.connectionLost && false === this.refs.gridControl.refs.userControl.state.activePlayer && !this.state.end
)
) {
this.makeGameStart(payload);
}
/** POST /api/game/join — register this player, broadcast subscription event via Mercure */
joinGame() {
return fetch('/api/game/join/' + this.state.gameAssoc, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}).catch(e => 'dev' === this.state.env && console.error('Join error', e));
}
wUnsubscribe(payload) {
'dev' === this.state.env && console.info(payload.msg);
this.refs.gridControl.setState({
overlay: true,
overlayTitle: 'The connection has been lost w/ your friend...',
overlaySubTitle: 'Please, restart the game!',
});
/** POST /api/game/step — persist a move and fan it out via Mercure */
publishStep(dataPack) {
return fetch('/api/game/step/' + this.state.gameAssoc, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(dataPack),
}).catch(e => 'dev' === this.state.env && console.error('Step error', e));
}
wTopic(payload) {
/** Auto-Step if this player is not the current user */
if (this.refs.gridControl.state.webPlayer !== payload.data.player) {
if (null === payload.data.resign) {
'dev' === this.state.env && console.warn(payload.user + ' has been stepped to coords: ' + payload.data.coords[0] + ', ' + payload.data.coords[1]);
'dev' === this.state.env && console.warn('Opponent stepped: Auto-Step process');
// ------------------------------------------------------------------ //
// Lifecycle
// ------------------------------------------------------------------ //
this.refs.gridControl.refs.userControl.setState({ bombSelected: payload.data.bomb });
async componentDidMount() {
if (!this.state.connectionLost) {
let gridClient = this.state.gameInherited ? null : new Grid().state.grid;
/** STEP */
let points = this.makePointsCalcAndStep(payload.data.coords);
try {
if (this.state.gameInherited) {
/** Fetch existing grid and player info */
const resp = await fetch('/api/game/connect/' + this.state.gameAssoc);
const b64 = await resp.text();
const serverData = JSON.parse(window.atob(b64));
/** THE END */
this.makeGameEndIfItEnds(points.blue, points.red);
} else {
/** RESIGN */
/** THE END */
this.resignProcess(payload.data.resign);
}
}
}
/** Connect - Subscribe */
subscribe(rpcUsers = null) {
this.state.session.subscribe(
this.state.channel,
(uri, payload) => {
let isTopicEvent = 'undefined' !== typeof payload.data,
isNotUnsubscribe = 'undefined' === typeof payload.msg;
/** CONNECTION */
if (isTopicEvent) {
this.wTopic(payload);
} else {
if (isNotUnsubscribe) {
this.wSubscribe(payload, rpcUsers);
} else {
this.wUnsubscribe(payload);
if ('undefined' === typeof serverData.grid || null === serverData.grid) {
this.refs.gridControl.setState({
overlay: true,
overlayTitle: 'This channel does not exists!',
overlaySubTitle: <a href="/play" target="_self">Restart game!</a>,
});
console.error('This channel does not exists!');
return;
}
this.rpcUsers = serverData.users;
this.openEventSource();
this.wInit(serverData.grid, null);
} else {
/** Create the game record with this client's grid */
await fetch('/api/game/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
grid: window.btoa(JSON.stringify(gridClient)),
gameAssoc: this.state.gameAssoc,
}),
});
this.openEventSource();
this.wInit(null, gridClient);
}
/** RECONNECTION */
if (2 === payload.userCnt && this.state.connectionLost) {
'dev' === this.state.env && console.info('Reconnection process');
'dev' === this.state.env && console.info('Connection initialised — joining channel');
await this.joinGame();
/** PUBLISH */
let cache = this.state.stepCache;
cache.forEach(item => this.state.session.publish(this.state.channel, item));
this.setState({ connectionLost: false, stepCache: [] });
}
});
}
connectWithWebsocket() {
/** Create Websocket w/ Bahnhof.js */
let websocket = WS.connect(
('true' === this.state.ssl ? 'wss' : 'ws') + '://' + window.location.hostname + '/ws/',
);
/**
* Connect
* Session is an Autobahn JS WAMP session.
*/
websocket.on('socket/connect', session => {
'dev' === this.state.env && console.info('Successfully connected to the Server!');
if (!this.state.connectionLost) {
let gridClient = this.state.gameInherited || new Grid().state.grid;
/**
* Connect - RPC
* Send grid information to the server
*/
session
.call(
this.state.gameInherited ? 'mineseeker-rpc/connectGame' : 'mineseeker-rpc/startGame',
this.state.gameInherited ? this.state.gameAssoc : [window.btoa(JSON.stringify(gridClient)), this.state.gameAssoc],
)
.then(
data => {
'dev' === this.state.env && console.info('RPC has been called');
let serverData = true !== data[0]
? JSON.parse(window.atob(data))
: data;
/** Check the grid if the user is inherited @see #30 */
if ((this.state.gameInherited && 'undefined' !== typeof serverData.grid) || !this.state.gameInherited) {
this.wInit(session, serverData.grid, gridClient);
this.subscribe(this.state.gameInherited && serverData.users);
} else {
this.refs.gridControl.setState({
overlay: true,
overlayTitle: 'This channel does not exists!',
overlaySubTitle: <a href="/play" target="_self">Restart game!</a>,
});
console.error('This channel does not exists!');
}
},
(error, desc) => 'dev' === this.state.env && console.error(['RPC Error', error, desc]),
);
} else {
this.setState({ session: session });
this.subscribe();
} catch (e) {
'dev' === this.state.env && console.error('Connection error', e);
setTimeout(() => this.componentDidMount(), 500);
}
});
/**
* DisConnect
* Error provides us with some insight into the disconnection: error.reason and error.code
*/
websocket.on('socket/disconnect', error => {
'dev' === this.state.env && console.error('Disconnected for ' + error.reason + ' with code ' + error.code);
} else {
/** Hard-reconnect path */
this.openEventSource();
}
6 === error.code && this.setState({ connectionLost: true });
3 === error.code && setTimeout(this.componentDidMount.bind(this), 500);
/** Notify the server when the player closes / navigates away */
window.addEventListener('pagehide', () => {
navigator.sendBeacon('/api/game/leave/' + this.state.gameAssoc);
});
}
/** After rendering */
componentDidMount() {
this.connectWithWebsocket();
}
/**
* Cache the steps unless reconnection
*
* @param dataPack
*/
cachePublish(dataPack) {
let cache = this.state.stepCache;
cache.push(dataPack);
@@ -387,30 +406,24 @@ class MineSeeker extends React.Component {
onClick(coords) {
let activePlayer = this.refs.gridControl.refs.userControl.state.activePlayer ? 'blue' : 'red';
/** if the clicked field is NEVER CLICKED */
if (this.refs.gridControl.checkFieldHasBeenNeverClicked(coords[0], coords[1])) {
/** Player step and it is the current player */
if (activePlayer === this.refs.gridControl.state.webPlayer) {
/** STEP */
let points = this.makePointsCalcAndStep(coords);
/** THE END */
this.makeGameEndIfItEnds(points.blue, points.red);
let dataPack = {
'coords': coords,
'player': activePlayer,
'bomb': this.refs.gridControl.refs.userControl.state.bombSelected,
'redPoints': points.red,
'bluePoints': points.blue,
'resign': null,
'redExplodedBomb': 'red' === activePlayer && this.refs.gridControl.refs.userControl.state.bombSelected,
'blueExplodedBomb': 'blue' === activePlayer && this.refs.gridControl.refs.userControl.state.bombSelected,
coords: coords,
player: activePlayer,
bomb: this.refs.gridControl.refs.userControl.state.bombSelected,
redPoints: points.red,
bluePoints: points.blue,
resign: null,
redExplodedBomb: 'red' === activePlayer && this.refs.gridControl.refs.userControl.state.bombSelected,
blueExplodedBomb: 'blue' === activePlayer && this.refs.gridControl.refs.userControl.state.bombSelected,
};
/** PUBLISH */
!this.state.connectionLost
? this.state.session.publish(this.state.channel, dataPack)
? this.publishStep(dataPack)
: this.cachePublish(dataPack);
}
}
@@ -428,4 +441,4 @@ class MineSeeker extends React.Component {
}
}
export default MineSeeker;
export default MineSeeker;

View File

@@ -173,8 +173,11 @@ class GridControl extends React.Component {
inactivePlayer = userControl.state.activePlayer ? 'red' : 'blue';
if (
userControl.state.bombSelected && idx === (max - 1)
|| !idx && !userControl.state.bombSelected && 'm' !== currentObject
userControl.state.bombSelected
&& idx === (max - 1)
|| !idx
&& !userControl.state.bombSelected
&& 'm' !== currentObject
) {
userControl.setState({
activePlayer: userControl.state.activePlayer ? 0 : 1,