예제 #1
0
        public async Task PostToConnection(ConnectionSocketModel connection, MemoryStream stream, ConnectionSocketService connectionService, AmazonApiGatewayManagementApiClient apiClient, ILambdaContext context)
        {
            var connectionId = connection.connection_id;

            context.Logger.LogLine($"Get Connection ID from DB: {connectionId}");

            var postConnectionRequest = new PostToConnectionRequest
            {
                ConnectionId = connectionId,
                Data         = stream
            };

            try
            {
                context.Logger.LogLine($"Post to connection: {connectionId}");
                stream.Position = 0;
                await apiClient.PostToConnectionAsync(postConnectionRequest);
            }
            catch (AmazonServiceException e)
            {
                if (e.StatusCode == HttpStatusCode.Gone)
                {
                    connectionService.GetConnection(connectionId);
                    context.Logger.LogLine($"Deleting gone connection: {connectionId}");
                }
                else
                {
                    context.Logger.LogLine($"Error posting message to {connectionId}: {e.Message}");
                    context.Logger.LogLine(e.StackTrace);
                }
            }
        }
예제 #2
0
        internal static Task SendMessage(string apiUrl, string connectionId, string room, JObject message)
        {
            Task result = Task.Run(() => {
                MemoryStream stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(message.ToString(Newtonsoft.Json.Formatting.None)));
                AmazonApiGatewayManagementApiConfig config = new AmazonApiGatewayManagementApiConfig()
                {
                    ServiceURL = apiUrl
                };
                AmazonApiGatewayManagementApiClient client = new AmazonApiGatewayManagementApiClient(config);
                PostToConnectionRequest postReq            = new PostToConnectionRequest()
                {
                    ConnectionId = connectionId, Data = stream
                };
                try
                {
                    Logging.LogDebug("Sending to: " + connectionId);
                    Task <PostToConnectionResponse> task = client.PostToConnectionAsync(postReq);
                    task.Wait();
                    Logging.LogDebug("Sent to: " + connectionId);
                }
                catch (Exception ex)
                {
                    Logging.LogDebug("Deleteing conneciton " + connectionId);
                    error = apiUrl + " - " + connectionId + " - " + ex.ToString();
                    Connection.Delete(apiUrl, room, connectionId);
                    Logging.LogDebug("Deleted conneciton " + connectionId);
                }
            });

            return(result);
        }
예제 #3
0
        public void ProcessDynamoEvent(DynamoDBEvent dynamoDBEvent, ILambdaContext context)
        {
            AmazonApiGatewayManagementApiClient client = new AmazonApiGatewayManagementApiClient(new AmazonApiGatewayManagementApiConfig()
            {
                ServiceURL = "https://g49fepw5h8.execute-api.us-west-2.amazonaws.com/Test"
            });

            AmazonDynamoDBClient amazonDynamoDbClient = new AmazonDynamoDBClient();

            Console.WriteLine("Voy a empezar");
            Console.WriteLine(dynamoDBEvent.Records);

            foreach (var dynamoRecord in dynamoDBEvent.Records)
            {
                MemoryStream stream      = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dynamoRecord.Dynamodb.NewImage)));
                String[]     connections = GetConnections(amazonDynamoDbClient, dynamoRecord.Dynamodb.NewImage);
                foreach (string connection in connections)
                {
                    PostToConnectionRequest postRequest = new PostToConnectionRequest()
                    {
                        ConnectionId = connection,
                        Data         = stream
                    };

                    var result = client.PostToConnectionAsync(postRequest);
                    result.Wait();
                }
            }
        }
        public APIGatewayProxyResponse Message(APIGatewayProxyRequest request)
        {
            Console.WriteLine("ConnectionId: " + request.RequestContext.ConnectionId);
            Request finalRequest = JsonConvert.DeserializeObject <Request>(request.Body);

            Asset    asset    = new Asset();
            Document document = asset.getItem(finalRequest.ContractId);
            AmazonApiGatewayManagementApiClient client = new AmazonApiGatewayManagementApiClient(new AmazonApiGatewayManagementApiConfig()
            {
                ServiceURL = "https://" + request.RequestContext.DomainName + "/" + request.RequestContext.Stage
            });

            MemoryStream            stream      = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(document)));
            PostToConnectionRequest postRequest = new PostToConnectionRequest()
            {
                ConnectionId = request.RequestContext.ConnectionId,
                Data         = stream
            };

            var result = client.PostToConnectionAsync(postRequest);

            result.Wait();

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK
            });
        }
