Giter VIP home page Giter VIP logo

ratelimit's Introduction

Rate Limit

Version Build Status Swift Version Carthage compatible CocoaPods compatible

Simple utility for only executing code every so often.

This will only execute the block passed for a given name if the last time it was called is greater than limit or it has never been called.

This is really handy for refreshing stuff in viewDidAppear: but preventing it from happening a ton if it was just refreshed.

Rate Limit is fully thread-safe. Released under the MIT license.

Usage

We’ll start out with a TimedLimiter:

// Initialize with a limit of 5, so you can only use this once every 5 seconds.
let refreshTimeline = TimedLimiter(limit: 5)

// Call the work you want to limit by passing a block to the execute method.
refreshTimeline.execute {
    // Do some work that runs a maximum of once per 5 seconds.
}

Limiters aren’t persisted across application launches.

Synchronous Limiters

TimedLimiter conforms to the SyncLimiter protocol. This means that the block you pass to execute will be called synchronously on the queue you called it from if it should fire. TimedLimiter uses time to limit.

CountedLimiter is also included. This works by taking a limit as a UInt for the maximum number of times to run the block.

The SyncLimiter protocol has a really neat extension that let’s you do things like this:

let funFactLimiter = CountedLimiter(limit: 2)
let funFact = funFactLimiter.execute { () -> String in
    // Do real things to get a fun fact from a list
    return "Hi"
}

Now funFact is a String?. It’s just an optional of whatever you return from the block. The returned value will be nil if the block didn’t run.

You can of course make your own SyncLimiters too!

Asynchronous Limiter

One AsyncLimiter is included. You can make your own too. The included async limiter is DebouncedLimiter. This is perfect for making network requests as a user types or other tasks that respond to very frequent events.

The interface is slightly different:

let searchLimiter = DebouncedLimiter(limit: 1, block: performSearch)

func textDidChange() {
  searchLimiter.execute()
}

You would have to setup the limiter in an initializer since it references an instance method, but you get the idea. The block will be called at most once per second in this configuration.

Pretty easy!

Open up the included Xcode project for an example app and tests.

Installation

Carthage

Carthage is the recommended way to install Rate Limit. Add the following to your Cartfile:

github "soffes/RateLimit"

CocoaPods

Add the following to your Podfile:

pod "RateLimit"

Then run pod install.

ratelimit's People

Contributors

basememara avatar calebd avatar carlj avatar hyperspacemark avatar javisoto avatar mz2 avatar piemonte avatar soffes avatar streeter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ratelimit's Issues

RateLimit is not Bitcode compatible

This one is hard to explain. If I upload a build that both contains RateLimit and has Bitcode enabled I get this:

screen shot 2015-11-25 at 11 31 07 pm

Thanks to @mattbischoff, I found the following message in this developer forum thread:

To see the error, achive/export/developer enable bitcode gen. Then when it errors, click the 'view logs' button to see the problem.

And indeed there it was:

error: Ld: cd /var/folders/1g/fssqm74d49qb4m09k14h_8780000gn/T/tempdVAWUo
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" "-arch" "armv7" "-dylib" "-compatibility_version" "1.0.0" "-current_version" "1.0.0.0.0" "-install_name" "@rpath/RateLimit.framework/RateLimit" "-ios_version_min" "8.0.0" "-rpath" "@executable_path/Frameworks" "-rpath" "@loader_path/Frameworks" "-dead_strip" "-application_extension" "-syslibroot" "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.1.sdk" "-sdk_version" "9.1.0" "-ignore_auto_link" "-allow_dead_duplicates" "1.o" "2.o" "3.o" "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.1.sdk/usr/lib/libSystem.B.tbd" "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.1.sdk/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation.tbd" "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.1.sdk/System/Library/Frameworks/Foundation.framework/Foundation.tbd" "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.1.sdk/usr/lib/libobjc.A.tbd" "/var/folders/1g/fssqm74d49qb4m09k14h_8780000gn/T/ipatool20151125-21309-1yedmou/MachOs/iphoneos/armv7/(dylibs)/libswiftCore.dylib" "/var/folders/1g/fssqm74d49qb4m09k14h_8780000gn/T/ipatool20151125-21309-1yedmou/MachOs/iphoneos/armv7/(dylibs)/libswiftDarwin.dylib" "/var/folders/1g/fssqm74d49qb4m09k14h_8780000gn/T/ipatool20151125-21309-1yedmou/MachOs/iphoneos/armv7/(dylibs)/libswiftDispatch.dylib" "/var/folders/1g/fssqm74d49qb4m09k14h_8780000gn/T/ipatool20151125-21309-1yedmou/MachOs/iphoneos/armv7/(dylibs)/libswiftFoundation.dylib" "/var/folders/1g/fssqm74d49qb4m09k14h_8780000gn/T/ipatool20151125-21309-1yedmou/MachOs/iphoneos/armv7/(dylibs)/libswiftObjectiveC.dylib" "-L" "/var/folders/1g/fssqm74d49qb4m09k14h_8780000gn/T/ipatool20151125-21309-1yedmou/MachOs/iphoneos/armv7/(dylibs)" "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/7.0.0/lib/darwin/libclang_rt.ios.a" "-o" "/private/var/folders/1g/fssqm74d49qb4m09k14h_8780000gn/T/RateLimitkGMPU9/RateLimit.armv7.out" 
-= Output =-
Undefined symbols for architecture armv7:
  "_llvm_gcov_init", referenced from:
      ___hidden#311_ in 3.o
  "_llvm_gcda_start_file", referenced from:
      ___hidden#309_ in 3.o
  "_llvm_gcda_summary_info", referenced from:
      ___hidden#309_ in 3.o
  "_llvm_gcda_end_file", referenced from:
      ___hidden#309_ in 3.o
