Code Monkey home page Code Monkey logo

expire-unused-keys's Introduction

Build Status

expire-unused-keys

So I'm writing this other library that needs to do some basic caching, right? You know - the first hard thing. (For an idea of my work on the second hard thing, see the examples below.)

It's not so much that I need flotsam deleted right away when it expires as I want the value to be refreshed every so often, and if that value goes a long enough time with out being accessed, theeeeen I'll drop it.

To lessen the pain in this task, I need a library that will keep track of what the last time was when I accessed something, and alert me if a certain amount of time passes without that thing being touched. So, making the assumption that those "somethings" can be identified by a string, and the assertion that I will need these last-access-times to persist even after reopening the screen or re-launching the process, I wrote this-here code.

It stores last-access times in a LevelUP db - if you don't need persistence, throw level-mem at it.

breaking changes: [email protected]

  • Only tested with LevelUP 3.x (should work fine on 2.x though)
  • Ordered arguments to the constructor are no longer accepted, you gotta pass in an object
  • Emitting events on the expirer object can no longer be done as a proxy for calling the functions
  • All functions return promises
  • Uses Promise + Set + ES2017, polyfill/transpile as needed

Example

const expireUnusedKeys = require('expire-unused-keys')

// Expire stuff after 15 seconds of inactivity
const expirer = expireUnusedKeys({ timeoutMs: 15 * 1000, db: someLevelUpDb })

// Things are only interesting if they were active in the last 15 seconds
const areTheseThingsInteresting = {
	'thing1': false,
	'thing2': false
}

function activity(thingKey) {
	areTheseThingsInteresting[thingKey] = true

	// note that this thing was fiddled with
	expirer.touch(thingKey)
}

expirer.on('expire', thingKey => {
	console.log(thingKey + " expired!")
	areTheseThingsInteresting[thingKey] = false
})

activity('thing1')
activity('thing2')

setTimeout(() => activity('thing1'), 10 * 1000)

 // thing1 will expire after 25 seconds after the first time it was touched
 // thing2 will expire 15 seconds after the first time it was touched

API

The module returns a constructor function:

const expireUnusedKeys = require('expire-unused-keys')

expirer = expireUnusedKeys({ timeoutMs, db, [checkIntervalMs,] [repeatExpirations] })

  • timeoutMs: how many milliseconds the object will wait before it emits an 'expire' event for a touched key
  • db: a LevelUP data store of some kind. Must be wrapped by encoding-down or some other encoder that is cool with strings and numbers.
  • checkIntervalMs: right now, this library works by iterating over all keys and emitting expire events for any items that were last touched timeoutMs ago. This value prescribes how often the keys should be iterated over. Defaults to 1000.
  • repeatExpirations: set to true to emit 'expire' events for keys every timeoutMs milliseconds. By default, keys will be forgotten at the first 'expire' event.

The resulting object is an EventEmitter with the following functions as properties:

promise = expirer.touch(key)

Updates the "last touched" timestamp. Expire events will not fire for a key until at least timeoutMs after the last time the key was touched.

promise = expirer.forget(key[, cb])

Forgets about a key. Won't fire any expire events for it (unless you touch that key again).

promise = expirer.createIfNotExists(key)

Creates it if it doesn't exist yet. If you called touch on the key without calling forget since, this will not create the key. If you have never called touch, or have called forget since, this will update the timestamp just like calling touch.

Note: It is possible to create a race condition if you call touch and createIfNotExists around the same time on a key that doesn't exist yet. In that case, the key will be created, and the timestamp will be updated once or twice around the same time.

expirer.stop()

Shuts down any timeouts that are floating around, letting you shut down your server nicely and stuff.

Events emitted

expirer is an event emitter with a better-emitter interface.

All events emit a single argument: they relevant key string.

  • expire: emits the key that should be expired
  • touch: emits when a key is touched and its expiration time is moved out
  • forget: emits when a key is forgotten

License

WTFPL

expire-unused-keys's People

Contributors

artskydj avatar saibotsivad avatar tehshrike avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar

expire-unused-keys's Issues

expire event has too many arguments

expirer.on('expire', function () { console.log(arguments) })
// logs...
{ '0': '99b32c5d-9039-43d7-bf51-4742efb66247',
  '1': 1,
  '2':
   [ '68b56b9a-00b2-4942-9324-77489044b229',
     '99b32c5d-9039-43d7-bf51-4742efb66247' ] }

This is due to this line arr.forEach(emitter.emit.bind(emitter, 'expire'))

Add a setInterval-like option on expirations

Right now, expire-unused-keys acts like a setTimeout. There should be an option to allow it to act like a setInterval.

Right now the expirer only takes options for the entire db. Keep it that way and make it for the entire db. (touch should push the interval back, same way as it does now for the non-repeating version.)

using with json encode

Well, I try use the unused-keys, but my valueEncode is a json.
If I don't "touch" the key, the expire not work, but if I "touch", my values on json will lost.

The behavior is this?

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.