Hello Fellow Stackers!
I am finally resorting to ask here:
I have a Lambda (Node 20.X) which is triggered by an SNS message. The of the message contains a connection ID.
The Lambda needs to identify all players and their connections and send the game object.
It does send a message, but not always… most of the times the client.send invocation, fails silently – which is the frustrating thing!
Here is the code:
import {
ApiGatewayManagementApiClient,
PostToConnectionCommand,
} from "@aws-sdk/client-apigatewaymanagementapi";
export const handler = async (event) => {
const ws_url = process.env.ws_url;
const client = new ApiGatewayManagementApiClient({ endpoint: ws_url });
const Game = JSON.parse(event.Records[0].Sns.Message);
switch (Game.type) {
case 'game':
wsMessage(client, Game.data);
break;
default:
console.error('Unknown Message Type', Game.type, 'Message', Game);
}
const response = { statusCode: 200 };
return response;
};
const wsMessage = async (client, Game) => {
if (!Game.hasOwnProperty('players')) return console.error('No Players in Game', Game);
const sendings = [];
if (Game.players.length > 0) {
try {
for (const player of Game.players) {
console.log('connection_id', player.connection_id);
if (!player.hasOwnProperty('connection_id') || !player.connection_id) continue;
const requestParams = {
ConnectionId: player.connection_id,
// Data: JSON.stringify({ type: "game", "data": Game }),
Data: JSON.stringify({ type: "game", "data": Game.id }),
};
console.log('player', player, requestParams);
const command = new PostToConnectionCommand(requestParams);
console.log("Sending", requestParams);
// sendings.push(client.send(command).then((r) => { console.log("Sent", r); return r; }).catch((e) => { console.error("Send Error", e.message); }));
await client.send(command).then((r) => { console.log("Sent", r); return r; }).catch((e) => { console.error("Send Error", e.message); });
}
// if (sendings.length > 0) await Promise.all(sendings);
} catch (error) {
console.error("WS Sending error", error.message, error.stack);
}
} else console.error('No Players in ', Game.id);
}
You will notice I have tried to reduce the message size – tried Promise.all as well to speed up the sending all to no avail. It sometimes sends the response to the web-socket and most of the times fails silently – i.e. does not deliver the message, and the console log does not show the result or any errors.
I am properly stuck. Any help and ideas?
1