Skip to content

Allow for Top-Level References - #3208

Merged
eahefnawy merged 7 commits into
serverless:masterfrom
erikerikson:allow-self-reference
Mar 1, 2017
Merged

eahefnawy merged 7 commits into
serverless:masterfrom
erikerikson:allow-self-reference

Conversation

@erikerikson

@erikerikson erikerikson commented Feb 8, 2017 •

Copy link
Copy Markdown
Contributor

What did you implement:

Closes #3207
Closes #3206

How did you implement it:

  1. Newly allow ${self:} as a valid reference to the current serverless.yml's root
    a. This allows for a more clean manner of passing names and identifiers around between projects. Particularly, this facilitates exporting values from projects so they can be used in other projects via Fn::ImportValue.
  2. Newly allow ${opt:} and ${env:} as a valid reference to the root of the option and environment settings hive, respectively
  3. Write a test ensuring 1. and 2. above
  4. Document the new capabilities
  5. Provide explicit support for the use of populateProperty in a not-in-place manner

Example usage of ${self:}: https://github.com/Nordstrom/hello-retail/pull/26/files

How can we verify it:

using hello-retail without the private.yml and some backing implementation will be a bit rough. I'm happy to discuss if use isn't clear. The associated issue may help a little.

Todos:

  • Write tests
  • Write documentation
  • Fix linting errors
  • Make sure code coverage hasn't dropped
  • Provide verification config / commands / resources
  • Enable "Allow edits from maintainers" for this PR
  • Update the messages below

Is this ready for review?: YES
Is it a breaking change?: NO (additive only)

1. Newly allow '${self:}' as a valid reference to the current serverless.yml's root
  a. This allows for a more clean manner of passing names and identifiers around between projects.  Particularly, this facilitates exporting values from projects so they can be used in other projects via Fn::ImportValue.
2. Write a test ensuring the above
3. Document the new capability

Example usage: https://github.com/Nordstrom/hello-retail/pull/26/files

@eahefnawy eahefnawy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @erikerikson ... added some comments 😊

Comment thread lib/classes/Variables.js

getValueFromSelf(variableString) {
let valueToPopulate = _.cloneDeep(this.service);
let valueToPopulate = this.service;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we clone just in case because objects are passed by reference, so any changes to valueToPopulate would actually affect the original service object. Is there any reason you removed cloning?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought this was the whole point! ;)

Actually, changing this moved me closer to enabling my scenario but may be legacy no longer necessary because of other changes. I have to admit that I haven't completely groked this code.

What I observed was that the attribute value ${self:} was being copied and then populate was being called again. I was concerned that it would infinitely recurse on that. I saw evidence later that expansion is on demand so I will try and remove this today and test it out some more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[sorry for the novel...]

TL;DR: 1) avoid infinite recursion 2) serverless depends on in-place affect on the original service object.

Detailed Discussion:

So, my reasoning was at least correctish... Not sure that my "evidence ... [of] expansion on demand" was properly interpreted.

