Skip to content
Draft
Show file tree
Hide file tree
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
13 changes: 5 additions & 8 deletions src/Compatibility/Core/src/GTK/GtkPlatformServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,11 @@ public Ticker CreateTicker()

public async Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken)
{
using (var client = new HttpClient())
{
// Do not remove this await otherwise the client will dispose before
// the stream even starts
var result = await StreamWrapper.GetStreamAsync(uri, cancellationToken, client).ConfigureAwait(false);

return result;
}
return await StreamWrapper.GetStreamAsync(
uri,
cancellationToken,
new HttpClient(),
cancellationToken).ConfigureAwait(false);
}

public IIsolatedStorageFile GetUserStoreForApplication()
Expand Down
12 changes: 11 additions & 1 deletion src/Compatibility/Core/src/Windows/StreamImagesourceHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,18 @@ public sealed class StreamImageSourceHandler : IImageSourceHandler
{
if (stream == null)
return null;
var seekableStream = await stream.EnsureSeekableAsync(cancellationToken);
bitmapimage = new BitmapImage();
await bitmapimage.SetSourceAsync(stream.AsRandomAccessStream());
try
{
using var randomAccessStream = seekableStream.AsRandomAccessStream();
await bitmapimage.SetSourceAsync(randomAccessStream);
}
finally
{
if (!ReferenceEquals(stream, seekableStream))
seekableStream.Dispose();
}
}
}

Expand Down
37 changes: 23 additions & 14 deletions src/Compatibility/Core/src/Windows/UriImageSourceHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,31 +44,40 @@ public Task<IconElement> LoadIconElementAsync(ImageSource imagesource, Cancellat
if (imageLoader?.Uri == null)
return null;

Stream streamImage = await ((IStreamImageSource)imageLoader).GetStreamAsync(cancellationToken);
using var streamImage = await ((IStreamImageSource)imageLoader).GetStreamAsync(cancellationToken);

if (streamImage == null || !streamImage.CanRead)
{
return null;
}

using (IRandomAccessStream stream = streamImage.AsRandomAccessStream())
var seekableStream = await streamImage.EnsureSeekableAsync(cancellationToken);
try
{
try
using (IRandomAccessStream stream = seekableStream.AsRandomAccessStream())
{
var image = new BitmapImage();
await image.SetSourceAsync(stream);
return image;
}
catch (Exception ex)
{
Application.Current?.FindMauiContext()?.CreateLogger<UriImageSourceHandler>()?.LogWarning(ex, "Could not load {uri}", imageLoader.Uri);
try
{
var image = new BitmapImage();
await image.SetSourceAsync(stream);
return image;
}
catch (Exception ex)
{
Application.Current?.FindMauiContext()?.CreateLogger<UriImageSourceHandler>()?.LogWarning(ex, "Could not load {uri}", imageLoader.Uri);

// According to https://msdn.microsoft.com/library/windows/apps/jj191522
// this can happen if the image data is bad or the app is close to its
// memory limit
return null;
// According to https://msdn.microsoft.com/library/windows/apps/jj191522
// this can happen if the image data is bad or the app is close to its
// memory limit
return null;
}
}
}
finally
{
if (!ReferenceEquals(streamImage, seekableStream))
seekableStream.Dispose();
}
}
}
}
2 changes: 1 addition & 1 deletion src/Controls/src/Core/Image/ImageSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public partial class StreamImageSource : IStreamImageSource
}

/// <summary>An ImageSource that loads an image from a URI, caching the result.</summary>
public partial class UriImageSource : IUriImageSource, IStreamImageSource
public partial class UriImageSource : IUriImageSource, IStreamImageSourceWithCache
{
}

Expand Down
124 changes: 113 additions & 11 deletions src/Controls/src/Core/StreamWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@

