Skip to content

Commit 25d9faf

Browse files
author
Hanza Ru
committed
+Version 0.2.2
+Fixed SendRequest direct calls
0 parents  commit 25d9faf

17 files changed

+1143
-0
lines changed

.icon.png

6.3 KB
Loading

LICENSE.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
MIT License
2+
3+
Copyright (c) 2015, Unity Technologies
4+
5+
Copyright (c) 2020 Game Workstore
6+
7+
Permission is hereby granted, free of charge, to any person obtaining a copy
8+
of this software and associated documentation files (the "Software"), to deal
9+
in the Software without restriction, including without limitation the rights
10+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
copies of the Software, and to permit persons to whom the Software is
12+
furnished to do so, subject to the following conditions:
13+
14+
The above copyright notice and this permission notice shall be included in all
15+
copies or substantial portions of the Software.
16+
17+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23+
SOFTWARE.

LICENSE.md.meta

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# Async Network Engine
2+
3+
Application Http requests made easy to interoperability with Go Lang Backend + Google Protobuf functions!
4+
5+
Supported Cloud Functions:
6+
- Google Cloud Functions
7+
- Amazon Web Services Lambdas
8+
9+
Use at your own risk!
10+
11+
# CppSDK
12+
13+
Visit this repo for more info: https://github.com/GameWorkstore/async-network-engine-cpp
14+
15+
# GoLangSDK
16+
17+
Visit this repo for more info: https://github.com/GameWorkstore/async-network-engine-go
18+
19+
# UnitySDK
20+
21+
## How to install
22+
23+
At package.json, add these 3 lines of code:
24+
```json
25+
"com.gameworkstore.asyncnetworkengine": "git://github.com/GameWorkstore/async-network-engine.git#0.2.1",
26+
"com.gameworkstore.googleprotobufunity": "git://github.com/GameWorkstore/google-protobuf-unity.git#3.15.2006",
27+
"com.gameworkstore.patterns": "git://github.com/GameWorkstore/patterns.git#1.1.2"
28+
```
29+
30+
And wait for unity to download and compile the package.
31+
32+
or update package for a newer version, update end of line from 0.2.1 to any released version on Releases.
33+
34+
## Usage Examples
35+
36+
You can find usage examples on Assets/Tests/ folder, for each cloud.
37+
38+
# FAQ
39+
40+
## Uploading to Google Cloud Functions
41+
42+
on upmsync, the job 'upload_gcp' illustrates a possible way to upload your functions into GCP.
43+
Requires a service account to enable it to upload.
44+
45+
### Uploading to Amazon Web Services
46+
47+
on upmsync.yaml, the job 'upload_aws' illustrates a possible way to upload your functions into AWS.
48+
Requires a service account to enable it to upload.
49+
> You need to set the template 'cloudformation_function.yaml' public in your bucket repository to enable AWS::Stack to read from it.
50+
51+
## GCP Troubleshoot
52+
53+
> My function is returning ErrorProtocol for any input.
54+
if you don't give access public for your function it might fail
55+
56+
## AWS Troubleshoot
57+
> CloudFormation is returning errors
58+
59+
Verify all variables, !Ref and links, you might be forgetting something. CloudFormations is very sensitive to linkage errors.
60+
61+
> My lambda is returning error 500 Internal Server error.
62+
63+
If you are receiving this and error object is returning null, it might be a bad configuration causing your lambda to not run.
64+
Verify if you function is running by adding a fmt.Println("test") at main() function to ensure the function is starting.
65+
Some issues that may prevent the start of function:
66+
- The functions ins't at correct path when extracted from the zip.
67+
- The function package name isn't main where main() function is declared.
68+
- lambda.Start() is never begin called to initialize the function.
69+
- The function is crashing upon initialization
70+
71+
If the function is working normally, them you might receive error 500 - ErrorInternalServer with AWSError, when specified by the programmer.
72+
73+
# Contributions
74+
75+
If you are using this library and want to submit a change, go ahead! Overall, this project accepts contributions if:
76+
- Is a bug fix;
77+
- Or, is a generalization of a well-known issue;
78+
- Or is performance improvement;
79+
- Or is an improvement to already supported feature.
80+
81+
Also, you can donate to allow us to drink coffee while we improve it for you!

README.md.meta

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Runtime.meta

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Runtime/AsyncNetworkEngine.cs

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
using Google.Protobuf;
2+
using GameWorkstore.Patterns;
3+
using System;
4+
using System.Collections;
5+
using System.Text;
6+
using UnityEngine.Networking;
7+
using System.Collections.Generic;
8+
using System.Linq;
9+
// ReSharper disable StaticMemberInGenericType
10+
11+
namespace GameWorkstore.AsyncNetworkEngine
12+
{
13+
public enum CloudProvider
14+
{
15+
Gcp = 0,
16+
Aws = 1
17+
}
18+
19+
public class FileData
20+
{
21+
public string URL;
22+
public byte[] Data;
23+
}
24+
25+
public static class AsyncNetworkEngineMap
26+
{
27+
internal static bool IsSingleCloud = true;
28+
internal static CloudProvider SingleCloudProvider = CloudProvider.Aws;
29+
internal static Dictionary<string, CloudProvider> MapCloudProvider;
30+
31+
/// <summary>
32+
/// Setup a single cloud provider for all functions.
33+
/// </summary>
34+
/// <param name="cloudProvider">Target cloud provider implementation.</param>
35+
public static void SetupCloud(CloudProvider cloudProvider)
36+
{
37+
IsSingleCloud = true;
38+
SingleCloudProvider = cloudProvider;
39+
}
40+
41+
/// <summary>
42+
/// Setup a multi cloud provider for all functions.
43+
/// </summary>
44+
/// <param name="mapCloudProvider">Maps base url to cloud provider. Use the lowest possible string to differentiate clouds.</param>
45+
public static void SetupCloudMap(Dictionary<string, CloudProvider> mapCloudProvider)
46+
{
47+
IsSingleCloud = false;
48+
MapCloudProvider = mapCloudProvider;
49+
}
50+
}
51+
52+
public static class AsyncNetworkEngine
53+
{
54+
private static EventService _eventService;
55+
56+
public static void Download(string url,Action<Transmission,FileData> callback)
57+
{
58+
if (_eventService == null) _eventService = ServiceProvider.GetService<EventService>();
59+
_eventService.StartCoroutine(SendRequest(new[] { url }, (result,files) => {
60+
callback?.Invoke(result,files.FirstOrDefault());
61+
}));
62+
}
63+
64+
public static void Download(string[] urls, Action<Transmission,HighSpeedArray<FileData>> callback)
65+
{
66+
if (_eventService == null) _eventService = ServiceProvider.GetService<EventService>();
67+
_eventService.StartCoroutine(SendRequest(urls, callback));
68+
}
69+
70+
public static IEnumerator SendRequest(string[] urls, Action<Transmission, HighSpeedArray<FileData>> callback)
71+
{
72+
var data = new HighSpeedArray<FileData>(urls.Length);
73+
foreach(var url in urls)
74+
{
75+
using var rqt = UnityWebRequest.Get(url);
76+
yield return rqt.SendWebRequest();
77+
78+
switch(rqt.result)
79+
{
80+
case UnityWebRequest.Result.ConnectionError:
81+
Return(Transmission.ErrorConnection, null, callback);
82+
break;
83+
case UnityWebRequest.Result.Success:
84+
data.Add(new FileData()
85+
{
86+
URL = url,
87+
Data = rqt.downloadHandler.data
88+
});
89+
break;
90+
case UnityWebRequest.Result.ProtocolError:
91+
Return(Transmission.ErrorProtocol, null, callback);
92+
break;
93+
case UnityWebRequest.Result.DataProcessingError:
94+
Return(Transmission.ErrorDecode, null, callback);
95+
break;
96+
}
97+
}
98+
Return(Transmission.Success, data, callback);
99+
}
100+
101+
private static void Return(Transmission result, HighSpeedArray<FileData> data, Action<Transmission, HighSpeedArray<FileData>> callback)
102+
{
103+
if (_eventService != null)
104+
{
105+
_eventService.QueueAction(() => callback.Invoke(result, data));
106+
}
107+
else
108+
{
109+
callback?.Invoke(result, data);
110+
}
111+
}
112+
}
113+
114+
/// <summary>
115+
/// Implements a UnityRequest for google protobuf web functions.
116+
/// </summary>
117+
/// <typeparam name="TRqt">Request</typeparam>
118+
/// <typeparam name="TResp">Response</typeparam>
119+
public static class AsyncNetworkEngine<TRqt,TResp>
120+
where TRqt : IMessage<TRqt>, new()
121+
where TResp : IMessage<TResp>, new()
122+
{
123+
private static readonly MessageParser<TResp> _tuParser = new MessageParser<TResp>(() => new TResp());
124+
private static readonly MessageParser<GenericErrorResponse> _tvParser = new MessageParser<GenericErrorResponse>(() => new GenericErrorResponse());
125+
private static EventService _eventService;
126+
127+
public static void Send(string url, TRqt request, Action<Transmission, TResp, GenericErrorResponse> callback)
128+
{
129+
if (_eventService == null) _eventService = ServiceProvider.GetService<EventService>();
130+
_eventService.StartCoroutine(SendRequest(url, request, callback));
131+
}
132+
133+
public static IEnumerator SendRequest(string url, TRqt request, Action<Transmission, TResp, GenericErrorResponse> callback)
134+
{
135+
//Notice: APIGateway automatically converts binary data into base64 strings
136+
using var rqt = new UnityWebRequest(url, "POST")
137+
{
138+
uploadHandler = new UploadHandlerRaw(request.ToByteArray()),
139+
downloadHandler = new DownloadHandlerBuffer()
140+
};
141+
yield return rqt.SendWebRequest();
142+
143+
switch (rqt.result)
144+
{
145+
case UnityWebRequest.Result.ConnectionError:
146+
Return(Transmission.ErrorConnection, callback);
147+
break;
148+
case UnityWebRequest.Result.ProtocolError:
149+
HandleError(GetCloudProvider(ref url), rqt, callback);
150+
break;
151+
case UnityWebRequest.Result.Success:
152+
while (!rqt.downloadHandler.isDone) yield return null;
153+
HandleSuccess(GetCloudProvider(ref url), rqt, callback);
154+
break;
155+
}
156+
}
157+
158+
private static CloudProvider GetCloudProvider(ref string url)
159+
{
160+
if (!AsyncNetworkEngineMap.IsSingleCloud)
161+
{
162+
foreach (var pair in AsyncNetworkEngineMap.MapCloudProvider)
163+
{
164+
if (!url.StartsWith(pair.Key)) continue;
165+
return pair.Value;
166+
}
167+
}
168+
return AsyncNetworkEngineMap.SingleCloudProvider;
169+
}
170+
171+
private static void HandleSuccess(CloudProvider provider, UnityWebRequest rqt, Action<Transmission, TResp, GenericErrorResponse> callback)
172+
{
173+
if (rqt.downloadHandler.data == null)
174+
{
175+
Return(Transmission.ErrorNoData, callback);
176+
return;
177+
}
178+
179+
var data = rqt.downloadHandler.data;
180+
if (provider == CloudProvider.Aws)
181+
{
182+
var s = Encoding.ASCII.GetString(rqt.downloadHandler.data);
183+
if (!Base64StdEncoding.Decode(s, out data))
184+
{
185+
Return(Transmission.ErrorParser, default, new GenericErrorResponse(){ Error = "base64 string is invalid:" + s }, callback);
186+
return;
187+
}
188+
}
189+
190+
TResp packet;
191+
try
192+
{
193+
packet = _tuParser.ParseFrom(data);
194+
}
195+
catch
196+
{
197+
Return(Transmission.ErrorParser, callback);
198+
return;
199+
}
200+
Return(Transmission.Success, packet, default, callback);
201+
}
202+
203+
private static void HandleError(CloudProvider provider, UnityWebRequest rqt, Action<Transmission, TResp, GenericErrorResponse> callback)
204+
{
205+
if (rqt.downloadHandler.data == null)
206+
{
207+
Return(Transmission.ErrorProtocol, callback);
208+
return;
209+
}
210+
211+
var data = rqt.downloadHandler.data;
212+
if (provider == CloudProvider.Aws)
213+
{
214+
var s = Encoding.ASCII.GetString(rqt.downloadHandler.data);
215+
if (!Base64StdEncoding.Decode(s, out data))
216+
{
217+
Return(Transmission.ErrorParser, default, new GenericErrorResponse(){ Error = "base64 string is invalid:" + s }, callback);
218+
return;
219+
}
220+
}
221+
222+
var transmission = (Transmission)rqt.responseCode;
223+
GenericErrorResponse packet;
224+
try
225+
{
226+
packet = _tvParser.ParseFrom(data);
227+
}
228+
catch
229+
{
230+
Return(Transmission.ErrorParser, callback);
231+
return;
232+
}
233+
Return(transmission, default, packet, callback);
234+
}
235+
236+
private static void Return(Transmission result, Action<Transmission, TResp, GenericErrorResponse> callback)
237+
{
238+
Return(result, default, default, callback);
239+
}
240+
241+
private static void Return(Transmission result, TResp data, GenericErrorResponse error, Action<Transmission, TResp, GenericErrorResponse> callback)
242+
{
243+
if (callback == null) return;
244+
if(_eventService != null)
245+
{
246+
_eventService.QueueAction(() => callback.Invoke(result, data, error));
247+
}
248+
else
249+
{
250+
callback.Invoke(result, data, error);
251+
}
252+
}
253+
}
254+
}

Runtime/AsyncNetworkEngine.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)