Re-adding the _.deepClone causes an infinite recursion (technically, it only got 177 iterations deep before I paused execution). It copies the custom.retailStream: ${self:} attribute and value pair that is to be replaced and then (because if (property !== this.service) fails to identify the property is a copy of the service [on line 73]) attempts to populateProperty on the service copy (that still contains the ${self:}. This repeats. That's layer one of the infinite recursion.

I could write a rough equivalency check to avoid the recursion on line 73. Something like if (!(property.service && property.service === this.service.service)) would probably suffice in most cases but _.deepEquals(property, this.service) definitely wouldn't work since the two will have already diverged (the parent service has an extra level that the cloned service does not).

The rough equivalency check will get us past the recursion on line 73 but then the traverse on line 41 will attempt to traverse the ${self:} and as a result get another one, et cetera, to "infinity and beyond!". 😄

It seems to me that if we want to protect the "original" in-memory copy of the service then we ought to do that once at the outset (i.e. in the constructor or the like). The problem is that this doesn't cover the bare use of populateProperty(<something-not-the-service>) but a revision to the call that adds a "called from populateService" parameter could distinguish between the cases. Passing the property in the populateProperty case but (relying on instance state and) not passing the service in the populateService case is a bit of a mental model mix-up that is legacy now.

Hmm... (sorry, writing as I code and test...)

It turns out that the framework is actually relying on the revision of the original service object. Adding the use of _.cloneDeep to the constructor causes the copy of the service that the framework uses to take action not on the altered copy but the original and thus I observed:

  Serverless Error ---------------------------------------
 
     Bucket name must start with a letter or number. ${self:custom.helloRetail.deploymentBucket}
 
  Stack Trace --------------------------------------------
 
ServerlessError: Bucket name must start with a letter or number. ${self:custom.helloRetail.deploymentBucket}
    at ~/serverless/lib/plugins/aws/lib/validate.js:57:17
From previous event:
    at AwsDeploy.validateS3BucketName (~/serverless/lib/plugins/aws/lib/validate.js:34:8)
    at AwsDeploy.<anonymous> (~/serverless/lib/plugins/aws/deploy/lib/configureStack.js:22:26)
From previous event:
    at AwsDeploy.configureStack (~/serverless/lib/plugins/aws/deploy/lib/configureStack.js:22:10)
From previous event:
    at __dirname.constructor.options.hooks.deploy:initialize (~/serverless/lib/plugins/aws/deploy/index.js:42:10)
    at ~/serverless/lib/classes/PluginManager.js:160:50
    at processImmediate [as _immediateCallback] (timers.js:383:17)
From previous event:
    at PluginManager.run (~/serverless/lib/classes/PluginManager.js:160:22)
    at Serverless.run (~/serverless/lib/Serverless.js:91:31)
    at ~/serverless/bin/serverless:23:50
 
  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
 
  Your Environment Information -----------------------------
     OS:                 darwin
     Node Version:       4.6.2
     Serverless Version: 1.5.1

So therefore... I can remove the top level clone and still do a clone below if the caller doesn't ask for an in-place population (which populate service would ask for). The remaining potential concern space then is that the service could be improperly altered by the population of a property, via a ${self:<var>*} declaration that isn't a part of the service. However, by definition, the self variable type only references the service, so that concern space is empty/size zero.

Maybe I fail to understand the case that you were concerned about that motivated the cloning? Sorry if so. I'd love some illumination.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@eahefnawy for me it makes sense to get rid of deep cloning to prevent an infinite loop / recursion.

What's your take on this since you've implemented it in the first place?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@erikerikson @pmuens I think you guys are right. I've been doing this since v0.5 because in v0.5 we used to serialize serverless.yml, so we wanted to keep an immutable version of the state of the file as it was before loading, hence the cloning. We don't do that anymore in v1, but I thought I keep it this way just in case. But considering @erikerikson use case, I think we don't need that anymore.

Comment thread lib/classes/Variables.js Outdated
if (typeof valueToPopulate === 'undefined') {
valueToPopulate = {};
} else {
} else if (subProperty !== '') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you clarify this extra conditional? Why is it necessary?

@erikerikson erikerikson Feb 8, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You bet. The additional conditional will resolve to true in the case of ${self:}, any multiple dots in a row (e.g. ${[...]attr1..attrNext[...]}), or a trailing dot (e.g. ${[...]attr1.attrNext.}). In each case, '""' in valueToPropagate will evaluate to false (I think? Actually, maybe I should add that check because I think obj[''] = {} is valid code, technically speaking [it is, I have confirmed]) and [outside of that case] the empty string indicates that the current value of valueToPropagate should continue to be the current value. Another way to state this is that the empty string does not represent an attribute to traverse, therefore no traversal should occur and the current state continues to be the specified valid state.

[Edits with investigation and formatting]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll expand this conditional today too

@erikerikson erikerikson changed the title Allow for Top-Level Self-Reference Allow for Top-Level References Feb 8, 2017
1. Newly allow `${opt:}` and `${env:}` as a valid reference to the root of the option and environment settings hive, respectively
2. Write a test ensuring the above
3. Document the new capability
4. Eliminate a silly through-${self:} use example
5. Allow for the use of populateProperty in a not-in-place manner
6. Allow for the valid (albeit odd) valueToPopulate[''] case
1. define new `logWarning` method in Error class and consolidate message formatting for consistency.
2. use new `logWarning` to inform users if a variable cannot be resolved.
@erikerikson

erikerikson commented Feb 8, 2017 •

Copy link
Copy Markdown
Contributor Author

Added fix for #3206 as well. Note that it only provides a warning, not an error, so as not to create a breaking change.

# Conflicts:
#	lib/classes/Error.js
@erikerikson

Copy link
Copy Markdown
Contributor Author

As mentioned briefly in #3206, cross-serverless-service loading causes the kinds of errors that are warned about. This potentially means that my fix here and strategy for allowing consistent cross-project resolution is unwise. A potentially better fix is to resolve all self variables to the file from whence they came and add a local variable type for rendering using the context into which you are being loaded. The loading of an external file would thus be able to resolve in its own or the loader's context as expected/intended by the file creator.

@pmuens
pmuens self-requested a review February 9, 2017 09:01

@pmuens pmuens left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @erikerikson nicely done! 👍 💯

Tested it and it works fine on my machine (I've used the example you've posted in your variables.md file).

Here's the serverless.yml file I've used:

service: service

provider:
  name: aws
  runtime: nodejs4.3

custom:
  newService: ${self:}
  exportName: ${self:custom.newService.service}-export

functions:
  hello:
    handler: handler.hello
  goodbye:
    handler: handler.goodbye
    events:
      - http:
          method: GET
          path: goodbye
          cors: true

resources:
  Outputs:
    NewServiceExport:
      Value: 'A Value To Export'
      Export:
        Name: ${self:custom.exportName}

I added some comments. Mostly about some tests. Not entirely sure if everything is covered by tests right now since our convenient test coverage tool of choice (Coveralls) disappeared.

I cannot say that much about the variable system since @eahefnawy did the implementation and is the single source of truth about the correct behavior ℹ️.

I'll leave it in a "Request changes" states because I want to give it a final spin again before we merge...

Let us know if you need any help with tests.

Comment thread docs/providers/aws/guide/variables.md Outdated

## Referencing Environment Variables
To reference environment variables, use the `${env:SOME_VAR}` syntax in your `serverless.yml` configuration file.
To reference environment variables, use the `${env:SOME_VAR}` syntax in your `serverless.yml` configuration file. `${env:}` references the environment variable hive.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we explain that a little bit 😬 . It's hard to understand what this means for me as a non-native speaker (my translator says smth. about 🐝 🐝 🐝 )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course. Thanks for calling out the poor communication! 👍
I'm thinking that I'll just be concrete and reference process.env.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @erikerikson!

No hard feelings. A reference to process.env sounds good! 👍

Comment thread docs/providers/aws/guide/variables.md Outdated

## Referencing CLI Options
To reference CLI options that you passed, use the `${opt:some_option}` syntax in your `serverless.yml` configuration file.
To reference CLI options that you passed, use the `${opt:some_option}` syntax in your `serverless.yml` configuration file. `${opt:}` references the options hive.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment about explanation like above.

Comment thread lib/classes/Variables.js Outdated
return valueToPopulate;
}

