Skip to content

Commit

Permalink
Added logging
Browse files Browse the repository at this point in the history
  • Loading branch information
mythz committed Aug 28, 2024
1 parent 163be73 commit bcd1028
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 25 deletions.
12 changes: 10 additions & 2 deletions MyApp.ServiceInterface/App/CreateAnswerCommand.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
using System.Data;
using Microsoft.Extensions.Logging;
using MyApp.Data;
using MyApp.ServiceModel;
using ServiceStack;
using ServiceStack.Jobs;
using ServiceStack.OrmLite;

namespace MyApp.ServiceInterface.App;

[Tag(Tags.Answers)]
[Worker(Databases.App)]
public class CreateAnswerCommand(AppConfig appConfig, IDbConnection db) : SyncCommand<Post>
public class CreateAnswerCommand(ILogger<CreateAnswerCommand> logger,
IBackgroundJobs jobs, AppConfig appConfig, IDbConnection db)
: SyncCommand<Post>
{
protected override void Run(Post answer)
{
if (answer.ParentId == null)
throw new ArgumentNullException(nameof(answer.ParentId));
if (answer.CreatedBy == null)
throw new ArgumentNullException(nameof(answer.CreatedBy));


var log = Request.CreateJobLogger(jobs, logger);
var postId = answer.ParentId!.Value;
var refId = $"{postId}-{answer.CreatedBy}";
if (!db.Exists(db.From<StatTotals>().Where(x => x.Id == refId)))
{
log.LogInformation("Adding StatTotals {Id} for Post {PostId}", refId, postId);
db.Insert(new StatTotals
{
Id = refId,
Expand All @@ -40,6 +46,7 @@ protected override void Run(Post answer)
// Notify Post Author of new Answer
if (post.CreatedBy != answer.CreatedBy && appConfig.IsHuman(post.CreatedBy))
{
log.LogInformation("Notify Post Author {User} of new Answer {Id} for Post {PostId}", post.CreatedBy, refId, postId);
db.Insert(new Notification
{
UserName = post.CreatedBy,
Expand Down Expand Up @@ -72,6 +79,7 @@ protected override void Run(Post answer)
var startPos = Math.Max(0, firstMentionPos - 50);
if (appConfig.IsHuman(existingUser.UserName))
{
log.LogInformation("Notify Post User Mention {User} for Answer {Id} in Post {PostId}", existingUser.UserName, refId, postId);
db.Insert(new Notification
{
UserName = existingUser.UserName!,
Expand Down
9 changes: 7 additions & 2 deletions MyApp.ServiceInterface/App/CreateCommentVoteCommand.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
using System.Data;
using Microsoft.Extensions.Logging;
using MyApp.Data;
using MyApp.ServiceModel;
using ServiceStack;
using ServiceStack.Jobs;
using ServiceStack.OrmLite;

namespace MyApp.ServiceInterface.App;

[Tag(Tags.Database)]
[Worker(Databases.App)]
public class CreateCommentVoteCommand(IDbConnection db, QuestionsProvider questions) : IAsyncCommand<Vote>
public class CreateCommentVoteCommand(ILogger<CreateCommentVoteCommand> logger, IBackgroundJobs jobs,
IDbConnection db, QuestionsProvider questions) : AsyncCommand<Vote>
{
public async Task ExecuteAsync(Vote vote)
protected override async Task RunAsync(Vote vote, CancellationToken token)
{
if (string.IsNullOrEmpty(vote.RefId))
throw new ArgumentNullException(nameof(vote.RefId));
if (string.IsNullOrEmpty(vote.UserName))
throw new ArgumentNullException(nameof(vote.UserName));

var log = Request.CreateJobLogger(jobs, logger);
var rowsDeleted = db.Delete<Vote>(new { vote.RefId, vote.UserName });

var meta = await questions.GetMetaAsync(vote.PostId);
Expand All @@ -30,6 +34,7 @@ public async Task ExecuteAsync(Vote vote)
if (comment.CreatedBy == vote.UserName)
throw new ArgumentException("Can't vote on your own comment", nameof(vote.RefId));

log.LogInformation("Recording {User} Vote {Score} for comment {RefId}", comment.CreatedBy, vote.Score, vote.RefId);
vote.RefUserName = comment.CreatedBy;
db.Insert(vote);

Expand Down
3 changes: 2 additions & 1 deletion MyApp.ServiceInterface/App/CreatePostCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ protected override async Task RunAsync(Post post, CancellationToken token)
var startPos = Math.Max(0, firstMentionPos - 50);
if (appConfig.IsHuman(existingUser.UserName))
{
log.LogInformation("Notify User Mention {User} for Question {PostId}", existingUser.UserName, post.Id);
db.Insert(new Notification
{
UserName = existingUser.UserName!,
Expand Down Expand Up @@ -103,7 +104,7 @@ protected override async Task RunAsync(Post post, CancellationToken token)
});
appConfig.IncrUnreadAchievementsFor(post.CreatedBy!);

// Setup auto-watch for new questions (Sending Emails for new Answers)
log.LogInformation("Setup auto-watch for new question {PostId} to {User}", post.Id, post.CreatedBy);
db.Insert(new WatchPost
{
UserName = post.CreatedBy!,
Expand Down
25 changes: 19 additions & 6 deletions MyApp.ServiceInterface/App/DeleteAnswersCommand.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,37 @@
using System.Data;
using Microsoft.Extensions.Logging;
using ServiceStack;
using ServiceStack.OrmLite;
using MyApp.Data;
using MyApp.ServiceModel;
using ServiceStack.Jobs;

namespace MyApp.ServiceInterface.App;

[Worker(Databases.App)]
[Tag(Tags.Answers)]
public class DeleteAnswersCommand(IDbConnection db) : SyncCommand<DeleteAnswers>
public class DeleteAnswersCommand(ILogger<DeleteAnswersCommand> logger, IBackgroundJobs jobs, IDbConnection db)
: SyncCommand<DeleteAnswers>
{
protected override void Run(DeleteAnswers request)
{
var log = Request.CreateJobLogger(jobs,logger);
foreach (var refId in request.Ids)
{
db.Delete<Vote>(x => x.RefId == refId);
db.DeleteById<Post>(refId);
db.Delete<StatTotals>(x => x.Id == refId);
db.Delete<Notification>(x => x.RefId == refId);
db.Delete<PostEmail>(x => x.RefId == refId);
try
{
log.LogInformation("Deleting answer {RefId}...", refId);

db.Delete<Vote>(x => x.RefId == refId);
db.DeleteById<Post>(refId);
db.Delete<StatTotals>(x => x.Id == refId);
db.Delete<Notification>(x => x.RefId == refId);
db.Delete<PostEmail>(x => x.RefId == refId);
}
catch (Exception e)
{
log.LogError(e, "Failed to delete Answer {RefId}: {Message}", refId, e.Message);
}
}
}
}
29 changes: 21 additions & 8 deletions MyApp.ServiceInterface/App/DeletePostsCommand.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,40 @@
using System.Data;
using Microsoft.Extensions.Logging;
using ServiceStack;
using ServiceStack.OrmLite;
using MyApp.Data;
using MyApp.ServiceModel;
using ServiceStack.Jobs;

namespace MyApp.ServiceInterface.App;

[Worker(Databases.App)]
[Tag(Tags.Database)]
public class DeletePostsCommand(AppConfig appConfig, IDbConnection db)
public class DeletePostsCommand(ILogger<DeleteAnswersCommand> logger, IBackgroundJobs jobs,
AppConfig appConfig, IDbConnection db)
: SyncCommand<DeletePosts>
{
protected override void Run(DeletePosts request)
{
var log = Request.CreateJobLogger(jobs,logger);
foreach (var postId in request.Ids)
{
db.Delete<Vote>(x => x.PostId == postId);
db.DeleteById<Post>(postId);
db.Delete<StatTotals>(x => x.PostId == postId);
db.Delete<Notification>(x => x.PostId == postId);
db.Delete<WatchPost>(x => x.PostId == postId);
db.Delete<PostEmail>(x => x.PostId == postId);
appConfig.ResetInitialPostId(db);
try
{
log.LogInformation("Deleting Question {Id}...", postId);

db.Delete<Vote>(x => x.PostId == postId);
db.DeleteById<Post>(postId);
db.Delete<StatTotals>(x => x.PostId == postId);
db.Delete<Notification>(x => x.PostId == postId);
db.Delete<WatchPost>(x => x.PostId == postId);
db.Delete<PostEmail>(x => x.PostId == postId);
appConfig.ResetInitialPostId(db);
}
catch (Exception e)
{
log.LogError(e, "Failed to delete Question {Id}: {Message}", postId, e.Message);
}
}
}
}
14 changes: 13 additions & 1 deletion MyApp.ServiceInterface/App/MarkAsReadCommand.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
using System.Data;
using Microsoft.Extensions.Logging;
using ServiceStack;
using ServiceStack.OrmLite;
using MyApp.Data;
using MyApp.ServiceModel;
using ServiceStack.Jobs;

namespace MyApp.ServiceInterface.App;

[Tag(Tags.Notifications)]
[Worker(Databases.App)]
public class MarkAsReadCommand(AppConfig appConfig, IDbConnection db) : SyncCommand<MarkAsRead>
public class MarkAsReadCommand(ILogger<MarkAsReadCommand> logger, IBackgroundJobs jobs, AppConfig appConfig, IDbConnection db)
: SyncCommand<MarkAsRead>
{
protected override void Run(MarkAsRead request)
{
var log = Request.CreateJobLogger(jobs,logger);
string entries = "";

var userName = Request.GetClaimsPrincipal().GetRequiredUserName();
if (request.AllNotifications == true)
{
entries = "All Notifications";
db.UpdateOnly(() => new Notification { Read = true }, x => x.UserName == userName);
appConfig.UsersUnreadNotifications[userName] = 0;
}
else if (request.NotificationIds?.Count > 0)
{
entries = $"Notifications {string.Join(", ", request.NotificationIds)}";
db.UpdateOnly(() => new Notification { Read = true },
x => x.UserName == userName && request.NotificationIds.Contains(x.Id));
appConfig.UsersUnreadNotifications[userName] = (int) db.Count(
Expand All @@ -28,15 +36,19 @@ protected override void Run(MarkAsRead request)
// Mark all achievements as read isn't used, they're auto reset after viewed
if (request.AllAchievements == true)
{
entries = "All Achievements";
db.UpdateOnly(() => new Achievement { Read = true }, x => x.UserName == userName);
appConfig.UsersUnreadAchievements[userName] = 0;
}
else if (request.AchievementIds?.Count > 0)
{
entries = $"Achievements {string.Join(", ", request.AchievementIds)}";
db.UpdateOnly(() => new Achievement { Read = true },
x => x.UserName == userName && request.AchievementIds.Contains(x.Id));
appConfig.UsersUnreadAchievements[userName] = (int) db.Count(
db.From<Achievement>().Where(x => x.UserName == userName && !x.Read));
}

log.LogInformation("Marked {Entries} as Read", entries);
}
}
6 changes: 5 additions & 1 deletion MyApp.ServiceInterface/App/PostSubscriptionsCommand.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.Data;
using Microsoft.Extensions.Logging;
using MyApp.ServiceModel;
using ServiceStack;
using ServiceStack.Jobs;
using ServiceStack.OrmLite;

namespace MyApp.ServiceInterface.App;
Expand All @@ -14,7 +16,7 @@ public class PostSubscriptions

[Worker(Databases.App)]
[Tag(Tags.Notifications)]
public class PostSubscriptionsCommand(IDbConnection db) : SyncCommand<PostSubscriptions>
public class PostSubscriptionsCommand(ILogger<MarkAsReadCommand> log, IDbConnection db) : SyncCommand<PostSubscriptions>
{
protected override void Run(PostSubscriptions request)
{
Expand All @@ -29,11 +31,13 @@ protected override void Run(PostSubscriptions request)
AfterDate = now,
});
db.InsertAll(subs);
log.LogInformation("Added watched post to {User} for questions {Ids}", request.UserName, string.Join(", ", subs.Select(x => x.PostId)));
}
if (request.Unsubscriptions is { Count: > 0 })
{
db.Delete<WatchPost>(
x => x.UserName == request.UserName && request.Unsubscriptions.Contains(x.PostId));
log.LogInformation("Deleted watched post from {User}", request.UserName);
}
}
}
8 changes: 4 additions & 4 deletions MyApp.Tests/Top1KQuestionTasks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,8 @@ public async Task Recreate_answers_for_Top1K_questions_for_Llama_3_1()
var apiCreate = await client.ApiAsync(new CreateAnswersForModels
{
Models = ["llama3.1-8b"],
PostIds = [9],
// PostIds = Migration1005.Top1KIds,
// PostIds = [9],
PostIds = Migration1005.Top1KIds,
});

apiCreate.Error.PrintDump();
Expand All @@ -235,8 +235,8 @@ public async Task Recreate_answers_for_Top1K_questions_for_Llama_3_1()
[Test]
public async Task Find_answers_that_have_not_been_individually_graded()
{
var client = await TestUtils.CreateAuthenticatedProdClientAsync();
// var client = await TestUtils.CreateAuthenticatedDevClientAsync();
// var client = await TestUtils.CreateAuthenticatedProdClientAsync();
var client = await TestUtils.CreateAuthenticatedDevClientAsync();

var api = await client.ApiAsync(new MissingGradedAnswersTop1K());

Expand Down

0 comments on commit bcd1028

Please sign in to comment.