# All files index.js

96.61% Statements 257/266
63.15% Branches 24/38
100% Functions 4/4
96.61% Lines 257/266

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    2671x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    12x
    12x
    12x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    3x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    6x
    6x
    6x
    6x
    6x
    4x
    4x
    4x
    4x
    12x
    12x
    12x
    12x
    12x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    5x
    5x
    5x
    5x
    5x
    4x
    4x
    4x
    28x
    4x
    2x
    2x
    2x
    2x
    2x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x

    4x
    1x
    1x
    4x
    4x
    4x
    6x
    6x
    4x
    4x
    4x
    4x
    4x
    6x
    6x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    1x
    1x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x

    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    21x
    4x
    4x
     import { promisify } from 'util'
    import errors from '@feathersjs/errors'
    import makeCote from 'cote'
    import { v4 as uuid } from 'uuid'
    import makeDebug from 'debug'
    import portfinder from 'portfinder'
    import { DEFAULT_METHODS, DEFAULT_EVENTS, HealthcheckService } from './utils.js'
    import { publishService, publishServices } from './publish.js'
    import { registerService, registerApplication } from './register.js'

    const { Unavailable } = errors
    const debug = makeDebug('feathers-distributed')

    export async function initialize (app) {
      debug('Initializing cote with options', app.coteOptions)
      // Setup cote with options
      app.cote = makeCote(app.coteOptions)
      app.distributionKey = app.distributionOptions.key || 'default'
      // Placeholder for request/events managers for remote services
      app.serviceRequesters = {}
      app.serviceEventsSubscribers = {}

      // This subscriber listen to an event each time a remote app service has been registered
      app.serviceSubscriber = new app.cote.Subscriber({
        name: 'feathers services subscriber',
        namespace: 'services',
        key: 'services',
        subscribesTo: ['service']
      }, app.coteOptions)
      debug('Services subscriber ready for app with uuid ' + app.uuid + ' and key ' + app.distributionKey)
      // When a remote service is declared create the local proxy interface to it
      app.serviceSubscriber.on('service', async serviceDescriptor => {
        // When a new app pops up create the required proxy to it first
        await registerApplication(app, serviceDescriptor)
        registerService(app, serviceDescriptor)
      })

      // Wait before instanciating new component to avoid too much concurrency on port allocation
      await promisify(setTimeout)(app.distributionOptions.componentDelay)
      // This publisher publishes an event each time a local app or service is registered
      app.servicePublisher = new app.cote.Publisher({
        name: 'feathers services publisher',
        namespace: 'services',
        key: 'services',
        broadcasts: ['service']
      }, app.coteOptions)
      debug('Services publisher ready for app with uuid ' + app.uuid + ' and key ' + app.distributionKey)
      // Dispatcher of service events to other nodes) {
      if (app.distributionOptions.publishEvents) {
        // Wait before instanciating new component to avoid too much concurrency on port allocation
        await promisify(setTimeout)(app.distributionOptions.componentDelay)
        app.serviceEventsPublisher = new app.cote.Publisher({
          name: 'feathers service events publisher',
          namespace: app.distributionKey,
          key: app.distributionKey,
          broadcasts: app.distributionOptions.distributedEvents || DEFAULT_EVENTS
        }, app.coteOptions)
        debug('Service events publisher ready for local app with uuid ' + app.uuid + ' and key ' + app.distributionKey)
      }
      // Wait before instanciating new component to avoid too much concurrency on port allocation
      await promisify(setTimeout)(app.distributionOptions.componentDelay)
      // Create the response manager for local services
      const methods = app.distributionOptions.distributedMethods || DEFAULT_METHODS
      app.serviceResponder = new app.cote.Responder({
        name: 'feathers services responder',
        namespace: app.distributionKey,
        key: app.distributionKey,
        requests: methods.concat(['healthcheck'])
      }, app.coteOptions)
      debug('Service responder ready for local app with uuid ' + app.uuid + ' and key ' + app.distributionKey)
      debug('Registering listeners for ', methods.concat(['healthcheck']))
      // Answer requests from other nodes
      if (methods.includes('find')) {
        app.serviceResponder.on('find', async (req) => {
          const service = app.service(req.path)
          debug('Responding find() local service on path ' + req.path + ' with key ' + req.key, req)
          const result = await service.find(Object.assign({ fromRemote: true }, req.params))
          debug('Successfully find() local service on path ' + req.path + ' with key ' + req.key)
          return result
        })
      }
      if (methods.includes('get')) {
        app.serviceResponder.on('get', async (req) => {
          const service = app.service(req.path)
          debug('Responding get() local service on path ' + req.path + ' with key ' + req.key, req)
          const result = await service.get(req.id, Object.assign({ fromRemote: true }, req.params))
          debug('Successfully get() local service on path ' + req.path + ' with key ' + req.key)
          return result
        })
      }
      if (methods.includes('create')) {
        app.serviceResponder.on('create', async (req) => {
          const service = app.service(req.path)
          debug('Responding create() local service on path ' + req.path + ' with key ' + req.key, req)
          const result = await service.create(req.data, Object.assign({ fromRemote: true }, req.params))
          debug('Successfully create() local service on path ' + req.path + ' with key ' + req.key)
          return result
        })
      }
      if (methods.includes('update')) {
        app.serviceResponder.on('update', async (req) => {
          const service = app.service(req.path)
          debug('Responding update() local service on path ' + req.path + ' with key ' + req.key, req)
          const result = await service.update(req.id, req.data, Object.assign({ fromRemote: true }, req.params))
          debug('Successfully update() local service on path ' + req.path + ' with key ' + req.key)
          return result
        })
      }
      if (methods.includes('patch')) {
        app.serviceResponder.on('patch', async (req) => {
          const service = app.service(req.path)
          debug('Responding patch() local service on path ' + req.path + ' with key ' + req.key, req)
          const result = await service.patch(req.id, req.data, Object.assign({ fromRemote: true }, req.params))
          debug('Successfully patch() local service on path ' + req.path + ' with key ' + req.key)
          return result
        })
      }
      if (methods.includes('remove')) {
        app.serviceResponder.on('remove', async (req) => {
          const service = app.service(req.path)
          debug('Responding remove() local service on path ' + req.path + ' with key ' + req.key, req)
          const result = await service.remove(req.id, Object.assign({ fromRemote: true }, req.params))
          debug('Successfully remove() local service on path ' + req.path + ' with key ' + req.key)
          return result
        })
      }
      // Healthcheck is always used
      app.serviceResponder.on('healthcheck', async (req) => {
        debug('Responding healthcheck() local service on path ' + req.path + ' with key ' + req.key, req)
        const service = app.service(req.path)
        if (!service) throw new Unavailable('Unavailable distributed service on path ' + req.path + ' with key ' + req.key)
        debug('Successfully healthcheck() local service on path ' + req.path + ' with key ' + req.key)
        return true
      })
      // Process custom methods
      methods.forEach(method => {
        if (!DEFAULT_METHODS.includes(method)) {
          app.serviceResponder.on(method, async (req) => {
            const service = app.service(req.path)
            debug(`Responding ${method}() local service on path ` + req.path + ' with key ' + req.key, req)
            const result = await service[method](req.data, Object.assign({ fromRemote: true }, req.params))
            debug(`Successfully ${method}() local service on path ` + req.path + ' with key ' + req.key)
            return result
          })
        }
      })

      // Each time a new app pops up we republish local services so that
      // service distribution does not depend on the initialization order of the apps
      app.servicePublisher.on('cote:added', (data) => { publishServices(app) })
      // FIXME: we should manage apps going offline
      app.servicePublisher.on('cote:removed', (data) => { })

      // Tell others apps I'm here
      publishServices(app)

      // Add an interval so that we regularly publish services to others nodes
      if (app.distributionOptions.heartbeatInterval > 0) {
        app.heartbeatInterval = setInterval(_ => {
          Object.getOwnPropertyNames(app.services).forEach(path => {
            publishService(app, path)
          })
        }, app.distributionOptions.heartbeatInterval)
        debug('Scheduled heartbeat local services publishing for app with uuid ' + app.uuid + ' and key ' + app.distributionKey)
      }
    }

    export function finalize (app) {
      debug('Finalizing cote')
      if (app.serviceRequesters) {
        Object.getOwnPropertyNames(app.serviceRequesters).forEach(key => {
          debug(`Finalizing service requester for remote app with key ${key}`)
          app.serviceRequesters[key].close()
        })
        delete app.serviceRequesters
      }
      if (app.serviceEventsSubscribers) {
        Object.getOwnPropertyNames(app.serviceEventsSubscribers).forEach(key => {
          debug(`Finalizing service event subscriber for remote app with key ${key}`)
          app.serviceEventsSubscribers[key].close()
        })
        delete app.serviceEventsSubscribers
      }
      if (app.serviceSubscriber) {
        debug(`Finalizing service subscriber for local app with key ${app.distributionKey}`)
        app.serviceSubscriber.close()
        delete app.serviceSubscriber
      }
      if (app.servicePublisher) {
        debug(`Finalizing service publisher for local app with key ${app.distributionKey}`)
        app.servicePublisher.close()
        delete app.servicePublisher
      }
      if (app.serviceResponder) {
        debug(`Finalizing service responder for local app with key ${app.distributionKey}`)
        app.serviceResponder.close()
        delete app.serviceResponder
      }
      if (app.applicationPublicationTimeout) clearTimeout(app.applicationPublicationTimeout)
      if (app.coteInitializationTimeout) clearTimeout(app.coteInitializationTimeout)
      if (app.heartbeatInterval) clearInterval(app.heartbeatInterval)
    }

    export default function init (options = {}) {
      return function (app) {
        // We need to uniquely identify the app to avoid infinite loop by registering our own services
        // This uuid is also used a partition key in cote unless provided
        app.uuid = uuid()
        app.coteOptions = Object.assign({
          helloInterval: 10000,
          checkInterval: 20000,
          nodeTimeout: 30000,
          masterTimeout: 60000,
          log: (!!process.env.COTE_LOG),
          basePort: (process.env.BASE_PORT ? Number(process.env.BASE_PORT) : 10000),
          highestPort: (process.env.HIGHEST_PORT ? Number(process.env.HIGHEST_PORT) : 20000)
        }, options.cote)
        app.distributionOptions = Object.assign({
          publicationDelay: (process.env.PUBLICATION_DELAY ? Number(process.env.PUBLICATION_DELAY) : 10000),
          componentDelay: (process.env.COMPONENT_DELAY ? Number(process.env.COMPONENT_DELAY) : 1000),
          coteDelay: (process.env.COTE_DELAY ? Number(process.env.COTE_DELAY) : undefined),
          heartbeatInterval: (process.env.HEARTBEAT_INTERVAL ? Number(process.env.HEARTBEAT_INTERVAL) : undefined),
          middlewares: {},
          publishEvents: true,
          distributedEvents: DEFAULT_EVENTS,
          distributedMethods: DEFAULT_METHODS
        }, options)

        debug('Initializing feathers-distributed with options', app.distributionOptions)
        // Change default base/highest port for automated port finding
        portfinder.basePort = app.coteOptions.basePort
        portfinder.highestPort = app.coteOptions.highestPort

        // Setup cote with options and required delay
        if (app.distributionOptions.coteDelay) {
          // -1 means the caller wants to initialize byitself
          if (app.distributionOptions.coteDelay > 0) {
            app.coteInitializationTimeout = setTimeout(_ => { initialize(app) }, app.distributionOptions.coteDelay)
          }
        } else {
          initialize(app)
        }

        // Healthcheck endpoint(s)
        const healthcheckRoute = (options.healthcheckPath || '/distribution/healthcheck/')
        debug('Initializing feathers-distributed healthcheck route', healthcheckRoute)
        // Route for specific app
        app.use(healthcheckRoute + ':key', new HealthcheckService(app))
        // Route for all registered apps
        app.use(healthcheckRoute, new HealthcheckService(app))

        // We replace the use method to inject service publisher/responder
        const superUse = app.use
        app.use = function () {
          const path = arguments[0]
          // Register the service normally first
          const superReturn = superUse.apply(app, arguments)
          // Check if cote has already been initialized
          if (!app.cote) return superReturn
          // With express apps we can directly register middlewares: not supported
          if (typeof path !== 'string') return superReturn
          publishService(app, path)
          return superReturn
        }
      }
    }