Skip to content

Commit

Permalink
Add etag to eliminate rate limit (aspnet#176)
Browse files Browse the repository at this point in the history
  • Loading branch information
zackliu authored Feb 21, 2022
1 parent f9bc2c3 commit 6217bcf
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 13 deletions.
17 changes: 15 additions & 2 deletions samples/QuickStartServerless/csharp/Function.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
Expand All @@ -14,6 +15,8 @@ namespace CSharp
public static class Function
{
private static HttpClient httpClient = new HttpClient();
private static string Etag = string.Empty;
private static string StartCount = "0";

[FunctionName("index")]
public static IActionResult GetHomePage([HttpTrigger(AuthorizationLevel.Anonymous)]HttpRequest req, ExecutionContext context)
Expand All @@ -40,13 +43,23 @@ public static async Task Broadcast([TimerTrigger("*/5 * * * * *")] TimerInfo myT
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.github.com/repos/azure/azure-signalr");
request.Headers.UserAgent.ParseAdd("Serverless");
request.Headers.Add("If-None-Match", Etag);
var response = await httpClient.SendAsync(request);
var result = JsonConvert.DeserializeObject<GitResult>(await response.Content.ReadAsStringAsync());
if (response.Headers.Contains("Etag"))
{
Etag = response.Headers.GetValues("Etag").First();
}
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var result = JsonConvert.DeserializeObject<GitResult>(await response.Content.ReadAsStringAsync());
StartCount = result.StartCount;
}

await signalRMessages.AddAsync(
new SignalRMessage
{
Target = "newMessage",
Arguments = new[] { $"Current star count of https://github.com/Azure/azure-signalr is: {result.StartCount}" }
Arguments = new[] { $"Current star count of https://github.com/Azure/azure-signalr is: {StartCount}" }
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
import java.util.Optional;

public class Function {
private static String Etag = "";
private static String StarCount;

@FunctionName("index")
public HttpResponseMessage run(
@HttpTrigger(
Expand Down Expand Up @@ -57,13 +60,21 @@ public SignalRConnectionInfo negotiate(
@SignalROutput(name = "$return", hubName = "serverless")
public SignalRMessage broadcast(
@TimerTrigger(name = "timeTrigger", schedule = "*/5 * * * * *") String timerInfo) throws IOException, InterruptedException {

HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder().uri(URI.create("https://api.github.com/repos/azure/azure-signalr")).header("User-Agent", "serverless").build();
HttpRequest req = HttpRequest.newBuilder().uri(URI.create("https://api.github.com/repos/azure/azure-signalr")).header("User-Agent", "serverless").header("If-None-Match", Etag).build();
HttpResponse<String> res = client.send(req, BodyHandlers.ofString());
Gson gson = new Gson();
GitResult result = gson.fromJson(res.body(), GitResult.class);
return new SignalRMessage("newMessage", "Current start count of https://github.com/Azure/azure-signalr is:".concat(result.stargazers_count));
if (res.headers().firstValue("Etag").isPresent())
{
Etag = res.headers().firstValue("Etag").get();
}
if (res.statusCode() == 200)
{
Gson gson = new Gson();
GitResult result = gson.fromJson(res.body(), GitResult.class);
StarCount = result.stargazers_count;
}

return new SignalRMessage("newMessage", "Current start count of https://github.com/Azure/azure-signalr is:".concat(StarCount));
}

class GitResult {
Expand Down
17 changes: 14 additions & 3 deletions samples/QuickStartServerless/javascript/broadcast/index.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
var https = require('https');

var etag = '';
var star = 0;

module.exports = function (context) {
var req = https.request("https://api.github.com/repos/azure/azure-signalr", {
method: 'GET',
headers: {'User-Agent': 'serverless'}
headers: {'User-Agent': 'serverless', 'If-None-Match': etag}
}, res => {
if (res.headers['etag']) {
etag = res.headers['etag']
}

var body = "";

res.on('data', data => {
body += data;
});
res.on("end", () => {
var jbody = JSON.parse(body);
if (res.statusCode === 200) {
var jbody = JSON.parse(body);
star = jbody['stargazers_count'];
}

context.bindings.signalRMessages = [{
"target": "newMessage",
"arguments": [ `Current star count of https://github.com/Azure/azure-signalr is: ${jbody['stargazers_count']}` ]
"arguments": [ `Current star count of https://github.com/Azure/azure-signalr is: ${star}` ]
}]
context.done();
});
Expand Down
15 changes: 12 additions & 3 deletions samples/QuickStartServerless/python/broadcast/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,22 @@

import azure.functions as func

etag = ''
start_count = 0

def main(myTimer: func.TimerRequest, signalRMessages: func.Out[str]) -> None:
headers = {'User-Agent': 'serverless'}
global etag
global start_count
headers = {'User-Agent': 'serverless', 'If-None-Match': etag}
res = requests.get('https://api.github.com/repos/azure/azure-signalr', headers=headers)
jres = res.json()
if res.headers.get('ETag'):
etag = res.headers.get('ETag')

if res.status_code == 200:
jres = res.json()
start_count = jres['stargazers_count']

signalRMessages.set(json.dumps({
'target': 'newMessage',
'arguments': [ 'Current star count of https://github.com/Azure/azure-signalr is: ' + str(jres['stargazers_count']) ]
'arguments': [ 'Current star count of https://github.com/Azure/azure-signalr is: ' + str(start_count) ]
}))

0 comments on commit 6217bcf

Please sign in to comment.