Skip to content

Asynchronous initialization of Feathers services #509

Closed

Description

@bisubus

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

  1. added a commit that references this issue on Feb 6, 2017
    8790511
  2. daffl commented on Feb 6, 2017

    @daffl
    Member

    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.

  3. bisubus commented on Feb 6, 2017

    @bisubus
    Author

    @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 configure alone, 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.

  4. idibidiart commented on Feb 8, 2017

    @idibidiart

    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.

  5. bisubus commented on Feb 8, 2017

    @bisubus
    Author

    @idibidiart I'm not sure if I understood correctly, does the code above fully cover the scenario you've described?

    Probably service setup may return a promise, too?

  6. idibidiart commented on Feb 8, 2017

    @idibidiart

    @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.

  7. bisubus commented on Feb 8, 2017

    @bisubus
    Author

    @idibidiart In implementation above it was done for configure functions only (this is where services are usually defined), not for service itself. Currently returned value from configure function is ignored, this allows to return something (a promise) from there without breaking anything. I guess that a similar thing can be done in service setup functions, 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.

  8. idibidiart commented on Feb 8, 2017

    @idibidiart

    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?

  9. bisubus commented on Feb 8, 2017

    @bisubus
    Author

    @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 setup promise in app.service(..) invocation, this would make app.service(..) to return a promise of a service, doesn't look good.

  10. idibidiart commented on Feb 8, 2017

    @idibidiart

    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.

  11. idibidiart commented on Feb 8, 2017

    @idibidiart

    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!)

  12. bisubus commented on Feb 8, 2017

    @bisubus
    Author

    @idibidiart By 'graphql service is launched' you mean setup method in graphql service, right? Because other methods (CRUD) won't be called until the server starts (and this can be guaranteed with app.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 than app.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 from Promise.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, like app.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.

  13. idibidiart commented on Feb 8, 2017

    @idibidiart

    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.

  14. idibidiart commented on Feb 8, 2017

    @idibidiart

    DI is too much agreed.

  15. idibidiart commented on Feb 9, 2017

    @idibidiart

    So if you look at src/services/resolvers.js here is what I mean:

    `
    // export async function
    export default async function Resolvers(){

    let app = this;
    
    // used to have: let Posts = app.service('posts') but that returned undefined 
    // because posts service was configured after the graphql service 
    // So instead of that, I was thinking: 
    

    // let Posts = await app.service('posts')
    // which in this version does imply app.service returns a promise

    return {
    
      // Type Resolvers (type, args, context)
      User: {
        posts(user, args, context){
         // Posts will be defined whereas it would be undefined without the promise/await
          return Posts.find({
            query: {
              authorId: user.id
            }
          });
        }
      },`
    

    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.

  16. 45 remaining items

  17. bitflower commented on Aug 14, 2018

    @bitflower
    Contributor

    Just to be sure: Would this officially support creating services at runtime anytime after start of the app (in my case user triggered) ?

  18. daffl commented on Aug 14, 2018

    @daffl
    Member

    This already works for websockets and is more of an Express than a Feathers limitation. You could create an updated notFound handler 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 the NotFound error if nothing matches.

  19. removed this from the milestone on Aug 18, 2018
  20. KrishnaPG commented on Jan 8, 2019

    @KrishnaPG

    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?

  21. germanp commented on Feb 6, 2019

    @germanp

    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)

  22. N8th8n8el commented on Aug 7, 2019

    @N8th8n8el

    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.

  23. daffl commented on Aug 7, 2019

    @daffl
    Member

    This will be part of v5 using the new hook system (#932).

  24. added a commit that references this issue on Aug 8, 2019
  25. added this to the v5 (Dove) milestone on Apr 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions