Last active
August 29, 2015 14:15
-
-
Save jerynmathew/831f98365695bcfa5cd1 to your computer and use it in GitHub Desktop.
Push ID implementation in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
import time | |
from random import random | |
class PushID(object): | |
# Modeled after base64 web-safe chars, but ordered by ASCII. | |
PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz' | |
def __init__(self, server_time=0): | |
# Timestamp of last push, used to prevent local collisions if you | |
# pushtwice in one ms. | |
self.last_push_time = server_time | |
# We generate 72-bits of randomness which get turned into 12 | |
# characters and appended to the timestamp to prevent | |
# collisions with other clients. We store the last characters | |
# we generated because in the event of a collision, we'll use | |
# those same characters except "incremented" by one. | |
self.last_rand_chars = [] # array | |
def next_id(self): | |
# Datetime now() in epoch | |
now = int(time.time() * 1000) | |
duplicate_time = (now == self.last_push_time) | |
self.last_push_time = now | |
timestamps_chars = [] # Use arrays | |
for i in range(7, -1, -1): | |
timestamps_chars.append(self.PUSH_CHARS[now % 64]) | |
now /= 64 | |
if now != 0: | |
raise ValueError('We should have converted the entire timestamp.') | |
if not duplicate_time: | |
self.last_rand_chars = [int(random() * 64) for i in range(0, 12)] | |
else: | |
# If the timestamp hasn't changed since last push, use the | |
# same random number, except incremented by 1. | |
for i in range(11, -1, -1): | |
if self.last_rand_chars[i] == 63: | |
self.last_rand_chars[i] = 0 | |
else: | |
break | |
self.last_rand_chars[i] += 1 | |
# Generate the UID | |
uid = "".join(timestamps_chars) + "".join([self.PUSH_CHARS[i] for i in self.last_rand_chars]) | |
if len(uid) != 20: | |
raise ValueError('Length should be 20.') | |
return uid | |
if __name__ == '__main__': | |
pid = PushID() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment