Skip to content

Commit

Permalink
Removed macid and added feature to retrieve the machine id from the g…
Browse files Browse the repository at this point in the history
…enerated ids, irrespective of the machine the id was generated on
  • Loading branch information
tangledbytes committed May 26, 2020
1 parent c737e99 commit 24867aa
Show file tree
Hide file tree
Showing 12 changed files with 80 additions and 115 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
.vscode
build
build
log
14 changes: 5 additions & 9 deletions lib/generateUniqueID.d.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,27 @@
interface Config {
customEpoch?: number;
returnNumber?: boolean;
machineID?: number;
}
/**
* Constructs a UniqueID object which stores method for generation
* of a unique 64 bit time sortable id and a method for retreiving
* time of creation for the ids
*
* @param {config} [customEpoch = 1546300800000] A 42 bit long custom epoch
* @param {config} [customEpoch = 1546300800000] A 32 bit long custom epoch
* in ms, defaults to 1546300800000 (01-01-2019)
*
* ```
* const uid = new UniqueID();
* const ID = uid.getUniqueID();
* const IDCreateAt = uid.getTimestampFromID(ID);
* const currentMacID = uid.getMacID();
* ```
*/
export declare class UniqueID {
private _CUSTOM_EPOCH;
private _MACID;
private _FORMATTEDMACID;
private _snowflake;
private _nextID;
private _MACHINE_ID?;
private returnNumber;
constructor(config?: Config);
/**
* Generates a unique time sortable 64 bit number using native code
Expand All @@ -42,10 +41,7 @@ export declare class UniqueID {
* @returns {number} timestamp of id creations
*/
getTimestampFromID(id: bigint | string): number;
/**
* @returns MAC address being used internally
*/
get macID(): string;
getMachineIDFromID(id: bigint | string): number;
}
export {};
//# sourceMappingURL=generateUniqueID.d.ts.map
2 changes: 1 addition & 1 deletion lib/generateUniqueID.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 21 additions & 30 deletions lib/generateUniqueID.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/generateUniqueID.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 13 additions & 4 deletions lib/test.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/test.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nodejs-snowflake",
"version": "1.4.1",
"version": "1.5.0",
"description": "Generate time sortable 64 bits unique ids for distributed systems (inspired from twitter snowflake)",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
45 changes: 23 additions & 22 deletions src/generateUniqueID.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const { Snowflake } = require('../build/Release/snowflake');
import getMacID from './getMacID';

const CUSTOM_EPOCH = 1546300800000; // 01-01-2019

interface Config {
customEpoch?: number;
returnNumber?: boolean
returnNumber?: boolean;
machineID?: number;
}

const initConfig: Config = {
Expand All @@ -18,41 +18,45 @@ const initConfig: Config = {
* of a unique 64 bit time sortable id and a method for retreiving
* time of creation for the ids
*
* @param {config} [customEpoch = 1546300800000] A 42 bit long custom epoch
* @param {config} [customEpoch = 1546300800000] A 32 bit long custom epoch
* in ms, defaults to 1546300800000 (01-01-2019)
*
* ```
* const uid = new UniqueID();
* const ID = uid.getUniqueID();
* const IDCreateAt = uid.getTimestampFromID(ID);
* const currentMacID = uid.getMacID();
* ```
*/
export class UniqueID {
private _CUSTOM_EPOCH: number;
private _MACID: string = '';
private _FORMATTEDMACID: string = '';
private _snowflake: any;
private _nextID: Function;
private _MACHINE_ID?: number;
private returnNumber = true;

constructor(config: Config = initConfig) {
this._CUSTOM_EPOCH = config.customEpoch || CUSTOM_EPOCH;
const { macIDString, macID } = getMacID();
this._MACID = macIDString;
this._FORMATTEDMACID = macID;
if (!this._MACID) throw new Error('No MAC ADDRESS found to initialise');
this._snowflake = new Snowflake(this._MACID, this._CUSTOM_EPOCH);
this._nextID = config.returnNumber
? () => this._snowflake.getUniqueIDBigInt()
: () => this._snowflake.getUniqueID()
this._MACHINE_ID = config.machineID;
this.returnNumber = !!config.returnNumber;

if ((this._MACHINE_ID !== undefined) && !isNaN(this._MACHINE_ID)) {
if (!Number.isInteger(this._MACHINE_ID)) throw Error("Machine Id should be a decimal number");
if (this._MACHINE_ID > (1 << 12) - 1) throw Error("Maximum value of machine id can be 2^12 - 1 (4095)")
this._snowflake = new Snowflake(this._CUSTOM_EPOCH, this._MACHINE_ID);
return;
}

this._snowflake = new Snowflake(this._CUSTOM_EPOCH);
}

/**
* Generates a unique time sortable 64 bit number using native code
* @returns {string | bigint} the unique id
*/
getUniqueID(): string | bigint {
return this._nextID();
const val = this._snowflake.getUniqueID()
if (!this.returnNumber)
return val.toString();
return val
}

/**
Expand All @@ -71,13 +75,10 @@ export class UniqueID {
* @returns {number} timestamp of id creations
*/
getTimestampFromID(id: bigint | string): number {
return this._snowflake.getTimestampFromID(id) + this._CUSTOM_EPOCH;
return this._snowflake.getTimestampFromID(id);
}

/**
* @returns MAC address being used internally
*/
get macID(): string {
return this._FORMATTEDMACID;
getMachineIDFromID(id: bigint | string): number {
return this._snowflake.getNodeIDFromID(id);
}
}
40 changes: 0 additions & 40 deletions src/getMacID.ts

This file was deleted.

15 changes: 11 additions & 4 deletions src/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@ import UniqueID from './index';
import NanoTimer from 'nanotimer';
import parser from 'minimist';

const { type, time, interval, v: verbose } = parser(process.argv.slice(2));
const { type, time, interval, v: verbose, metadata, demoonly } = parser(process.argv.slice(2));
const timer = new NanoTimer();
const uid = new UniqueID({
returnNumber: type === "number" || type === "num"
returnNumber: type === "number" || type === "num",
machineID: Number(process.env.MACHINE_ID)
});

const benchmark = (totalTime: string, Function: Function) => {
console.log('[STARTING]')
let times = 0;
timer.setInterval(() => {
times++;
times += 1;
Function();
}, '', interval || '1u');
timer.setTimeout((timer: any) => {
Expand All @@ -26,4 +27,10 @@ const benchmarkFunction = () => {
else return () => uid.getUniqueID()
}

benchmark(time || '1s', benchmarkFunction());
if (demoonly) {
console.log(uid.getUniqueID())
} else if (metadata) {
console.log(uid.getMachineIDFromID(metadata), uid.getTimestampFromID(metadata))
} else {
benchmark(time || '1s', benchmarkFunction());
}

0 comments on commit 24867aa

Please sign in to comment.