You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@james.apache.org by GitBox <gi...@apache.org> on 2022/01/19 10:06:15 UTC
[GitHub] [james-project] chibenwa opened a new pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
chibenwa opened a new pull request #851:
URL: https://github.com/apache/james-project/pull/851
TODO: Write test for this mailet
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788365051
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,211 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Quantity.Quantity
+import org.apache.james.rate.limiter.api.{AcceptableRate, Quantity, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Quantity
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Quantity = 1
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getRecipients.size())
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getMessageSize.toInt)
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow((mail.getMessageSize * mail.getRecipients.size()).toInt)
Review comment:
Fair. We may need to split `Quantity` in two: `Increments` and `AllowedQuantity`.
Note that the underlying library `RateLimitJ` would anyway enforce int usage for the increments.... Not much we could do for this. (But the above proposition lifts the contstraint for the allowed quantity and is thus desirable).
Maybe this could be done in a third party PR...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] Arsnael commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
Arsnael commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r790594632
##########
File path: server/mailet/rate-limiter/README.adoc
##########
@@ -0,0 +1,61 @@
+= Rate limiting for Apache James
+
+This maven module provide a James extension allowing one to enforce rate limiting for Apache James email processing.
+
+== Running rate limiting with the memory implementation
+
+ - 1. Compile this project.
+ - 2. Place the generated "jar with dependencies" in James `extensions-jars` folder.
+ - 3. Configure James to use the memory implementation for Rate Limiting by putting the following content within
+`extension.properties`:
+
+----
+guice.extension.module=org.apache.james.rate.limiter.memory.MemoryRateLimiterModule
+----
+
+ - 4. Use the rate limiting mailets within `mailetcontainer.xml`
+
+We provide a sample `docker-compose` demonstrating this setup.
+
+== Mailets
+
+=== PerSenderRateLimit
+
+*PerSenderRateLimit* allows defining and enforcing rate limits for the sender of matching emails.
+
+This allows writing rules like:
+
+ - A sender can send 10 emails per hour
+ - A sender can send email to a total of 20 recipients per hour
+ - A sender can send 100 MB of emails (total computed taking only the email size into account) per hour
+ - A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour
+
+Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+submitted emails, received emails or emitted email being relayed to third parties.
+
+Here are supported configuration parameters:
+
+ - *keyPrefix*: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ this mailet twice within your `mailetcontainer.xml` file. Defaults to none.
+ - *exceededProcessor*: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ Use this to customize the behaviour upon exceeded rate.
+ - *duration*: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).
+ - *count*: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *recipients*: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *size*: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.
+ - *totalSize*: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
Review comment:
For typo correction, use the suggestion snippet next time @quantranhong1999 , it's very explicit :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] vttranlina commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
vttranlina commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788499977
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,220 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Increment.Increment
+import org.apache.james.rate.limiter.api.{AcceptableRate, AllowedQuantity, Increment, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import scala.util.Try
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Option[Increment]
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(1)
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getRecipients.size()))
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getMessageSize.toInt))
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Option[Increment] =
+ Try(Math.multiplyExact(mail.getMessageSize.toInt, mail.getRecipients.size()).toInt)
+ .map(Increment.liftOrThrow)
+ .toOption
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter =>
+ entityType.extractQuantity(mail)
+ .map(increment => limiter.rateLimit(rateLimitingKey, increment))
+ .getOrElse(SMono.just[RateLimitingResult](RateExceeded)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
+ * <li>A sender can send 100 MB of emails (total computed taking only the email size into account) per hour</li>
+ * <li>A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour</li>
+ * </ul>
+ *
+ * <p>Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+ * submitted emails, received emails or emitted email being relayed to third parties.</p>
+ *
+ * <ul>Here are supported configuration parameters:
+ * <li><b>keyPrefix</b>: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ * this mailet twice within your <code>mailetcontainer.xml</code> file. Defaults to none.</li>
+ * <li><b>exceededProcessor</b>: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ * Use this to customize the behaviour upon exceeded rate.</li>
+ * <li><b>duration</b>: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).</li>
+ * <li><b>count</b>: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>recipients</b>: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>size</b>: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.</li>
+ * <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
+ * totalSize is limited in increments of 2exp(31) - ~2 billions: sending a 10MB file to more than 205 recipients will be rejected if this parameter is enabled.</li>
+ * </ul>
+ *
+ * <p>For instance, to apply all the examples given above:</p>
+ *
+ * <pre><code>
+ * <mailet matcher="All" class="PerSenderRateLimit">
+ * <keyPrefix>myPrefix</keyPrefix>
+ * <duration>1h</duration>
+ * <count>10</count>
+ * <recipients>20</recipients>
+ * <size>100M</size>
+ * <totalSize>200M</totalSize>
+ * </mailet>
+ * </code></pre>
+ *
+ * <p>Note that to use this extension you need to place the rate-limiter JAR in the <code>extensions-jars</code> folder
+ * and need to configure a viable option to invoke <code>RateLimiterFactoryProvider</code> which can be done by
+ * loading <code>org.apache.james.rate.limiter.memory.MemoryRateLimiterModule</code> Guice module within the
+ * <code>guice.extension.module</code> in <code>extensions.properties</code> configuration file. Note that other Rate
+ * limiter implementation might require extra configuration parameters within your mailet.</p>
+ *
+ * @param rateLimiterFactoryProvider Allows instantiations of the underlying rate limiters.
+ */
+class PerSenderRateLimit @Inject()(rateLimiterFactoryProvider: RateLimiterFactoryProvider) extends GenericMailet {
+ private var countRateLimiter: PerSenderRateLimiter = _
+ private var recipientsRateLimiter: PerSenderRateLimiter = _
+ private var sizeRateLimiter: PerSenderRateLimiter = _
+ private var totalSizeRateLimiter: PerSenderRateLimiter = _
+ private var exceededProcessor: String = _
+ private var keyPrefix: Option[KeyPrefix] = _
+
+ override def init(): Unit = {
+ val rateLimiterFactory = rateLimiterFactoryProvider.create(getMailetConfig)
+ val duration: Duration = parseDuration()
+
+ keyPrefix = Option(getInitParameter("keyPrefix")).map(KeyPrefix)
+ exceededProcessor = getInitParameter("exceededProcessor", Mail.ERROR)
+
+ countRateLimiter = PerSenderRateLimiter(rateLimiter = extractCountRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = Count)
+ recipientsRateLimiter = PerSenderRateLimiter(rateLimiter = extractRecipientsRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = RecipientsType)
+ sizeRateLimiter = PerSenderRateLimiter(rateLimiter = extractSizeRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = Size)
+ totalSizeRateLimiter = PerSenderRateLimiter(rateLimiter = extractTotalSizeRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = TotalSize)
+ }
+
+ @VisibleForTesting
+ def parseDuration(): Duration =
+ Option(getInitParameter("duration"))
+ .map(string => DurationParser.parse(string, ChronoUnit.SECONDS))
+ .getOrElse(throw new IllegalArgumentException("'duration' is compulsory"))
+
+ private def extractCountRules(duration: Duration): Option[Rules] = Option(getInitParameter("count"))
+ .map(_.toLong)
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ private def extractRecipientsRules(duration: Duration): Option[Rules] = Option(getInitParameter("recipients"))
+ .map(_.toLong)
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ private def extractSizeRules(duration: Duration): Option[Rules] = Option(getInitParameter("size"))
+ .map {
+ case "" => throw new IllegalArgumentException("'size' field cannot be empty if specified")
+ case s => s
+ }
+ .map(org.apache.james.util.Size.parse)
+ .map(_.asBytes())
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ private def extractTotalSizeRules(duration: Duration): Option[Rules] = Option(getInitParameter("totalSize"))
+ .map {
+ case "" => throw new IllegalArgumentException("'totalSize' field cannot be empty if specified")
+ case s => s
+ }
+ .map(org.apache.james.util.Size.parse)
+ .map(_.asBytes())
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ override def service(mail: Mail): Unit = mail.getMaybeSender
+ .asOptional()
+ .ifPresent(sender => {
+ applyRateLimiter(mail, sender)
+ })
+
+ private def applyRateLimiter(mail: Mail, sender: MailAddress): Unit = {
+ val pivot: RateLimitingResult = AcceptableRate
+ val result = SFlux.merge(Seq(
+ countRateLimiter.rateLimit(sender, mail),
+ recipientsRateLimiter.rateLimit(sender, mail),
+ sizeRateLimiter.rateLimit(sender, mail),
+ totalSizeRateLimiter.rateLimit(sender, mail)))
+ .fold(pivot)((a, b) => a.merge(b))
+ .block()
+
+ if (result.equals(RateExceeded)) {
+ mail.setState(exceededProcessor)
Review comment:
Before reading this line,
I thought `exceededProcessor` will similar to a publisher, that sends events. (mechanism look like to MailboxListener).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] quantranhong1999 edited a comment on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
quantranhong1999 edited a comment on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1020768123
> I think this is more part of the underlying `RateLimiter` component and we _might_ be limited on this by the `RateLimitJ` choice.
I did read some implementation code of RateLimitJ. I think it works fine for an individual rate limit. e.g when a user requests a number of requests that exceed the limit, RateLimitJ does not increase the counter.
I think the issue here is that we combine many rate limits. E.g rate limits A and B: when user requests exceed A but do not exceed B => A counter is not changed but B increases.
If we have an API for checking whether the rate limit will be exceeded without actually increasing it yet, we can check all rate limits together. But I do not see RateLimitJ exposing that API... Any idea? Should we just skip this case?
IMO this does not impact much the overall rate limit use cases. This only happens at the edge use case when the user exceeds a rate limit. If we choose a suitable group of rate limits then it is likely that the user will exceed the other rate limit soon => that user should wait for resources regeneration.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r790476053
##########
File path: server/mailet/rate-limiter/README.adoc
##########
@@ -0,0 +1,61 @@
+= Rate limiting for Apache James
+
+This maven module provide a James extension allowing one to enforce rate limiting for Apache James email processing.
+
+== Running rate limiting with the memory implementation
+
+ - 1. Compile this project.
+ - 2. Place the generated "jar with dependencies" in James `extensions-jars` folder.
+ - 3. Configure James to use the memory implementation for Rate Limiting by putting the following content within
+`extension.properties`:
+
+----
+guice.extension.module=org.apache.james.rate.limiter.memory.MemoryRateLimiterModule
+----
+
+ - 4. Use the rate limiting mailets within `mailetcontainer.xml`
+
+We provide a sample `docker-compose` demonstrating this setup.
+
+== Mailets
+
+=== PerSenderRateLimit
+
+*PerSenderRateLimit* allows defining and enforcing rate limits for the sender of matching emails.
+
+This allows writing rules like:
+
+ - A sender can send 10 emails per hour
+ - A sender can send email to a total of 20 recipients per hour
+ - A sender can send 100 MB of emails (total computed taking only the email size into account) per hour
+ - A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour
+
+Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+submitted emails, received emails or emitted email being relayed to third parties.
+
+Here are supported configuration parameters:
+
+ - *keyPrefix*: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ this mailet twice within your `mailetcontainer.xml` file. Defaults to none.
+ - *exceededProcessor*: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ Use this to customize the behaviour upon exceeded rate.
+ - *duration*: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).
+ - *count*: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *recipients*: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *size*: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.
+ - *totalSize*: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
Review comment:
```suggestion
- *totalSize*: Size of emails allowed for a given sender during duration (each recipient of the email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] vttranlina commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
vttranlina commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788499977
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,220 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Increment.Increment
+import org.apache.james.rate.limiter.api.{AcceptableRate, AllowedQuantity, Increment, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import scala.util.Try
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Option[Increment]
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(1)
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getRecipients.size()))
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getMessageSize.toInt))
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Option[Increment] =
+ Try(Math.multiplyExact(mail.getMessageSize.toInt, mail.getRecipients.size()).toInt)
+ .map(Increment.liftOrThrow)
+ .toOption
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter =>
+ entityType.extractQuantity(mail)
+ .map(increment => limiter.rateLimit(rateLimitingKey, increment))
+ .getOrElse(SMono.just[RateLimitingResult](RateExceeded)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
+ * <li>A sender can send 100 MB of emails (total computed taking only the email size into account) per hour</li>
+ * <li>A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour</li>
+ * </ul>
+ *
+ * <p>Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+ * submitted emails, received emails or emitted email being relayed to third parties.</p>
+ *
+ * <ul>Here are supported configuration parameters:
+ * <li><b>keyPrefix</b>: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ * this mailet twice within your <code>mailetcontainer.xml</code> file. Defaults to none.</li>
+ * <li><b>exceededProcessor</b>: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ * Use this to customize the behaviour upon exceeded rate.</li>
+ * <li><b>duration</b>: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).</li>
+ * <li><b>count</b>: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>recipients</b>: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>size</b>: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.</li>
+ * <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
+ * totalSize is limited in increments of 2exp(31) - ~2 billions: sending a 10MB file to more than 205 recipients will be rejected if this parameter is enabled.</li>
+ * </ul>
+ *
+ * <p>For instance, to apply all the examples given above:</p>
+ *
+ * <pre><code>
+ * <mailet matcher="All" class="PerSenderRateLimit">
+ * <keyPrefix>myPrefix</keyPrefix>
+ * <duration>1h</duration>
+ * <count>10</count>
+ * <recipients>20</recipients>
+ * <size>100M</size>
+ * <totalSize>200M</totalSize>
+ * </mailet>
+ * </code></pre>
+ *
+ * <p>Note that to use this extension you need to place the rate-limiter JAR in the <code>extensions-jars</code> folder
+ * and need to configure a viable option to invoke <code>RateLimiterFactoryProvider</code> which can be done by
+ * loading <code>org.apache.james.rate.limiter.memory.MemoryRateLimiterModule</code> Guice module within the
+ * <code>guice.extension.module</code> in <code>extensions.properties</code> configuration file. Note that other Rate
+ * limiter implementation might require extra configuration parameters within your mailet.</p>
+ *
+ * @param rateLimiterFactoryProvider Allows instantiations of the underlying rate limiters.
+ */
+class PerSenderRateLimit @Inject()(rateLimiterFactoryProvider: RateLimiterFactoryProvider) extends GenericMailet {
+ private var countRateLimiter: PerSenderRateLimiter = _
+ private var recipientsRateLimiter: PerSenderRateLimiter = _
+ private var sizeRateLimiter: PerSenderRateLimiter = _
+ private var totalSizeRateLimiter: PerSenderRateLimiter = _
+ private var exceededProcessor: String = _
+ private var keyPrefix: Option[KeyPrefix] = _
+
+ override def init(): Unit = {
+ val rateLimiterFactory = rateLimiterFactoryProvider.create(getMailetConfig)
+ val duration: Duration = parseDuration()
+
+ keyPrefix = Option(getInitParameter("keyPrefix")).map(KeyPrefix)
+ exceededProcessor = getInitParameter("exceededProcessor", Mail.ERROR)
+
+ countRateLimiter = PerSenderRateLimiter(rateLimiter = extractCountRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = Count)
+ recipientsRateLimiter = PerSenderRateLimiter(rateLimiter = extractRecipientsRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = RecipientsType)
+ sizeRateLimiter = PerSenderRateLimiter(rateLimiter = extractSizeRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = Size)
+ totalSizeRateLimiter = PerSenderRateLimiter(rateLimiter = extractTotalSizeRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = TotalSize)
+ }
+
+ @VisibleForTesting
+ def parseDuration(): Duration =
+ Option(getInitParameter("duration"))
+ .map(string => DurationParser.parse(string, ChronoUnit.SECONDS))
+ .getOrElse(throw new IllegalArgumentException("'duration' is compulsory"))
+
+ private def extractCountRules(duration: Duration): Option[Rules] = Option(getInitParameter("count"))
+ .map(_.toLong)
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ private def extractRecipientsRules(duration: Duration): Option[Rules] = Option(getInitParameter("recipients"))
+ .map(_.toLong)
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ private def extractSizeRules(duration: Duration): Option[Rules] = Option(getInitParameter("size"))
+ .map {
+ case "" => throw new IllegalArgumentException("'size' field cannot be empty if specified")
+ case s => s
+ }
+ .map(org.apache.james.util.Size.parse)
+ .map(_.asBytes())
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ private def extractTotalSizeRules(duration: Duration): Option[Rules] = Option(getInitParameter("totalSize"))
+ .map {
+ case "" => throw new IllegalArgumentException("'totalSize' field cannot be empty if specified")
+ case s => s
+ }
+ .map(org.apache.james.util.Size.parse)
+ .map(_.asBytes())
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ override def service(mail: Mail): Unit = mail.getMaybeSender
+ .asOptional()
+ .ifPresent(sender => {
+ applyRateLimiter(mail, sender)
+ })
+
+ private def applyRateLimiter(mail: Mail, sender: MailAddress): Unit = {
+ val pivot: RateLimitingResult = AcceptableRate
+ val result = SFlux.merge(Seq(
+ countRateLimiter.rateLimit(sender, mail),
+ recipientsRateLimiter.rateLimit(sender, mail),
+ sizeRateLimiter.rateLimit(sender, mail),
+ totalSizeRateLimiter.rateLimit(sender, mail)))
+ .fold(pivot)((a, b) => a.merge(b))
+ .block()
+
+ if (result.equals(RateExceeded)) {
+ mail.setState(exceededProcessor)
Review comment:
Before reading this line,
I thought `exceededProcessor` will similar to a publisher, that sends events. (mechanism look like to MailboxListener).
// just a thinking
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] vttranlina commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
vttranlina commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788417485
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,211 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Quantity.Quantity
+import org.apache.james.rate.limiter.api.{AcceptableRate, Quantity, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Quantity
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Quantity = 1
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getRecipients.size())
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getMessageSize.toInt)
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow((mail.getMessageSize * mail.getRecipients.size()).toInt)
Review comment:
Or we can convert bytes number to KB/MB number before input to API.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788714513
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,220 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Increment.Increment
+import org.apache.james.rate.limiter.api.{AcceptableRate, AllowedQuantity, Increment, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import scala.util.Try
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Option[Increment]
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(1)
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getRecipients.size()))
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getMessageSize.toInt))
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Option[Increment] =
+ Try(Math.multiplyExact(mail.getMessageSize.toInt, mail.getRecipients.size()).toInt)
+ .map(Increment.liftOrThrow)
+ .toOption
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter =>
+ entityType.extractQuantity(mail)
+ .map(increment => limiter.rateLimit(rateLimitingKey, increment))
+ .getOrElse(SMono.just[RateLimitingResult](RateExceeded)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
+ * <li>A sender can send 100 MB of emails (total computed taking only the email size into account) per hour</li>
+ * <li>A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour</li>
+ * </ul>
+ *
+ * <p>Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+ * submitted emails, received emails or emitted email being relayed to third parties.</p>
+ *
+ * <ul>Here are supported configuration parameters:
+ * <li><b>keyPrefix</b>: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ * this mailet twice within your <code>mailetcontainer.xml</code> file. Defaults to none.</li>
+ * <li><b>exceededProcessor</b>: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ * Use this to customize the behaviour upon exceeded rate.</li>
+ * <li><b>duration</b>: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).</li>
+ * <li><b>count</b>: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>recipients</b>: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>size</b>: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.</li>
+ * <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
+ * totalSize is limited in increments of 2exp(31) - ~2 billions: sending a 10MB file to more than 205 recipients will be rejected if this parameter is enabled.</li>
+ * </ul>
+ *
+ * <p>For instance, to apply all the examples given above:</p>
+ *
+ * <pre><code>
+ * <mailet matcher="All" class="PerSenderRateLimit">
+ * <keyPrefix>myPrefix</keyPrefix>
+ * <duration>1h</duration>
+ * <count>10</count>
+ * <recipients>20</recipients>
+ * <size>100M</size>
+ * <totalSize>200M</totalSize>
+ * </mailet>
+ * </code></pre>
+ *
+ * <p>Note that to use this extension you need to place the rate-limiter JAR in the <code>extensions-jars</code> folder
+ * and need to configure a viable option to invoke <code>RateLimiterFactoryProvider</code> which can be done by
+ * loading <code>org.apache.james.rate.limiter.memory.MemoryRateLimiterModule</code> Guice module within the
+ * <code>guice.extension.module</code> in <code>extensions.properties</code> configuration file. Note that other Rate
+ * limiter implementation might require extra configuration parameters within your mailet.</p>
+ *
+ * @param rateLimiterFactoryProvider Allows instantiations of the underlying rate limiters.
+ */
+class PerSenderRateLimit @Inject()(rateLimiterFactoryProvider: RateLimiterFactoryProvider) extends GenericMailet {
Review comment:
For what?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] Arsnael commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
Arsnael commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r789346423
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,211 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Quantity.Quantity
+import org.apache.james.rate.limiter.api.{AcceptableRate, Quantity, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Quantity
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Quantity = 1
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getRecipients.size())
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getMessageSize.toInt)
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow((mail.getMessageSize * mail.getRecipients.size()).toInt)
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter => limiter.rateLimit(rateLimitingKey, entityType.extractQuantity(mail)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
Review comment:
I don't remember the number of recipients as a rate limit being discussed? Is this new?
##########
File path: server/mailet/rate-limiter/docker-compose.yml
##########
@@ -0,0 +1,18 @@
+version: '3'
+
+# In order to start James JPA app on top of mariaDB:
Review comment:
Bad copy paste spotted! It's james memory here, nothing to do with the JPA version :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] quantranhong1999 commented on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
quantranhong1999 commented on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1019997061
Hi,
I think I might find a bug here. I think we should not increase the counter when it exceeds one of the rate limits. Please have a look at the test below:
```
@Test
def mix(): Unit = {
val mailet = testee(FakeMailetConfig.builder()
.mailetName("GlobalRateLimit")
.setProperty("duration", "1000s")
.setProperty("size", "100K")
.setProperty("recipients", "6")
.build())
val mail1: Mail = FakeMail.builder()
.name("mail1")
.sender("sender@domain.tld")
.recipients("rcpt1@linagora.com", "rcpt2@linagora.com")
.size(50 * 1024)
.state("transport")
.build()
// Will exceed the size rate limit
val mail2: Mail = FakeMail.builder()
.name("mail2")
.sender("sender@domain.tld")
.recipients("rcpt1@linagora.com", "rcpt3@linagora.com")
.size(60 * 1024)
.state("transport")
.build()
// Will not exceed anything
val mail3: Mail = FakeMail.builder()
.name("mail4")
.sender("sender@domain.tld")
.recipients("rcpt1@linagora.com", "rcpt3@linagora.com", "rcpt3@linagora.com")
.size(10 * 1024)
.state("transport")
.build()
mailet.service(mail1)
mailet.service(mail2)
mailet.service(mail3)
SoftAssertions.assertSoftly(softly => {
softly.assertThat(mail1.getState).isEqualTo("transport")
softly.assertThat(mail2.getState).isEqualTo("error")
// the total recipients of acceptable email is 2 + 3 (mail1 + mail2) = 5 < 6 so this should be transport.
softly.assertThat(mail3.getState).isEqualTo("transport")
// But actually this will be failed cause the total recipient counts the exceeded mail2 also: 2+2+3 = 7 > 6
})
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1020792286
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788713607
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,220 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Increment.Increment
+import org.apache.james.rate.limiter.api.{AcceptableRate, AllowedQuantity, Increment, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import scala.util.Try
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Option[Increment]
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(1)
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getRecipients.size()))
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getMessageSize.toInt))
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Option[Increment] =
+ Try(Math.multiplyExact(mail.getMessageSize.toInt, mail.getRecipients.size()).toInt)
+ .map(Increment.liftOrThrow)
+ .toOption
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter =>
+ entityType.extractQuantity(mail)
+ .map(increment => limiter.rateLimit(rateLimitingKey, increment))
+ .getOrElse(SMono.just[RateLimitingResult](RateExceeded)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
+ * <li>A sender can send 100 MB of emails (total computed taking only the email size into account) per hour</li>
+ * <li>A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour</li>
+ * </ul>
+ *
+ * <p>Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+ * submitted emails, received emails or emitted email being relayed to third parties.</p>
+ *
+ * <ul>Here are supported configuration parameters:
+ * <li><b>keyPrefix</b>: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ * this mailet twice within your <code>mailetcontainer.xml</code> file. Defaults to none.</li>
+ * <li><b>exceededProcessor</b>: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ * Use this to customize the behaviour upon exceeded rate.</li>
+ * <li><b>duration</b>: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).</li>
+ * <li><b>count</b>: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>recipients</b>: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>size</b>: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.</li>
+ * <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
+ * totalSize is limited in increments of 2exp(31) - ~2 billions: sending a 10MB file to more than 205 recipients will be rejected if this parameter is enabled.</li>
+ * </ul>
+ *
+ * <p>For instance, to apply all the examples given above:</p>
+ *
+ * <pre><code>
+ * <mailet matcher="All" class="PerSenderRateLimit">
+ * <keyPrefix>myPrefix</keyPrefix>
+ * <duration>1h</duration>
+ * <count>10</count>
+ * <recipients>20</recipients>
+ * <size>100M</size>
+ * <totalSize>200M</totalSize>
+ * </mailet>
+ * </code></pre>
+ *
+ * <p>Note that to use this extension you need to place the rate-limiter JAR in the <code>extensions-jars</code> folder
+ * and need to configure a viable option to invoke <code>RateLimiterFactoryProvider</code> which can be done by
+ * loading <code>org.apache.james.rate.limiter.memory.MemoryRateLimiterModule</code> Guice module within the
+ * <code>guice.extension.module</code> in <code>extensions.properties</code> configuration file. Note that other Rate
+ * limiter implementation might require extra configuration parameters within your mailet.</p>
+ *
+ * @param rateLimiterFactoryProvider Allows instantiations of the underlying rate limiters.
+ */
+class PerSenderRateLimit @Inject()(rateLimiterFactoryProvider: RateLimiterFactoryProvider) extends GenericMailet {
+ private var countRateLimiter: PerSenderRateLimiter = _
+ private var recipientsRateLimiter: PerSenderRateLimiter = _
+ private var sizeRateLimiter: PerSenderRateLimiter = _
+ private var totalSizeRateLimiter: PerSenderRateLimiter = _
+ private var exceededProcessor: String = _
+ private var keyPrefix: Option[KeyPrefix] = _
+
+ override def init(): Unit = {
+ val rateLimiterFactory = rateLimiterFactoryProvider.create(getMailetConfig)
+ val duration: Duration = parseDuration()
+
+ keyPrefix = Option(getInitParameter("keyPrefix")).map(KeyPrefix)
+ exceededProcessor = getInitParameter("exceededProcessor", Mail.ERROR)
+
+ countRateLimiter = PerSenderRateLimiter(rateLimiter = extractCountRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = Count)
+ recipientsRateLimiter = PerSenderRateLimiter(rateLimiter = extractRecipientsRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = RecipientsType)
+ sizeRateLimiter = PerSenderRateLimiter(rateLimiter = extractSizeRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = Size)
+ totalSizeRateLimiter = PerSenderRateLimiter(rateLimiter = extractTotalSizeRules(duration).map(rateLimiterFactory.withSpecification),
+ keyPrefix = keyPrefix,
+ entityType = TotalSize)
+ }
+
+ @VisibleForTesting
+ def parseDuration(): Duration =
+ Option(getInitParameter("duration"))
+ .map(string => DurationParser.parse(string, ChronoUnit.SECONDS))
+ .getOrElse(throw new IllegalArgumentException("'duration' is compulsory"))
+
+ private def extractCountRules(duration: Duration): Option[Rules] = Option(getInitParameter("count"))
+ .map(_.toLong)
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ private def extractRecipientsRules(duration: Duration): Option[Rules] = Option(getInitParameter("recipients"))
+ .map(_.toLong)
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ private def extractSizeRules(duration: Duration): Option[Rules] = Option(getInitParameter("size"))
+ .map {
+ case "" => throw new IllegalArgumentException("'size' field cannot be empty if specified")
+ case s => s
+ }
+ .map(org.apache.james.util.Size.parse)
+ .map(_.asBytes())
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ private def extractTotalSizeRules(duration: Duration): Option[Rules] = Option(getInitParameter("totalSize"))
+ .map {
+ case "" => throw new IllegalArgumentException("'totalSize' field cannot be empty if specified")
+ case s => s
+ }
+ .map(org.apache.james.util.Size.parse)
+ .map(_.asBytes())
+ .map(AllowedQuantity.liftOrThrow)
+ .map(quantity => Rules(Seq(Rule(quantity, duration))))
+
+ override def service(mail: Mail): Unit = mail.getMaybeSender
+ .asOptional()
+ .ifPresent(sender => {
+ applyRateLimiter(mail, sender)
+ })
+
+ private def applyRateLimiter(mail: Mail, sender: MailAddress): Unit = {
+ val pivot: RateLimitingResult = AcceptableRate
+ val result = SFlux.merge(Seq(
+ countRateLimiter.rateLimit(sender, mail),
+ recipientsRateLimiter.rateLimit(sender, mail),
+ sizeRateLimiter.rateLimit(sender, mail),
+ totalSizeRateLimiter.rateLimit(sender, mail)))
+ .fold(pivot)((a, b) => a.merge(b))
+ .block()
+
+ if (result.equals(RateExceeded)) {
+ mail.setState(exceededProcessor)
Review comment:
Processor is a logical groups of mailets and matchers, and it appears in the mailet container conf file.
This is a different domain area than Java publishers...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r789353183
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,211 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Quantity.Quantity
+import org.apache.james.rate.limiter.api.{AcceptableRate, Quantity, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Quantity
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Quantity = 1
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getRecipients.size())
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getMessageSize.toInt)
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow((mail.getMessageSize * mail.getRecipients.size()).toInt)
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter => limiter.rateLimit(rateLimitingKey, entityType.extractQuantity(mail)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
Review comment:
Yes this is new. While writing the code I just elt like this ade sense. This was easy to add, so I did.
Retrospectively this is required to implement some limits defined eg on the fastmail limit page (https://www.fastmail.help/hc/en-us/articles/1500000277382-Account-limits#sending/receiving) which we uses as an inspiration for this feature.
```
Please note that when you send an email to multiple recipients, this is considered one email per each recipient.
```
This proposed change allows one to turn off/on this mode at will and even combine them!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r790464379
##########
File path: server/mailet/rate-limiter/README.adoc
##########
@@ -0,0 +1,61 @@
+= Rate limiting for Apache James
+
+This maven module provide a James extension allowing one to enforce rate limiting for Apache James email processing.
+
+== Running rate limiting with the memory implementation
+
+ - 1. Compile this project.
+ - 2. Place the generated "jar with dependencies" in James `extensions-jars` folder.
+ - 3. Configure James to use the memory implementation for Rate Limiting by putting the following content within
+`extension.properties`:
+
+----
+guice.extension.module=org.apache.james.rate.limiter.memory.MemoryRateLimiterModule
+----
+
+ - 4. Use the rate limiting mailets within `mailetcontainer.xml`
+
+We provide a sample `docker-compose` demonstrating this setup.
+
+== Mailets
+
+=== PerSenderRateLimit
+
+*PerSenderRateLimit* allows defining and enforcing rate limits for the sender of matching emails.
+
+This allows writing rules like:
+
+ - A sender can send 10 emails per hour
+ - A sender can send email to a total of 20 recipients per hour
+ - A sender can send 100 MB of emails (total computed taking only the email size into account) per hour
+ - A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour
+
+Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+submitted emails, received emails or emitted email being relayed to third parties.
+
+Here are supported configuration parameters:
+
+ - *keyPrefix*: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ this mailet twice within your `mailetcontainer.xml` file. Defaults to none.
+ - *exceededProcessor*: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ Use this to customize the behaviour upon exceeded rate.
+ - *duration*: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).
+ - *count*: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *recipients*: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *size*: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.
+ - *totalSize*: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
Review comment:
Nope read more carefully please.
One is `size` one is `totalSize`. Units are the same and their difference is also explained.
Looks great to me!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1020792286
> I think the issue here is that we combine many rate limits. E.g rate limits A and B: when user requests exceed A but do not exceed B => A counter is not changed but B increases.
This mailet relies on individual, distinct rate limiters: one per limit. This wouldn't make sense.
> Should we just skip this case?
I need to have a deeper look too.
> IMO this does not impact much the overall rate limit use cases. This only happens at the edge use case when the user exceeds a rate limit. If we choose a suitable group of rate limits then it is likely that the user will exceed the other rate limit soon => that user should wait for resources regeneration.
:+1:
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r790476291
##########
File path: server/mailet/rate-limiter/README.adoc
##########
@@ -0,0 +1,61 @@
+= Rate limiting for Apache James
+
+This maven module provide a James extension allowing one to enforce rate limiting for Apache James email processing.
+
+== Running rate limiting with the memory implementation
+
+ - 1. Compile this project.
+ - 2. Place the generated "jar with dependencies" in James `extensions-jars` folder.
+ - 3. Configure James to use the memory implementation for Rate Limiting by putting the following content within
+`extension.properties`:
+
+----
+guice.extension.module=org.apache.james.rate.limiter.memory.MemoryRateLimiterModule
+----
+
+ - 4. Use the rate limiting mailets within `mailetcontainer.xml`
+
+We provide a sample `docker-compose` demonstrating this setup.
+
+== Mailets
+
+=== PerSenderRateLimit
+
+*PerSenderRateLimit* allows defining and enforcing rate limits for the sender of matching emails.
+
+This allows writing rules like:
+
+ - A sender can send 10 emails per hour
+ - A sender can send email to a total of 20 recipients per hour
+ - A sender can send 100 MB of emails (total computed taking only the email size into account) per hour
+ - A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour
+
+Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+submitted emails, received emails or emitted email being relayed to third parties.
+
+Here are supported configuration parameters:
+
+ - *keyPrefix*: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ this mailet twice within your `mailetcontainer.xml` file. Defaults to none.
+ - *exceededProcessor*: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ Use this to customize the behaviour upon exceeded rate.
+ - *duration*: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).
+ - *count*: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *recipients*: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *size*: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.
+ - *totalSize*: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
Review comment:
(finally got it after re-reading the code change and the comment 10 times...)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] quantranhong1999 commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
quantranhong1999 commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r790473801
##########
File path: server/mailet/rate-limiter/README.adoc
##########
@@ -0,0 +1,61 @@
+= Rate limiting for Apache James
+
+This maven module provide a James extension allowing one to enforce rate limiting for Apache James email processing.
+
+== Running rate limiting with the memory implementation
+
+ - 1. Compile this project.
+ - 2. Place the generated "jar with dependencies" in James `extensions-jars` folder.
+ - 3. Configure James to use the memory implementation for Rate Limiting by putting the following content within
+`extension.properties`:
+
+----
+guice.extension.module=org.apache.james.rate.limiter.memory.MemoryRateLimiterModule
+----
+
+ - 4. Use the rate limiting mailets within `mailetcontainer.xml`
+
+We provide a sample `docker-compose` demonstrating this setup.
+
+== Mailets
+
+=== PerSenderRateLimit
+
+*PerSenderRateLimit* allows defining and enforcing rate limits for the sender of matching emails.
+
+This allows writing rules like:
+
+ - A sender can send 10 emails per hour
+ - A sender can send email to a total of 20 recipients per hour
+ - A sender can send 100 MB of emails (total computed taking only the email size into account) per hour
+ - A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour
+
+Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+submitted emails, received emails or emitted email being relayed to third parties.
+
+Here are supported configuration parameters:
+
+ - *keyPrefix*: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ this mailet twice within your `mailetcontainer.xml` file. Defaults to none.
+ - *exceededProcessor*: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ Use this to customize the behaviour upon exceeded rate.
+ - *duration*: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).
+ - *count*: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *recipients*: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *size*: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.
+ - *totalSize*: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
Review comment:
I mean "(each recipient of the email email count one time)".
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] quantranhong1999 commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
quantranhong1999 commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r790457674
##########
File path: server/mailet/rate-limiter/README.adoc
##########
@@ -0,0 +1,61 @@
+= Rate limiting for Apache James
+
+This maven module provide a James extension allowing one to enforce rate limiting for Apache James email processing.
+
+== Running rate limiting with the memory implementation
+
+ - 1. Compile this project.
+ - 2. Place the generated "jar with dependencies" in James `extensions-jars` folder.
+ - 3. Configure James to use the memory implementation for Rate Limiting by putting the following content within
+`extension.properties`:
+
+----
+guice.extension.module=org.apache.james.rate.limiter.memory.MemoryRateLimiterModule
+----
+
+ - 4. Use the rate limiting mailets within `mailetcontainer.xml`
+
+We provide a sample `docker-compose` demonstrating this setup.
+
+== Mailets
+
+=== PerSenderRateLimit
+
+*PerSenderRateLimit* allows defining and enforcing rate limits for the sender of matching emails.
+
+This allows writing rules like:
+
+ - A sender can send 10 emails per hour
+ - A sender can send email to a total of 20 recipients per hour
+ - A sender can send 100 MB of emails (total computed taking only the email size into account) per hour
+ - A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour
+
+Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+submitted emails, received emails or emitted email being relayed to third parties.
+
+Here are supported configuration parameters:
+
+ - *keyPrefix*: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ this mailet twice within your `mailetcontainer.xml` file. Defaults to none.
+ - *exceededProcessor*: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ Use this to customize the behaviour upon exceeded rate.
+ - *duration*: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).
+ - *count*: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *recipients*: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *size*: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.
+ - *totalSize*: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
Review comment:
duplicated email L46
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] quantranhong1999 commented on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
quantranhong1999 commented on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1020768123
> I think this is more part of the underlying `RateLimiter` component and we _might_ be limited on this by the `RateLimitJ` choice.
I did read some implementation code of RateLimitJ. I think it works fine for an individual rate limit. e.g when a user requests a number of requests that exceed the limit, RateLimitJ does not increase the counter.
I think the issue here is that we combine many rate limits. E.g rate limits A and B: when user requests exceed A but do not exceed B => A counter is not changed but B increases.
If we have an API for checking whether the rate limit will be exceeded without actually increasing it yet, we can check all rate limits together. But I do not see RateLimitJ exposing that API... Any idea? Should we just skip this case?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1020975708
> I think I might find a bug here. I think we should not increase the counter when it exceeds one of the rate limits. Please have a look at the test below:
Ah I got it: it is an **atomicity** problem!
If one of the limits is reached, we will increment the ones that were checked before - and passed.
Ok I understand, and this would actually be a really hard problem to tackle. I would also agree ignoring this,
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1019999304
> I think I might find a bug here. I think we should not increase the counter when it exceeds one of the rate limits. Please have a look at the test below:
I think this is more part of the underlying `RateLimiter` component and we *might* be limited on this by the `RateLimitJ` choice.
Could you be having a look, @quantranhong1999 ?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa merged pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa merged pull request #851:
URL: https://github.com/apache/james-project/pull/851
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r790476562
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,220 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Increment.Increment
+import org.apache.james.rate.limiter.api.{AcceptableRate, AllowedQuantity, Increment, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import scala.util.Try
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Option[Increment]
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(1)
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getRecipients.size()))
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getMessageSize.toInt))
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Option[Increment] =
+ Try(Math.multiplyExact(mail.getMessageSize.toInt, mail.getRecipients.size()).toInt)
+ .map(Increment.liftOrThrow)
+ .toOption
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter =>
+ entityType.extractQuantity(mail)
+ .map(increment => limiter.rateLimit(rateLimitingKey, increment))
+ .getOrElse(SMono.just[RateLimitingResult](RateExceeded)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
+ * <li>A sender can send 100 MB of emails (total computed taking only the email size into account) per hour</li>
+ * <li>A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour</li>
+ * </ul>
+ *
+ * <p>Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+ * submitted emails, received emails or emitted email being relayed to third parties.</p>
+ *
+ * <ul>Here are supported configuration parameters:
+ * <li><b>keyPrefix</b>: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ * this mailet twice within your <code>mailetcontainer.xml</code> file. Defaults to none.</li>
+ * <li><b>exceededProcessor</b>: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ * Use this to customize the behaviour upon exceeded rate.</li>
+ * <li><b>duration</b>: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).</li>
+ * <li><b>count</b>: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>recipients</b>: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>size</b>: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.</li>
+ * <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
Review comment:
```suggestion
* <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] quantranhong1999 commented on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
quantranhong1999 commented on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1020768123
> I think this is more part of the underlying `RateLimiter` component and we _might_ be limited on this by the `RateLimitJ` choice.
I did read some implementation code of RateLimitJ. I think it works fine for an individual rate limit. e.g when a user requests a number of requests that exceed the limit, RateLimitJ does not increase the counter.
I think the issue here is that we combine many rate limits. E.g rate limits A and B: when user requests exceed A but do not exceed B => A counter is not changed but B increases.
If we have an API for checking whether the rate limit will be exceeded without actually increasing it yet, we can check all rate limits together. But I do not see RateLimitJ exposing that API... Any idea? Should we just skip this case?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] vttranlina commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
vttranlina commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788359528
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,211 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Quantity.Quantity
+import org.apache.james.rate.limiter.api.{AcceptableRate, Quantity, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Quantity
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Quantity = 1
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getRecipients.size())
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getMessageSize.toInt)
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow((mail.getMessageSize * mail.getRecipients.size()).toInt)
Review comment:
`mail.getMessageSize` returning `long`.
So `.toLong` is better?
Anw,
Max value of `Int` = 2147483647
2147483647 bytes = ~ 2147MB = ~ 2GB
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] Arsnael commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
Arsnael commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r789362037
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,211 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Quantity.Quantity
+import org.apache.james.rate.limiter.api.{AcceptableRate, Quantity, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Quantity
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Quantity = 1
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getRecipients.size())
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getMessageSize.toInt)
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow((mail.getMessageSize * mail.getRecipients.size()).toInt)
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter => limiter.rateLimit(rateLimitingKey, entityType.extractQuantity(mail)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
Review comment:
Well I'm ok with it, maybe should add it quickly on the ticket though :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] vttranlina commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
vttranlina commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788503706
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,220 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Increment.Increment
+import org.apache.james.rate.limiter.api.{AcceptableRate, AllowedQuantity, Increment, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import scala.util.Try
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Option[Increment]
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(1)
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getRecipients.size()))
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getMessageSize.toInt))
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Option[Increment] =
+ Try(Math.multiplyExact(mail.getMessageSize.toInt, mail.getRecipients.size()).toInt)
+ .map(Increment.liftOrThrow)
+ .toOption
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter =>
+ entityType.extractQuantity(mail)
+ .map(increment => limiter.rateLimit(rateLimitingKey, increment))
+ .getOrElse(SMono.just[RateLimitingResult](RateExceeded)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
+ * <li>A sender can send 100 MB of emails (total computed taking only the email size into account) per hour</li>
+ * <li>A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour</li>
+ * </ul>
+ *
+ * <p>Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+ * submitted emails, received emails or emitted email being relayed to third parties.</p>
+ *
+ * <ul>Here are supported configuration parameters:
+ * <li><b>keyPrefix</b>: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ * this mailet twice within your <code>mailetcontainer.xml</code> file. Defaults to none.</li>
+ * <li><b>exceededProcessor</b>: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ * Use this to customize the behaviour upon exceeded rate.</li>
+ * <li><b>duration</b>: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).</li>
+ * <li><b>count</b>: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>recipients</b>: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>size</b>: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.</li>
+ * <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
+ * totalSize is limited in increments of 2exp(31) - ~2 billions: sending a 10MB file to more than 205 recipients will be rejected if this parameter is enabled.</li>
+ * </ul>
+ *
+ * <p>For instance, to apply all the examples given above:</p>
+ *
+ * <pre><code>
+ * <mailet matcher="All" class="PerSenderRateLimit">
+ * <keyPrefix>myPrefix</keyPrefix>
Review comment:
format...difficult to read,
is this just temporary?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788714374
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,220 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Increment.Increment
+import org.apache.james.rate.limiter.api.{AcceptableRate, AllowedQuantity, Increment, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import scala.util.Try
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Option[Increment]
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(1)
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getRecipients.size()))
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getMessageSize.toInt))
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Option[Increment] =
+ Try(Math.multiplyExact(mail.getMessageSize.toInt, mail.getRecipients.size()).toInt)
+ .map(Increment.liftOrThrow)
+ .toOption
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter =>
+ entityType.extractQuantity(mail)
+ .map(increment => limiter.rateLimit(rateLimitingKey, increment))
+ .getOrElse(SMono.just[RateLimitingResult](RateExceeded)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
+ * <li>A sender can send 100 MB of emails (total computed taking only the email size into account) per hour</li>
+ * <li>A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour</li>
+ * </ul>
+ *
+ * <p>Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+ * submitted emails, received emails or emitted email being relayed to third parties.</p>
+ *
+ * <ul>Here are supported configuration parameters:
+ * <li><b>keyPrefix</b>: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ * this mailet twice within your <code>mailetcontainer.xml</code> file. Defaults to none.</li>
+ * <li><b>exceededProcessor</b>: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ * Use this to customize the behaviour upon exceeded rate.</li>
+ * <li><b>duration</b>: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).</li>
+ * <li><b>count</b>: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>recipients</b>: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>size</b>: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.</li>
+ * <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
+ * totalSize is limited in increments of 2exp(31) - ~2 billions: sending a 10MB file to more than 205 recipients will be rejected if this parameter is enabled.</li>
+ * </ul>
+ *
+ * <p>For instance, to apply all the examples given above:</p>
+ *
+ * <pre><code>
+ * <mailet matcher="All" class="PerSenderRateLimit">
+ * <keyPrefix>myPrefix</keyPrefix>
Review comment:
Nope, javadoc needs escaped HTML! That's needed for the mailet doc plugin... No choice ;-) Hopefully the readme is more friendly.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r789353183
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,211 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Quantity.Quantity
+import org.apache.james.rate.limiter.api.{AcceptableRate, Quantity, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Quantity
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Quantity = 1
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getRecipients.size())
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow(mail.getMessageSize.toInt)
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Quantity = Quantity.liftOrThrow((mail.getMessageSize * mail.getRecipients.size()).toInt)
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter => limiter.rateLimit(rateLimitingKey, entityType.extractQuantity(mail)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
Review comment:
Yes this is new. While writing the code I just elt like this ade sense. This was easy to add, so I did.
Retrospectively this is required to implement some limits defined eg on the fastmail limit page (https://www.fastmail.help/hc/en-us/articles/1500000277382-Account-limits) which we uses as an inspiration for this feature.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] vttranlina commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
vttranlina commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r788651870
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,220 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Increment.Increment
+import org.apache.james.rate.limiter.api.{AcceptableRate, AllowedQuantity, Increment, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import scala.util.Try
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Option[Increment]
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(1)
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getRecipients.size()))
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getMessageSize.toInt))
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Option[Increment] =
+ Try(Math.multiplyExact(mail.getMessageSize.toInt, mail.getRecipients.size()).toInt)
+ .map(Increment.liftOrThrow)
+ .toOption
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter =>
+ entityType.extractQuantity(mail)
+ .map(increment => limiter.rateLimit(rateLimitingKey, increment))
+ .getOrElse(SMono.just[RateLimitingResult](RateExceeded)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
+ * <li>A sender can send 100 MB of emails (total computed taking only the email size into account) per hour</li>
+ * <li>A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour</li>
+ * </ul>
+ *
+ * <p>Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+ * submitted emails, received emails or emitted email being relayed to third parties.</p>
+ *
+ * <ul>Here are supported configuration parameters:
+ * <li><b>keyPrefix</b>: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ * this mailet twice within your <code>mailetcontainer.xml</code> file. Defaults to none.</li>
+ * <li><b>exceededProcessor</b>: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ * Use this to customize the behaviour upon exceeded rate.</li>
+ * <li><b>duration</b>: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).</li>
+ * <li><b>count</b>: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>recipients</b>: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>size</b>: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.</li>
+ * <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
+ * totalSize is limited in increments of 2exp(31) - ~2 billions: sending a 10MB file to more than 205 recipients will be rejected if this parameter is enabled.</li>
+ * </ul>
+ *
+ * <p>For instance, to apply all the examples given above:</p>
+ *
+ * <pre><code>
+ * <mailet matcher="All" class="PerSenderRateLimit">
+ * <keyPrefix>myPrefix</keyPrefix>
+ * <duration>1h</duration>
+ * <count>10</count>
+ * <recipients>20</recipients>
+ * <size>100M</size>
+ * <totalSize>200M</totalSize>
+ * </mailet>
+ * </code></pre>
+ *
+ * <p>Note that to use this extension you need to place the rate-limiter JAR in the <code>extensions-jars</code> folder
+ * and need to configure a viable option to invoke <code>RateLimiterFactoryProvider</code> which can be done by
+ * loading <code>org.apache.james.rate.limiter.memory.MemoryRateLimiterModule</code> Guice module within the
+ * <code>guice.extension.module</code> in <code>extensions.properties</code> configuration file. Note that other Rate
+ * limiter implementation might require extra configuration parameters within your mailet.</p>
+ *
+ * @param rateLimiterFactoryProvider Allows instantiations of the underlying rate limiters.
+ */
+class PerSenderRateLimit @Inject()(rateLimiterFactoryProvider: RateLimiterFactoryProvider) extends GenericMailet {
Review comment:
Should we need `@Named` here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] vttranlina commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
vttranlina commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r789327519
##########
File path: server/mailet/rate-limiter/src/main/scala/org/apache/james/transport/mailets/PerSenderRateLimit.scala
##########
@@ -0,0 +1,220 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets
+
+import java.time.Duration
+import java.time.temporal.ChronoUnit
+
+import com.google.common.annotations.VisibleForTesting
+import eu.timepit.refined.auto._
+import javax.inject.Inject
+import org.apache.james.core.MailAddress
+import org.apache.james.rate.limiter.api.Increment.Increment
+import org.apache.james.rate.limiter.api.{AcceptableRate, AllowedQuantity, Increment, RateExceeded, RateLimiter, RateLimiterFactoryProvider, RateLimitingKey, RateLimitingResult, Rule, Rules}
+import org.apache.james.util.DurationParser
+import org.apache.mailet.Mail
+import org.apache.mailet.base.GenericMailet
+import org.reactivestreams.Publisher
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import scala.util.Try
+
+case class KeyPrefix(value: String)
+
+sealed trait EntityType {
+ def asString(): String
+
+ def extractQuantity(mail: Mail): Option[Increment]
+}
+
+case object Count extends EntityType {
+ override def asString(): String = "count"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(1)
+}
+case object RecipientsType extends EntityType {
+ override def asString(): String = "recipients"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getRecipients.size()))
+}
+case object Size extends EntityType {
+ override def asString(): String = "size"
+
+ override def extractQuantity(mail: Mail): Option[Increment] = Some(Increment.liftOrThrow(mail.getMessageSize.toInt))
+}
+case object TotalSize extends EntityType {
+ override def asString(): String = "totalSize"
+
+ override def extractQuantity(mail: Mail): Option[Increment] =
+ Try(Math.multiplyExact(mail.getMessageSize.toInt, mail.getRecipients.size()).toInt)
+ .map(Increment.liftOrThrow)
+ .toOption
+}
+
+case class PerSenderRateLimiter(rateLimiter: Option[RateLimiter], keyPrefix: Option[KeyPrefix], entityType: EntityType) {
+ def rateLimit(sender: MailAddress, mail: Mail): Publisher[RateLimitingResult] = {
+ val rateLimitingKey = SenderKey(keyPrefix, entityType, sender)
+
+ rateLimiter.map(limiter =>
+ entityType.extractQuantity(mail)
+ .map(increment => limiter.rateLimit(rateLimitingKey, increment))
+ .getOrElse(SMono.just[RateLimitingResult](RateExceeded)))
+ .getOrElse(SMono.just[RateLimitingResult](AcceptableRate))
+ }
+}
+
+case class SenderKey(keyPrefix: Option[KeyPrefix], entityType: EntityType, mailAddress: MailAddress) extends RateLimitingKey {
+ override def asString(): String = keyPrefix.map(prefix => s"${prefix.value}_${entityType.asString()}_${mailAddress.asString()}")
+ .getOrElse(s"${entityType.asString()}_${mailAddress.asString()}")
+}
+
+/**
+ * <p><b>PerSenderRateLimit</b> allows defining and enforcing rate limits for the sender of matching emails.</p>
+ *
+ * <ul>This allows writing rules like:
+ * <li>A sender can send 10 emails per hour</li>
+ * <li>A sender can send email to a total of 20 recipients per hour</li>
+ * <li>A sender can send 100 MB of emails (total computed taking only the email size into account) per hour</li>
+ * <li>A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour</li>
+ * </ul>
+ *
+ * <p>Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+ * submitted emails, received emails or emitted email being relayed to third parties.</p>
+ *
+ * <ul>Here are supported configuration parameters:
+ * <li><b>keyPrefix</b>: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ * this mailet twice within your <code>mailetcontainer.xml</code> file. Defaults to none.</li>
+ * <li><b>exceededProcessor</b>: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ * Use this to customize the behaviour upon exceeded rate.</li>
+ * <li><b>duration</b>: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).</li>
+ * <li><b>count</b>: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>recipients</b>: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.</li>
+ * <li><b>size</b>: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.</li>
+ * <li><b>totalSize</b>: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
+ * totalSize is limited in increments of 2exp(31) - ~2 billions: sending a 10MB file to more than 205 recipients will be rejected if this parameter is enabled.</li>
+ * </ul>
+ *
+ * <p>For instance, to apply all the examples given above:</p>
+ *
+ * <pre><code>
+ * <mailet matcher="All" class="PerSenderRateLimit">
+ * <keyPrefix>myPrefix</keyPrefix>
+ * <duration>1h</duration>
+ * <count>10</count>
+ * <recipients>20</recipients>
+ * <size>100M</size>
+ * <totalSize>200M</totalSize>
+ * </mailet>
+ * </code></pre>
+ *
+ * <p>Note that to use this extension you need to place the rate-limiter JAR in the <code>extensions-jars</code> folder
+ * and need to configure a viable option to invoke <code>RateLimiterFactoryProvider</code> which can be done by
+ * loading <code>org.apache.james.rate.limiter.memory.MemoryRateLimiterModule</code> Guice module within the
+ * <code>guice.extension.module</code> in <code>extensions.properties</code> configuration file. Note that other Rate
+ * limiter implementation might require extra configuration parameters within your mailet.</p>
+ *
+ * @param rateLimiterFactoryProvider Allows instantiations of the underlying rate limiters.
+ */
+class PerSenderRateLimit @Inject()(rateLimiterFactoryProvider: RateLimiterFactoryProvider) extends GenericMailet {
Review comment:
> IMO we do not need named injects: all instances creating rateLimiters could use the very same factory.
ok (y)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] quantranhong1999 edited a comment on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
quantranhong1999 edited a comment on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1020768123
> I think this is more part of the underlying `RateLimiter` component and we _might_ be limited on this by the `RateLimitJ` choice.
I did read some implementation code of RateLimitJ. I think it works fine for an individual rate limit. e.g when a user requests a number of requests that exceed the limit, RateLimitJ does not increase the counter.
I think the issue here is that we combine many rate limits. E.g rate limits A and B: when user requests exceed A but do not exceed B => A counter is not changed but B increases.
If we have an API for checking whether the rate limit will be exceeded without actually increasing it yet, we can check all rate limits together. But I do not see RateLimitJ exposing that API... Any idea? Should we just skip this case?
IMO this does not impact much the overall rate limit use cases. This only happens at the edge use case when the user exceeds a rate limit. If we choose a suitable group of rate limits then it is likely that the user will exceed the other rate limit soon => that user should wait for resources regeneration.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] quantranhong1999 commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
quantranhong1999 commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r790457674
##########
File path: server/mailet/rate-limiter/README.adoc
##########
@@ -0,0 +1,61 @@
+= Rate limiting for Apache James
+
+This maven module provide a James extension allowing one to enforce rate limiting for Apache James email processing.
+
+== Running rate limiting with the memory implementation
+
+ - 1. Compile this project.
+ - 2. Place the generated "jar with dependencies" in James `extensions-jars` folder.
+ - 3. Configure James to use the memory implementation for Rate Limiting by putting the following content within
+`extension.properties`:
+
+----
+guice.extension.module=org.apache.james.rate.limiter.memory.MemoryRateLimiterModule
+----
+
+ - 4. Use the rate limiting mailets within `mailetcontainer.xml`
+
+We provide a sample `docker-compose` demonstrating this setup.
+
+== Mailets
+
+=== PerSenderRateLimit
+
+*PerSenderRateLimit* allows defining and enforcing rate limits for the sender of matching emails.
+
+This allows writing rules like:
+
+ - A sender can send 10 emails per hour
+ - A sender can send email to a total of 20 recipients per hour
+ - A sender can send 100 MB of emails (total computed taking only the email size into account) per hour
+ - A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour
+
+Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+submitted emails, received emails or emitted email being relayed to third parties.
+
+Here are supported configuration parameters:
+
+ - *keyPrefix*: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ this mailet twice within your `mailetcontainer.xml` file. Defaults to none.
+ - *exceededProcessor*: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ Use this to customize the behaviour upon exceeded rate.
+ - *duration*: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).
+ - *count*: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *recipients*: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *size*: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.
+ - *totalSize*: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
Review comment:
duplicated email
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa commented on a change in pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa commented on a change in pull request #851:
URL: https://github.com/apache/james-project/pull/851#discussion_r790475939
##########
File path: server/mailet/rate-limiter/README.adoc
##########
@@ -0,0 +1,61 @@
+= Rate limiting for Apache James
+
+This maven module provide a James extension allowing one to enforce rate limiting for Apache James email processing.
+
+== Running rate limiting with the memory implementation
+
+ - 1. Compile this project.
+ - 2. Place the generated "jar with dependencies" in James `extensions-jars` folder.
+ - 3. Configure James to use the memory implementation for Rate Limiting by putting the following content within
+`extension.properties`:
+
+----
+guice.extension.module=org.apache.james.rate.limiter.memory.MemoryRateLimiterModule
+----
+
+ - 4. Use the rate limiting mailets within `mailetcontainer.xml`
+
+We provide a sample `docker-compose` demonstrating this setup.
+
+== Mailets
+
+=== PerSenderRateLimit
+
+*PerSenderRateLimit* allows defining and enforcing rate limits for the sender of matching emails.
+
+This allows writing rules like:
+
+ - A sender can send 10 emails per hour
+ - A sender can send email to a total of 20 recipients per hour
+ - A sender can send 100 MB of emails (total computed taking only the email size into account) per hour
+ - A sender can send 200 MB of emails (total computed taking each recipient copies into account) per hour
+
+Depending on its position and the matcher it is being combined with, those rate limiting rules could be applied to
+submitted emails, received emails or emitted email being relayed to third parties.
+
+Here are supported configuration parameters:
+
+ - *keyPrefix*: An optional key prefix to apply to rate limiting. Choose distinct values if you specify
+ this mailet twice within your `mailetcontainer.xml` file. Defaults to none.
+ - *exceededProcessor*: Processor to which emails whose rate is exceeded should be redirected to. Defaults to error.
+ Use this to customize the behaviour upon exceeded rate.
+ - *duration*: Duration during which the rate limiting shall be applied. Compulsory, must be a valid duration of at least one second. Supported units includes s (second), m (minute), h (hour), d (day).
+ - *count*: Count of emails allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *recipients*: Count of recipients allowed for a given sender during duration. Optional, if unspecified this rate limit is not applied.
+ - *size*: Size of emails allowed for a given sender during duration (each email count one time, regardless of recipient count). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B.
+ - *totalSize*: Size of emails allowed for a given sender during duration (each recipient of the email email count one time). Optional, if unspecified this rate limit is not applied. Supported units : B ( 2^0 ), K ( 2^10 ), M ( 2^20 ), G ( 2^30 ), defaults to B. Note that
Review comment:
Sorry, your comments are not clear enough. Please be more precise.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
[GitHub] [james-project] chibenwa edited a comment on pull request #851: JAMES-3683 Implement PerSenderRateLimit mailet
Posted by GitBox <gi...@apache.org>.
chibenwa edited a comment on pull request #851:
URL: https://github.com/apache/james-project/pull/851#issuecomment-1019999304
> I think I might find a bug here. I think we should not increase the counter when it exceeds one of the rate limits. Please have a look at the test below:
I think this is more part of the underlying `RateLimiter` component and we *might* be limited on this by the `RateLimitJ` choice.
Could you be having a look, @quantranhong1999 ?
(If you are right, this IMO do not impact much rate limiting use cases but definitely jeopardizes throttling use cases)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org