Repository navigation
Allow for Top-Level References - #3208
Conversation
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
left a comment
There was a problem hiding this comment.
Thanks @erikerikson ... added some comments 😊
|
|
||
| getValueFromSelf(variableString) { | ||
| let valueToPopulate = _.cloneDeep(this.service); | ||
| let valueToPopulate = this.service; |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
@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?
There was a problem hiding this comment.
@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.
| if (typeof valueToPopulate === 'undefined') { | ||
| valueToPopulate = {}; | ||
| } else { | ||
| } else if (subProperty !== '') { |
There was a problem hiding this comment.
could you clarify this extra conditional? Why is it necessary?
There was a problem hiding this comment.
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]
There was a problem hiding this comment.
I'll expand this conditional today too
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.
|
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
|
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 |
There was a problem hiding this comment.
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.
|
|
||
| ## 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. |
There was a problem hiding this comment.
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 🐝 🐝 🐝 )
There was a problem hiding this comment.
Of course. Thanks for calling out the poor communication! 👍
I'm thinking that I'll just be concrete and reference process.env.
There was a problem hiding this comment.
Thanks @erikerikson!
No hard feelings. A reference to process.env sounds good! 👍
|
|
||
| ## 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. |
There was a problem hiding this comment.
Same comment about explanation like above.
| return valueToPopulate; | ||
| } | ||
|
|
||
| warnIfNotFound(variableString, valueToPopulate) { |
There was a problem hiding this comment.
Can we add a unit test for this?
| console.log(message); // eslint-disable-line no-console | ||
| }; | ||
|
|
||
| const writeMessage = (messageType, message) => { |
There was a problem hiding this comment.
Can we add a unit test for this?
There was a problem hiding this comment.
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.
|
There is an ugly consequence of not having the Concretely:
|
|
However, the |
|
It could be a bit too paranoid but worth at least a moment's consideration... For the 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`
|
@pmuens please...
|
|
Thanks for the updates @erikerikson added it to my todo list 👍 |
There was a problem hiding this comment.
@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:
- Create a service with the following
serverless.ymlfile
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:}-
Run
serverless deploy --noDeploy -
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 👍
eahefnawy
left a comment
There was a problem hiding this comment.
Thanks @erikerikson ... this is good to gooooooo! 👯
|
|
||
| getValueFromSelf(variableString) { | ||
| let valueToPopulate = _.cloneDeep(this.service); | ||
| let valueToPopulate = this.service; |
There was a problem hiding this comment.
@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.
What did you implement:
Closes #3207
Closes #3206
How did you implement it:
${self:}as a valid reference to the current serverless.yml's roota. 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.
${opt:}and${env:}as a valid reference to the root of the option and environment settings hive, respectivelyExample usage of
${self:}: https://github.com/Nordstrom/hello-retail/pull/26/filesHow 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:
Is this ready for review?: YES
Is it a breaking change?: NO (additive only)