Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Pipeline for zipping multiple file chanel into a single output channel
Parent
Pipeline for zipping multiple file chanel into a single output channel
I am in need of downloading some files (from dynamic list of URLs) and archive them into a single zip file. Since these files can be arbitrarily sized (totaling hundreds of MB), I want to avoid downloading each entry individually, creating the entire archive in-memory and then uploading it, but rather make a sort of streamed pipeline for it.
In short, I want to have something going through the list of URLs, streaming each file into a ZipOutputStream
(adding a new entry per file), and another thing consuming that stream (ktor multipart request, for example).
I have tried creating a ByteChannel
and passing .toOutputStream()
to a ZipOutputStream
. Then, spawn a background job to grab each URL, create a zip entry and write packets into the stream, and finally return the channel wrapper in a ChannelProvider
to pass into FormBuilder#append
.
However, sometimes ktor times out, sometimes it doesn't and I manage to upload the archive as a multipart request, but it is corrupt.
Has anyone tried anything similar? If so, how have you tackled it?
Here's the code I have:
ChannelProvider {
val fileChannel = ByteChannel()
val zos = ZipOutputStream(fileChannel.toOutputStream())
coroScope.launch {
files.forEach { f ->
httpClient.get(f.url).reader {
zos.putNextEntry(ZipEntry(f.filename))
while (!channel.isClosedForRead) {
channel.readRemaining(DEFAULT_BUFFER_SIZE.toLong()).let {
zos.writePacket(it)
}
}
zos.closeEntry()
}
}
zos.close()
fileChannel.close()
}
fileChannel
}
Post
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
tmpod |
Thread: Works for me OP's own solution. |
Sep 12, 2023 at 00:31 |
Well, ain't this fun hehe
Turns out I failed to see .reader
launches its own job, which resulted in multiple coroutines contending for the zip stream, each trying to write an entry... 🤦
The solution was just to get a channel and use that instead. Additionally, to mitigate the still blocking nature of Java's ZipOutputStream
, I spawned the job in the appropriate Dispatchers.IO
.
Here it is:
ChannelProvider {
val fileChannel = ByteChannel()
val zos = ZipOutputStream(fileChannel.toOutputStream())
coroScope.launch(Dispatchers.IO) {
files.forEach { f ->
val body = httpClient.get(f.url).bodyAsChannel()
zos.putNextEntry(ZipEntry(f.filename))
while (!body.isClosedForRead) {
body.readRemaining(DEFAULT_BUFFER_SIZE.toLong()).let {
zos.writePacket(it)
}
}
zos.closeEntry()
}
zos.close()
fileChannel.close()
}
fileChannel
}
0 comment threads