warnIfNotFound(variableString, valueToPopulate) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a unit test for this?

Comment thread lib/classes/Error.js
console.log(message); // eslint-disable-line no-console
};

const writeMessage = (messageType, message) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a unit test for this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

writeMessage is an unchanged movement of code from the logError method to a private method of the module. Because it is a private method, it is not externally available. Given its use by logError, it gets the same exact coverage as before plus overlapping coverage from the new logWarning tests.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, you're totally right @erikerikson 👍

@erikerikson

Copy link
Copy Markdown
Contributor Author

There is an ugly consequence of not having the local reference type. While I have successfully included the exports of other services, the dependencies that must be declared are cumulative through dependency chains.

Concretely:

  1. Service A
  2. Service B
    a. B depends on A, using one of its exports. It must declare custom.A and custom.AVersion.
  3. Service C
    a. C depends on B, using one of its exports. In order to load depend on B successfully, it has to declare custom.B and custom.BVersion but also custom.A and custom.AVersion.
    b. custom.AVersion must match what the version of B declared for custom.AVersion or obscure hilarity will ensue.

@erikerikson

Copy link
Copy Markdown
Contributor Author

However, the local bit probably deserves a separate Issue and PR.

@erikerikson

erikerikson commented Feb 10, 2017 •

Copy link
Copy Markdown
Contributor Author