namespace Microsoft.Maui.Controls
{
internal class StreamWrapper : Stream
internal class StreamWrapper : Stream, IImageSourceCacheStream
{
readonly Stream _wrapped;
readonly bool _canCache;
readonly long? _expectedLength;
readonly CancellationToken _cancellationToken;
IDisposable _additionalDisposable;

public StreamWrapper(Stream wrapped)
Expand All @@ -19,14 +22,31 @@ public StreamWrapper(Stream wrapped)
}

public StreamWrapper(Stream wrapped, IDisposable additionalDisposable)
: this(wrapped, additionalDisposable, canCache: true, expectedLength: null, default)
{
}

StreamWrapper(
Stream wrapped,
IDisposable additionalDisposable,
bool canCache,
long? expectedLength,
CancellationToken cancellationToken)
{
if (wrapped == null)
throw new ArgumentNullException(nameof(wrapped));

_wrapped = wrapped;
_additionalDisposable = additionalDisposable;
_canCache = canCache;
_expectedLength = expectedLength;
_cancellationToken = cancellationToken;
}

public bool CanCache => _canCache;

public long? ExpectedLength => _expectedLength;

public override bool CanRead
{
get { return _wrapped.CanRead; }
Expand Down Expand Up @@ -62,7 +82,32 @@ public override void Flush()

public override int Read(byte[] buffer, int offset, int count)
{
return _wrapped.Read(buffer, offset, count);
_cancellationToken.ThrowIfCancellationRequested();
try
{
return _wrapped.Read(buffer, offset, count);
}
catch (Exception ex) when (
(ex is IOException || ex is ObjectDisposedException) &&
_cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException(_cancellationToken);
}
}

public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
_cancellationToken.ThrowIfCancellationRequested();
try
{
return await _wrapped.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (
(ex is IOException || ex is ObjectDisposedException) &&
_cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException(_cancellationToken);
}
}

public override long Seek(long offset, SeekOrigin origin)
Expand Down Expand Up @@ -90,20 +135,77 @@ protected override void Dispose(bool disposing)
base.Dispose(disposing);
}

public static async Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken, HttpClient client)
public static async Task<Stream> GetStreamAsync(
Uri uri,
CancellationToken cancellationToken,
HttpClient client,
CancellationToken responseCancellationToken = default)
{
var response = await client.GetAsync(uri, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
HttpResponseMessage response = null;
try
{
response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[major] Cross-Platform Behavioral Consistency — Switching to HttpCompletionOption.ResponseHeadersRead changes the contract of the stream returned by StreamWrapper.GetStreamAsync on every platform: it was a fully-buffered, seekable stream (default HttpCompletionOption.ResponseContentRead reads the body before GetAsync completes) and is now an unbuffered, non-seekable live network stream. The PR adapts only the Windows consumers (EnsureSeekableAsync added to UriImageSourceService.Windows.cs, StreamImageSourceService.Windows.cs, and the two compatibility handlers). The Android consumer src/Core/src/ImageSources/StreamImageSourceService/StreamImageSourceService.Android.cs (lines 25 and 62) takes the same IStreamImageSource.GetStreamAsync result and was not audited or adapted, and neither was Tizen. Any consumer that relied on CanSeek, Length, or on re-reading from position 0 now silently changes behavior on those platforms. Please state which non-Windows consumers were checked, or add the equivalent seekable-stream guarantee at the source.

if (!response.IsSuccessStatusCode)
{
Application.Current?.FindMauiContext()?.CreateLogger<StreamWrapper>()?
.LogWarning("Could not retrieve {Uri}, status code {StatusCode}", uri, response.StatusCode);

response.Dispose();
response = null;
client.Dispose();
return null;
}

var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
// The response and client own the live network stream and must outlive the caller's reads.
var owner = new HttpResponseOwner(response, client, responseCancellationToken);
response = null;
return new StreamWrapper(
stream,
owner,
canCache: owner.Response.Headers.CacheControl?.NoStore != true,
expectedLength: owner.Response.Content.Headers.ContentLength,
responseCancellationToken);
}
catch
{
Application.Current?.FindMauiContext()?.CreateLogger<StreamWrapper>()?
.LogWarning("Could not retrieve {Uri}, status code {StatusCode}", uri, response.StatusCode);
response?.Dispose();
client.Dispose();
throw;
}
}

sealed class HttpResponseOwner : IDisposable
{
readonly HttpClient _client;
readonly CancellationTokenRegistration _cancellationRegistration;
int _disposed;

return null;
public HttpResponseOwner(HttpResponseMessage response, HttpClient client, CancellationToken cancellationToken)
{
Response = response;
_client = client;
_cancellationRegistration = cancellationToken.Register(
static state => ((HttpResponseOwner)state).DisposeResources(),
this);
}

// the HttpResponseMessage needs to be disposed of after the calling code is done with the stream
// otherwise the stream may get disposed before the caller can use it
return new StreamWrapper(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), response);
public HttpResponseMessage Response { get; }

public void Dispose()
{
_cancellationRegistration.Dispose();
DisposeResources();
}

void DisposeResources()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
return;

Response.Dispose();
_client.Dispose();
}
}
}
}
49 changes: 25 additions & 24 deletions src/Controls/src/Core/UriImageSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

