I would like my Cocoa app to communicate with a database server. Following the principle in the app sandbox design, it would make sense for the DB communications to be split out into an XPC service.
Since an XPC service is supposed to be stateless, the struct containing the connection info (eg. a MySQL connection handle) would need to be held by the main app and passed into the XPC service as needed. However the handle is an opaque type which does not appear to be supported by XPC services - only basic arithmetic/logic/collection types are allowed.
Is there some way to box a connection handle (or other opaque type) such that it can be passed to an XPC service?
Since a MySQL connection handle isn't stateless, and because the whole point of isolating the network code into an XPC in the first place is stability, I wouldn't worry about the statelessness. It is considered preferable, but it isn't a requirement. To quote:
Because an XPC service can be terminated suddenly at any time, it must be designed
to hold on to minimal state—ideally, your service should be completely stateless,
although this is not always possible.
This is one of those cases where it isn't always possible. The MySQL connection holds state of its own, so if you want to remain stateless, your best bet would be to pass all of your credentials to the XPC as an atomic operation each time, and that's going to be inefficient.
Instead, I'd suggest that you create some kind of "handle" passed back and forth between your app and the XPC which can be looked up in a table within the XPC for validation (that way if the XPC is terminated and started again it can tell that it was interrupted and send an error back). Then, on the application side, you can send that handle for operations and have your internal API handle re-opening if appropriate by re-acquiring the "handle" from the XPC when necessary. This could be done directly in your code which makes the database calls, but if the XPC is prone to death, then you would want to put it into an internal library and maintain the credentials so that you could restart the XPC and re-initaite the connection without bothering the higher-level code.
Either way, you're going to want to keep calls to the XPC at an SQL transaction level, because the MySQL connection could abort between calls to the XPC, and that would cause a roll-back and you'd have to start over.