It could be a bit too paranoid but worth at least a moment's consideration... For the ${env:} scope of this change, there is a security risk being created. The warning I have added to the docs (it'll be checked in shortly) follows. This may influence whether we want that to be in scope for this PR.

!!!WARNING!!! If you use use the environment to provide sensitive data such as 
credentials or private keys to your project, there is a risk that this sensitive 
information could be written into less protected or publicly accessible build logs, 
CloudFormation Templates, et cetera. !!!WARNING!!!

I don't believe there are any sensitive items expected to be in the sls options. If this is incorrect, we should definitely discuss the concern for that scope as well.

1. Improve wording of documentation.  Note the concrete object that will be written in its entirety
2. Expand documentation.  Note a potential security risk for secrets
3. Move, without changes, the `warnIfNotFound` method because it was putting space between `getValueFromSource` and the various source type specific functions it uses
4. Implement unit tests for `warnIfNotFound`
5. Implement unit tests for `logWarning`
@erikerikson

Copy link
Copy Markdown
Contributor Author

@pmuens please...

  1. let me know if the documentation clarifications could still use improvement.
  2. feel free to suggest different ways to think on the Error.js/writeMessage tests topic. I think my considerations are correct but feel free to contradict.
  3. let me know what you (and invite anyone else who should weigh in) think of the "WARNING" comment.
  4. mention anything else that should occur, of course

@pmuens

pmuens commented Feb 17, 2017

Copy link
Copy Markdown
Contributor

Thanks for the updates @erikerikson added it to my todo list 👍

@pmuens pmuens added this to the 1.9 milestone Feb 27, 2017
@pmuens pmuens self-assigned this Feb 28, 2017

@pmuens pmuens left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@erikerikson thanks for the recent update! 👍

I just merged the current master branch into this one so it's up to date. Furthermore I've pushed some tiny fixes on top of this PR (nothing special).

I looked through the code which looks good from my side.

Here are the steps I used to test this PR:

  1. Create a service with the following serverless.yml file
service: self-reference

provider:
  name: aws
  runtime: nodejs4.3

custom:
  newService: ${self:}
  exportName: ${self:custom.newService.service}-export

functions:
  hello:
    handler: handler.hello

resources:
  Outputs:
    selfExport:
      Value: 'A Value To Export'
      Export:
        Name: ${self:custom.exportName}
    OptExport:
      Value: 'Exported option variable'
      Export:
        Name: ${opt:}
    EnvExport:
      Value: 'Exported env variable'
      Export:
        Name: ${env:}
  1. Run serverless deploy --noDeploy

  2. Inspect the generated CloudFormation template


I leave the final decision to merge this to @eahefnawy since he wrote the inital variable system and has a deeper knowledge about possible pitfalls.

Thanks for the PR @erikerikson 👍

@pmuens pmuens assigned eahefnawy and unassigned pmuens Mar 1, 2017

@eahefnawy eahefnawy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @erikerikson ... this is good to gooooooo! 👯

Comment thread lib/classes/Variables.js

getValueFromSelf(variableString) {
let valueToPopulate = _.cloneDeep(this.service);
let valueToPopulate = this.service;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@erikerikson @pmuens I think you guys are right. I've been doing this since v0.5 because in v0.5 we used to serialize serverless.yml, so we wanted to keep an immutable version of the state of the file as it was before loading, hence the cloning. We don't do that anymore in v1, but I thought I keep it this way just in case. But considering @erikerikson use case, I think we don't need that anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants