Giter VIP home page Giter VIP logo

cloud-functions-runtime-config's Introduction

Cloud Functions Runtime Config

DEPRECATED

There are better ways of doing this now, such as GCP Secret Manager or Firebase env config.


This is a wrapper around Google API Client to read Runtime Config variables in Cloud Functions.

Note: Runtime Config is currently in beta so things might break!

Installation

npm install --save cloud-functions-runtime-config

Usage

const runtimeConfig = require('cloud-functions-runtime-config');
const lunchPlans = runtimeConfig.getVariable('dev-config', 'lunch-plans');

exports.lunchPlanner = (req, res) => {
    return lunchPlans
        .then((val) => {
            console.log(val);
            res.status(200).send(val);
        })
        .catch((err) => {
            console.error(err);
            res.status(500).send(err);
        });
};

Basic example

Enable the RuntimeConfig API

Either using the API Manager in Cloud Console or using gcloud:

gcloud services enable runtimeconfig.googleapis.com

Config setup

Create a config resource and store a variable in it.

gcloud beta runtime-config configs create dev-config
gcloud beta runtime-config configs variables \
    set lunch-plans "lets go for a hamburger!" \
    --config-name dev-config

Cloud Function

A basic HTTP Function that returns the variable value.

const runtimeConfig = require('cloud-functions-runtime-config');
const lunchPlans = runtimeConfig.getVariable('dev-config', 'lunch-plans');

exports.lunchPlanner = (req, res) => {
    return lunchPlans
        .then((val) => res.status(200).send(val))
        .catch((err) => res.status(500).send(err));
};

Deploying the Function with an HTTP trigger:

gcloud beta functions deploy lunchPlanner \
    --trigger-http \
    --stage-bucket=<YOUR-BUCKET>

Test the Function:

curl https://us-central1-$(gcloud config get-value core/project).cloudfunctions.net/lunchPlanner

Cleanup

gcloud beta runtime-config configs delete dev-config
gcloud beta functions delete lunchPlanner

API

runtimeConfig.getVariable(config, variable)

Returns a Promise that is either resolved to the value read from Runtime Config or rejected if the variable could not be read.

config

Type: string

variable

Type: string

runtimeConfig.getVariables(config, variables)

Returns a Promise that is either resolved to an Array of values or rejected if any of the variables could not be read. The values are returned in the same order as the variableNames.

config

Type: string

variables

Type: Array<string>

License

The MIT License (MIT)

cloud-functions-runtime-config's People

Contributors

eddiezane avatar fredriks 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

Watchers

 avatar  avatar  avatar

cloud-functions-runtime-config's Issues

Consider global scope to 'cache' deployment (!) config

This is neat solution, thanks!

It was pointed out to me by a colleague on the Cloud Functions team that you may also leverage the Functions' global scope to cache per-deployment (!) config.

So, augmenting your purely dynamic example for static config:

/*jshint esversion: 6 */
/*globals exports, require */
var runtimeConfig = require('cloud-functions-runtime-config');

const configName = 'dev-config';
const variableName = 'lunch-plans';

var instanceConfig = {};

exports.lunchPlanner = function(req, res) {
    if (instanceConfig.hasOwnProperty(variableName)) {
      console.log(`Get instance global variable: ${variableName} == ${instanceConfig[variableName]}`);
      res.status(200).send(instanceConfig[variableName]);
    } else {
      runtimeConfig.getVariable(configName, variableName)
      .then((val) => {
        instanceConfig[variableName] = val;
        console.log(`Set instance global variable: ${variableName} == ${instanceConfig[variableName]}`);
        res.status(200).send(instanceConfig[variableName]);
      })
      .catch((err) => res.status(500).send(err));
    }
};

basic example needs update

In the README.md,

There's this in the basic example section:

gcloud service-management enable runtimeconfig.googleapis.com

However, I believe that should now say:

gcloud services enable runtimeconfig.googleapis.com

See the Cloud SDK release notes:

188.0.0 (2018-02-07)
Breaking Changes
(REMOVED) Removed deprecated gcloud service-management. Use gcloud endpoints and gcloud services instead.

Default credentials in Cloud Functions throws Not Found

Hi,

Very usefull library you have here, thanks for that.

This library worked fine for me, untill today. It seems to be related to a new Cloud Function environment:

Error: A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified. Requested entity was not found. at createError (/user_code/node_modules/googleapis/node_modules/axios/lib/core/createError.js:16:15) at settle (/user_code/node_modules/googleapis/node_modules/axios/lib/core/settle.js:18:12) at IncomingMessage.handleStreamEnd (/user_code/node_modules/googleapis/node_modules/axios/lib/adapters/http.js:201:11) at emitNone (events.js:91:20) at IncomingMessage.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:80:11) at process._tickDomainCallback (internal/process/next_tick.js:128:9)

