Skip to content

Instantly share code, notes, and snippets.

@ManojLingala
Created July 13, 2023 10:57
Show Gist options
  • Save ManojLingala/81ffd6cabc77357dc3522133b29654c4 to your computer and use it in GitHub Desktop.
Save ManojLingala/81ffd6cabc77357dc3522133b29654c4 to your computer and use it in GitHub Desktop.
Cloud Charging - MemCache <<memcached-stack-charge_request_memcached-lambda-fn>>
using System;
using System.Threading.Tasks;
using Enyim.Caching;
using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;
public class MemcachedChargingService
{
private readonly IMemcachedClient _client;
private const string Key = "account1/balance";
private const int DefaultBalance = 100;
private const int MaxExpiration = 60 * 60 * 24 * 30;
public MemcachedChargingService()
{
var config = new MemcachedClientConfiguration();
config.AddServer(Environment.GetEnvironmentVariable("ENDPOINT"), Convert.ToInt32(Environment.GetEnvironmentVariable("PORT")));
_client = new MemcachedClient(config);
}
public async Task ResetMemcachedAsync()
{
await _client.StoreAsync(StoreMode.Set, Key, DefaultBalance, TimeSpan.FromSeconds(MaxExpiration));
}
public async Task<object> ChargeRequestMemcachedAsync(object input)
{
var remainingBalance = await GetBalanceMemcachedAsync(Key);
var charges = GetCharges();
var isAuthorized = AuthorizeRequest(remainingBalance, charges);
if (!isAuthorized)
{
return new
{
remainingBalance,
isAuthorized,
charges = 0
};
}
remainingBalance = await ChargeMemcachedAsync(Key, charges);
return new
{
remainingBalance,
charges,
isAuthorized
};
}
private static bool AuthorizeRequest(int remainingBalance, int charges)
{
return remainingBalance >= charges;
}
private static int GetCharges()
{
return DefaultBalance / 20;
}
private async Task<int> GetBalanceMemcachedAsync(string key)
{
var result = await _client.GetAsync<int>(key);
return result.HasValue ? result.Value : 0;
}
private async Task<int> ChargeMemcachedAsync(string key, int charges)
{
return await _client.DecrementAsync(key, (uint)charges, 0, TimeSpan.FromSeconds(MaxExpiration));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment