Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #112 and cleans up readers and stream #114

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using System.Buffers;
using System.IO;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Expand All @@ -18,42 +17,26 @@ public class JsonServerlessProtocol : IServerlessProtocol

public bool TryParseMessage(ref ReadOnlySequence<byte> input, out ServerlessMessage message)
{
var textReader = new JsonTextReader(new StreamReader(new ReadOnlySequenceStream(input)));
var jObject = JObject.Load(textReader);
if (jObject.TryGetValue(TypePropertyName, StringComparison.OrdinalIgnoreCase, out var token))
{
var type = token.Value<int>();
switch (type)
{
case ServerlessProtocolConstants.InvocationMessageType:
message = SafeParseMessage<InvocationMessage>(jObject);
break;
case ServerlessProtocolConstants.OpenConnectionMessageType:
message = SafeParseMessage<OpenConnectionMessage>(jObject);
break;
case ServerlessProtocolConstants.CloseConnectionMessageType:
message = SafeParseMessage<CloseConnectionMessage>(jObject);
break;
default:
message = null;
break;
}
return message != null;
}
message = null;
return false;
}
using var inputStream = new ReadOnlySequenceStream(input);
using var streamReader = new StreamReader(inputStream);
using var textReader = new JsonTextReader(streamReader);

private ServerlessMessage SafeParseMessage<T>(JObject jObject) where T : ServerlessMessage
{
try
{
return jObject.ToObject<T>();
}
catch
{
return null;
var jObject = JObject.Load(textReader);
if (jObject.TryGetValue(TypePropertyName, StringComparison.OrdinalIgnoreCase, out var token)
&& token.Type == JTokenType.Integer)
message = token.Value<int>() switch
{
ServerlessProtocolConstants.InvocationMessageType => jObject.ToObject<InvocationMessage>(),
ServerlessProtocolConstants.OpenConnectionMessageType => jObject.ToObject<OpenConnectionMessage>(),
ServerlessProtocolConstants.CloseConnectionMessageType => jObject.ToObject<CloseConnectionMessage>(),
_ => null,
};
}
catch { }
return message != null;
}
}
}