ld: symbol(s) not found for architecture armv7
Exited with 1


error: Failed to compile bundle: /var/folders/1g/fssqm74d49qb4m09k14h_8780000gn/T/RateLimitkGMPU9/RateLimit.armv7.xar}

I'm now trying to figure out exactly what these symbols are and why they are allegedly referenced from RateLimit. I will post back here when I know more.

Timed+CountedLimit

Is it possible to combine two or more rate limits in order to achieve max N requests every M seconds?

Update Lookup date only when ShouldExecute is true

I was reading the class that implements the validation logic to run the rate limit.
While reading the class method below:

private class func shouldExecute(name name: String, limit: NSTimeInterval) -> Bool

I've notice the lookup date is updated regardless if 'should' is true or false.
I would expect the last executed date to be updated when the limit has passed. That way, subsequent request could refer to the original date instead of the last checked date.

Sorry for not making a pull request.

Possible bug?

Line 67 in RateLimit.swift:

// Record execution
dictionary[name] = NSDate()

You record new execution time even if decide to not execute? Is that right?

Adding block parameter to DebouncedLimiter.execute?

Great library btw, thanks for sharing this!

I was wondering what the thoughts were behind not providing a block parameter to the execute function of the DebouncedLimiter like TimedLimiter? I wanted to do something like this:

let refreshTimeline = DebouncedLimiter(limit: 5)

refreshTimeline.execute {
    // Do some work that only runs last block per 5 seconds.
}

I have extended this in my fork to do this, but wanted to get your thoughts before creating a PR in case there's something I'm missing: https://github.com/basememara/RateLimit/commit/763a1b60fdc5884b70540cbb1c58aff6874a68b9

Defer execution until end of limit

I think this library is a really great idea, but I have one question about how this would work.

I would like to use RateLimit within updateSearchResultsForSearchController(), as is shown in Little Bytes Of Cocoa 81. http://i.imgur.com/srdLoLr.png

My problem is, though I don't want to call the search request too often, if the user STOPS typing then the request should be made no matter what. I don't want to have the user type in My Search Term but the last network request was with the query My Sea. Their results would be pretty off in that case.

Does RateLimit already implement anything to handle this scenario? I'm thinking of maybe having an option where, if at any point DURING the limited time execute is called again, then the call will be deferred until the end of the limit time. It would only execute once at the end of the limit time, no matter how many times execute was called during that time.

Is this already implemented? If not, is it a viable addition?

TVOS Support?

Any plan to add it?

  spec.osx.deployment_target = '10.9'
  spec.ios.deployment_target = '8.0'
  spec.watchos.deployment_target = '2.0'

Of course not having access to store we can't just add it there, maybe add it as key-value storage in iCloud or something similar?

Not sure this be useful, but...

What about CFTimeInterval and CACurrentMediaTime() instead of NSDate?

private static var executionTimeByName = [String: CFTimeInterval]()
...
if let lastExecutedTime = executionTimeByName[name] {
            let elapsed = CACurrentMediaTime() - lastExecutedTime
            shouldExecute = elapsed > limit
}
...

Swift 4 🙏

hey soffes – awesome library. i'd love to use it in a proj at some point, would be great if it had swift 4 some day.

Thoughts on adding a simple macro based solution (for non-persisted)?

Macro

#define RateLimit(SECS) \
({ \
    static NSDate *lastCall = nil; \
    ^(dispatch_block_t block) { \
        @synchronized(lastCall) { \
            if (!lastCall || fabs(lastCall.timeIntervalSinceNow) > SECS) { \
                lastCall = NSDate.date; \
                block(); \
            } \
        } \
    }; \
})

Usage

RateLimit(60.0)(^{
    // Do some work that runs a maximum of once per minute
});

Swift 3 version

Would it be possible to get a version of this pod with the swift the updates pushed to the Cocoapods master repo?

Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.