Skip to content
This repository was archived by the owner on Jan 3, 2024. It is now read-only.

Commit 8fdf71f

Browse files
committed
Fix CPU/memory issue + add Bot.clearCache()
This also now shuts down the unused event loop as well clears the cache
1 parent 7a3547c commit 8fdf71f

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

Sources/Discord/Discord.swift

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,21 @@ public class Bot {
352352
}
353353
}
354354

355+
private func clearCache() {
356+
dms.removeAll()
357+
users.removeAll()
358+
msgCacheLock.lock()
359+
for messageId in Set<Snowflake>(cachedMessages.map({ $0.id })) {
360+
removeCachedMessage(messageId)
361+
}
362+
msgCacheLock.unlock()
363+
for guild in guilds {
364+
guild.channelsCache.removeAll()
365+
guild.membersCache.removeAll()
366+
}
367+
guildsCache.removeAll()
368+
}
369+
355370
/// Create a guild. Your bot must be in less than 10 guilds to use this.
356371
/// - Parameters:
357372
/// - name: Name of the guild.
@@ -389,12 +404,16 @@ public class Bot {
389404
}
390405
}
391406

392-
/// Disconnects the bot from Discord and releases the block from ``connect()``.
407+
/// Disconnects the bot from Discord, releases the block from ``connect()`` and clears the cache.
393408
public func disconnect() {
394409
if let gw {
395-
_ = gw.ws.close(code: .normalClosure)
410+
try! gw.ws.close(code: .normalClosure).wait()
396411
gw.resetGatewayValues()
412+
clearCache()
413+
try! gw.settings.loop.syncShutdownGracefully()
397414
self.gw = nil
415+
416+
// Must be last
398417
isConnected = false
399418
}
400419
}

Sources/Discord/Gateway.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ class Gateway {
151151
private var heartbeatInterval = 0
152152
private var receivedReconnectRequest = false
153153

154-
private let settings = (
154+
let settings = (
155155
port: 443,
156156
query: "v=10&encoding=json",
157157
config: WebSocketClient.Configuration(maxFrameSize: 1 << 20),
@@ -207,6 +207,11 @@ class Gateway {
207207
while true {
208208
await sleep(heartbeatInterval)
209209
sendHeartbeat()
210+
do {
211+
try Task.checkCancellation()
212+
} catch {
213+
return
214+
}
210215
}
211216
}
212217

Sources/Discord/Models/Guild.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ public class Guild : Object, Hashable, Updateable {
146146

147147
/// All members in the guild.
148148
public var members: [Member] { [Member](membersCache.values) }
149-
private var membersCache = [Snowflake: Member]()
149+
var membersCache = [Snowflake: Member]()
150150

151151
/// Total number of members in the guild.
152152
public internal(set) var memberCount = 0

0 commit comments

Comments
 (0)