예제 #5
0
        private async Task <APIGatewayProxyResponse> _broadcast(ScanResponse list, AmazonApiGatewayManagementApiClient apiClient, MemoryStream stream, ILambdaContext context)
        {
            var count = 0;

            foreach (var item in list.Items)
            {
                var connectionId = item[Constants.ConnectionIdField].S;

                var postConnectionRequest = new PostToConnectionRequest
                {
                    ConnectionId = connectionId,
                    Data         = stream
                };

                try
                {
                    LambdaLogger.Log($"Post to connection {count}: {connectionId}");
                    stream.Position = 0;
                    await apiClient.PostToConnectionAsync(postConnectionRequest);

                    count++;
                }
                catch (AmazonServiceException e)
                {
                    // API Gateway returns a status of 410 GONE when the connection is no
                    // longer available. If this happens, we simply delete the identifier
                    // from our DynamoDB table.
                    if (e.StatusCode == HttpStatusCode.Gone)
                    {
                        var ddbDeleteRequest = new DeleteItemRequest
                        {
                            TableName = Constants.WEBSOCKET_TABLE,
                            Key       = new Dictionary <string, AttributeValue>
                            {
                                { Constants.ConnectionIdField, new AttributeValue {
                                      S = connectionId
                                  } }
                            }
                        };

                        context.Logger.LogLine($"Deleting gone connection: {connectionId}");
                        await _ddbClient.DeleteItemAsync(ddbDeleteRequest);
                    }
                    else
                    {
                        context.Logger.LogLine($"Error posting message to {connectionId}: {e.Message}");
                        context.Logger.LogLine(e.StackTrace);
                    }
                }
            }

            return(new APIGatewayProxyResponse
            {
                StatusCode = 200,
                Body = "Data send to " + count + " connection" + (count == 1 ? "" : "s")
            });
        }
예제 #6
0
        private async Task <APIGatewayProxyResponse> _broadcast(List <WSConnection> list, AmazonApiGatewayManagementApiClient client, MemoryStream stream)
        {
            var count = 0;

            foreach (var item in list)
            {
                var connectionId          = item.connectionId;
                var postConnectionRequest = new PostToConnectionRequest
                {
                    ConnectionId = connectionId,
                    Data         = stream
                };

                try
                {
                    LambdaLogger.Log($"Post to connection {count}: {connectionId}");
                    stream.Position = 0;
                    await client.PostToConnectionAsync(postConnectionRequest);

                    count++;
                }
                catch (AmazonServiceException e)
                {
                    LambdaLogger.Log($"Connection had appeared to have a problem! " + e.StatusCode);
                    // API Gateway returns a status of 410 GONE when the connection is no
                    // longer available. If this happens, we simply delete the identifier
                    // from our DynamoDB table.
                    if (e.StatusCode == HttpStatusCode.Gone)
                    {
                        var wsConnection = new WSConnection();
                        wsConnection.connectionId = connectionId;
                        LambdaLogger.Log($"Deleting gone connection: {connectionId}");
                        await wsdm.deleteSubcriber(wsConnection);
                    }
                    else
                    {
                        var wsConnection = new WSConnection();
                        wsConnection.connectionId = connectionId;
                        LambdaLogger.Log($"Deleting invalid connection: {connectionId}");
                        await wsdm.deleteSubcriber(wsConnection);

                        LambdaLogger.Log(e.StackTrace);
                        //LambdaLogger.Log($"Error posting message to {connectionId}: {e.Message}");
                    }
                }
            }

            return(new APIGatewayProxyResponse
            {
                StatusCode = 200,
                Body = "Connected."
            });
        }
예제 #7
0
        internal static void SendCatchup(string serviceUrl, string connectionId, string room, JArray messages)
        {
            JObject message = new JObject()
            {
                { "action", "catchup" }, { "room", room }, { "messages", messages }
            };
            MemoryStream stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(message.ToString(Newtonsoft.Json.Formatting.None)));
            AmazonApiGatewayManagementApiConfig config = new AmazonApiGatewayManagementApiConfig()
            {
                ServiceURL = serviceUrl
            };
            AmazonApiGatewayManagementApiClient client  = new AmazonApiGatewayManagementApiClient(config);
            PostToConnectionRequest             postReq = new PostToConnectionRequest()
            {
                ConnectionId = connectionId, Data = stream
            };

            client.PostToConnectionAsync(postReq);
        }
