eric-maynard commented on code in PR #278:
URL: https://github.com/apache/polaris/pull/278#discussion_r1770877189


##########
polaris-service/src/main/java/org/apache/polaris/service/ratelimiter/TokenBucketRateLimiter.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.polaris.service.ratelimiter;
+
+import java.time.InstantSource;
+
+/**
+ * Token bucket implementation of a Polaris RateLimiter. Acquires tokens at a 
fixed rate and has a
+ * maximum amount of tokens. Each "acquire" costs 1 token.
+ */
+public class TokenBucketRateLimiter implements RateLimiter {
+  private final double tokensPerMilli;
+  private final long maxTokens;
+  private final InstantSource instantSource;
+
+  private double tokens;
+  private long lastAcquireMillis;
+
+  public TokenBucketRateLimiter(long tokensPerSecond, long maxTokens, 
InstantSource instantSource) {
+    this.tokensPerMilli = tokensPerSecond / 1000D;
+    this.maxTokens = maxTokens;
+    this.instantSource = instantSource;
+
+    tokens = maxTokens;
+    lastAcquireMillis = instantSource.millis();
+  }
+
+  /**
+   * Tries to acquire and spend 1 token. Doesn't block if a token isn't 
available.
+   *
+   * @return whether a token was successfully acquired & spent
+   */
+  @Override
+  public synchronized boolean tryAcquire() {
+    // Grant tokens for the time that has passed since our last tryAcquire()
+    long t = instantSource.millis();
+    long millisPassed = t - lastAcquireMillis;
+    lastAcquireMillis = t;

Review Comment:
   Shouldn't we only be updating this if the acquire is successful?



##########
polaris-service/src/main/java/org/apache/polaris/service/ratelimiter/TokenBucketRateLimiter.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.polaris.service.ratelimiter;
+
+import java.time.InstantSource;
+
+/**
+ * Token bucket implementation of a Polaris RateLimiter. Acquires tokens at a 
fixed rate and has a
+ * maximum amount of tokens. Each "acquire" costs 1 token.
+ */
+public class TokenBucketRateLimiter implements RateLimiter {
+  private final double tokensPerMilli;
+  private final long maxTokens;
+  private final InstantSource instantSource;
+
+  private double tokens;
+  private long lastAcquireMillis;
+
+  public TokenBucketRateLimiter(long tokensPerSecond, long maxTokens, 
InstantSource instantSource) {
+    this.tokensPerMilli = tokensPerSecond / 1000D;
+    this.maxTokens = maxTokens;
+    this.instantSource = instantSource;
+
+    tokens = maxTokens;
+    lastAcquireMillis = instantSource.millis();
+  }
+
+  /**
+   * Tries to acquire and spend 1 token. Doesn't block if a token isn't 
available.
+   *
+   * @return whether a token was successfully acquired & spent
+   */
+  @Override
+  public synchronized boolean tryAcquire() {
+    // Grant tokens for the time that has passed since our last tryAcquire()
+    long t = instantSource.millis();
+    long millisPassed = t - lastAcquireMillis;
+    lastAcquireMillis = t;
+    tokens = Math.min(maxTokens, tokens + (millisPassed * tokensPerMilli));

Review Comment:
   We should check for overflow here too. All of this is kind of scary. I would 
rather us not write this ourselves if we can use something existing.



##########
polaris-service/src/main/java/org/apache/polaris/service/ratelimiter/TokenBucketRateLimiter.java:
##########
@@ -0,0 +1,62 @@
+/*
+ * 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.polaris.service.ratelimiter;
+
+/**
+ * Token bucket implementation of a Polaris RateLimiter. Acquires tokens at a 
fixed rate and has a
+ * maximum amount of tokens. Each "acquire" costs 1 token.
+ */
+public class TokenBucketRateLimiter implements RateLimiter {

Review Comment:
   Java's Semaphore has a 
[tryAcquire](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html#tryAcquire()),
 and you could reject the request if that returns `false`.



##########
polaris-service/src/main/java/org/apache/polaris/service/ratelimiter/RateLimiterFilter.java:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.polaris.service.ratelimiter;
+
+import jakarta.annotation.Priority;
+import jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.core.Response;
+import java.io.IOException;
+import java.time.Clock;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.apache.polaris.core.context.CallContext;
+import org.apache.polaris.core.context.RealmContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Request filter that returns a 429 Too Many Requests if the rate limiter 
says so */
+@Priority(Priorities.AUTHORIZATION + 1)
+public class RateLimiterFilter implements Filter {
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(RateLimiterFilter.class);
+  private static final RateLimiter NO_OP_LIMITER = new NoOpRateLimiter();
+  private static final RateLimiter ALWAYS_REJECT_LIMITER =
+      new TokenBucketRateLimiter(0, 0, Clock.systemUTC());
+
+  private final RateLimiterConfig config;
+  private final Map<String, Future<RateLimiter>> perRealmLimiters = new 
ConcurrentHashMap<>();
+
+  public RateLimiterFilter(RateLimiterConfig config) {
+    this.config = config;
+  }
+
+  /** Returns a 429 if the rate limiter says so. Otherwise, forwards the 
request along. */
+  @Override
+  public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain)
+      throws IOException, ServletException {
+    RealmContext realmContext = 
CallContext.getCurrentContext().getRealmContext();
+    RateLimiter rateLimiter = maybeBlockToGetRateLimiter(realmContext);
+    if (!rateLimiter.tryAcquire()) {
+      ((HttpServletResponse) 
response).setStatus(Response.Status.TOO_MANY_REQUESTS.getStatusCode());
+      return;
+    }
+    chain.doFilter(request, response);
+  }
+
+  private RateLimiter maybeBlockToGetRateLimiter(RealmContext realmContext) {
+    try {
+      return perRealmLimiters

Review Comment:
   +1 to this, maybe we can introduce a thin type to cover our bases here. 
   
   So...
   ```
   public record RateLimiterInfo(RealmContext realmContext) {}
   
   . . .
   
   private RateLimiter maybeBlockToGetRateLimiter(RateLimiterInfo 
rateLimiterInfo) { ... }
   private final Map<RateLimiterInfo, Future<RateLimiter>> rateLimiters = new 
ConcurrentHashMap<>();
   // etc.
   
   ...
   ```
   
   This might let us add more fine grained rate limiters later on without 
having to hack up the APIs.



-- 
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: commits-unsubscr...@polaris.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to