namespace Microsoft.Maui.Controls
{
// TODO: CACHING https://github.com/dotnet/runtime/issues/52332
/// <summary>An <see cref="ImageSource"/> that loads an image from a URI, with caching support.</summary>
public sealed partial class UriImageSource : ImageSource, IStreamImageSource
{
Expand Down Expand Up @@ -63,7 +62,7 @@ async Task<Stream> IStreamImageSource.GetStreamAsync(CancellationToken userToken

try
{
stream = await GetStreamAsync(Uri, CancellationTokenSource.Token);
stream = await GetStreamAsync(Uri, CancellationTokenSource.Token, userToken);
await OnLoadingCompleted(false);
}
catch (OperationCanceledException)
Expand All @@ -86,40 +85,42 @@ public override string ToString()
return $"Uri: {Uri}";
}

async Task<Stream> GetStreamAsync(Uri uri, CancellationToken cancellationToken = default(CancellationToken))
async Task<Stream> GetStreamAsync(
Uri uri,
CancellationToken cancellationToken,
CancellationToken responseCancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

Stream stream = null;

if (CachingEnabled)
{
// TODO: CACHING https://github.com/dotnet/runtime/issues/52332

// var key = GetKey();
// var cached = TryGetFromCache(key, out stream)
if (stream is null)
stream = await DownloadStreamAsync(uri, cancellationToken).ConfigureAwait(false);
// if (!cached)
// Cache(key, stream)
}
else
{
stream = await DownloadStreamAsync(uri, cancellationToken).ConfigureAwait(false);
return await UriImageSourceCache.GetStreamAsync(
uri,
CacheValidity,
token => DownloadStreamAsync(uri, token, responseCancellationToken),
ex => Application.Current?.FindMauiContext()?.CreateLogger<UriImageSource>()?.LogWarning(ex, "Unable to cache image URI '{Uri}'.", uri),
cancellationToken).ConfigureAwait(false);
}

return stream;
return await DownloadStreamAsync(uri, cancellationToken, responseCancellationToken).ConfigureAwait(false);
}

async Task<Stream> DownloadStreamAsync(Uri uri, CancellationToken cancellationToken)
async Task<Stream> DownloadStreamAsync(
Uri uri,
CancellationToken cancellationToken,
CancellationToken responseCancellationToken)
{
try
{
using var client = new HttpClient();

// Do not remove this await otherwise the client will dispose before
// the stream even starts
return await StreamWrapper.GetStreamAsync(uri, cancellationToken, client).ConfigureAwait(false);
return await StreamWrapper.GetStreamAsync(
uri,
cancellationToken,
new HttpClient(),
responseCancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
Expand Down
Loading
Loading