예제 #8
0
        public async Task <bool> PostMessage(string connectionId, Message message)
        {
            try
            {
                await _apiClient.PostToConnectionAsync(new PostToConnectionRequest
                {
                    ConnectionId = connectionId,
                    Data         = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)))
                });
            }
            catch (AmazonServiceException e)
            {
                if (e.StatusCode == HttpStatusCode.Gone)
                {
                    return(false);
                }
            }

            return(true);
        }
        public static void SendPosition(ProxyRequestContext context, string contractId)
        {
            Asset    asset    = new Asset();
            Document document = asset.getItem(contractId);
            AmazonApiGatewayManagementApiClient client = new AmazonApiGatewayManagementApiClient(new AmazonApiGatewayManagementApiConfig()
            {
                ServiceURL = "https://" + context.DomainName + "/" + context.Stage
            });

            MemoryStream            stream      = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(document)));
            PostToConnectionRequest postRequest = new PostToConnectionRequest()
            {
                ConnectionId = context.ConnectionId,
                Data         = stream
            };

            var result = client.PostToConnectionAsync(postRequest);

            result.Wait();
        }
예제 #10
0
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            LambdaLogger.Log(JObject.FromObject(request).ToString());

            try
            {
                var domainName = request.RequestContext.DomainName;
                var stage      = request.RequestContext.Stage;
                var endpoint   = $"https://{domainName}/{stage}";
                LambdaLogger.Log("API Gateway management endpoint:" + endpoint);

                var message = JsonConvert.DeserializeObject <JObject>(request.Body);
                var data    = message["data"]?.ToString();

                var stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data));

                var scanRequest = new ScanRequest
                {
                    TableName            = Environment.GetEnvironmentVariable("DynamoChatTable"),
                    ProjectionExpression = "ConnectionId"
                };

                var scanResponse = await ddbClient.ScanAsync(scanRequest);

                var apiClient = new AmazonApiGatewayManagementApiClient(new AmazonApiGatewayManagementApiConfig
                {
                    ServiceURL = endpoint
                });

                var count = 0;
                foreach (var item in scanResponse.Items)
                {
                    var connectionId = item["ConnectionId"].S;


                    var postConnectionRequest = new PostToConnectionRequest
                    {
                        ConnectionId = connectionId,
                        Data         = stream
                    };

                    try
                    {
                        context.Logger.LogLine($"Post to connection {count}: {connectionId}");
                        stream.Position = 0;
                        await apiClient.PostToConnectionAsync(postConnectionRequest);

                        count++;
                    }
                    catch (AmazonServiceException e)
                    {
                        // API Gateway returns a status of 410 GONE when the connection is no
                        // longer available. If this happens, we simply delete the identifier
                        // from our DynamoDB table.
                        if (e.StatusCode == HttpStatusCode.Gone)
                        {
                            var ddbDeleteRequest = new DeleteItemRequest
                            {
                                TableName = Environment.GetEnvironmentVariable("DynamoChatTable"),
                                Key       = new Dictionary <string, AttributeValue>
                                {
                                    { "ConnectionId", new AttributeValue {
                                          S = connectionId
                                      } }
                                }
                            };

                            context.Logger.LogLine($"Deleting gone connection: {connectionId}");
                            await ddbClient.DeleteItemAsync(ddbDeleteRequest);
                        }
                        else
                        {
                            context.Logger.LogLine($"Error posting message to {connectionId}: {e.Message}");
                            context.Logger.LogLine(e.StackTrace);
                        }
                    }
                }

                return(new APIGatewayProxyResponse
                {
                    StatusCode = 200,
                    Body = "Data send to " + count + " connection" + (count == 1 ? "" : "s")
                });
            }
            catch (Exception e)
            {
                LambdaLogger.Log("Error disconnecting: " + e.Message);
                LambdaLogger.Log(e.StackTrace);
                return(new APIGatewayProxyResponse
                {
                    StatusCode = 500,
                    Body = $"Failed to send message: {e.Message}"
                });
            }
        }
