orlandos-nl / MongoKitten

Native MongoDB driver for Swift, written in Swift

Home Page:https://orlandos.nl/docs/mongokitten/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Detecting When MongoDB Server is down

icyield opened this issue · comments

I was wondering what the recommended way of detecting/dealing with a mongoDB stop/start. I must admit mongodb is pretty stable but I need to still consider what to do. I call a reinit func to restart when I detect an Error .notConnected but this is complicated by the way MongoKitten behaves, if I cannot get a reconnection on the first error.


Some observation of 4.1.2 behaviour.

In my tests I get a .notConnected Error after trying to insert some documents the first time after mongodb was stopped.

But the second time I try inserting some documents I get .cannotSendData MongoSocket.Error
This enum is not public so is difficult to catch, explicitly.

The database.server.isConnected still returns true. But I can see that the number of openConnections is 0.

I have added a hasOpenConnection getter but maybe it should just include the $0.openConnections > 0 in the isConnected getter. I do not understand why there is an array of hosts (I only have one) so am a bit wary of changing it.

I also added public to the enum MongoSocket.Error

But maybe I'm missing something?

=====

/// Are we currently connected?
public var isConnected: Bool {
guard connections.count > 0 else {
return false
}

    return self.servers.contains(where: { $0.online && $0.isPrimary })
}

public var hasOpenConnection: Bool {
    guard connections.count > 0 else {
        return false
    }
    
    return self.servers.contains(where: { $0.openConnections > 0 })
}

This is an old issue that I didn't get to yet. With MongoKitten 4 and earlier versions the architecture wouldn't allow us to tackle this. I can add support in MongoKitten 5 by reading the pool array and its count.

For lazily connecting clusters I can imagine the following API:

enum ConnectionStatus {
  case connected, disconnected
  case unknown // Used when still connecting or disconnecting
}

let connectionStatus = cluster.status

Poking @Obbut for thoughts.