NullReferenceException in StrongGrid.Utilities.Extensions.GetEncoding
We've started getting this error, simultaneously across all our systems, some of which are running on 0.49.1 and some on 0.50.0. This started around 11:55 am PDT.
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: ERROR SendGridService - SendEmail | Error sending email [To:"TestEmailOverride" <[email protected]>, [email protected], [email protected], Cc:, Subject:[Test] Swyfft is sending a building inspector to 2302 Hathcox St, Mobile AL 36617 for policy CB766709-00 | Exception: (AggregateException) One or more errors occurred.;
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: (
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: (NullReferenceException) Object reference not set to an instance of an object. ( at StrongGrid.Utilities.Extensions.GetEncoding(HttpContent content, Encoding defaultEncoding)
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: at StrongGrid.Utilities.Extensions.<ReadAsStringAsync>d__3.MoveNext())
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: )
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: ( at StrongGrid.Utilities.DiagnosticHandler.OnResponse(IResponse response, Boolean httpErrorAsException)
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: at Pathoschild.Http.Client.Internal.Request.<Execute>d__46.MoveNext()
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: at StrongGrid.Resources.Mail.<SendAsync>d__10.MoveNext()
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: at Swyfft.Services.SendGrid.SendGridProxy.<>c__DisplayClass11_0.<<SendEmail>b__0>d.MoveNext() in C:\source\swyfft\Swyfft.Services\SendGrid\SendGridProxy.cs:line 183
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: at Swyfft.Common.Helpers.NumberHelpers.<RetriesAsync>d__28.MoveNext() in C:\source\swyfft\Swyfft.Common\Helpers\NumberHelpers.cs:line 386
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: at Swyfft.Services.SendGrid.SendGridProxy.<SendEmail>d__11.MoveNext() in C:\source\swyfft\Swyfft.Services\SendGrid\SendGridProxy.cs:line 178
Mar 26 13:24:06 DESKTOP-LLC082N Web.AT: at Swyfft.Services.SendGrid.SendGridService.<SendEmail>d__26.MoveNext() in C:\source\swyfft\Swyfft.Services\SendGrid\SendGridService.cs:line 535)
That leads me to believe that something is wrong (or at least different) in the SendGrid API, but StrongGrid should still handle the error better than just throwing a NullReferenceException.
Any additional information you can provide to reproduce this error? I have run all the integration tests and as far as I can tell they all complete as expected.
Having said that, based on the error log you provided I will guess that the problem is on this line in the GetEncoding method:
var charset = content.Headers.ContentType.CharSet;
In your scenario, probably the content of the response is null or maybe the headers are null? That's just a guess on my part but I would find that a very unusual situation. But I could add more defensive coding to avoid a problem if the content is null no matter if I find it unusual for the content (or the headers) to be null.
I've got a corresponding ticket open with SendGrid, and (of course) they're pointing the finger back at you guys. And yeah, the NullReferenceException is clearly in the StrongGrid code. But I'm convinced that something is triggering the SendGrid API to stop responding in a correct manner: whether that's completely on their side, or some configuration issue, I have no idea.
Unfortunately, I'm not sure how to easily debug down into the StrongGrid code from within our app. I've tried stepping down into your code, but VS doesn't seem to want to do that. I suppose I could get your source, build it on my machine, and then reference those assemblies...? maybe? Open to suggestions on how to do that.
FWIW, this is the last message I sent to SendGrid:
What primarily leads us to believe that the issue is on your side is that the error is utterly random, and occurs in code that's been working fine for years. When we send emails, we push them into a queue, and from the queue, we submit them to SendGrid. Up until today around 11:00 am, this has worked perfectly. But at 11:00 am, all of our test machines, all of our development machines, all of our various test instances, and our production machines, all started experiencing the same problem, namely, that some (not all) of the emails we submit out of the queue fail to send. Yes, the presenting error is a NullReferenceException, and that's on StrongGrid, but precisely that same code was working just fine until 11:00 am, when it started failing simultaneously on all of our systems (some of them running code which hadn't been touched for a good week). But not all of the emails fail - just some of them. And when we resubmit the emails to the queue, sometimes the exact same email is passed successfully to SendGrid. And then - surprisingly - all emails will suddenly start working, and will work correctly for a good half hour or so, before the issue starts up again.
I know that you don't support third-party code, and can't, but there's no plausible bug within StrongGrid which could cause that, unless the SendGrid API behavior suddenly changed. The more that I've looked at this, the more convinced I am that SendGrid's API is the underlying cause.
I encourage you to send this email and the behavior we're seeing to the highest level support tech that you have access to.
We are seeing the same thing since roughly 9 PM (UTC) yesterday. I would say that it's definitely something going on with SendGrid as re-sending the failed emails worked flawlessly only 10 minutes later. Everything was fine all night and then it started throwing the same exception at 11:29 UTC today. Thanks for looking into this!
Give me a few minutes: I'm putting together a few thoughts to help investigating
Here are some suggestions to help investigating:
- Use a local proxy which can display every HTTP request and response. My favorite is Fiddler. This will allow you to eyeball the request/response causing the problem and you can even save it and send it to me. Once you have installed Fiddler and it's running, you can configure StrongGrid to forward every request through this proxy like so:
var proxy = new WebProxy("http://localhost:8888");
var apiKey = "<... your api key ...>";
var client = new Client(apiKey, proxy);
-
StrongGrid has built-in support for NLog, Log4Net, Serilog and Loupe. So, if you use any of these logging frameworks, you simply need to configure them to "Debug" level and you should automatically see logging entries generated by StrongGrid.
-
You could display every HTTP request/response to the console. It can be overwhelming if you are sending a lot of request though. You configure StrongGrid to log to the console like so:
LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
The code for the console log provider is available here.
@Jericho Awesome thanks! I switched to LogLevel: Debug (using Serilog) in production but it seems that I only get log entries for successfully sent email (where status from SendGrid is 202 Accepted). Right now it seems to work (again, it's working on and off...) so I'm getting 202 Accepted also on localhost using Fiddler. Response log from Fiddler seems to be OK:
HTTP/1.1 202 Accepted
Server: nginx
Date: Wed, 27 Mar 2019 14:01:44 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 0
Connection: keep-alive
X-Message-Id: <removed>
Access-Control-Allow-Origin: https://sendgrid.api-docs.io
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
Access-Control-Max-Age: 600
X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
I'll try it a couple of more times and see if anything comes up.
Thanks for investigating so quickly!
StrongGrid logs successful responses (i.e. HTTP 202) as well as exceptions (such as HTTP 400 for example). However, it just occurred to me that it won't log anything if something goes wrong when inspecting the response from SendGrid which, according to the stack trace provided by @smithkl42, is exactly what is happening. The exception log he provided shows that the problem occurs:
at StrongGrid.Utilities.DiagnosticHandler.OnResponse(IResponse response, Boolean httpErrorAsException)
which is where we inspect and log the response.
All this to say that my suggestion to look at the log won't help us in this case.
Hold on, I am in the process of publishing a hotfix with improved logging. It will log even when we fail to inspect the unusual response from SendGrid.
Seems to be very sporadic. 15:28 local time it worked fine. 15:43 it stopped again.
Beta version of 0.50.1 available on my MyGet feed: https://www.myget.org/feed/Packages/jericho
Pushing 0.50.1 to Nuget now. Should be available shortly.
@Jericho - Thanks so much for getting the hotfix out so quickly. I've tested the fix locally, and rolled it out to our production servers. It definitely seems to stop the bleeding, in that it catches the error in the diagnostics code, rather than throwing it up to the caller. However, the error itself is still happening, and is getting logged:
Mar 27 09:47:07 RD0003FF6228A8 Web.Prod: 10680_3515771436 | ERROR | StrongGrid.Utilities.DiagnosticHandler | An exception occured when inspecting the response from SendGrid
Mar 27 09:47:07 RD0003FF6228A8 Web.Prod: System.NullReferenceException: Object reference not set to an instance of an object.
Mar 27 09:47:07 RD0003FF6228A8 Web.Prod: at StrongGrid.Utilities.Extensions.GetEncoding(HttpContent content, Encoding defaultEncoding)
Mar 27 09:47:07 RD0003FF6228A8 Web.Prod: at StrongGrid.Utilities.Extensions.<ReadAsStringAsync>d__3.MoveNext()
Mar 27 09:47:07 RD0003FF6228A8 Web.Prod: --- End of stack trace from previous location where exception was thrown ---
Mar 27 09:47:07 RD0003FF6228A8 Web.Prod: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
Mar 27 09:47:07 RD0003FF6228A8 Web.Prod: at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Mar 27 09:47:07 RD0003FF6228A8 Web.Prod: at StrongGrid.Utilities.DiagnosticHandler.OnResponse(IResponse response, Boolean httpErrorAsException)
Hotfix 0.50.2 on its way with 3 improvements:
- Additional logging to help us understand why this problem is happening in the first place
- Ignore exceptions thrown when logging
- Improve GetEncoding so it does not throw exceptions no matter how unusual the HTTP response received from SendGrid
Thanks again for fixing this. We're still at 0.50.1 out in prod, and are still logging the error there, but we've pushed out 0.50.2 to our test systems, and the error has gone away entirely on those.
@Jericho Thanks for the hotfix! It seems to have fixed the problem for us as well.
Before upgrading (causing null pointer)
HTTP/1.1 202 Accepted
Server: nginx
Date: Thu, 28 Mar 2019 07:40:04 GMT
Content-Length: 0
Connection: keep-alive
X-Message-Id: <removed>
Access-Control-Allow-Origin: https://sendgrid.api-docs.io
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
Access-Control-Max-Age: 600
X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
After upgrading (no null pointer):
Response: StatusCode: 202, ReasonPhrase: 'Accepted', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: keep-alive
X-Message-Id: <removed>
Access-Control-Allow-Origin: https://sendgrid.api-docs.io
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
Access-Control-Max-Age: 600
X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
Date: Thu, 28 Mar 2019 07:43:13 GMT
Server: nginx
Content-Length: 0
}
Response.Content is null: False
Response.Content.Headers is null: False
Response.Content.Headers.ContentType is null: True
Response.Content.Headers.ContentType.CharSet: <NULL>
Response.Content:
Can confirm that the issue is fixed in our PROD environment using 0.50.2. Well done @Jericho! 👍
thanks for quick fix, any information from SendGrid what happened?
@pajics No official info afaik but they removed the Content-Type header in all responses and as StrongGrid reads the Content-Type to determine response encoding we got a null pointer. It seems like SendGrid rolled this change out gradually as we got bursts of exceptions.
@smatsson is right: it looks like SendGrid has removed the Content-Type from their response when invoking `POST /mail/send'. As far as I can tell, all other API endpoints in SendGrid's API are unaffected.
In case anybody is interested, here's the reason why StrongGrid reads the Content-Type:
Back in 2016, I discovered that some (but not all) of SendGrid's API calls would return a Content-Type with a typo. Specifically, I observed that I would sometimes get utf8 instead of the expected utf-8 (notice the missing dash). This was causing Microsoft's HttpClient to be unable to determine the appropriate encoding and therefore throw an exception when I would try to get the content of the response by invoking ReadAsStringAsync. Of course I opened a support case with SendGrid to report this issue but I was told that "most" programming languages are able to handle a misspelled content type and therefore they would not fix this issue since it only affected C# (and presumably all other .net languages). By the way, I was not the only one who noticed this problem: there are two issues (here and here) that were created in late 2016 and are still open, as of this writing. So the solution I came up with was to read the charset and attempt to determine the proper encoding and to fall back on UTF8 if the charset was not recognized. But I guess I did not account for the possibility of the Content-Type to be missing outright!
Anyway, I'm glad we figured it out and we have a solution that overcomes this issue but it would have been great for SendGrid to give us a heads-up that they were making this change and avoid this whole situation.
Thanks to @smithkl42 and @smatsson for reporting this issue and helping me investigate.