Skip to content

Commit

Permalink
Moved MongoStore into this project from separate nuget
Browse files Browse the repository at this point in the history
  • Loading branch information
gonace committed Jun 3, 2024
1 parent 5964f09 commit 50d2b9a
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 4 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,13 @@ limiter.Limit(() =>
```c#
await limiter.LimitAsync(() => Task.CompletedTask);
```

## Stores
### Mongo
> This example is shown using Autofac since this is the go-to IoC for us.
```c#
builder.Register<ISomeLimit>(c =>
new AuthorizationLimit(new MongoStore(new MongoUrl(c.Resolve<IConfiguration>().GetConnectionString("MongoConnectionString")), "authorization.calls"),
new StandardLimit(300, TimeSpan.FromHours(3)))
).SingleInstance();
```
88 changes: 88 additions & 0 deletions laget.Limiter/Stores/MongoStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;

namespace laget.Limiter.Stores
{
public class Call
{
[BsonElement("id"), BsonId, BsonIgnoreIfDefault, BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }

[BsonElement("createdAt"), BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime CreatedAt { get; set; } = DateTime.Now;

[BsonElement("value")]
public long Value { get; set; }
}

public class MongoStore : IStore
{
private readonly IMongoCollection<Call> _store;
private readonly TimeSpan _ttl;

public MongoStore(MongoUrl url)
: this(url, TimeSpan.FromHours(1), "calls")
{
}

public MongoStore(MongoUrl url, TimeSpan ttl)
: this(url, ttl, "calls")
{
}

public MongoStore(MongoUrl url, TimeSpan ttl, string collection = "calls")
{
var client = new MongoClient(url);

var database = client.GetDatabase(url.DatabaseName, new MongoDatabaseSettings
{
ReadConcern = ReadConcern.Default,
ReadPreference = ReadPreference.SecondaryPreferred,
WriteConcern = WriteConcern.Acknowledged
});

_store = database.GetCollection<Call>(collection);
_ttl = ttl;

EnsureIndexes();
}

public void Add(DateTime item)
{
_store.InsertOne(new Call { Value = item.ToBinary() });
}

public IList<DateTime> Get() => _store.Find(new BsonDocument()).ToList()
.Select(x => DateTime.FromBinary(x.Value))
.ToList();

public void Trim(int amount)
{
var items = Get()
.OrderByDescending(x => x)
.Take(amount)
.Select(x => x.ToBinary())
.ToList();

var builder = Builders<Call>.Filter;
var filter = builder.Nin(x => x.Value, items);

_store.DeleteMany(filter);
}

private void EnsureIndexes()
{
var builder = Builders<Call>.IndexKeys;
var indexes = new List<CreateIndexModel<Call>>
{
new CreateIndexModel<Call>(builder.Ascending(_ => _.CreatedAt), new CreateIndexOptions { Background = true, ExpireAfter = _ttl }),
new CreateIndexModel<Call>(builder.Ascending(_ => _.Value), new CreateIndexOptions { Background = true, Unique = true })
};
_store.Indexes.CreateMany(indexes);
}
}
}
4 changes: 4 additions & 0 deletions laget.Limiter/laget.Limiter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,8 @@
<NuspecProperties>version=$(Version)</NuspecProperties>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MongoDB.Driver" Version="2.25.0" />
</ItemGroup>

</Project>
16 changes: 12 additions & 4 deletions laget.Limiter/laget.Limiter.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,18 @@
<readme>assets\README.md</readme>
<repository type="git" url="https://github.com/laget-se/laget.Limiter" branch="master" />
<dependencies>
<group targetFramework="net8.0"></group>
<group targetFramework="net6.0"></group>
<group targetFramework="netstandard2.1"></group>
<group targetFramework="netstandard2.0"></group>
<group targetFramework="net8.0">
<dependency id="MongoDb.Driver" version="2.25.0" />
</group>
<group targetFramework="net6.0">
<dependency id="MongoDb.Driver" version="2.25.0" />
</group>
<group targetFramework="netstandard2.1">
<dependency id="MongoDb.Driver" version="2.25.0" />
</group>
<group targetFramework="netstandard2.0">
<dependency id="MongoDb.Driver" version="2.25.0" />
</group>
</dependencies>
</metadata>
<files>
Expand Down

0 comments on commit 50d2b9a

Please sign in to comment.