Skip to content
This repository has been archived by the owner on Jan 29, 2022. It is now read-only.

Suggested changes #3

Merged
merged 3 commits into from
Jun 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 101 additions & 88 deletions Sources/MongoMobile/MongoMobile.swift
Original file line number Diff line number Diff line change
@@ -1,124 +1,137 @@
import Foundation
import mongo_embedded
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[q] Should this also have import MongoSwift?

Copy link
Contributor Author

@kmahar kmahar Jun 13, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried, but MongoMobile won't build within another project (such as TestMongoMobile) if it's there and says it can't find the package. I guess with the way MongoSwift ends up getting included, the code is available but not under that name

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, since MongoSwift is being vendored in it no longer exists in that package name. This is an unfortunate sideeffect of not being able to properly set up the dependency between the libraries.


let MONGO_EMBEDDED_V1_ERROR_EXCEPTION = 2;

/// Settings for constructing a `MongoClient`
public struct MongoClientSettings {
/// the database path to use
public let dbPath: String
/// the database path to use
public let dbPath: String

/// public member-wise initializer
public init(dbPath: String) {
self.dbPath = dbPath
}
/// public member-wise initializer
public init(dbPath: String) {
self.dbPath = dbPath
}
}

public enum MongoMobileError: Error {
/// Errors associated with `MongoMobile`.
public enum MongoMobileError: LocalizedError {
case invalidClient()
case invalidInstance(message: String)
case invalidLibrary()
case instanceDropError(message: String)
case cleanupError(message: String)

/// a string to be printed out when the error is thrown
public var errorDescription: String? {
switch self {
case let .invalidInstance(message),
let .instanceDropError(message),
let .cleanupError(message):
return message
default:
return nil
}
}
}

/// Prints a log statement in the format `[component] message`.
private func mongo_mobile_log_callback(userDataPtr: UnsafeMutableRawPointer?,
messagePtr: UnsafePointer<Int8>?,
componentPtr: UnsafePointer<Int8>?,
contextPtr: UnsafePointer<Int8>?,
severityPtr: Int32)
{
let message = String(cString: messagePtr!)
let component = String(cString: componentPtr!)
severityPtr: Int32) {
let message = messagePtr != nil ? String(cString: messagePtr!) : ""
let component = componentPtr != nil ? String(cString: componentPtr!) : ""
print("[\(component)] \(message)")
}

/// Given an `OpaquePointer` to a `mongo_embedded_v1_status`, get the status's explanation.
private func getStatusExplanation(_ status: OpaquePointer?) -> String {
return String(cString: mongo_embedded_v1_status_get_explanation(status))
}

/// A class containing static methods for working with MongoMobile.
public class MongoMobile {
private static var libraryInstance: OpaquePointer?
private static var embeddedInstances = [String: OpaquePointer]()

/**
* Perform required operations to initialize the embedded server.
*/
public static func initialize() throws {
// NOTE: remove once MongoSwift is handling this
mongoc_init()

let status = mongo_embedded_v1_status_create()
var initParams = mongo_embedded_v1_init_params()
initParams.log_callback = mongo_mobile_log_callback
initParams.log_flags = 4 // LIBMONGODB_CAPI_LOG_CALLBACK

guard let instance = mongo_embedded_v1_lib_init(&initParams, status) else {
throw MongoMobileError.invalidInstance(message:
String(cString: mongo_embedded_v1_status_get_explanation(status)))
private static var libraryInstance: OpaquePointer?
private static var embeddedInstances = [String: OpaquePointer]()

/**
* Perform required operations to initialize the embedded server.
*/
public static func initialize() throws {
MongoSwift.initialize()

let status = mongo_embedded_v1_status_create()
var initParams = mongo_embedded_v1_init_params()
initParams.log_callback = mongo_mobile_log_callback
initParams.log_flags = UInt64(MONGO_EMBEDDED_V1_LOG_CALLBACK.rawValue)

guard let instance = mongo_embedded_v1_lib_init(&initParams, status) else {
throw MongoMobileError.invalidInstance(message: getStatusExplanation(status))
}

libraryInstance = instance
}

libraryInstance = instance
}

/**
* Perform required operations to cleanup the embedded server.
*/
public static func close() throws {
let status = mongo_embedded_v1_status_create()
for (_, instance) in embeddedInstances {
let result = mongo_embedded_v1_instance_destroy(instance, status)
if result == MONGO_EMBEDDED_V1_ERROR_EXCEPTION {
throw MongoMobileError.instanceDropError(message:
String(cString: mongo_embedded_v1_status_get_explanation(status)))
/**
* Perform required operations to clean up the embedded server.
*/
public static func close() throws {
let status = mongo_embedded_v1_status_create()
for (_, instance) in embeddedInstances {
let result = mongo_embedded_v1_instance_destroy(instance, status)
if result == MONGO_EMBEDDED_V1_ERROR_EXCEPTION.rawValue {
throw MongoMobileError.instanceDropError(message: getStatusExplanation(status))
}
}

let result = mongo_embedded_v1_lib_fini(libraryInstance, status)
if result == MONGO_EMBEDDED_V1_ERROR_EXCEPTION.rawValue {
throw MongoMobileError.cleanupError(message: getStatusExplanation(status))
}
}

let result = mongo_embedded_v1_lib_fini(libraryInstance, status)
if result == MONGO_EMBEDDED_V1_ERROR_EXCEPTION {
throw MongoMobileError.cleanupError(message:
String(cString: mongo_embedded_v1_status_get_explanation(status)))
MongoSwift.cleanup()
}

// NOTE: remove once MongoSwift is handling this
mongoc_cleanup()
}

/**
* Create a new `MongoClient` for the database indicated by `dbPath` in
* the passed in settings.
*
* - Parameters:
* - settings: required settings for client creation
*
* - Returns: a new `MongoClient`
*/
public static func create(_ settings: MongoClientSettings) throws -> MongoClient {
let status = mongo_embedded_v1_status_create()
var instance: OpaquePointer
if let cachedInstance = embeddedInstances[settings.dbPath] {
instance = cachedInstance
} else {
let configuration = [
"storage": [
"dbPath": settings.dbPath
/**
* Create a new `MongoClient` for the database indicated by `dbPath` in
* the passed in settings.
*
* - Parameters:
* - settings: required settings for client creation
*
* - Returns: a new `MongoClient`
*/
public static func create(_ settings: MongoClientSettings) throws -> MongoClient {
let status = mongo_embedded_v1_status_create()
var instance: OpaquePointer?
if let cachedInstance = embeddedInstances[settings.dbPath] {
instance = cachedInstance
} else {
// get the configuration as a JSON string
let configuration = [
"storage": [
"dbPath": settings.dbPath
]
]
]
let configurationData = try JSONSerialization.data(withJSONObject: configuration)
let configurationString = String(data: configurationData, encoding: .utf8)

let configurationData = try JSONSerialization.data(withJSONObject: configuration)
let configurationString = String(data: configurationData, encoding: .utf8)
guard let library = libraryInstance else {
throw MongoMobileError.invalidLibrary()
}
guard let library = libraryInstance else {
throw MongoMobileError.invalidLibrary()
}

guard let capiInstance = mongo_embedded_v1_instance_create(library, configurationString, status) else {
throw MongoMobileError.invalidInstance(message:
String(cString: mongo_embedded_v1_status_get_explanation(status)))
guard let capiInstance = mongo_embedded_v1_instance_create(library, configurationString, status) else {
throw MongoMobileError.invalidInstance(message: getStatusExplanation(status))
}

instance = capiInstance
embeddedInstances[settings.dbPath] = instance
}

instance = capiInstance
embeddedInstances[settings.dbPath] = instance
}
guard let capiClient = mongo_embedded_v1_mongoc_client_create(instance) else {
throw MongoMobileError.invalidClient()
}

guard let capiClient = mongo_embedded_v1_mongoc_client_create(instance) else {
throw MongoMobileError.invalidClient()
return MongoClient(fromPointer: capiClient)
}

return MongoClient(fromPointer: capiClient)
}
}
12 changes: 6 additions & 6 deletions Tests/MongoMobileTests/MongoMobileTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ final class MongoMobileTests: XCTestCase {
}

func testMongoMobile() throws {
let client = MongoMobile.create(settings: MongoClientSettings [ dbPath: "test-path" ])
let coll = try client.db("test").collection("foo")
let insertResult = try coll.insertOne([ "test": 42 ])
let findResult = try coll.find([ "_id": insertResult!.insertedId ])
let docs = Array(findResult)
XCTAssertEqual(docs[0]["test"] as? Int, 42)
let client = MongoMobile.create(settings: MongoClientSettings(dbPath: "test-path"))
let coll = try client.db("test").collection("foo")
let insertResult = try coll.insertOne([ "test": 42 ])
let findResult = try coll.find([ "_id": insertResult!.insertedId ])
let docs = Array(findResult)
XCTAssertEqual(docs[0]["test"] as? Int, 42)
}
}