Skip to content

Commit

Permalink
Remove Response and specify the type needed to avoid extra allocation…
Browse files Browse the repository at this point in the history
… coming from DownloadHandler.Text (#314)

## Description

-   Briefly describe what this change will do
There is an issue with avatar loader when cache is disabled this is
meant to fix it by avoiding the call to downloadHandler.Text when
attempting to push it.

## How to Test

- Attempt to load avatar with caching disable and observe a spike in
profiler
-  With this PR observe no spike is happening.
  • Loading branch information
abaza121 authored Aug 29, 2024
1 parent 2879f7a commit 72b081e
Show file tree
Hide file tree
Showing 13 changed files with 55 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public static void ThrowIfError(this IResponse response)
}
}

public static void ThrowIfError(this Response response)
public static void ThrowIfError(this ResponseText response)
{
if (!response.IsSuccess)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public AssetAPIRequests(string appId)

var url = BuildAssetListUrl(type, limit, pageNumber, AuthManager.UserSession.Id, appId, gender == OutfitGender.Masculine ? "male" : "female");

var response = await authorizedRequest.SendRequest<Response>(new RequestData
var response = await authorizedRequest.SendRequest<ResponseText>(new RequestData
{
Url = url,
Method = HttpMethod.GET
Expand Down
10 changes: 5 additions & 5 deletions Runtime/AvatarCreator/Scripts/WebRequests/AuthAPIRequests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public AuthAPIRequests(string domain)

public async Task<UserSession> LoginAsAnonymous(CancellationToken cancellationToken = default)
{
var response = await webRequestDispatcher.SendRequest<Response>($"{rpmAuthBaseUrl}/users", HttpMethod.POST, headers, ctx:cancellationToken);
var response = await webRequestDispatcher.SendRequest<ResponseText>($"{rpmAuthBaseUrl}/users", HttpMethod.POST, headers, ctx:cancellationToken);
response.ThrowIfError();

var data = AuthDataConverter.ParseResponse(response.Text);
Expand All @@ -60,7 +60,7 @@ public async Task SendCodeToEmail(string email, string userId = "",CancellationT

var payload = AuthDataConverter.CreatePayload(data);

var response = await webRequestDispatcher.SendRequest<Response>($"{rpmAuthBaseUrl}/auth/start", HttpMethod.POST, headers, payload, ctx:cancellationToken);
var response = await webRequestDispatcher.SendRequest<ResponseText>($"{rpmAuthBaseUrl}/auth/start", HttpMethod.POST, headers, payload, ctx:cancellationToken);
response.ThrowIfError();
}

Expand All @@ -76,7 +76,7 @@ public async Task<UserSession> LoginWithCode(string code, string userIdToMerge =
}
var payload = AuthDataConverter.CreatePayload(body);

var response = await webRequestDispatcher.SendRequest<Response>($"{rpmAuthBaseUrl}/auth/login", HttpMethod.POST, headers, payload, ctx:cancellationToken);
var response = await webRequestDispatcher.SendRequest<ResponseText>($"{rpmAuthBaseUrl}/auth/login", HttpMethod.POST, headers, payload, ctx:cancellationToken);
response.ThrowIfError();

var data = AuthDataConverter.ParseResponse(response.Text);
Expand All @@ -93,7 +93,7 @@ public async Task Signup(string email, string userId, CancellationToken cancella
};

var payload = AuthDataConverter.CreatePayload(data);
var response = await webRequestDispatcher.SendRequest<Response>($"{rpmAuthBaseUrl}/auth/start", HttpMethod.POST, headers, payload, ctx:cancellationToken);
var response = await webRequestDispatcher.SendRequest<ResponseText>($"{rpmAuthBaseUrl}/auth/start", HttpMethod.POST, headers, payload, ctx:cancellationToken);
response.ThrowIfError();
}

Expand Down Expand Up @@ -122,7 +122,7 @@ private async Task<JToken> RefreshRequest(string token, string refreshToken, Can
{ AuthConstants.REFRESH_TOKEN, refreshToken }
});

var response = await webRequestDispatcher.SendRequest<Response>(url, HttpMethod.POST, headers, payload, ctx:cancellationToken);
var response = await webRequestDispatcher.SendRequest<ResponseText>(url, HttpMethod.POST, headers, payload, ctx:cancellationToken);
response.ThrowIfError();

return AuthDataConverter.ParseResponse(response.Text);
Expand Down
24 changes: 12 additions & 12 deletions Runtime/AvatarCreator/Scripts/WebRequests/AvatarAPIRequests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public AvatarAPIRequests(CancellationToken ctx = default)

public async Task<List<UserAvatarResponse>> GetUserAvatars(string userId)
{
var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = $"{RPM_AVATAR_V1_BASE_URL}/?userId={userId}&select={ID},{PARTNER},{DATA}.{BODY_TYPE}",
Expand All @@ -58,7 +58,7 @@ public async Task<List<UserAvatarResponse>> GetUserAvatars(string userId)

public async Task<List<AvatarTemplateData>> GetAvatarTemplates()
{
var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = $"{RPM_AVATAR_V2_BASE_URL}/templates?{BODY_TYPE}={CoreSettingsHandler.CoreSettings.BodyType.GetDescription()}",
Expand All @@ -83,7 +83,7 @@ public async Task<AvatarProperties> CreateFromTemplateAvatar(string templateId,

var payload = AuthDataConverter.CreatePayload(payloadData);

var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = $"{RPM_AVATAR_V2_BASE_URL}/templates/{templateId}",
Expand All @@ -109,7 +109,7 @@ public async Task<AssetColor[]> GetAvatarColors(string avatarId, AssetType asset
colorParameters = "skin,beard,hair,eyebrow";
}

var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = $"{RPM_AVATAR_V2_BASE_URL}/{avatarId}/colors?type={colorParameters}",
Expand All @@ -130,7 +130,7 @@ public async Task<AvatarProperties> GetAvatarMetadata(string avatarId, bool isDr
if (isDraft)
url += "preview=true";

var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = url,
Expand All @@ -148,7 +148,7 @@ public async Task<AvatarProperties> GetAvatarMetadata(string avatarId, bool isDr

public async Task<AvatarProperties> CreateNewAvatar(AvatarProperties avatarProperties)
{
var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = RPM_AVATAR_V2_BASE_URL,
Expand All @@ -175,7 +175,7 @@ public async Task<byte[]> GetAvatar(string avatarId, bool isPreview = false, str
if (isPreview)
url += "preview=true";

var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseData>(
new RequestData
{
Url = url,
Expand All @@ -192,7 +192,7 @@ public async Task<AvatarProperties> GetAvatarProperties(string avatarId)
ValidateAvatarId(avatarId);
var url = $"{RPM_AVATAR_V2_BASE_URL}/{avatarId}.json?";

var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = url,
Expand All @@ -211,7 +211,7 @@ public async Task<byte[]> UpdateAvatar(string avatarId, AvatarProperties avatarP
ValidateAvatarId(avatarId);
var url = $"{RPM_AVATAR_V2_BASE_URL}/{avatarId}?responseType=glb&{parameters}";

var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseData>(
new RequestData
{
Url = url,
Expand All @@ -228,7 +228,7 @@ public async Task PrecompileAvatar(string avatarId, PrecompileData precompileDat
ValidateAvatarId(avatarId);
var json = JsonConvert.SerializeObject(precompileData);

var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = $"{RPM_AVATAR_V2_BASE_URL}/{avatarId}/precompile?{parameters ?? string.Empty}",
Expand All @@ -243,7 +243,7 @@ public async Task PrecompileAvatar(string avatarId, PrecompileData precompileDat
public async Task<string> SaveAvatar(string avatarId)
{
ValidateAvatarId(avatarId);
var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = $"{RPM_AVATAR_V2_BASE_URL}/{avatarId}",
Expand All @@ -263,7 +263,7 @@ public async Task DeleteAvatar(string avatarId, bool isDraft = false)
if (isDraft)
url += "draft";

var response = await authorizedRequest.SendRequest<Response>(
var response = await authorizedRequest.SendRequest<ResponseText>(
new RequestData
{
Url = url,
Expand Down
2 changes: 1 addition & 1 deletion Runtime/Core/Scripts/Analytics/AmplitudeEventLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ private static async Task Dispatch(string url, string payload)
}

var webRequestDispatcher = new WebRequestDispatcher();
var response = await webRequestDispatcher.SendRequest<Response>(url, HttpMethod.POST, CommonHeaders.GetHeadersWithAppId(), payload);
var response = await webRequestDispatcher.SendRequest<ResponseText>(url, HttpMethod.POST, CommonHeaders.GetHeadersWithAppId(), payload);

if (!response.IsSuccess)
{
Expand Down
3 changes: 0 additions & 3 deletions Runtime/Core/Scripts/Data/Response.cs.meta

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

namespace ReadyPlayerMe.Core
{
public class Response : IResponse
public class ResponseData : IResponse
{
public string Text;
public byte[] Data;

public bool IsSuccess { get; set; }
Expand All @@ -18,7 +17,6 @@ public void Parse(UnityWebRequest request)
return;
}

Text = request.downloadHandler.text;
Data = request.downloadHandler.data;
}
}
Expand Down
2 changes: 2 additions & 0 deletions Runtime/Core/Scripts/Data/ResponseData.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions Runtime/Core/Scripts/Data/ResponseText.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using UnityEngine.Networking;

namespace ReadyPlayerMe.Core
{
public class ResponseText : IResponse
{
public string Text;

public bool IsSuccess { get; set; }
public string Error { get; set; }
public long ResponseCode { get; set; }

public void Parse(UnityWebRequest request)
{
if (request.downloadHandler is DownloadHandlerFile)
{
return;
}

Text = request.downloadHandler.text;
}
}
}
2 changes: 2 additions & 0 deletions Runtime/Core/Scripts/Data/ResponseText.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions Runtime/Core/Scripts/Extensions/WebRequestDispatcherExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ public static class WebRequestDispatcherExtension

/// <summary>
/// This asynchronous method makes GET request to the <paramref name="url" /> and returns the data in the
/// <see cref="Response" />.
/// <see cref="IResponse" />.
/// </summary>
/// <param name="webRequestDispatcher">WebRequestDispatcher object</param>
/// <param name="url">The URL to make the <see cref="UnityWebRequest" /> to.</param>
/// <param name="token">Can be used to cancel the operation.</param>
/// <param name="timeout">The number of seconds to wait for the WebRequest to finish before aborting.</param>
/// <returns>A <see cref="Response" /> if successful otherwise it will throw an exception.</returns>
public static async Task<Response> DownloadIntoMemory(this WebRequestDispatcher webRequestDispatcher, string url, CancellationToken token,
int timeout = TIMEOUT)
/// <returns>A <see cref="IResponse" /> if successful otherwise it will throw an exception.</returns>
public static async Task<T> DownloadIntoMemory<T>(this WebRequestDispatcher webRequestDispatcher, string url, CancellationToken token,
int timeout = TIMEOUT) where T : IResponse, new()
{
if (!HasInternetConnection)
{
Expand All @@ -45,7 +45,7 @@ public static async Task<Response> DownloadIntoMemory(this WebRequestDispatcher
headers.Add(CommonHeaders.GetAppIdHeader());

webRequestDispatcher.Timeout = timeout;
var response = await webRequestDispatcher.SendRequest<Response>(url, HttpMethod.GET, headers, ctx: token);
var response = await webRequestDispatcher.SendRequest<T>(url, HttpMethod.GET, headers, ctx: token);
token.ThrowCustomExceptionIfCancellationRequested();

if (!response.IsSuccess)
Expand Down
2 changes: 1 addition & 1 deletion Runtime/Core/Scripts/Operations/AvatarDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public async Task<AvatarContext> Execute(AvatarContext context, CancellationToke

try
{
var response = await dispatcher.DownloadIntoMemory(url, token, Timeout);
var response = await dispatcher.DownloadIntoMemory<ResponseData>(url, token, Timeout);
return response.Data;
}
catch (CustomException exception)
Expand Down
2 changes: 1 addition & 1 deletion Runtime/Core/Scripts/Operations/MetadataDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private AvatarContext UpdateContext(AvatarContext avatarContext, AvatarMetadata
// add random tail to the url to prevent JSON from being loaded from the browser cache
var response = await dispatcher.DownloadIntoMemory(url + "?tail=" + Guid.NewGuid(), token, Timeout);
#else
Response response = await dispatcher.DownloadIntoMemory(url, token, Timeout);
ResponseText response = await dispatcher.DownloadIntoMemory<ResponseText>(url, token, Timeout);
#endif
return ParseResponse(response.Text);
}
Expand Down

0 comments on commit 72b081e

Please sign in to comment.