예제 #11
0
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            try
            {
                var domainName = request.RequestContext.DomainName;
                var stage      = request.RequestContext.Stage;
                var endpoint   = $"https://{domainName}/{stage}";
                context.Logger.LogLine($"API Gateway management endpoint: {endpoint}");

                var message = JsonConvert.DeserializeObject <JObject>(request.Body);
                var data    = message["data"]?.ToString();

                var stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data));

                var scanRequest = new ScanRequest
                {
                    TableName            = Constants.TABLE_NAME,
                    ProjectionExpression = Constants.ConnectionIdField
                };

                var scanResponse = await _ddbClient.ScanAsync(scanRequest);

                var apiClient = new AmazonApiGatewayManagementApiClient(new AmazonApiGatewayManagementApiConfig
                {
                    ServiceURL = endpoint
                });

                var count = 0;
                foreach (var item in scanResponse.Items)
                {
                    var connectionId = item[Constants.ConnectionIdField].S;

                    var postConnectionRequest = new PostToConnectionRequest
                    {
                        ConnectionId = connectionId,
                        Data         = stream
                    };

                    try
                    {
                        context.Logger.LogLine($"Post to connection {count}: {connectionId}");
                        stream.Position = 0;
                        await apiClient.PostToConnectionAsync(postConnectionRequest);

                        count++;
                    }
                    catch (AmazonServiceException e)
                    {
                        if (e.StatusCode == HttpStatusCode.Gone)
                        {
                            var ddbDeleteRequest = new DeleteItemRequest
                            {
                                TableName = Constants.TABLE_NAME,
                                Key       = new Dictionary <string, AttributeValue>
                                {
                                    { Constants.ConnectionIdField, new AttributeValue {
                                          S = connectionId
                                      } }
                                }
                            };

                            context.Logger.LogLine($"Deleting gone connection: {connectionId}");
                            await _ddbClient.DeleteItemAsync(ddbDeleteRequest);
                        }
                        else
                        {
                            context.Logger.LogLine($"Error posting message to {connectionId}: {e.Message}");
                            context.Logger.LogLine(e.StackTrace);
                        }
                    }
                }

                return(new APIGatewayProxyResponse
                {
                    StatusCode = 200,
                    Body = "Data send to " + count + " connection" + (count == 1 ? "" : "s")
                });
            }
            catch (Exception e)
            {
                context.Logger.LogLine("Error disconnecting: " + e.Message);
                context.Logger.LogLine(e.StackTrace);
                return(new APIGatewayProxyResponse
                {
                    StatusCode = 500,
                    Body = $"Failed to send message: {e.Message}"
                });
            }
        }
예제 #12
0
        public async Task <APIGatewayProxyResponse> Handler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            var client = new AmazonDynamoDBClient();

            var scanRequest = new ScanRequest
            {
                TableName            = Environment.ExpandEnvironmentVariables("%TABLE_NAME%"),
                ProjectionExpression = "connectionId"
            };

            ScanResponse connections = null;

            try
            {
                connections = await client.ScanAsync(scanRequest);
            }
            catch (Exception e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = e.Message,
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }

            var data      = JObject.Parse(input.Body)["data"].ToString();
            var byteArray = Encoding.UTF8.GetBytes(data);

            var config = new AmazonApiGatewayManagementApiConfig
            {
                ServiceURL = $"https://{input.RequestContext.DomainName}/{input.RequestContext.Stage}"
            };

            var apiClient = new AmazonApiGatewayManagementApiClient(config);

            var connectionIds = connections.Items.Select(item => item["connectionId"].S).ToList();

            foreach (var connectionId in connectionIds)
            {
                var postData = new MemoryStream(byteArray);

                try
                {
                    var postToRequest = new PostToConnectionRequest
                    {
                        ConnectionId = connectionId,
                        Data         = postData
                    };

                    await apiClient.PostToConnectionAsync(postToRequest);
                }
                catch (GoneException)
                {
                    Console.WriteLine($"Found dead connection, deleting {connectionId}");

                    var attributes = new Dictionary <string, AttributeValue>();

                    attributes["connectionId"] = new AttributeValue {
                        S = connectionId
                    };

                    var deleteRequest = new DeleteItemRequest
                    {
                        TableName = Environment.ExpandEnvironmentVariables("%TABLE_NAME%"),
                        Key       = attributes
                    };

                    try
                    {
                        await client.DeleteItemAsync(deleteRequest);
                    }
                    catch (Exception e)
                    {
                        return(new APIGatewayProxyResponse
                        {
                            StatusCode = (int)HttpStatusCode.InternalServerError,
                            Body = e.Message,
                            Headers = new Dictionary <string, string> {
                                { "Content-Type", "text/plain" }
                            },
                        });
                    }
                }
                catch (Exception e)
                {
                    return(new APIGatewayProxyResponse
                    {
                        StatusCode = (int)HttpStatusCode.InternalServerError,
                        Body = e.Message,
                        Headers = new Dictionary <string, string> {
                            { "Content-Type", "text/plain" }
                        },
                    });
                }
            }

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = "data sent",
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            });
        }