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

Add EnableResponseCallback #617

Merged
merged 32 commits into from
Aug 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
5b041b1
Add EnableResponseCallback
Oceania2018 Aug 12, 2024
64d088c
Fix GoToPage
Oceania2018 Aug 13, 2024
b7dadd3
ResponseInMemory
Oceania2018 Aug 14, 2024
d4c6039
Merge branch 'SciSharp:master' into master
Oceania2018 Aug 15, 2024
f95dc65
Merge branch 'SciSharp:master' into master
Oceania2018 Aug 17, 2024
0dcb9f8
修改Locator匹配到多个时取第一个值
AnonymousDotNet Aug 21, 2024
a926e0d
Revert "修改Locator匹配到多个时取第一个值"
AnonymousDotNet Aug 21, 2024
384c933
更改Locator取值以参数判断的方式
AnonymousDotNet Aug 21, 2024
2066ce5
Merge branch 'master' of https://github.com/AnonymousDotNet/BotSharp
AnonymousDotNet Aug 21, 2024
be83f20
fix locker timeout issue.
Oceania2018 Aug 21, 2024
5b1a9d9
Lock sync
Oceania2018 Aug 21, 2024
3bce2c5
Claim 1 Redis connection only
Oceania2018 Aug 21, 2024
ff01d14
Set ConnectionMultiplexer as static
Oceania2018 Aug 21, 2024
933a01a
Merge branch 'master' into lida_dev
AnonymousDotNet Aug 22, 2024
6bba847
Merge pull request #7 from AnonymousDotNet/lida_dev
Oceania2018 Aug 22, 2024
7b05bbf
Merge branch 'SciSharp:master' into master
Oceania2018 Aug 22, 2024
7b95726
ICacheService, SharpCache
Oceania2018 Aug 22, 2024
1d9ef81
Merge branch 'SciSharp:master' into master
Oceania2018 Aug 22, 2024
563b983
Add cache prefix.
Oceania2018 Aug 23, 2024
dfd0507
Merge branch 'master' of https://github.com/Qtoss-AI/BotSharp
Oceania2018 Aug 23, 2024
7ec7c67
Merge branch 'SciSharp:master' into master
Oceania2018 Aug 23, 2024
3b449f0
Fix cache key issue.
Oceania2018 Aug 23, 2024
c928262
Merge branch 'master' of https://github.com/Qtoss-AI/BotSharp
Oceania2018 Aug 23, 2024
3eddcb9
RunCrawlingTaskById
Oceania2018 Aug 23, 2024
1869657
JwtRegisteredLaimNames.Email null exception
AnonymousDotNet Aug 24, 2024
e579dab
Merge pull request #8 from AnonymousDotNet/lida_dev
Oceania2018 Aug 24, 2024
7527f78
Remove LastSoldCount, Add LastIncreSoldCount. https://github.com/Qtos…
Oceania2018 Aug 25, 2024
8bbe78e
Reset page after crawling.
Oceania2018 Aug 26, 2024
64a1f68
Ignore StepId for cache key
Oceania2018 Aug 26, 2024
2e5abe5
如果有新记录就暂不缓存本次搜索结果
Oceania2018 Aug 27, 2024
f6651b5
IgnoreIfNotFound
Oceania2018 Aug 31, 2024
e369e1f
Resolve conflict
Oceania2018 Aug 31, 2024
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -293,4 +293,5 @@ logs
wwwroot
appsettings.Production.json
*.csproj.user
env/
env/
FodyWeavers.*
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
<PackageReference Include="System.Text.Json" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Rougamo.Fody" Version="4.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ namespace BotSharp.Abstraction.Browsing;

