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

Implement asynchronous support in RawValueWriter #2121

Merged
merged 1 commit into from
Jul 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
89 changes: 83 additions & 6 deletions src/Microsoft.OData.Core/RawValueWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ namespace Microsoft.OData
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.OData.Json;
using Microsoft.Spatial;

Expand Down Expand Up @@ -119,17 +119,15 @@ internal void WriteRawValue(object value)
{
Debug.Assert(!(value is byte[]), "!(value is byte[])");

string valueAsString;
ODataEnumValue enumValue = value as ODataEnumValue;
if (enumValue != null)
if (value is ODataEnumValue enumValue)
{
this.textWriter.Write(enumValue.Value);
}
else if (value is Geometry || value is Geography)
{
PrimitiveConverter.Instance.WriteJsonLight(value, jsonWriter);
}
else if (ODataRawValueUtils.TryConvertPrimitiveToString(value, out valueAsString))
else if (ODataRawValueUtils.TryConvertPrimitiveToString(value, out string valueAsString))
{
this.textWriter.Write(valueAsString);
}
Expand All @@ -154,6 +152,85 @@ internal void Flush()
}
}

/// <summary>
/// Asynchronously start writing a raw output. This should only be called once.
/// </summary>
/// <returns>A task that represents the asynchronous write operation.</returns>
internal async Task StartAsync()
{
if (this.settings.HasJsonPaddingFunction())
{
await this.textWriter.WriteAsync(this.settings.JsonPCallback)
.ConfigureAwait(false);
await this.textWriter.WriteAsync(JsonConstants.StartPaddingFunctionScope)
.ConfigureAwait(false);
}
}

/// <summary>
/// Asynchronously end the writing of a raw output. This should be the last thing called.
/// </summary>
/// <returns>A task that represents the asynchronous write operation.</returns>
internal Task EndAsync()
{
if (this.settings.HasJsonPaddingFunction())
{
return this.textWriter.WriteAsync(JsonConstants.EndPaddingFunctionScope);
g2mula marked this conversation as resolved.
Show resolved Hide resolved
}

return TaskUtils.CompletedTask;
gathogojr marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
/// Asynchronously converts the specified <paramref name="value"/> into its raw format and writes it to the output.
/// The value has to be of enumeration or primitive type. Only one WriteRawValue call should be made before this object gets disposed.
/// </summary>
/// <param name="value">The (non-binary) value to write.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
/// <remarks>We do not accept binary values here; WriteBinaryValue should be used for binary data.</remarks>
/// <returns>A task that represents the asynchronous write operation.</returns>
internal Task WriteRawValueAsync(object value)
{
Debug.Assert(!(value is byte[]), "!(value is byte[])");

if (value is ODataEnumValue enumValue)
{
return this.textWriter.WriteAsync(enumValue.Value);
}

if (value is Geometry || value is Geography)
{
return TaskUtils.GetTaskForSynchronousOperation(
() => PrimitiveConverter.Instance.WriteJsonLight(value, jsonWriter));
gathogojr marked this conversation as resolved.
Show resolved Hide resolved
}

if (ODataRawValueUtils.TryConvertPrimitiveToString(value, out string valueAsString))
{
return this.textWriter.WriteAsync(valueAsString);
}

// Value is neither enum nor primitive
return TaskUtils.GetFaultedTask(
new ODataException(Strings.ODataUtils_CannotConvertValueToRawString(value.GetType().FullName)));
}

/// <summary>
/// Asynchronously flushes the RawValueWriter.
/// The call gets pushed to the TextWriter (if there is one). In production code, this is StreamWriter.Flush, which turns into Stream.Flush.
/// In the synchronous case the underlying stream is the message stream itself, which will then Flush as well.
/// In the async case the underlying stream is the async buffered stream, which ignores Flush call.
/// </summary>
/// <returns>A task that represents the asynchronous flush operation.</returns>
internal Task FlushAsync()
{
if (this.TextWriter != null)
{
return this.TextWriter.FlushAsync();
}

return TaskUtils.CompletedTask;
}

/// <summary>
/// Initialized a new text writer over the message payload stream.
/// </summary>
Expand All @@ -173,7 +250,7 @@ private void InitializeTextWriter()
{
nonDisposingStream = MessageStreamWrapper.CreateNonDisposingStream(this.stream);
}

this.textWriter = new StreamWriter(nonDisposingStream, this.encoding) { NewLine = this.settings.MultipartNewLine };
this.jsonWriter = new JsonWriter(this.textWriter, isIeee754Compatible: false);
}
Expand Down
115 changes: 115 additions & 0 deletions test/FunctionalTests/Microsoft.OData.Core.Tests/RawValueWriterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
// </copyright>
//---------------------------------------------------------------------

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.OData.Edm;
using Microsoft.Spatial;
using Xunit;
Expand Down Expand Up @@ -121,12 +123,125 @@ public void WriteRawValueWritesGeometryValue()
Assert.Equal(@"{""type"":""Point"",""coordinates"":[1.2,3.16],""crs"":{""type"":""name"",""properties"":{""name"":""EPSG:0""}}}", this.StreamAsString(target));
}

