Skip to content

Instantly share code, notes, and snippets.

@ManojLingala
Last active July 13, 2023 10:41
Show Gist options
  • Save ManojLingala/c5d16110126ea8055d2570cc77e6fa54 to your computer and use it in GitHub Desktop.
Save ManojLingala/c5d16110126ea8055d2570cc77e6fa54 to your computer and use it in GitHub Desktop.
CloudCharging -<<redis-stack-charge_request_redis-lambda-fn >>
using StackExchange.Redis;
using System;
using System.Threading.Tasks;
public class ChargingEngineService
{
private static readonly string Key = "account1/balance";
private static readonly int DefaultBalance = 100;
private static ConnectionMultiplexer redis;
public static async Task<ChargeResult> ChargeRequestAsync()
{
var db = await GetDatabaseAsync();
var remainingBalance = await GetBalanceAsync(db, Key);
var charges = GetCharges();
var isAuthorized = remainingBalance >= charges;
if (!isAuthorized)
{
return new ChargeResult
{
RemainingBalance = remainingBalance,
IsAuthorized = false,
Charges = 0
};
}
var newRemainingBalance = await ChargeAsync(db, Key, charges);
return new ChargeResult
{
RemainingBalance = newRemainingBalance,
IsAuthorized = true,
Charges = charges
};
}
public static async Task<int> ResetAsync()
{
var db = await GetDatabaseAsync();
await db.StringSetAsync(Key, DefaultBalance);
return DefaultBalance;
}
private static async Task<IDatabase> GetDatabaseAsync()
{
if (redis == null || !redis.IsConnected)
{
redis = await ConnectionMultiplexer.ConnectAsync($"{Environment.GetEnvironmentVariable("ENDPOINT")}:{Environment.GetEnvironmentVariable("PORT") ?? "6379"}");
}
return redis.GetDatabase();
}
private static int GetCharges()
{
return DefaultBalance / 20;
}
private static async Task<int> GetBalanceAsync(IDatabase db, string key)
{
var res = await db.StringGetAsync(key);
return (int)res;
}
private static async Task<int> ChargeAsync(IDatabase db, string key, int charges)
{
return (int)await db.StringDecrementAsync(key, charges);
}
}
public class ChargeResult
{
public int RemainingBalance { get; set; }
public int Charges { get; set; }
public bool IsAuthorized { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment