Fix NSMallocException when writing envelope to disk
Description
We see a couple of NSMallocException: Failed to grow buffer in our internal SDK crash detection and also a customer reported this error.
The crash happens when serializing the envelope item data
https://github.com/getsentry/sentry-cocoa/blob/ac8fd5353ed60b08a13a4ad891b7ca374e258f01/Sources/Sentry/SentrySerialization.m#L77
The SentrySerialization.dataWithEnvelope puts the whole content of an envelope into NSData and then the SentryFileManager files the envelope to disk. https://github.com/getsentry/sentry-cocoa/blob/ac8fd5353ed60b08a13a4ad891b7ca374e258f01/Sources/Sentry/SentryFileManager.m#L284
When customers use large attachments, the SDK duplicates the memory footprint before writing the envelope to disk, which then causes the NSMallocException. To reduce the memory footprint of the SDK, especially with attachments, we can do the following improvements independently:
- Use a
NSFileHandleto write envelopes to disk inSentryFileManager.storeEnvelopeinstead of putting the contents of the envelope into NSData before writing to disk. The improvement should write envelope item directly to disk. - Instead of reading the data of attachments with a path into memory when initializing an envelope item, we could directly write the contents to disk: https://github.com/getsentry/sentry-cocoa/blob/ac8fd5353ed60b08a13a4ad891b7ca374e258f01/Sources/Sentry/SentryEnvelope.m#L159-L184
This will also be used for Session Replay.