Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converted Chapter2 to C# #90

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
454 changes: 454 additions & 0 deletions c#/.gitignore

Large diffs are not rendered by default.

132 changes: 132 additions & 0 deletions c#/Chapter1/Chapter1.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// See https://aka.ms/new-console-template for more information

using System.Diagnostics;
using StackExchange.Redis;

namespace Chapter1;

public class Chapter1 {
private const int OneWeekInSeconds = 7 * 86400;
private const int VoteScore = 432;
private const int ArticlesPerPage = 25;

public static void Main() {
new Chapter1().run();
}

private void run() {
var con = ConnectionMultiplexer.Connect("localhost");
var db = con.GetDatabase();

var articleId = postArticle(db, "username", "A title", "https://www.google.com");
Console.WriteLine("We posted a new article with id: " + articleId);
Console.WriteLine("Its HASH looks like:");
var articleData = db.HashGetAll("article:" + articleId);

foreach (var entry in articleData) {
Console.WriteLine(" " + entry.Name + ": " + entry.Value);
}

Console.WriteLine();

articleVote(db, "other_user", "article:" + articleId);
var votes = (int?)db.HashGet("article:" + articleId, "votes") ?? 0;
Console.WriteLine("We voted for the article, it now has votes: " + votes);
Debug.Assert(votes > 1, "Vote count is less than 1");

Console.WriteLine("The currently highest-scoring articles are:");
var articles = getArticles(db, 1);
printArticles(articles);
Debug.Assert(articles.Count >= 1, "Article count is less than 1");

addGroups(db, articleId, new[]{"new-group"});
Console.WriteLine("We added the article to a new group, other articles include:");
var groupArticles = getGroupArticles(db, "new-group", 1);
printArticles(groupArticles);
Debug.Assert(groupArticles.Count >= 1, "Article group count is less than 1");
}

private string postArticle(IDatabase db, string user, string title, string link) {
var articleId = db.StringIncrement("article:").ToString();

var voted = "voted:" + articleId;
db.SetAdd(voted, user);
db.KeyExpire(voted, TimeSpan.FromSeconds(OneWeekInSeconds));

var now = DateTimeOffset.Now.ToUnixTimeSeconds();
var article = "article:" + articleId;
var articleData = new List<HashEntry> {
new("title", title),
new("link", link),
new("user", user),
new("now", now.ToString()),
new("votes", "1")
};
db.HashSet(article, articleData.ToArray());

db.SortedSetAdd("score:", article, now + VoteScore);
db.SortedSetAdd("time:", article, now);

return articleId;
}

private void articleVote(IDatabase db, string user, string article) {
var cutoff = DateTimeOffset.Now.ToUnixTimeSeconds() - OneWeekInSeconds;
var articleScore = db.SortedSetScore("time:", article) ?? 0;

if (articleScore < cutoff) {
return;
}

var articleId = article.Substring(article.IndexOf(':') + 1);

if (db.SetAdd("voted:" + articleId, user)) {
db.SortedSetIncrement("score:", article, VoteScore);
db.HashIncrement(article, "votes");
}
}

private List<Dictionary<RedisValue, RedisValue>>
getArticles(IDatabase db, int page, string order = "score:") {
var start = (page - 1) * ArticlesPerPage;
var end = start + ArticlesPerPage - 1;

var ids = db.SortedSetRangeByRank(order, start, end, order: Order.Descending);
var articles = new List<Dictionary<RedisValue, RedisValue>>();

foreach (var id in ids) {
var articleData = db.HashGetAll(id.ToString())
.ToDictionary(c => c.Name, c => c.Value);
articleData["id"] = id;
articles.Add(articleData);
}

return articles;
}

private void printArticles(List<Dictionary<RedisValue, RedisValue>> articles) {
foreach (var article in articles) {
Console.WriteLine(" id: " + article["id"]);
foreach (var articleData in article.Where(c => !c.Key.Equals("id"))) {
Console.WriteLine(" " + articleData.Key + ": " + articleData.Value);
}
}
}

private void addGroups(IDatabase db, string articleId, string[] toAdd) {
var article = "article:" + articleId;
foreach (var group in toAdd) {
db.SetAdd("group:" + group, article);
}
}

private List<Dictionary<RedisValue, RedisValue>> getGroupArticles(IDatabase db, string group, int page, string order = "score:") {
var key = order + group;
if (!db.KeyExists(key)) {
db.SortedSetCombineAndStore(SetOperation.Intersect, key, "group:" + group, order, aggregate: Aggregate.Max);
db.KeyExpire(key, TimeSpan.FromSeconds(60));
}

return getArticles(db, page, key);
}
}
14 changes: 14 additions & 0 deletions c#/Chapter1/Chapter1.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="StackExchange.Redis" Version="2.6.90" />
</ItemGroup>

</Project>
16 changes: 16 additions & 0 deletions c#/Chapter1/Chapter1.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Chapter1", "Chapter1.csproj", "{F01C7220-1D82-4691-8EB2-DB79842BEC82}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F01C7220-1D82-4691-8EB2-DB79842BEC82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F01C7220-1D82-4691-8EB2-DB79842BEC82}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F01C7220-1D82-4691-8EB2-DB79842BEC82}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F01C7220-1D82-4691-8EB2-DB79842BEC82}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
63 changes: 63 additions & 0 deletions c#/Chapter2/CacheRowsThread.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using StackExchange.Redis;
using System.Text.Json;

namespace Chapter2;

public class CacheRowsThread {
private readonly IDatabase _db;
private bool _quit;
private readonly Thread _thread;

public CacheRowsThread(IDatabase db) {
_db = db;
_thread = new Thread(run);
_quit = false;
}

public void Start() {
_thread.Start();
}

public void Quit() {
_quit = true;
}

public bool IsAlive() {
return _thread.IsAlive;
}

private void run() {
while (!_quit) {
var range = _db.SortedSetRangeByRankWithScores("schedule:", 0, 0);
var enumerator = range.GetEnumerator();
var next = (SortedSetEntry?)(enumerator.MoveNext() ? enumerator.Current : null);
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (next == null || next.Value.Score > now) {
try {
Thread.Sleep(50);
} catch (Exception ex) {
Console.WriteLine("error at thread:" + ex);
}

continue;
}

var rowId = next.Value.Element.ToString();
var delay = _db.SortedSetScore("delay:", rowId) ?? 0;
if (delay <= 0) {
_db.SortedSetRemove("delay:", rowId);
_db.SortedSetRemove("schedule:", rowId);
_db.KeyDelete("inv:" + rowId);
continue;
}

var row = new Inventory(rowId);
if (row == null) {
throw new ArgumentNullException(nameof(row));
}

_db.SortedSetAdd("schedule:", rowId, now + delay);
_db.StringSet("inv:" + rowId, JsonSerializer.Serialize(row));
}
}
}
Loading