Vercel "This Serverless Function has crashed" with simple GraphQL request from SvelteKit app - graphql

I am getting frequent, seemingly random errors on initial page load. I think the problem has to do with Vercel Serverless Functions.
I regularly get this error on the website itself:
Full log from Vercel:
[GET] /
14:54:19:39
2022-07-21T12:54:19.426Z 3a175b6b-396b-45d5-b1a1-46072201cd6a ERROR Unhandled Promise Rejection
{"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"FetchError: request to
https://api-eu-central-1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason:
Client network socket disconnected before secure TLS connection was
established","reason":{"errorType":"FetchError","errorMessage":"request to https://api-
eu-central-1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason: Client
network socket disconnected before secure TLS connection was
established","code":"ECONNRESET","message":"request to https://api-eu-central-
1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason: Client network socket
disconnected before secure TLS connection was
established","type":"system","errno":"ECONNRESET","stack":["FetchError: request to
https://api-eu-central-1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason:
Client network socket disconnected before secure TLS connection was established"," at
ClientRequest.<anonymous> (/var/task/index.js:7892:18)"," at ClientRequest.emit
(node:events:527:28)"," at TLSSocket.socketErrorListener (node:_http_client:454:9)","
at TLSSocket.emit (node:events:527:28)"," at emitErrorNT (node:internal/streams
/destroy:157:8)"," at emitErrorCloseNT (node:internal/streams/destroy:122:3)"," at
processTicksAndRejections (node:internal/process/task_queues:83:21)"]},"promise":
{},"stack":["Runtime.UnhandledPromiseRejection: FetchError: request to https://api-eu-
central-1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason: Client network
socket disconnected before secure TLS connection was established"," at process.
<anonymous> (file:///var/runtime/index.mjs:775:15)"," at process.emit
(node:events:539:35)"," at emit (node:internal/process/promises:140:20)"," at
processPromiseRejections (node:internal/process/promises:274:27)"," at
processTicksAndRejections (node:internal/process/task_queues:97:32)"]}[ERROR]
[1658408059427] LAMBDA_RUNTIME Failed to post handler success response. Http response
code: 400.RequestId: 2a0597b4-6684-4f2a-a724-2333b4f9332d Error: Runtime exited with
error: exit status 128Runtime.ExitError
Example code from SvelteKit endpoint:
import {client} from '$lib/js/graphql-client'
import {projectsQuery} from '$lib/js/graphql-queries'
export async function get() {
let sm = 640;
let md = 768;
let lg = 1024;
let xl = 1280;
let xxl = 1536;
const variables = {sm, md, lg, xl, xxl}
const {projects} = await client.request(projectsQuery, variables)
return {
body: {
projects, sm, md, lg, xl, xxl
}
}
}
Now, other people seem to have similar problems:
Vercel + NextJS : Client network socket disconnected before secure TLS connection was established - Help - Fauna Forums
node.js - Getting a 504/502 error on api requests in Nextjs deployed on Vercel - Stack Overflow
[AWS-Lambda] - NetworkingError: Client network socket disconnected before secure TLS connection was established · Issue #3591 · aws/aws-sdk-js · GitHub
Especially the last link makes it seem like the source of the problem lies in AWS Lambda. I do not expect a magic bullet, but I do want to make sure the problem is in fact what I think it is (and not a mistake in my code).
Has anyone found any workarounds? Ways of minimizing the probability of these functions crashing?

I had to add index.js in vercel.json. See this link for more information.

Related

WebSocket React Native Invalid error: Invalid Sec-WebSocket-Accept response

I am receiving an Invalid Sec-WebSocket-Accept response when client (running on a simulator) tries to establish connection to the server. My server is written in Spring boot - java (websocket), client react native. I am using WebSocket to establish the connection to the server. This is what my client code looks like
const client = new WebSocketClient('ws://localhost:5000/websocket');
Result:
Event {
"isTrusted": false,
"message": "Invalid Sec-WebSocket-Accept response",
}
I have tried everything but I keep getting this error. I tested the connection to a mock server ws://echo.websocket.events/ and it works fine - I am confused on what I am doing wrong. I also tested this with ws://10.0.2.2:5000/websocket and i get
Event {
"isTrusted": false,
"message": "The operation couldn’t be completed. Connection refused",
}
help :)
NOTE: everything works fine on a browser

Ocelot API gateway fails to establish SSL connection to downstream

I have an Ocelot API gateway in front of all our microservices providing some form of an API. We also have some external services hosted in Azure, one which I figured I wanted to route through our API gateway. However, as the title says, when attempting to connect using https as the downstream scheme I get the following error message:
Error Code: ConnectionToDownstreamServiceError Message: Error connecting to downstream service, exception: System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.IO.IOException: Cannot determine the frame size or a corrupted frame was received.
at System.Net.Security.SslStream.ReceiveBlobAsync[TIOAdapter](TIOAdapter adapter)
at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
Googling the inner exception leads to some posts suggesting that since .net 5.0 preview 6 the default tls version is determined by the operating system default which by now should probably be TLSv1.3. I believe Azure functions does not support TLSv1.3 yet and it appears that the downstream request from Ocelot does not fall back on TLSv1.2 when this is the case.
Attempting to run the request a number of other ways yields only success which leads me to believe that this is an issue specific to Ocelot. Running requests directly to the Azure resource via
Postman: succeeds. TLSv1.2 is used.
curl: succeeds. TLS1.2 is used here too.
GetAsync using HttpClient in C# (.net 5.0): succeeds.
Running curl with -v I can see that it attempts a handshake with TLSv1.3 first but then falls back to TLS1.2.
Can anyone confirm that the tls version is indeed the problem? And in that case is there any way to allow TLSv1.2 in an asp.net 5 ocelot API Gateway project?
Additional information:
Setting "DangerousAcceptAnyServerCertificateValidator": true does not resolve the issue
The gateway has no issues when using http as downstream scheme
I have a similar environement where most of my Ocelot downstream requests are currently pointing to localhost microservices (in development). However i have rigged up an Azure Function (Http Trigger) that i deployed to Azure and therefore need Ocelot to route a downstream request to the external facing url.
What I can confirm is that my Ocelot environment is running on .NET Core 5.0 and am able to succesfully call the Azure Function and return the data to my front end Web App (upstream route)
I havent had to do anything different with Ocelot for it to work. Below is the snippet from the ocelot.json file
"Routes": [
// ---------------------------------------------------
// ---------- Azure Functions HTTP Triggers ----------
// ---------------------------------------------------
// ----------- Logs -----------
{
"DownstreamPathTemplate": "/api/logproperties",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "azurefunction-httpget-logproperties.azurewebsites.net",
"Port": 443
}
],
"UpstreamPathTemplate": "/logs/logproperties",
"UpstreamHttpMethod": [ "Get" ],
"RouteIsCaseSensitive": false,
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer",
"AllowedScopes": []
}
}
]
The actual url path for my function is shown below (obviously with the api key removed)
https://azurefunction-httpget-logproperties.azurewebsites.net/api/logproperties?code=<MyApiKeyHere>&containerName=ohiAppSource&logPropertyName=OhiAppSource
I was having issues intitially but after removing 'https://' from the string set for the "Host" in the Json config then it went through OK.
My Ocelot environement authenticates upstream requests (Client App --> Ocelot) using Microsoft Identity Web library so calling a function with a simple API key is not a security concern for me. But regardless of how you're securing the inbound side of ocelot, I dont think that would affect the issue you encountered. My solution is not promising a fix to your particular issue but it always helps to see a working configuration.

Modify server response using node http proxy

I am a beginner to node js and this is my first post in here so apologies if this is a stupid question.
The problem I need to solve is to change information in an HTTPS server response before it hits the client. The reason is that my my client (Im developing a GARMIN sports watch application) cannot read the server response as the body data format differs from the content_type as defined in the response header. I have no means of impacting the server code and on the client I am stuck as well, Garmin has acknowledged it should be fixed but have not put it on priority.
I guess that leaves me with having to implement my own http proxy that I can connect in between the client and server to change either the header or the data format in the server response.
I have browsed around a bit and also played around a bit with node-http-proxy but I am not sure what is the best solution approach. Basically, the SERVER expects HTTPS comms, and preferably I also want secured comms between the PROXY and the CLIENT (since they will exchange user credentials).
I guess my first question is if this is a possible use case:
CLIENT -> (HTTPS_POST_req) -> PROXY -> (HTTPS_POST_req) -> SERVER
SERVER -> (HTTPS_resp) -> PROXY -> (modified_HTTPS_resp) -> CLIENT
I took a quick shot at it using node-http-proxy sample code but got stuck. What I did was to create an http server on localhost and a proxy server that would proxy the request to SERVER.
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
http.createServer(function(req, res) {
console.log('incoming request');
console.log('URL:' + req.url);
console.log('Method:' + req.method);
console.log('Headers:' + JSON.stringify(req.headers));
proxy.web(req, res, { target:'SERVER ADDRESS HERE' });
}).listen(8888, () => {
console.log("Waiting for requests...");
});
From the console I can see the incoming request and also read the url, headers and method but then after a short while I get this:
Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 80
}
I have no idea why something want to connect to localhost on port 80.
Perhaps this approach will never work for HTTPS/SSL traffic? For instance, do I have to setup my own server certificate to do this or can node-http-proxy handle it "under the hood"? Need a bit of help, please.
//Fredrik

Connect Laravel echo from Angular project

I have a Laravel-echo-server with Redis running on my local.
I created a test API endpoint, that emits broadcastable event.
on http://localhost:8000/api/web-socket-test I see the response in echo server CLI.
I set-up laravel-echo auth key and I can get the stat info from server API
http://localhost:6001/apps/APP_ID/status?auth_key=b73a61d0.
The problem is with connecting to echo-server from Angular via ws: protocol.
My connection code is
import {webSocket, WebSocketSubject} from 'rxjs/webSocket';
export class MyComponent implements OnInit, OnDestroy {
myWebSocket: WebSocketSubject<any> = webSocket('ws://127.0.0.1:6001');
ngOnInit() {
this.myWebSocket.subscribe(
msg => console.log('message received: ' + msg),
err => console.log(err),
() => console.log('complete')
);
}
And finally I've got an error: WebSocket connection to 'ws://127.0.0.1:6001/' failed: Connection closed before receiving a handshake response.
How can I establish ws connection?
I believe you want to try connecting using the socket.io client libraries instead of using rxjs raw websockets.
Although it's not immediately clear from the laravel echo server docs, the project title states it's a 'Socket.io server for Laravel Echo'. So I'm assuming you should use the socket.io client libraries for connections.

How to connect to django channel socket?

I followed the tutorial on the official site of the django channels. Everything is fine. But now, how do I connect to the ongoing socket and push message to the group in the server side (i.e. via django) ?
In the tutorial, following line of code in the js opens up a WebSocket connection simply by calling the WebSocket constructor:
var chatSocket = new WebSocket('ws://' + window.location.host + '/ws/chat/' + roomName + '/');
And I want to connect to the same socket in the server side. I tried this:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('ws://127.0.0.1/ws/chat/2', 6379))
but I get error saying
socket.gaierror: [Errno -2] Name or service not known
I am a complete beginner in socket programming, and apologize if there is anything minor that I may have skipped.

Resources