[Fact]
public async Task RawValueWriterStartAsync()
{
var result = await SetupRawValueWriterAndRunTestAsync(
(rawValueWriter) => rawValueWriter.StartAsync());

Assert.Equal("", result);
}

[Fact]
public async Task RawValueWriterStartAsyncWithJsonPadding()
{
this.settings.JsonPCallback = "foo";

var result = await SetupRawValueWriterAndRunTestAsync(
(rawValueWriter) => rawValueWriter.StartAsync());

Assert.Equal("foo(", result);
}

[Fact]
public async Task RawValueWriterEndAsync()
{
var result = await SetupRawValueWriterAndRunTestAsync(
(rawValueWriter) => rawValueWriter.EndAsync());

Assert.Equal("", result);
}

[Fact]
public async Task RawValueWriterEndAsyncWithJsonPadding()
{
this.settings.JsonPCallback = "foo";

var result = await SetupRawValueWriterAndRunTestAsync(
(rawValueWriter) => rawValueWriter.EndAsync());

Assert.Equal(")", result);
}

[Fact]
public async Task WriteRawStringValueAsync()
{
var value = "foobar";

var result = await SetupRawValueWriterAndRunTestAsync(
(rawValueWriter) => rawValueWriter.WriteRawValueAsync(value));

Assert.Equal("foobar", result);
}

[Fact]
public async Task WriteRawDateValueAsync()
{
var value = new Date(2014, 9, 18);

var result = await SetupRawValueWriterAndRunTestAsync(
(rawValueWriter) => rawValueWriter.WriteRawValueAsync(value));

Assert.Equal("2014-09-18", result);
}

[Fact]
public async Task WriteRawTimeOfDayValueAsync()
{
var value = new TimeOfDay(9, 47, 5, 900);

var result = await SetupRawValueWriterAndRunTestAsync(
(rawValueWriter) => rawValueWriter.WriteRawValueAsync(value));

Assert.Equal("09:47:05.9000000", result);
}

[Fact]
public async Task WriteRawGeographyValueAsync()
{
var value = GeographyPoint.Create(22.2, 22.2);

var result = await SetupRawValueWriterAndRunTestAsync(
(rawValueWriter) => rawValueWriter.WriteRawValueAsync(value));

Assert.Equal(
"{\"type\":\"Point\",\"coordinates\":[22.2,22.2],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:4326\"}}}",
result);
}

[Fact]
public async Task WriteRawGeometryValuesync()
{
var value = GeometryPoint.Create(1.2, 3.16);

var result = await SetupRawValueWriterAndRunTestAsync(
(rawValueWriter) => rawValueWriter.WriteRawValueAsync(value));

Assert.Equal(
"{\"type\":\"Point\",\"coordinates\":[1.2,3.16],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:0\"}}}",
result);
}

private async Task<string> SetupRawValueWriterAndRunTestAsync(Func<RawValueWriter, Task> func)
{
var rawValueWriter = new RawValueWriter(this.settings, this.stream, new UTF32Encoding());

await func(rawValueWriter);

await rawValueWriter.FlushAsync();
await this.stream.FlushAsync();

this.stream.Position = 0;
return await new StreamReader(this.stream).ReadToEndAsync();
}

private string StreamAsString(RawValueWriter target)
{
if (target.TextWriter != null)
{
target.TextWriter.Flush();
}

this.stream.Flush();
this.stream.Position = 0;
return new StreamReader(this.stream).ReadToEnd();
Expand Down