diff --git a/localEvaluation.js b/localEvaluation.js index f04c1cb..8abd787 100644 --- a/localEvaluation.js +++ b/localEvaluation.js @@ -1,12 +1,44 @@ const Experiment = require('@amplitude/experiment-node-server'); const _ = require('lodash'); +const { Client, Config } = require('./rootOrg'); var experiment; -var debug = process.env.LOCAL_EVALUATION_CONFIG_DEBUG=="true" || false; -var serverUrl = process.env.LOCAL_EVALUATION_CONFIG_SERVER_URL || "https://api.lambdatest.com"; -var flagConfigPollingIntervalMillis = process.env.LOCAL_EVALUATION_CONFIG_POLL_INTERVAL || 10; +let rootOrgClient = null; + +var debug = process.env.LOCAL_EVALUATION_CONFIG_DEBUG || false; +var serverUrl = process.env.LOCAL_EVALUATION_CONFIG_SERVER_URL || "http://api.lambdatest.com"; +var flagConfigPollingIntervalMillis = process.env.LOCAL_EVALUATION_CONFIG_POLL_INTERVAL || 120; +var apiRequestTimeout = process.env.LOCAL_EVALUATION_API_REQUEST_TIMEOUT || 10; var deploymentKey = process.env.LOCAL_EVALUATION_DEPLOYMENT_KEY || "server-jAqqJaX3l8PgNiJpcv9j20ywPzANQQFh"; + +async function initializeRootOrg(retries = 3) { + + rootOrgClient = new Client(deploymentKey, new Config( + serverUrl, + flagConfigPollingIntervalMillis * 1000, + apiRequestTimeout * 1000 + )); + + let error = null; + for (let i = 0; i < retries; i++) { + try { + await rootOrgClient.start(); + error = null; + break; + } catch (err) { + error = new Error(`Unable to get root orgs with given config ${JSON.stringify(rootOrgClient.config)} attempt:${i + 1} with error ${err.message}`); + continue; + } + } + + if (error) { + throw new Error(`Unable to get root orgs with given config ${JSON.stringify(rootOrgClient.config)} with error ${error.message}`); + } + + return true; +} + function validateuser(user) { let userProperties = {}; if (user && user.org_id && typeof user.org_id === "string") { @@ -50,6 +82,7 @@ async function Initialize() { config.flagConfigPollingIntervalMillis = flagConfigPollingIntervalMillis * 1000; experiment = Experiment.Experiment.initializeLocal(deploymentKey, config); await experiment.start(); + await initializeRootOrg(); } catch (e) { throw new Error(`unable to create local evaluation client with error ${e.message}`) } @@ -59,6 +92,12 @@ async function fetch(flagName, user) { try { const userProp = validateuser(user); const expUser = {user_properties: userProp}; + if (userProp?.org_id) { + const [org, exists] = rootOrgClient.evaluate(userProp.org_id); + if (exists && org) { + expUser.user_properties.org_id=org; + } + } return await experiment.evaluate(expUser, [flagName]); } catch (e) { return new Error(`error in evaluating flag: ${flagName} error: ${e}`) @@ -89,4 +128,11 @@ async function GetFeatureFlagPayload(flagName, user) { return data[flagName]; } -module.exports = {GetFeatureFlagPayload, GetFeatureFlagBool, GetFeatureFlagString, Initialize} +module.exports = { + initializeRootOrg, + getRootOrgClient: () => rootOrgClient, + GetFeatureFlagPayload, + GetFeatureFlagBool, + GetFeatureFlagString, + Initialize +}; diff --git a/package-lock.json b/package-lock.json index 599ff00..fffbe65 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,16 @@ { - "name": "local-evaluation", - "version": "1.0.1", + "name": "lambda-featureflag-nodejs-sdk", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "local-evaluation", - "version": "1.0.1", + "name": "lambda-featureflag-nodejs-sdk", + "version": "1.0.0", "license": "ISC", "dependencies": { "@amplitude/experiment-node-server": "^1.4.0", + "axios": "^1.6.7", "lodash": "^4.17.21" } }, @@ -19,17 +20,295 @@ "integrity": "sha512-//PMRmRrmBQMA94hYrDKWvU+037IDxM3rfdyPS3GiQKXMTg6CWPZWsOVlbD2RtXf0QMx5C7q2O6bCjId4tsUWQ==" }, "node_modules/@amplitude/experiment-node-server": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@amplitude/experiment-node-server/-/experiment-node-server-1.6.0.tgz", - "integrity": "sha512-jVMGAphZRmvedjuVV4IEGVh/Ls+AZKYcKeVErjBATaIDzV5NW3ElYpcTltxBadCoFGa7o6LBTE7P+jrY8ofykA==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@amplitude/experiment-node-server/-/experiment-node-server-1.4.0.tgz", + "integrity": "sha512-MbpW50oVndmXH/aKPDXfIM1AmGOhFkzpt5gl9OyZxBAkE/JT5CyeeWXTa2Qj4KcbyRyrBm80BDHoJ/BNhDPIew==", "dependencies": { "@amplitude/evaluation-js": "1.1.0" } }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz", + "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz", + "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" } } } diff --git a/package.json b/package.json index 5749ac6..348e28e 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,21 @@ { - "name": "local-evaluation", - "version": "1.0.1", - "description": "starts local evaluation amplitudes server", - "main": "index.js", + "name": "lambda-featureflag-nodejs-sdk", + "version": "1.0.0", + "description": "Lambda Feature Flag SDK for Node.js", + "main": "rootOrg/index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, - "keywords": [], - "author": "chandrjeetn@lambdatest.com", + "keywords": [ + "feature-flag", + "lambda", + "sdk" + ], + "author": "", "license": "ISC", "dependencies": { - "@amplitude/experiment-node-server": "1.4.0", - "lodash": "^4.17.21" + "@amplitude/experiment-node-server": "^1.4.0", + "lodash": "^4.17.21", + "axios": "^1.6.7" } } diff --git a/rootOrg/client.js b/rootOrg/client.js new file mode 100644 index 0000000..f823a78 --- /dev/null +++ b/rootOrg/client.js @@ -0,0 +1,44 @@ +const { DefaultConfig } = require('./config'); +const Poller = require('./poller'); +const LumsClient = require('./lumsClient'); + +class Client { + constructor(apiKey, config = DefaultConfig) { + this.apiKey = apiKey; + this.config = config; + this.flags = new Map(); + this.poller = new Poller(); + this.lumsClient = new LumsClient(config.serverUrl, config.flagConfigPollerRequestTimeout); + } + + async start() { + if (this.poller) { + this.poller.stop(); + } + this.poller = new Poller(); + this.poller.poll(this.config.flagConfigPollerInterval, () => this.pollFlags()); + return this.pollFlags(); + } + + stop() { + this.poller.stop(); + } + + async pollFlags() { + try { + const rootOrgs = await this.lumsClient.getRootOrgs(this.apiKey); + this.flags = new Map(Object.entries(rootOrgs)); + return true; + } catch (error) { + console.error('Error polling flags:', error); + return false; + } + } + + evaluate(orgId) { + const org = this.flags.get(orgId); + return [org, !!org]; + } +} + +module.exports = Client; \ No newline at end of file diff --git a/rootOrg/config.js b/rootOrg/config.js new file mode 100644 index 0000000..36197d5 --- /dev/null +++ b/rootOrg/config.js @@ -0,0 +1,15 @@ +class Config { + constructor(serverUrl, flagConfigPollerInterval, flagConfigPollerRequestTimeout) { + this.serverUrl = serverUrl; + this.flagConfigPollerInterval = flagConfigPollerInterval; + this.flagConfigPollerRequestTimeout = flagConfigPollerRequestTimeout; + } +} + +const DefaultConfig = new Config( + 'https://api.lambdatest.com', + 120 * 1000, // 120 seconds in milliseconds + 10 * 1000 // 10 seconds in milliseconds +); + +module.exports = { Config, DefaultConfig }; \ No newline at end of file diff --git a/rootOrg/index.js b/rootOrg/index.js new file mode 100644 index 0000000..4563006 --- /dev/null +++ b/rootOrg/index.js @@ -0,0 +1,12 @@ +const Client = require('./client'); +const { Config, DefaultConfig } = require('./config'); +const LumsClient = require('./lumsClient'); +const Poller = require('./poller'); + +module.exports = { + Client, + Config, + DefaultConfig, + LumsClient, + Poller +}; \ No newline at end of file diff --git a/rootOrg/lumsClient.js b/rootOrg/lumsClient.js new file mode 100644 index 0000000..95f9d88 --- /dev/null +++ b/rootOrg/lumsClient.js @@ -0,0 +1,38 @@ +const axios = require('axios'); + +class LumsClient { + constructor(baseURL, timeout) { + this.baseURL = baseURL; + this.timeout = timeout; + this.httpClient = axios.create({ + baseURL, + timeout, + validateStatus: function (status) { + return status >= 200 && status < 300; + } + }); + } + + async getRootOrgs(apiKey) { + try { + if (!apiKey) { + throw new Error('API key is required'); + } + + const response = await this.httpClient.get('/sdk/rootOrg', { + headers: { + 'Authorization': `Api-Key ${apiKey}` + } + }); + + return response.data.data; + } catch (error) { + if (error.response) { + throw new Error(`${error.response.data?.title || 'Error'}: ${error.response.data?.message || error.message}`); + } + throw new Error(`Failed to make request: ${error.message}`); + } + } +} + +module.exports = LumsClient; \ No newline at end of file diff --git a/rootOrg/poller.js b/rootOrg/poller.js new file mode 100644 index 0000000..5f9e156 --- /dev/null +++ b/rootOrg/poller.js @@ -0,0 +1,29 @@ +class Poller { + constructor() { + this.shutdown = false; + } + + poll(interval, callback) { + const pollFunction = async () => { + if (this.shutdown) { + return; + } + try { + await callback(); + } catch (error) { + console.error('Error in poller callback:', error); + } + if (!this.shutdown) { + setTimeout(pollFunction, interval); + } + }; + + pollFunction(); + } + + stop() { + this.shutdown = true; + } +} + +module.exports = Poller; \ No newline at end of file