From 4993b167deeebbef3808f17537d886560379fc5a Mon Sep 17 00:00:00 2001 From: rob Date: Sat, 5 Nov 2022 05:53:06 -0400 Subject: [PATCH] Service Node disconnect processing --- app/services/hive.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/app/services/hive.js b/app/services/hive.js index 5b8490f..6d8112d 100644 --- a/app/services/hive.js +++ b/app/services/hive.js @@ -7,6 +7,8 @@ const mongoose = require('mongoose'); const UserSubscription = mongoose.model('UserSubscription'); +const UserNotification = mongoose.model('UserSubscription'); + const KaleidoscopeEvent = mongoose.model('KaleidoscopeEvent'); const slug = require('slug'); @@ -20,6 +22,25 @@ class HiveService extends SiteService { super(dtp, module.exports); } + async start ( ) { + const { oauth2: oauth2Service } = this.dtp.services; + + this.eventHandlers = { + onOAuth2RemoveClient: this.onOAuth2RemoveClient.bind(this), + }; + + oauth2Service.on(oauth2Service.getEventName('client.remove'), this.eventHandlers.onOAuth2RemoveClient); + } + + async stop ( ) { + const { oauth2: oauth2Service } = this.dtp.services; + + oauth2Service.off(oauth2Service.getEventName('client.remove'), this.eventHandlers.onOAuth2RemoveClient); + delete this.eventHandlers.onOAuth2RemoveClient; + + delete this.eventHandlers; + } + async subscribe (user, client, emitterId) { await UserSubscription.updateOne( { user: user._id }, @@ -277,6 +298,27 @@ class HiveService extends SiteService { .lean(); return { events, totalEventCount }; } + + /* + * OAuth2 event handlers + */ + + /** + * This event fires when an OAuth2Client is being disconnected and removed by a + * Core, or a client app is being removed from a Service Node. The Hive service + * will remove all KaleidoscopeEvent records created on behalf of the client. + * @param {OAuth2Client} client the client being removed + */ + async onOAuth2RemoveClient (client) { + this.log.alert('removing KaleidoscopeEvent records from OAuth2Client', { clientId: client._id, domain: client.site.domain }); + await KaleidoscopeEvent + .find({ 'source.client': client._id }) + .cursor() + .eachAsync(async (event) => { + await UserNotification.deleteMany({ event: event._id }); + await KaleidoscopeEvent.deleteOne({ _id: event._id }); + }, 1); + } } module.exports = {