Even though this is probably related to the Cloud Function environment and not your library, it could still be usefull to have the option to pass a keyFile.json to your library, instead of using the env default credentials:

      const key = require('path/to/file.json');
      const jwtClient = new google.auth.JWT(
        key.client_email,
        null,
        key.private_key,
        ['https://www.googleapis.com/auth/cloud-platform',
          'https://www.googleapis.com/auth/cloudruntimeconfig'], // an array of auth scopes
        null
      );

      jwtClient.authorize(function (err, tokens) {
        if (err) {
          console.log(err);
          return;
        }
      });

      return Promise.resolve(jwtClient);
    }

Anyhow, thanks again for creating this library :)

Feature Request "getVariables"

Happy New Year!

Using your library (again) this week, I think it would be useful to add a getVariables function:

lunchPlansWeek = runtimeConfig.getVariables('lunch-plans', ['monday', 'tuesday', ...]);

Perhaps Promise.all the individual calls in your library and only return successes?

Found this neat trick that effectively ignores rejects:

Promise.all(promises.map(p => p.catch(() => undefined)))

I may submit a PR for it.

get entire config at once?

Currently, getVariables() is great but it calls getVariable() repeatedly (which, side effect, also calls auth repeatedly). So it looks like one call could generate 2*N network hits, for N variables.

It's possible to return all variables at once:

https://cloud.google.com/deployment-manager/runtime-configurator/set-and-get-variables#getting_a_variables_value

https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables/

Possible feature request then would be perhaps a method like listVariables(returnValues: true|false) which could return something like

[ object(Variable) ]

possibly with name on objects changed to just the varname, or a variableName property added that has just the var name (not the fully qualified name).

For a small config, this would be 1 auth network hit + 1 config network hit. For larger configs, the results are paged so additional config network hits for each page.

Update takes long time

I am updating my runtime variable with following command:

gcloud beta runtime-config configs variables set var "value" --is-text --config-name global

When I check the provided direct URL I can see that the variable is well updated in google cloud.

Unfortunately when I call my function the variable keeps its old value and takes as long as 15 minutes to get updated.

const runtimeConfig = require('cloud-functions-runtime-config');
const environment = runtimeConfig.getVariable('global', 'var');

exports.helloWorld = (req, res) => {
    environment
			.then((val) => res.status(200).send(`Var is ${val}`))
			.catch((err) => res.status(500).send(`Problem resolving var: ${err}`));
};

npm install fails

any idea why this blows up? npm version is 6.14.8

$ npm install --save cloud-functions-runtime-config
npm ERR! code ENOSELF
npm ERR! Refusing to install package with name "cloud-functions-runtime-config" under a package
npm ERR! also called "cloud-functions-runtime-config". Did you name your project the same
npm ERR! as the dependency you're installing?
npm ERR!
npm ERR! For more information, see:
npm ERR! https://docs.npmjs.com/cli/install#limitations-of-npms-install-algorithm

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/tr/.npm/_logs/2020-10-31T15_59_02_009Z-debug.log

"A Not Found error"

Hi,

I'm trying to consume cloud-functions-runtime-config indirectly, via https://github.com/pendo-io/gcs-s3-sync. While trying to get it working I kept running into:

{ Error: A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified. Requested entity was not found. at Request._callback (/user_code/node_modules/cloud-functions-runtime-config/node_modules/google-auth-library/lib/transporters.js:85:15) at Request.self.callback (/user_code/node_modules/cloud-functions-runtime-config/node_modules/request/request.js:186:22) at emitTwo (events.js:106:13) at Request.emit (events.js:191:7) at Request.<anonymous> (/user_code/node_modules/cloud-functions-runtime-config/node_modules/request/request.js:1163:10) at emitOne (events.js:96:13) at Request.emit (events.js:188:7) at IncomingMessage.<anonymous> (/user_code/node_modules/cloud-functions-runtime-config/node_modules/request/request.js:1085:12) at IncomingMessage.g (events.js:292:16) at emitNone (events.js:91:20) code: 404, errors: [ { message: 'Requested entity was not found.', domain: 'global', reason: 'notFound' } ] }

Digging around I found it's fixed in 1.2.1 of google-auth-library:

googleapis/google-auth-library-nodejs#274

Any chance I can get you to make a 0.4 with updated dependencies on googleapis etc to pull in updated versions of this code? I'd really appreciate it. I'd have just sent a PR but I don't know how to test this code (having never written a line of javascript)!

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.