Repository navigation
Description
This is real issue that I've recently had, but I guess this concerns the framework in whole. I think that it is natural for Feathers services to be asynchronously initialized. They can pick their configuration from asynchronous sources, or it can be something else.
In most cases synchronous application initialization is presumed, but I've encountered design problems when started using Sequelize.
While Mongoose does some good job on accumulating promises inside for initialization actions (connection, index creation), so queries are automatically chained to initial promises, Sequelize does nothing like that, e.g. when sync() is called.
I would expect that SQL database is ready at the moment when web server has been started, but when the application is defined in synchronous manner, it will not. And this is what happens with typical Feathers setup. In some cases async initialization may take several ms, in other cases it may take seconds, while the server will pollute logs with errors that should have been never happen normally.
Another problem is error handling. If there are uncaught errors during async service initialization, the reasonable move would be to halt app initialization and catch errors in a single place.
Here's a small example that explains the idea and is based on the structure proposed by Feathers generator template.
app.js:
const app = require('feathers')();
// THIS!
app.set('feathersServicePromises', []);
app
.use(require('body-parser').json())
.configure(require('feathers-hooks'))
.configure(require('feathers-rest'))
.configure(require('./middleware'))
.configure(require('./services'));
// THIS!
Promise.all(app.get('feathersServicePromises'))
.then(() => app.listen(3000), console.error);services/index.js:
module.exports = () => {
const app = this;
app
.configure(require('./foo-async-service')
.configure(require('./bar-async-service')
.configure(require('./baz-sync-service')
};services/foo-async-service.js:
const sequelize = require('./common/sequelize');
module.exports = () => {
const app = this;
const fooModel = sequelize.model('foo');
// AND THIS!
const initPromise = fooModel.sync();
app.get('feathersServicePromises').push(initPromise);
app.use('/foo', require('feathers-sequelize')({ Model: fooModel }));
app.service('/foo');
};The places of interest here are initPromise and Promise.all(...). It would be convenient to just return initPromise from service function, like it is done in hooks. And Promise.all(...) could probably be lazily executed with app object toPromise() method or promise getter property. So it could be
module.exports = () => {
...
return fooModel.sync();
};in service function, and
app
...
.configure(require('./services'))
.promise
.then(() => app.listen(3000), console.error);in entry point.
I suppose that the pattern I've used for async initialization is already simple and clean, but it would be great if the framework would take this job.
My suggestion is to place this feature under consideration.
I would appreciate any thoughts on the subject.
Activity
Add service initializations
daffl commentedon Feb 6, 2017
I've been thinking about that a couple of times as well. The problem was that it will be a breaking change but we can probably get in with #258.
bisubus commentedon Feb 6, 2017
@daffl #258 is huge. I've got my share of Hapi before, and it is totally different beast under the hood, the work on unification looks really tough. And Passport+Hapi initiative was abandoned years ago, so it is a fresh start.
As for
configurealone, the thing described above is quite easy to implement and doesn't introduce breaking changes. Just not sure how many cases it will cover in larger perspective.idibidiart commentedon Feb 8, 2017
Well, after suggesting that service creation should return a function the other day, so as to signal to user that it's a dynamic thing, the next thought was to return a Promise. So no matter the order of service creation when you use .then() you can be sure the service is already initialized. However, you do the Promise scheme it's gonna be better than how it is at present :) A very minor nitpick, but has big consequence for DX imo.... Circular references between services are common place.
bisubus commentedon Feb 8, 2017
@idibidiart I'm not sure if I understood correctly, does the code above fully cover the scenario you've described?
Probably service
setupmay return a promise, too?idibidiart commentedon Feb 8, 2017
@bisubus if I understand your proposal correctly (and I am knew to the Feathers and Express way of things), my concern is that A) it is a breaking change since the app.service function doesn't return a promise and B) slow startup time as you have to wait on all services to launch as opposed to starting the app and then yielding/awaiting until promise for a given service resolves before proceeding with service invocations.... if that makes any sense.
bisubus commentedon Feb 8, 2017
@idibidiart In implementation above it was done for
configurefunctions only (this is where services are usually defined), not forserviceitself. Currently returned value fromconfigurefunction is ignored, this allows to return something (a promise) from there without breaking anything. I guess that a similar thing can be done in servicesetupfunctions, currently they don't return values, this can be used too.This proposal in its current form doesn't slow or break anything. It just provides a promise of initialization, it can be either chained to make sure that everything is ready or ignored. In my case I chained
app.listen(...)because it made perfect sense there.idibidiart commentedon Feb 8, 2017
i see what you mean! Thanks for the clarification. I think it makes sense to do it the way you've described including returning a promise from setup. What remains vague to me is where you say that app.service returns an instance of the service. I've gotten undefined when invoking it while the service is not ready. You're suggesting to wait on the setup promise to resolve prior to invoking app.service?
bisubus commentedon Feb 8, 2017
@idibidiart Do you have a real-world example where
app.service(..)can face a race condition?I didn't mean that it will wait for
setuppromise inapp.service(..)invocation, this would makeapp.service(..)to return a promise of a service, doesn't look good.idibidiart commentedon Feb 8, 2017
Yes I have an example I can describe and point you to.
I did not mean to wait for setup promise in app.service but to 'await' it from an async function (or use generator equivalent) before invoking the service methods. Won't require app.service to return a promise.
The example is where graphql service is configured before the services it depends on so when invoking app.service when graphql service is launched those services don't exist yet.
idibidiart commentedon Feb 8, 2017
the thing is the dependency graph for services may have cycles (service A depends on service B and service B depends on service A) so we can't guarantee a linear dependency order, which is why I was thinking of waiting on setup promise resolving before proceeding with app.service invocation (again, if that makes any sense!)
bisubus commentedon Feb 8, 2017
@idibidiart By 'graphql service is launched' you mean
setupmethod in graphql service, right? Because other methods (CRUD) won't be called until the server starts (and this can be guaranteed withapp.toPromise().then(() => app.listen(...))).From my understanding of how Feathers service registration works, services will become available in the order in which they are defined, so the solution is to have
app.configure(...)with dependency services definitions to be executed earlier thanapp.configure(...)with graphql service definition.Yes, the thing you're describing is usually addressed with DI container. I like DI a lot, but here it looks like overkill to me. With Node modules, the proper order of service definition can be relatively easily maintained.
But you've touched unon interesting subject. There may be scenarios where it may be beneficial to have a promise of some particular service (returned from service
setup), not just a resulting promise fromPromise.all. I guess that this can be solved by storing initialization promises as a map, not as an array. This way the promises for separate services can be retrieved any moment, likeapp.service(...).toPromise().then(initializedService => ...). But I don't think that this can be used as a replacement for DI to solve the problem you've mentioned, returning a promise for yet undefined service will silently cause pending promise if there are circular dependencies.idibidiart commentedon Feb 8, 2017
The problem was in this project: https://github.com/advanwinkel/feathers-apollo-SQLite
Note how graphql is configured before the services that it uses in the resolvers. Moving app.service calls to the dynamic parts of the resolver fixes it. Correcting the configuration order fixes it too.
idibidiart commentedon Feb 8, 2017
DI is too much agreed.
idibidiart commentedon Feb 9, 2017
So if you look at src/services/resolvers.js here is what I mean:
`
// export async function
export default async function Resolvers(){
// let Posts = await app.service('posts')
// which in this version does imply app.service returns a promise
So elsewhere we'd have Resolvers().then(...)
Not sure what setup() does. In this case, the graphql "service" (aka graphqlExpress) does not have the Feathers service interface.
And what I meant by invocation-time circular dependency is like when Post resolver uses Users service and User resolver uses the Posts service. It wouldn't be a problem in this case because we're awaiting on Users service to resolve before calling it from Post resolver and awaiting on Posts service to resolve before calling it from User resolver. So I guess it's not a circular dependency between the Posts and Users service but a reciprocal relationship between the resolvers that depend on those services. Sorry to confuse.
Updated comments accordingly
I hope some of this makes some sense generally speaking despite my not fully grasping the way things work in Express and Feathers.
45 remaining items
bitflower commentedon Aug 14, 2018
Just to be sure: Would this officially support creating services at runtime anytime after start of the app (in my case user triggered) ?
daffl commentedon Aug 14, 2018
This already works for websockets and is more of an Express than a Feathers limitation. You could create an updated
notFoundhandler to be registered after all custom middleware but before your services and have it check the URL against the paths in app.services and only throw theNotFounderror if nothing matches.fix(package): update ms to version 2.0.0 (#509)
fix(package): update ms to version 2.0.0 (#509)
KrishnaPG commentedon Jan 8, 2019
Is this working? The documentation of setup indicates that it returns a promise. Will the app wait for the promise or should we use the hooks as indicated here. Because the documentation of hooks does not indicate any hook for setup.
What is, currently, the right way to make the setup wait?
germanp commentedon Feb 6, 2019
I'm think is missing returning a promise in app.configure(), that was the original cause for this issue. There is no way of aborting in case of fail during configuration (eg. database not available)
N8th8n8el commentedon Aug 7, 2019
What's the status on this issue?
I am using version 4.3.0-pre.2 and service.setup methods don't seem to be asynchronous yet.
daffl commentedon Aug 7, 2019
This will be part of v5 using the new hook system (#932).
TypeScript generator for v4 (#424)