public interface IWebPageResponseHook
{
void OnDataFetched(MessageInfo message, string url, string postData, string responsData);
T? GetResponse<T>(MessageInfo message, string url, string? queryParameter = null);
void OnDataFetched(MessageInfo message, WebPageResponseData response);
T? GetResponse<T>(MessageInfo message, WebPageResponseFilter filter);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ public class ElementActionArgs

public string? PressKey { get; set; }

/// <summary>
/// Locator option
/// </summary>
public bool FirstIfMultipleFound { get; set; } = false;

/// <summary>
/// Wait time in seconds
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class ElementLocatingArgs
public bool Parent { get; set; }

public bool FailIfMultiple { get; set; }
public bool IgnoreIfNotFound { get; set; }

/// <summary>
/// Draw outline around the element
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
using BotSharp.Abstraction.Infrastructures;

namespace BotSharp.Abstraction.Browsing.Models;

public class MessageInfo
public class MessageInfo : ICacheKey
{
public string AgentId { get; set; } = null!;
public string UserId { get; set; } = null!;
public string ContextId { get; set; } = null!;
public string? MessageId { get; set; }
public string? TaskId { get; set; }
public string StepId { get; set; } = Guid.NewGuid().ToString();

public string GetCacheKey()
=> $"{nameof(MessageInfo)}-{ContextId}";
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,25 @@ public class PageActionArgs
/// This value has to be set to true if you want to get the page XHR/ Fetch responses
/// </summary>
public bool OpenNewTab { get; set; } = false;

public bool EnableResponseCallback { get; set; } = false;

/// <summary>
/// Exclude urls for XHR/ Fetch responses
/// </summary>
public string[]? ExcludeResponseUrls { get; set; }

/// <summary>
/// Only include urls for XHR/ Fetch responses
/// </summary>
public string[]? IncludeResponseUrls { get; set; }

/// <summary>
/// If set to true, the response will be stored in memory
/// </summary>
public bool ResponseInMemory { get; set; } = false;
public List<WebPageResponseData>? ResponseContainer { get; set; }

public bool UseExistingPage { get; set; } = false;

public bool WaitForNetworkIdle { get; set; } = true;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace BotSharp.Abstraction.Browsing.Models;

public class WebPageResponseData
{
public string Url { get; set; } = null!;
public string PostData { get; set; } = null!;
public string ResponseData { get; set; } = null!;
public bool ResponseInMemory { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace BotSharp.Abstraction.Browsing.Models;

public class WebPageResponseFilter
{
public string Url { get; set; } = null!;
public string[]? QueryParameters { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace BotSharp.Abstraction.Infrastructures;

public interface ICacheKey
{
string GetCacheKey();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace BotSharp.Abstraction.Infrastructures;

public interface ICacheService
{
Task<T?> GetAsync<T>(string key);
Task<object> GetAsync(string key, Type type);
Task SetAsync<T>(string key, T value, TimeSpan? expiry);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using BotSharp.Abstraction.Infrastructures;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Rougamo;
using Rougamo.Context;

namespace BotSharp.Core.Infrastructures;

public class SharpCacheAttribute : MoAttribute
{
public static IServiceProvider Services { get; set; } = null!;

private int _minutes;

public SharpCacheAttribute(int minutes = 60)
{
_minutes = minutes;
}

public override void OnEntry(MethodContext context)
{
var settings = Services.GetRequiredService<SharpCacheSettings>();
if (!settings.Enabled)
{
return;
}

var cache = Services.GetRequiredService<ICacheService>();

var key = GetCacheKey(settings, context);
var value = cache.GetAsync(key, context.TaskReturnType).Result;
if (value != null)
{
context.ReplaceReturnValue(this, value);
}
}

public override void OnSuccess(MethodContext context)
{
var settings = Services.GetRequiredService<SharpCacheSettings>();
if (!settings.Enabled)
{
return;
}

var httpContext = Services.GetRequiredService<IHttpContextAccessor>();
if (httpContext.HttpContext.Response.Headers["Cache-Control"].ToString().Contains("no-store"))
{
return;
}

var cache = Services.GetRequiredService<ICacheService>();

if (context.ReturnValue != null)
{
var key = GetCacheKey(settings, context);
cache.SetAsync(key, context.ReturnValue, new TimeSpan(0, _minutes, 0)).Wait();
}
}

private string GetCacheKey(SharpCacheSettings settings, MethodContext context)
{
var key = settings.Prefix + "-" + context.Method.Name;
foreach (var arg in context.Arguments)
{
if (arg is null)
{
key += "-" + "<NULL>";
}
else if (arg is ICacheKey withCacheKey)
{
key += "-" + withCacheKey.GetCacheKey();
}
else
{
key += "-" + arg.ToString();
}
}

return key;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace BotSharp.Abstraction.Infrastructures;

public class SharpCacheSettings
{
public bool Enabled { get; set; } = false;
public string Prefix { get; set; } = "cache";
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using BotSharp.Abstraction.Infrastructures;

namespace BotSharp.Abstraction.Utilities;

public class Pagination
public class Pagination : ICacheKey
{
private int _page;
private int _size;
Expand Down Expand Up @@ -39,6 +41,9 @@ public int Offset
}

public bool ReturnTotal { get; set; } = true;

public string GetCacheKey()
=> $"{nameof(Pagination)}_{_page}_{_size}_{Sort}_{Order}";
}

public class PagedItems<T>
Expand Down
3 changes: 3 additions & 0 deletions src/Infrastructure/BotSharp.Core/BotSharp.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,13 @@
</PropertyGroup>

<ItemGroup>
<Compile Remove="packages\**" />
<Compile Remove="Planning\**" />
<Compile Remove="Translation\Models\**" />
<EmbeddedResource Remove="packages\**" />
<EmbeddedResource Remove="Planning\**" />
<EmbeddedResource Remove="Translation\Models\**" />
<None Remove="packages\**" />
<None Remove="Planning\**" />
<None Remove="Translation\Models\**" />
</ItemGroup>
Expand Down
13 changes: 12 additions & 1 deletion src/Infrastructure/BotSharp.Core/BotSharpCoreExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
using BotSharp.Abstraction.Functions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using BotSharp.Abstraction.Functions;
using BotSharp.Core.Plugins;
using BotSharp.Abstraction.Settings;
using BotSharp.Abstraction.Options;
using BotSharp.Abstraction.Messaging.JsonConverters;
using BotSharp.Abstraction.Users.Settings;
using BotSharp.Abstraction.Interpreters.Settings;
using BotSharp.Abstraction.Infrastructures;

namespace BotSharp.Core;

Expand All @@ -22,8 +23,15 @@ public static IServiceCollection AddBotSharpCore(this IServiceCollection service

services.AddScoped<ISettingService, SettingService>();
services.AddScoped<IUserService, UserService>();

services.AddSingleton<DistributedLocker>();

// Register cache service
var cacheSettings = new SharpCacheSettings();
config.Bind("SharpCache", cacheSettings);
services.AddSingleton(x => cacheSettings);
services.AddSingleton<ICacheService, CacheService>();

RegisterPlugins(services, config);
ConfigureBotSharpOptions(services, configOptions);

Expand Down Expand Up @@ -61,6 +69,9 @@ public static IApplicationBuilder UseBotSharp(this IApplicationBuilder app)

app.ApplicationServices.GetRequiredService<PluginLoader>().Configure(app);

// Set root services for SharpCacheAttribute
SharpCacheAttribute.Services = app.ApplicationServices;

return app;
}

Expand Down
74 changes: 74 additions & 0 deletions src/Infrastructure/BotSharp.Core/Infrastructures/CacheService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using BotSharp.Abstraction.Infrastructures;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace BotSharp.Core.Infrastructures;

public class CacheService : ICacheService
{
private readonly BotSharpDatabaseSettings _settings;
private static ConnectionMultiplexer redis = null!;

public CacheService(BotSharpDatabaseSettings settings)
{
_settings = settings;
}

public async Task<T?> GetAsync<T>(string key)
{
if (string.IsNullOrEmpty(_settings.Redis))
{
return default;
}

if (redis == null)
{
redis = ConnectionMultiplexer.Connect(_settings.Redis);
}

var db = redis.GetDatabase();
var value = await db.StringGetAsync(key);

if (value.HasValue)
{
return JsonConvert.DeserializeObject<T>(value);
}

return default;
}

public async Task<object> GetAsync(string key, Type type)
{
if (string.IsNullOrEmpty(_settings.Redis))
{
return default;
}

if (redis == null)
{
redis = ConnectionMultiplexer.Connect(_settings.Redis);
}

var db = redis.GetDatabase();
var value = await db.StringGetAsync(key);

if (value.HasValue)
{
return JsonConvert.DeserializeObject(value, type);
}

return default;
}


public async Task SetAsync<T>(string key, T value, TimeSpan? expiry)
{
if (string.IsNullOrEmpty(_settings.Redis))
{
return;
}

var db = redis.GetDatabase();
await db.StringSetAsync(key, JsonConvert.SerializeObject(value), expiry);
}
}
Loading