diff --git a/apple/InlineIOS/Features/Compose/PhotoUtils.swift b/apple/InlineIOS/Features/Compose/PhotoUtils.swift index 01ce6c5a7..e542dd385 100644 --- a/apple/InlineIOS/Features/Compose/PhotoUtils.swift +++ b/apple/InlineIOS/Features/Compose/PhotoUtils.swift @@ -43,14 +43,51 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe } } - private func shouldSendAsFile(_ image: UIImage) -> Bool { + private nonisolated static func shouldSendAsFile(_ image: UIImage) -> Bool { let width = max(image.size.width, 1) let height = max(image.size.height, 1) let ratio = max(width / height, height / width) return ratio > 20 || (width < 50 && height < 50) } - private func makeImageAttachment(_ image: UIImage, optimizePhoto: Bool) throws -> FileMediaItem { + /// Saves at most this many images at once; each holds a full-resolution encode in memory. + private nonisolated static let imageSaveConcurrency = 2 + + /// Saves picked images as attachments off the main actor, keeping their order; nil where one + /// failed. Each is a full-resolution JPEG or PNG encode plus a file and a database write, which + /// took the main thread for a noticeable time per photo. + private nonisolated static func imageAttachments(_ images: [UIImage], optimizePhoto: Bool) async -> [FileMediaItem?] { + guard !images.isEmpty else { return [] } + return await Task.detached(priority: .userInitiated) { + await withTaskGroup(of: (Int, FileMediaItem?).self) { group in + @Sendable func save(_ index: Int) -> (Int, FileMediaItem?) { + do { + return (index, try imageAttachment(images[index], optimizePhoto: optimizePhoto)) + } catch { + Log.shared.error("Failed to save photo attachment", error: error) + return (index, nil) + } + } + var items = [FileMediaItem?](repeating: nil, count: images.count) + var next = min(imageSaveConcurrency, images.count) + for index in 0 ..< next { + group.addTask { save(index) } + } + for await (index, item) in group { + items[index] = item + if next < images.count { + let index = next + group.addTask { save(index) } + next += 1 + } + } + return items + } + }.value + } + + /// Synchronous disk and database work: off the main actor, use `imageAttachments`. + private nonisolated static func imageAttachment(_ image: UIImage, optimizePhoto: Bool) throws -> FileMediaItem { if shouldSendAsFile(image) { let tempDirectory = FileHelpers.getTrueTemporaryDirectory() let fileName = "image-\(UUID().uuidString).jpg" @@ -325,19 +362,18 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe func sendImage(_ image: UIImage, caption: String) { guard let peerId else { return } + let chatId = chatId + let replyToMsgId = ChatState.shared.getState(peer: peerId).replyingMessageId clearAttachments() + resetComposeStateAfterPreviewSend() + dismissPreview(dismissAttachmentPicker: currentPreviewUsesAttachmentPicker) + clearAttachments() + // sendMessageHaptic() - do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: false) - let uniqueId = mediaItem.getItemUniqueId() - attachmentItems[uniqueId] = mediaItem - } catch { - Log.shared.error("Failed to save photo", error: error) - } - - let didPrepareImage = !attachmentItems.isEmpty - for (_, attachment) in attachmentItems { + // The preview closes now; the message is sent once the photo is saved off the main thread. + Task { @MainActor in + guard let attachment = await Self.imageAttachments([image], optimizePhoto: false).first ?? nil else { return } Transactions.shared.mutate( transaction: .sendMessage( .init( @@ -345,61 +381,61 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe peerId: peerId, chatId: chatId ?? 0, mediaItems: [attachment], - replyToMsgId: ChatState.shared.getState(peer: peerId).replyingMessageId, + replyToMsgId: replyToMsgId, isSticker: nil, entities: nil ) ) ) + if let chatId { + IntentDonationCoordinator.donateOutgoing(peerId: peerId, chatId: chatId) + } } - - if didPrepareImage, let chatId { - IntentDonationCoordinator.donateOutgoing(peerId: peerId, chatId: chatId) - } - - resetComposeStateAfterPreviewSend() - dismissPreview(dismissAttachmentPicker: currentPreviewUsesAttachmentPicker) - clearAttachments() - // sendMessageHaptic() } func sendMultipleImages(_ photoItems: [PhotoItem]) { guard let peerId else { return } + let chatId = chatId let replyToMessageId = ChatState.shared.getState(peer: peerId).replyingMessageId - - var items: [AlbumSendItem] = [] - for (index, photoItem) in photoItems.enumerated() { - do { - let mediaItem = try makeImageAttachment(photoItem.image, optimizePhoto: true) - // Each photo keeps its own caption; the album shows the first one. - let captionText = photoItem.caption?.trimmingCharacters(in: .whitespacesAndNewlines) - items.append(AlbumSendItem(media: mediaItem, text: captionText?.isEmpty == false ? captionText : nil)) - } catch { - Log.shared.error("Failed to save and send photo \(index + 1)", error: error) - } - } - // Photos picked together go out as albums of up to ten. - for send in TransactionSendMessage.sends( - peerId: peerId, - chatId: chatId ?? 0, - items: items, - replyToMsgId: replyToMessageId - ) { - Transactions.shared.mutate(transaction: .sendMessage(send)) + let images = photoItems.map(\.image) + // Each photo keeps its own caption; the album shows the first one. + let captions = photoItems.map { photoItem -> String? in + let captionText = photoItem.caption?.trimmingCharacters(in: .whitespacesAndNewlines) + return captionText?.isEmpty == false ? captionText : nil } - let didSendImage = !items.isEmpty - if didSendImage, let chatId { - IntentDonationCoordinator.donateOutgoing(peerId: peerId, chatId: chatId) - } - - // Clear state and dismiss + // Clear state and dismiss now; the photos are saved off the main thread, then sent. resetComposeStateAfterPreviewSend() dismissMultiPreview(dismissAttachmentPicker: currentPreviewUsesAttachmentPicker) clearAttachments() ChatState.shared.clearReplyingMessageId(peer: peerId) // sendMessageHaptic() + + Task { @MainActor in + let saved = await Self.imageAttachments(images, optimizePhoto: true) + var items: [AlbumSendItem] = [] + for (index, mediaItem) in saved.enumerated() { + guard let mediaItem else { + Log.shared.error("Failed to save and send photo \(index + 1)") + continue + } + items.append(AlbumSendItem(media: mediaItem, text: captions[index])) + } + guard !items.isEmpty else { return } + // Photos picked together go out as albums of up to ten. + for send in TransactionSendMessage.sends( + peerId: peerId, + chatId: chatId ?? 0, + items: items, + replyToMsgId: replyToMessageId + ) { + Transactions.shared.mutate(transaction: .sendMessage(send)) + } + if let chatId { + IntentDonationCoordinator.donateOutgoing(peerId: peerId, chatId: chatId) + } + } } func handlePastedImage() { @@ -430,21 +466,20 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe func addImages(_ images: [UIImage]) { guard !images.isEmpty else { return } - var didAddAny = false - for image in images { - do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: true) + let destination = peerId + Task { @MainActor [weak self] in + let saved = await Self.imageAttachments(images, optimizePhoto: true) + guard let self, peerId == destination else { return } + var didAddAny = false + for mediaItem in saved.compactMap({ $0 }) { let uniqueId = mediaItem.getItemUniqueId() attachmentItems[uniqueId] = mediaItem didAddAny = true Log.shared.debug("Added image attachment with uniqueId: \(uniqueId)") - } catch { - Log.shared.error("Failed to save photo in attachments", error: error) } - } - - if didAddAny { - handleAttachmentItemsChanged(animated: false) + if didAddAny { + handleAttachmentItemsChanged(animated: false) + } } } @@ -578,7 +613,8 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe } do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: true) + // Rare (a GIF that is not animated), so saved here rather than off the main thread. + let mediaItem = try Self.imageAttachment(image, optimizePhoto: true) attachmentItems[mediaItem.getItemUniqueId()] = mediaItem completePendingVideoAttachments([pendingId]) } catch { @@ -693,13 +729,10 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe return .failure(.message("Couldn't open that recent photo.")) } - do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: true) - return .success(mediaItem) - } catch { - Log.shared.error("Failed to save photo in attachments", error: error) + guard let mediaItem = await Self.imageAttachments([image], optimizePhoto: true).first ?? nil else { return .failure(.message("Couldn't open that recent photo.")) } + return .success(mediaItem) } private func loadRecentImage(from asset: PHAsset) async -> UIImage? { @@ -833,6 +866,14 @@ extension ComposeView: PHPickerViewControllerDelegate { } } + // Save the photos off the main thread before touching the attachments. + let pickedImages = loadedItems.compactMap { entry -> (index: Int, image: UIImage)? in + guard case let .image(image) = entry.item else { return nil } + return (entry.index, image) + } + let savedImages = await Self.imageAttachments(pickedImages.map(\.image), optimizePhoto: true) + let savedImageByIndex = Dictionary(uniqueKeysWithValues: zip(pickedImages.map(\.index), savedImages)) + await MainActor.run { [weak self, weak picker] in guard let self else { return } @@ -856,15 +897,12 @@ extension ComposeView: PHPickerViewControllerDelegate { for entry in sortedEntries { let item = entry.item switch item { - case let .image(image): - do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: true) - let uniqueId = mediaItem.getItemUniqueId() - attachmentItems[uniqueId] = mediaItem - } catch { - Log.shared.error("Failed to save photo in attachments", error: error) + case .image: + guard let mediaItem = savedImageByIndex[entry.index] ?? nil else { cancelQueuedPendingVideoSend() + continue } + attachmentItems[mediaItem.getItemUniqueId()] = mediaItem case let .video(videoItem): if let pendingId = pendingVideoIdsByIndex[entry.index], isPendingVideoAttachmentCanceled(pendingId) { continue diff --git a/apple/InlineKit/Sources/InlineKit/Transactions/Methods/AlbumSend.swift b/apple/InlineKit/Sources/InlineKit/Transactions/Methods/AlbumSend.swift index 6346af2cc..bc2d6d2b0 100644 --- a/apple/InlineKit/Sources/InlineKit/Transactions/Methods/AlbumSend.swift +++ b/apple/InlineKit/Sources/InlineKit/Transactions/Methods/AlbumSend.swift @@ -133,12 +133,15 @@ public extension TransactionSendMessage { ) -> [TransactionSendMessage] { var sends: [TransactionSendMessage] = [] sends.reserveCapacity(items.count) + // Message rows keep dates to the millisecond, and sends made in one go share one. Spacing them + // keeps their order after a relaunch, when interrupted sends resume oldest first. + let firstDate = Date() for run in albumSendRuns(items.map(\.media)) { let groupedId: Int64? = run.count > 1 ? Int64.random(in: 1 ... Int64.max) : nil var ids: [String] = [] for index in run { let item = items[index] - let send = TransactionSendMessage( + var send = TransactionSendMessage( text: item.text, peerId: peerId, chatId: chatId, @@ -148,6 +151,7 @@ public extension TransactionSendMessage { sendMode: sendMode, groupedId: groupedId ) + send.date = firstDate.addingTimeInterval(Double(sends.count) / 1_000) ids.append(send.id) sends.append(send) } diff --git a/apple/InlineKit/Sources/InlineKit/Transactions/Methods/PendingSendRecovery.swift b/apple/InlineKit/Sources/InlineKit/Transactions/Methods/PendingSendRecovery.swift index f195a8685..5472bd279 100644 --- a/apple/InlineKit/Sources/InlineKit/Transactions/Methods/PendingSendRecovery.swift +++ b/apple/InlineKit/Sources/InlineKit/Transactions/Methods/PendingSendRecovery.swift @@ -27,7 +27,9 @@ public enum PendingSendRecovery { /// Pure selection so the policy is testable without a running queue. static func plan(for messages: [Message], now: Date, window: TimeInterval = automaticResumeWindow) -> Plan { var plan = Plan() - for message in messages.sorted(by: { $0.date < $1.date }) { + // Insertion order breaks ties: rows store dates to the millisecond, and an album's items, sent + // together before their dates were spaced, can share one. + for message in messages.sorted(by: { ($0.date, $0.globalId ?? 0) < ($1.date, $1.globalId ?? 0) }) { let isRecoverable = message.randomId != nil && !(message.transactionId ?? "").isEmpty && now.timeIntervalSince(message.date) <= window diff --git a/apple/InlineKit/Tests/InlineKitTests/MessageAlbumsTests.swift b/apple/InlineKit/Tests/InlineKitTests/MessageAlbumsTests.swift index e4627d01d..bd04e5380 100644 --- a/apple/InlineKit/Tests/InlineKitTests/MessageAlbumsTests.swift +++ b/apple/InlineKit/Tests/InlineKitTests/MessageAlbumsTests.swift @@ -128,6 +128,9 @@ struct MessageAlbumsTests { let albumId = sends[0].groupedId #expect(albumId != nil) #expect(sends.allSatisfy { $0.groupedId == albumId }) + // Each send is a millisecond after the one before, so stored rows keep their order. + let milliseconds = sends.map { Int64(($0.date.timeIntervalSince1970 * 1_000).rounded(.down)) } + #expect(zip(milliseconds, milliseconds.dropFirst()).allSatisfy { $0 < $1 }) #expect(AlbumSendBarrier.shared.isRegistered(transactionId: sends[0].id)) for send in sends { AlbumSendBarrier.shared.settle(transactionId: send.id) diff --git a/apple/InlineKit/Tests/InlineKitTests/PendingSendRecoveryTests.swift b/apple/InlineKit/Tests/InlineKitTests/PendingSendRecoveryTests.swift index e694cc1ab..4899c4243 100644 --- a/apple/InlineKit/Tests/InlineKitTests/PendingSendRecoveryTests.swift +++ b/apple/InlineKit/Tests/InlineKitTests/PendingSendRecoveryTests.swift @@ -44,6 +44,18 @@ struct PendingSendRecoveryTests { #expect(plan.fail == [-2, -4, -5]) } + @Test("sends that share a stored date resume in the order their rows were written") + @MainActor + func tiesResumeInInsertionOrder() { + let now = Date() + let rows = [(Int64(-30), Int64(12)), (-10, 10), (-20, 11)].map { messageId, globalId in + var message = outgoing(id: messageId, age: 5, now: now) + message.globalId = globalId + return message + } + #expect(PendingSendRecovery.plan(for: rows, now: now).resume == [-10, -20, -30]) + } + @Test("recovered send reuses the interrupted row's identity") @MainActor func recoveredTransactionKeepsIdentity() throws { diff --git a/server/src/modules/transfers/trace.test.ts b/server/src/modules/transfers/trace.test.ts index 101351c59..b47d6dddf 100644 --- a/server/src/modules/transfers/trace.test.ts +++ b/server/src/modules/transfers/trace.test.ts @@ -4,6 +4,7 @@ import { countTransferWork, recordSqlStatement, recordStorageOperation, + recordStoragePutTime, } from "./trace" describe("transfer traces", () => { @@ -14,10 +15,11 @@ describe("transfer traces", () => { await Promise.resolve() recordSqlStatement() recordStorageOperation("put") + recordStoragePutTime(12) }) - expect(inner.counters).toEqual({ sqlStatements: 1, storagePut: 1, storageGet: 0, storageDelete: 0 }) + expect(inner.counters).toEqual({ sqlStatements: 1, storagePut: 1, storageGet: 0, storageDelete: 0, storagePutMs: 12 }) }) - expect(outer.counters).toEqual({ sqlStatements: 2, storagePut: 1, storageGet: 0, storageDelete: 0 }) + expect(outer.counters).toEqual({ sqlStatements: 2, storagePut: 1, storageGet: 0, storageDelete: 0, storagePutMs: 12 }) // Outside any scope nothing is recorded and nothing throws. recordSqlStatement() }) @@ -43,7 +45,7 @@ describe("transfer traces", () => { traces.finish("upload:7", "complete") expect(lines).toEqual([{ direction: "upload", carrier: "v3", bytes: 150, parts: 2, durationMs: 42, peakInFlightBytes: 150, - sqlStatements: 1, storageOps: { put: 0, get: 1, delete: 0 }, retries: 0, outcome: "complete", + sqlStatements: 1, storageOps: { put: 0, get: 1, delete: 0 }, putMs: 0, retries: 0, outcome: "complete", }]) expect(JSON.stringify(lines)).not.toContain("upload:7") expect(traces.openCount).toBe(0) diff --git a/server/src/modules/transfers/trace.ts b/server/src/modules/transfers/trace.ts index e065d51ba..7579e41a3 100644 --- a/server/src/modules/transfers/trace.ts +++ b/server/src/modules/transfers/trace.ts @@ -12,6 +12,8 @@ export type TransferCounters = { storagePut: number storageGet: number storageDelete: number + /** Wall time spent in storage writes, summed; overlapping writes each count in full. */ + storagePutMs: number } type CounterScope = { @@ -26,6 +28,7 @@ export const emptyTransferCounters = (): TransferCounters => ({ storagePut: 0, storageGet: 0, storageDelete: 0, + storagePutMs: 0, }) /** Runs `operation` with `counters` receiving every statement and storage operation it causes. */ @@ -55,6 +58,11 @@ export const recordStorageOperation = (operation: StorageOperation): void => { } } +/** Adds a finished storage write's duration to every active scope. */ +export const recordStoragePutTime = (milliseconds: number): void => { + for (let scope = scopes.getStore(); scope; scope = scope.parent) scope.counters.storagePutMs += milliseconds +} + export type TransferDirection = "upload" | "download" export type TransferCarrier = "v2" | "v3" export type TransferOutcome = "complete" | "failed" | "canceled" | "eof" | "abandoned" @@ -150,6 +158,7 @@ export class TransferTraces { get: trace.counters.storageGet, delete: trace.counters.storageDelete, }, + putMs: Math.round(trace.counters.storagePutMs), retries: trace.retries, outcome, }) diff --git a/server/src/modules/uploads/multipartStore.ts b/server/src/modules/uploads/multipartStore.ts index f7ff611bf..15383008b 100644 --- a/server/src/modules/uploads/multipartStore.ts +++ b/server/src/modules/uploads/multipartStore.ts @@ -1,4 +1,4 @@ -import { recordStorageOperation } from "@in/server/modules/transfers/trace" +import { recordStorageOperation, recordStoragePutTime } from "@in/server/modules/transfers/trace" import { AbortMultipartUploadCommand, CompleteMultipartUploadCommand, @@ -234,6 +234,7 @@ export class R2MultipartObjectStore implements MultipartObjectStore { }): Promise { recordStorageOperation("put") const md5 = createHash("md5").update(input.bytes).digest() + const startedAt = performance.now() try { const { bucket, client } = this.#requireConfiguration() const result = await client.send(new UploadPartCommand({ @@ -252,6 +253,8 @@ export class R2MultipartObjectStore implements MultipartObjectStore { if (cause instanceof MultipartIntegrityError) throw cause if (isNoSuchUpload(cause)) throw new MultipartUploadNotFoundError({ cause }) throw new MultipartStorageUnavailableError({ cause }) + } finally { + recordStoragePutTime(performance.now() - startedAt) } } @@ -295,6 +298,7 @@ export class R2MultipartObjectStore implements MultipartObjectStore { }): Promise<{ etag: string }> { recordStorageOperation("put") const md5 = createHash("md5").update(input.bytes).digest() + const startedAt = performance.now() try { const { bucket, client } = this.#requireConfiguration() const result = await client.send(new PutObjectCommand({ @@ -311,6 +315,8 @@ export class R2MultipartObjectStore implements MultipartObjectStore { } catch (cause) { if (cause instanceof MultipartIntegrityError) throw cause throw new MultipartStorageUnavailableError({ cause }) + } finally { + recordStoragePutTime(performance.now() - startedAt) } } diff --git a/server/src/modules/uploads/operations.ts b/server/src/modules/uploads/operations.ts index ef8f922ca..54bf59cb8 100644 --- a/server/src/modules/uploads/operations.ts +++ b/server/src/modules/uploads/operations.ts @@ -50,7 +50,7 @@ import { markPartAccepted, type UploadGeometry, } from "./geometryCache" -import { countTransferWork, transferTraces } from "@in/server/modules/transfers/trace" +import { countTransferWork, transferTraces, withTransferCounters } from "@in/server/modules/transfers/trace" const log = new Log("modules/uploads", uploadTraceLogLevel()) const RETRY_AFTER_SECONDS = 1 @@ -181,13 +181,17 @@ export type NativeUploadOperationsOptions = { finishInline?: ( upload: { id: number; partCount: number; kind: InlineUploadRecord["kind"] }, signal?: AbortSignal, + stored?: Promise, ) => Promise<"complete" | "running" | "processing"> + /** Writes a whole file sent with CREATE_UPLOAD to its final key; see NativeUploadWorker.storeEarly. */ + storeEarly?: (upload: InlineUploadRecord, bytes: Uint8Array, signal: AbortSignal) => Promise } export class NativeUploadOperations { readonly #geometry: UploadGeometryCache readonly #groupBuffer: UploadGroupBuffer | undefined readonly #finishInline: NativeUploadOperationsOptions["finishInline"] + readonly #storeEarly: NativeUploadOperationsOptions["storeEarly"] constructor( private readonly repository: InlineUploadRepository, @@ -201,6 +205,7 @@ export class NativeUploadOperations { this.#geometry = options.geometry ?? new UploadGeometryCache() this.#groupBuffer = options.groupBuffer this.#finishInline = options.finishInline + this.#storeEarly = options.storeEarly } async create(input: CreateUploadInput, context: HandlerContext): Promise { @@ -242,25 +247,34 @@ export class NativeUploadOperations { expiresAt: BigInt(Math.floor(result.upload.expiresAt.getTime() / 1_000)), acceptedParts: result.upload.acceptedParts, } - return input.inlineData === undefined ? created : await this.#finishInlineData(created, input.inlineData, context) + return input.inlineData === undefined + ? created + : await this.#finishInlineData(created, result.upload, owner, input.inlineData, context) } /** * Saves a whole single-part file sent with CREATE_UPLOAD and finishes it in the same call, so a * small photo costs one round trip instead of create, part and finish. On any failure the * upload still exists and the client continues with the ordinary part and finish calls. + * + * The final object is written alongside staging rather than after it (see + * NativeUploadWorker.storeEarly for who cleans up a write that outlives its upload). */ async #finishInlineData( created: CreateUploadResult, + upload: InlineUploadRecord, + owner: InlineUploadOwner, data: Uint8Array, context: HandlerContext, ): Promise { if (created.partCount !== 1) return created + const early = this.#startEarlyStore(upload, data, context) + const stored = early?.stored try { if (!created.acceptedParts.includes(0)) { await this.savePart({ uploadId: created.uploadId, partIndex: 0, data }, context) } - const finished = await this.finish({ uploadId: created.uploadId }, context) + const finished = await this.#finish({ uploadId: created.uploadId }, context, owner, stored) switch (finished.state.oneofKind) { case "complete": return { ...created, acceptedParts: [0], complete: finished.state.complete } case "missing": return created @@ -270,9 +284,30 @@ export class NativeUploadOperations { if (context.signal?.aborted) throw error log.warn("Inline upload data was not finished in create", { error }) return created + } finally { + // The reply waits for no storage deadline: a write still running here (the finish timed out + // or failed early) is stopped, and the worker writes the object itself if it needs it. + early?.stop() + await stored } } + /** Starts `storeEarly` when this request can finish the upload itself; `stored` never rejects. */ + #startEarlyStore( + upload: InlineUploadRecord, + data: Uint8Array, + context: HandlerContext, + ): { stored: Promise; stop: () => void } | undefined { + const storeEarly = this.#storeEarly + if (!storeEarly || !this.#finishInline || upload.status !== "uploading" || + upload.byteCount > INLINE_FINISH_MAX_BYTES) return undefined + const controller = new AbortController() + const signal = context.signal ? AbortSignal.any([controller.signal, context.signal]) : controller.signal + const trace = transferTraces.touch(uploadTraceKey(upload.id), "upload", context.inlineProtocol ? "v3" : "v2") + const stored = withTransferCounters(trace.counters, () => storeEarly(upload, data, signal)).catch(() => false) + return { stored, stop: () => controller.abort() } + } + async savePart(input: SaveUploadPartInput, context: HandlerContext): Promise { throwIfAborted(context.signal) if (input.uploadId.length !== 16 || !Number.isInteger(input.partIndex) || input.partIndex < 0) return badRequest() @@ -484,9 +519,19 @@ export class NativeUploadOperations { } async finish(input: FinishUploadInput, context: HandlerContext): Promise { + return await this.#finish(input, context) + } + + /** `owner` is one the same request already resolved; `stored` comes from `#startEarlyStore`. */ + async #finish( + input: FinishUploadInput, + context: HandlerContext, + resolvedOwner?: InlineUploadOwner, + stored?: Promise, + ): Promise { const startedAt = Date.now() throwIfAborted(context.signal) - const owner = await this.#owner(context) + const owner = resolvedOwner ?? await this.#owner(context) throwIfAborted(context.signal) const result = await this.repository.requestFinish(input.uploadId, owner) if (result.kind !== "missing") this.#geometry.drop(input.uploadId) @@ -498,11 +543,14 @@ export class NativeUploadOperations { return { state: { oneofKind: "processing", processing: { retryAfterSeconds: RETRY_AFTER_SECONDS } } } case "queued": { const inline = result.byteCount <= INLINE_FINISH_MAX_BYTES && this.#finishInline - ? await this.#finishInline({ id: result.uploadDbId, partCount: result.partCount, kind: result.uploadKind }, context.signal) - .catch((error) => { - log.warn("Native upload inline finish failed", { error, uploadDbId: result.uploadDbId }) - return "processing" as const - }) + ? await this.#finishInline( + { id: result.uploadDbId, partCount: result.partCount, kind: result.uploadKind }, + context.signal, + stored, + ).catch((error) => { + log.warn("Native upload inline finish failed", { error, uploadDbId: result.uploadDbId }) + return "processing" as const + }) : "processing" log.debug("UPLOAD_TRACE phase=finish_queued", { uploadDbId: result.uploadDbId, @@ -665,6 +713,7 @@ export const nativeUploadOperations = new NativeUploadOperations( (uploadDbId) => nativeUploadWorker.cancel(uploadDbId), { groupBuffer: uploadGroupBuffer, - finishInline: (upload, signal) => nativeUploadWorker.processNow(upload, signal), + finishInline: (upload, signal, stored) => nativeUploadWorker.processNow(upload, signal, stored), + storeEarly: (upload, bytes, signal) => nativeUploadWorker.storeEarly(upload, bytes, signal), }, ) diff --git a/server/src/modules/uploads/partStore.ts b/server/src/modules/uploads/partStore.ts index 0a0479bc8..eff855fa6 100644 --- a/server/src/modules/uploads/partStore.ts +++ b/server/src/modules/uploads/partStore.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto" import { getR2 } from "@in/server/libs/r2" import { readFileBytes, FileByteLengthError } from "@in/server/modules/files/readFileBytes" import { INLINE_TRANSFER_PART_SIZE } from "@inline-chat/protocol/transfers" -import { recordStorageOperation } from "@in/server/modules/transfers/trace" +import { recordStorageOperation, recordStoragePutTime } from "@in/server/modules/transfers/trace" import { createR2S3Configuration, storageDeadlineSignal, @@ -120,6 +120,7 @@ export class R2UploadPartStore implements UploadPartStore { }, signal?: AbortSignal): Promise { const key = objectKey(input) recordStorageOperation("put") + const startedAt = performance.now() try { const written = await this.#writePart( key, @@ -132,6 +133,8 @@ export class R2UploadPartStore implements UploadPartStore { } catch (cause) { signal?.throwIfAborted() throw new UploadPartStorageUnavailableError({ cause }) + } finally { + recordStoragePutTime(performance.now() - startedAt) } return key } diff --git a/server/src/modules/uploads/worker.test.ts b/server/src/modules/uploads/worker.test.ts index f65274869..b3aa8cd17 100644 --- a/server/src/modules/uploads/worker.test.ts +++ b/server/src/modules/uploads/worker.test.ts @@ -25,7 +25,7 @@ import { type MultipartUploadedPart, } from "./multipartStore" import { NativeUploadOperations } from "./operations" -import type { UploadPartStore } from "./partStore" +import { UploadPartStorageUnavailableError, type UploadPartStore } from "./partStore" import { NativeUploadWorker, storagePartGeometry } from "./worker" import { UploadGroupBuffer } from "./groupBuffer" @@ -197,6 +197,84 @@ class PuttingMultipartStore extends MemoryMultipartStore { } } +/** Holds every final-object PUT until released; the first `failures` PUTs fail. */ +class GatedPuttingMultipartStore extends PuttingMultipartStore { + attempts = 0 + #release!: () => void + readonly released = new Promise((resolve) => { this.#release = resolve }) + + constructor(private readonly failures = 0, private readonly gated = false) { + super() + } + + release(): void { + this.#release() + } + + override async put(input: { key: string; bytes: Uint8Array; signal?: AbortSignal }): Promise<{ etag: string }> { + this.attempts += 1 + if (this.attempts <= this.failures) throw new MultipartStorageUnavailableError() + if (this.gated) { + await Promise.race([ + this.released, + new Promise((resolve) => { + input.signal?.addEventListener("abort", () => resolve(), { once: true }) + if (input.signal?.aborted) resolve() + }), + ]) + if (input.signal?.aborted) throw new MultipartStorageUnavailableError() + } + return await super.put(input) + } +} + +/** Staging that is down. */ +class FailingPartStore extends BatchingPartStore { + override async put(): Promise { + throw new UploadPartStorageUnavailableError() + } +} + +class ThumbnailLookupRepository extends InlineUploadRepository { + thumbnailLookups = 0 + + override async completedPhotoId( + ...args: Parameters + ): Promise { + this.thumbnailLookups += 1 + return await super.completedPhotoId(...args) + } +} + +/** Holds staging writes until released. */ +class GatedPartStore extends BatchingPartStore { + writes = 0 + #release!: () => void + readonly released = new Promise((resolve) => { this.#release = resolve }) + + release(): void { + this.#release() + } + + override async put(input: Parameters[0]): Promise { + this.writes += 1 + await this.released + return await super.put(input) + } +} + +class CountingRenewRepository extends InlineUploadRepository { + renewCalls = 0 + + override async renew( + input: Parameters[0], + signal?: AbortSignal, + ): Promise { + this.renewCalls += 1 + return await super.renew(input, signal) + } +} + class LostInstallResponseRepository extends InlineUploadRepository { #loseResponse = true @@ -717,6 +795,8 @@ describe("native upload multipart worker", () => { const worker = createWorker(repository, staging, multipart, finalizer, { concurrency: 1, leaseRenewTimeoutMs: 10, + // Every ownership check goes to the database. + freshLeaseMs: 0, pollIntervalMs: 20, }) worker.start() @@ -862,6 +942,7 @@ describe("native upload multipart worker", () => { finalizerFor: (body: Uint8Array) => MediaUploadFinalizer body: Uint8Array inline?: boolean + early?: boolean multipart?: MemoryMultipartStore repository?: InlineUploadRepository }) => { @@ -876,7 +957,10 @@ describe("native upload multipart worker", () => { const operations = new NativeUploadOperations(repository, staging, finalizer, (uploadDbId, groupNumber) => worker.wake(uploadDbId, groupNumber), undefined, undefined, { groupBuffer: buffer, - finishInline: options.inline === false ? undefined : (upload, signal) => worker.processNow(upload, signal), + finishInline: options.inline === false + ? undefined + : (upload, signal, stored) => worker.processNow(upload, signal, stored), + storeEarly: options.early === false ? undefined : (upload, bytes, signal) => worker.storeEarly(upload, bytes, signal), }) return { repository, staging, multipart, buffer, worker, operations, finalizer } } @@ -1013,6 +1097,151 @@ describe("native upload multipart worker", () => { expect((await db.select().from(inlineUploads)).length).toBe(rows) }) + test("writes a file sent with create to its final key alongside staging, once", async () => { + const user = await testUtils.createUser("native-upload-inline-early-store@example.com") + const account = await testUtils.createSessionForUser(user.id) + const requestContext = context(user.id, account.session.id) + const body = new Uint8Array(30_000).fill(9) + const staging = new GatedPartStore() + const multipart = new GatedPuttingMultipartStore() + const repository = new CountingRenewRepository() + const { worker, operations } = pipeline({ body, staging, multipart, repository, finalizerFor: makeFinalizer }) + worker.start() + const creating = operations.create({ + clientUploadId: new Uint8Array(16).fill(152), + fileName: "early.bin", + mimeType: "application/octet-stream", + byteCount: BigInt(body.byteLength), + sha256: createHash("sha256").update(body).digest(), + kind: UploadKind.DOCUMENT, + metadata: { oneofKind: undefined }, + inlineData: body, + }, requestContext) + // The final object is written while the staging write is still running. + await waitFor(() => multipart.putCount === 1 && staging.writes === 1) + expect(staging.objects.size).toBe(0) + staging.release() + const created = await creating + expect(created.complete?.fileUniqueId).toBeString() + // The worker did not write it again, and a fresh claim needed no lease renewal. + expect(multipart.attempts).toBe(1) + const [stored] = [...multipart.objects.values()] + expect(Buffer.from(stored!.bytes).equals(Buffer.from(body))).toBe(true) + expect(repository.renewCalls).toBe(0) + }) + + test("writes the final object in the worker when the early write failed", async () => { + const user = await testUtils.createUser("native-upload-inline-early-store-failed@example.com") + const account = await testUtils.createSessionForUser(user.id) + const requestContext = context(user.id, account.session.id) + const body = new Uint8Array(20_000).fill(6) + const multipart = new GatedPuttingMultipartStore(1) + const { worker, operations } = pipeline({ body, multipart, finalizerFor: makeFinalizer }) + worker.start() + const created = await operations.create({ + clientUploadId: new Uint8Array(16).fill(153), + fileName: "early-failed.bin", + mimeType: "application/octet-stream", + byteCount: BigInt(body.byteLength), + sha256: createHash("sha256").update(body).digest(), + kind: UploadKind.DOCUMENT, + metadata: { oneofKind: undefined }, + inlineData: body, + }, requestContext) + expect(created.complete?.fileUniqueId).toBeString() + expect(multipart.attempts).toBe(2) + expect(multipart.putCount).toBe(1) + const [stored] = [...multipart.objects.values()] + expect(Buffer.from(stored!.bytes).equals(Buffer.from(body))).toBe(true) + }) + + test("a claim that fails before its write waits for the early write, so cleanup removes it", async () => { + const user = await testUtils.createUser("native-upload-inline-early-store-thumbnail@example.com") + const account = await testUtils.createSessionForUser(user.id) + const requestContext = context(user.id, account.session.id) + const owner = { userId: user.id, accountSessionId: account.session.id } + const body = new Uint8Array(12_000).fill(3) + const multipart = new GatedPuttingMultipartStore(0, true) + const repository = new ThumbnailLookupRepository() + const { worker, operations } = pipeline({ body, multipart, repository, finalizerFor: makeFinalizer }) + worker.start() + const creating = operations.create({ + clientUploadId: new Uint8Array(16).fill(155), + fileName: "early-thumbnail.bin", + mimeType: "application/octet-stream", + byteCount: BigInt(body.byteLength), + sha256: createHash("sha256").update(body).digest(), + kind: UploadKind.DOCUMENT, + // No completed photo has this id, so the claim fails as invalid media before its write. + thumbnailFileUniqueId: "missing-thumbnail", + metadata: { oneofKind: undefined }, + inlineData: body, + }, requestContext) + await waitFor(() => repository.thumbnailLookups > 0 && multipart.attempts === 1) + await new Promise((resolve) => setTimeout(resolve, 50)) + multipart.release() + const created = await creating + expect(created.complete).toBeUndefined() + await waitFor(async () => (await repository.get(created.uploadId, owner))?.status === "failed") + expect((await repository.get(created.uploadId, owner))?.failureCode).toBe("invalid_media") + expect(multipart.putCount).toBe(1) + expect(multipart.objects.size).toBe(0) + }) + + test("create does not wait for an early write once staging has failed", async () => { + const user = await testUtils.createUser("native-upload-inline-early-store-stop@example.com") + const account = await testUtils.createSessionForUser(user.id) + const requestContext = context(user.id, account.session.id) + const body = new Uint8Array(8_000).fill(7) + const multipart = new GatedPuttingMultipartStore(0, true) + const { worker, operations } = pipeline({ + body, multipart, staging: new FailingPartStore(), finalizerFor: makeFinalizer, + }) + worker.start() + const startedAt = performance.now() + const created = await operations.create({ + clientUploadId: new Uint8Array(16).fill(156), + fileName: "early-stop.bin", + mimeType: "application/octet-stream", + byteCount: BigInt(body.byteLength), + sha256: createHash("sha256").update(body).digest(), + kind: UploadKind.DOCUMENT, + metadata: { oneofKind: undefined }, + inlineData: body, + }, requestContext) + expect(performance.now() - startedAt).toBeLessThan(5_000) + expect(created.complete).toBeUndefined() + expect(created.acceptedParts).toEqual([]) + expect(multipart.attempts).toBe(1) + expect(multipart.putCount).toBe(0) + multipart.release() + }) + + test("never writes early a file that does not match its declared digest", async () => { + const user = await testUtils.createUser("native-upload-inline-early-store-digest@example.com") + const account = await testUtils.createSessionForUser(user.id) + const requestContext = context(user.id, account.session.id) + const owner = { userId: user.id, accountSessionId: account.session.id } + const body = new Uint8Array(10_000).fill(2) + const multipart = new GatedPuttingMultipartStore() + const { worker, operations, repository } = pipeline({ body, multipart, finalizerFor: makeFinalizer }) + worker.start() + const created = await operations.create({ + clientUploadId: new Uint8Array(16).fill(154), + fileName: "early-digest.bin", + mimeType: "application/octet-stream", + byteCount: BigInt(body.byteLength), + sha256: createHash("sha256").update(new Uint8Array(body.byteLength).fill(1)).digest(), + kind: UploadKind.DOCUMENT, + metadata: { oneofKind: undefined }, + inlineData: body, + }, requestContext) + expect(created.complete).toBeUndefined() + await waitFor(async () => (await repository.get(created.uploadId, owner))?.status === "failed") + expect(multipart.attempts).toBe(0) + expect(multipart.objects.size).toBe(0) + }) + test("stores a ten-part upload with one PUT even after a group wake", async () => { let released = 0 class Repository extends InlineUploadRepository { diff --git a/server/src/modules/uploads/worker.ts b/server/src/modules/uploads/worker.ts index 332e5ced5..10a04728d 100644 --- a/server/src/modules/uploads/worker.ts +++ b/server/src/modules/uploads/worker.ts @@ -41,6 +41,13 @@ const DEFAULT_POLL_INTERVAL_MS = 2_000 const MAX_PROCESSING_ATTEMPTS = 12 const LEASE_RENEW_INTERVAL_MS = Math.min(60_000, INLINE_UPLOAD_PROCESSING_LEASE_MS / 3) const DEFAULT_LEASE_RENEW_TIMEOUT_MS = Math.min(5_000, INLINE_UPLOAD_PROCESSING_LEASE_MS / 4) +/** An ownership check this soon after the lease was confirmed skips the database. */ +const FRESH_LEASE_MS = Math.min(5_000, INLINE_UPLOAD_PROCESSING_LEASE_MS / 6) +/** + * An early store needs this long before the upload expires: expiry cleanup removes the final key + * and then the row, and a write landing after both would be left with no owner. + */ +const EARLY_STORE_EXPIRY_MARGIN_MS = 5 * 60_000 const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS = 5_000 const STAGING_READ_CONCURRENCY = 4 const DEFAULT_EXPIRY_CLEANUP_INTERVAL_MS = 60_000 @@ -61,6 +68,8 @@ type WorkerOptions = { inlineFinishTimeoutMs?: number expiryCleanupIntervalMs?: number leaseRenewTimeoutMs?: number + /** How soon after a lease was confirmed an ownership check skips the database. */ + freshLeaseMs?: number maximumIdleIntervalMs?: number pollIntervalMs?: number random?: () => number @@ -103,6 +112,17 @@ const throwIfAborted = (signal: AbortSignal): void => { if (signal.aborted) throw signal.reason ?? new DOMException("The operation was aborted", "AbortError") } +/** + * Both results once neither is running, so a failure never leaves the other's object write in + * flight behind cleanup. Rethrows the first failure in argument order. + */ +const settleBoth = async (first: Promise, second: Promise): Promise<[A, B]> => { + const [left, right] = await Promise.allSettled([first, second]) + if (left.status === "rejected") throw left.reason + if (right.status === "rejected") throw right.reason + return [left.value, right.value] +} + const settlesWithin = async (promise: Promise, timeoutMs: number): Promise => await new Promise((resolve) => { let settled = false @@ -165,6 +185,7 @@ export class NativeUploadWorker { readonly #pollIntervalMs: number readonly #expiryCleanupIntervalMs: number readonly #leaseRenewTimeoutMs: number + readonly #freshLeaseMs: number readonly #shutdownDrainTimeoutMs: number readonly #random: () => number readonly #backoff: IdleBackoff @@ -175,6 +196,8 @@ export class NativeUploadWorker { readonly #queued = new Map | "full">() readonly #activeUploads = new Set() readonly #claimControllers = new Map() + /** When each claim was requested; the database starts its lease no earlier. */ + readonly #claimRequestedAt = new WeakMap() readonly #tasks = new Set>() readonly #cleanupTasks = new Set>() #abort = new AbortController() @@ -198,6 +221,7 @@ export class NativeUploadWorker { this.#pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS this.#expiryCleanupIntervalMs = options.expiryCleanupIntervalMs ?? DEFAULT_EXPIRY_CLEANUP_INTERVAL_MS this.#leaseRenewTimeoutMs = options.leaseRenewTimeoutMs ?? DEFAULT_LEASE_RENEW_TIMEOUT_MS + this.#freshLeaseMs = Math.min(options.freshLeaseMs ?? FRESH_LEASE_MS, FRESH_LEASE_MS) this.#shutdownDrainTimeoutMs = options.shutdownDrainTimeoutMs ?? DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS this.#random = options.random ?? Math.random this.#groupBuffer = options.groupBuffer ?? new UploadGroupBuffer() @@ -319,14 +343,16 @@ export class NativeUploadWorker { * still holds every group in memory. Returns `complete` when published within * the timeout, `running` when this process claimed the work and it continues as * an ordinary worker task (no wake is needed), and `processing` when nothing - * was claimed here. + * was claimed here. `stored` is a `storeEarly` write of this upload's bytes; when + * it resolves true the final object is not written again. */ async processNow( upload: { id: number; partCount: number; kind: InlineUploadRecord["kind"] }, signal?: AbortSignal, + stored?: Promise, ): Promise<"complete" | "running" | "processing"> { if (!this.#started || this.#activeUploads.has(upload.id) || !this.#holdsInMemory(upload)) return "processing" - const claim = await this.repository.claimProcessing(upload.id) + const claim = await this.#claim(() => this.repository.claimProcessing(upload.id)) if (!claim) return "processing" if (this.#activeUploads.has(upload.id)) { await this.repository.releaseProcessingClaim({ uploadDbId: claim.upload.id, lockToken: claim.lockToken }) @@ -335,7 +361,7 @@ export class NativeUploadWorker { } this.#queued.delete(upload.id) let published = false - const task = this.#track(upload.id, async () => { published = await this.#processClaim(claim) }) + const task = this.#track(upload.id, async () => { published = await this.#processClaim(claim, stored) }) let timer: ReturnType | undefined let onAbort: (() => void) | undefined await Promise.race([ @@ -353,6 +379,46 @@ export class NativeUploadWorker { return published ? "complete" : "running" } + /** + * Writes a whole single-group upload to its final key before it is finished, so the write + * overlaps staging; pass the result to `processNow`. Resolves false, never rejects, when the + * upload does not qualify or the write failed, and the worker writes it as usual. The write is + * not fenced: a claim given it waits for it before any cleanup, and a key that lands after + * another process's cleanup (a cancel sent after a retried create, a claim by its poll) is + * removed with the row at expiry, which is why an upload near expiry does not qualify. + */ + async storeEarly(upload: InlineUploadRecord, bytes: Uint8Array, signal?: AbortSignal): Promise { + const latestStart = Math.min(upload.expiresAt.getTime(), upload.hardExpiresAt.getTime()) - + EARLY_STORE_EXPIRY_MARGIN_MS + // Only `processNow` here can use the write, and it needs a running worker. + if (!this.#started || Date.now() >= latestStart || !this.multipartStore.put || upload.status !== "uploading" || + upload.storageFormat !== IDENTITY_STORAGE_FORMAT || upload.storageUploadId || + upload.partCount > STORAGE_FRAMES_PER_PART || BigInt(bytes.byteLength) !== upload.byteCount || + !sameBytes(createHash("sha256").update(bytes).digest(), upload.sha256)) return false + try { + await this.multipartStore.put({ + key: storageKeyFor(upload), + bytes, + contentType: upload.mimeType, + signal, + }) + return true + } catch (error) { + if (!signal?.aborted) log.warn("Native upload early store failed", { error, uploadDbId: upload.id }) + return false + } + } + + /** Claims through `take`, noting when the claim was requested. */ + async #claim( + take: () => Promise, + ): Promise { + const requestedAt = performance.now() + const claim = await take() + if (claim) this.#claimRequestedAt.set(claim, requestedAt) + return claim + } + /** Every group is either already in the running digest or fully buffered; photos need every frame. */ #holdsInMemory(upload: { id: number; partCount: number; kind: InlineUploadRecord["kind"] }): boolean { if (bufferedPublicationNeedsBytes(upload.kind)) { @@ -492,7 +558,7 @@ export class NativeUploadWorker { try { this.#pump() while (this.#started && this.#active < this.#concurrency) { - const claim = await this.repository.claimProcessing() + const claim = await this.#claim(() => this.repository.claimProcessing()) if (!claim) break claimed = true if (this.#activeUploads.has(claim.upload.id)) { @@ -525,7 +591,7 @@ export class NativeUploadWorker { if (!this.#started || this.#abort.signal.aborted) return if (!work) return if (work.upload.status === "processing") { - const claim = await this.repository.claimProcessing(uploadDbId) + const claim = await this.#claim(() => this.repository.claimProcessing(uploadDbId)) if (!claim) return if (!this.#started || this.#abort.signal.aborted) { await this.repository.releaseProcessingClaim({ @@ -538,7 +604,7 @@ export class NativeUploadWorker { return } if (work.upload.storageFormat) { - const claim = await this.repository.claimUploadingCompaction(uploadDbId) + const claim = await this.#claim(() => this.repository.claimUploadingCompaction(uploadDbId)) if (!claim) return await this.#processUploadingClaim(claim) } @@ -551,7 +617,7 @@ export class NativeUploadWorker { */ async #runGroups(uploadDbId: number, groupNumbers: number[], attempt = 0): Promise { throwIfAborted(this.#abort.signal) - const claim = await this.repository.claimUploadingCompaction(uploadDbId) + const claim = await this.#claim(() => this.repository.claimUploadingCompaction(uploadDbId)) if (!claim) { if (attempt < GROUP_CLAIM_RETRIES && this.#started) { const retry = setTimeout(() => { @@ -584,8 +650,15 @@ export class NativeUploadWorker { if (this.#abort.signal.aborted) abortFromRoot() let heartbeatRenewal: Promise | undefined let leaseLost = false - const assertOwnership = async (): Promise => { + let confirmedAt = this.#claimRequestedAt.get(claim) + const confirm = async (renewNow: boolean): Promise => { throwIfAborted(controller.signal) + // The database starts or extends the lease no earlier than our request, so one confirmed + // moments ago is still ours unless the upload was canceled, which the conditional publish + // and the next heartbeat both catch. The heartbeat always renews; it keeps the lease alive. + if (!renewNow && !leaseLost && confirmedAt !== undefined && + performance.now() - confirmedAt < this.#freshLeaseMs) return + const requestedAt = performance.now() let renewed = false if (!leaseLost) { renewed = await this.repository.renew({ @@ -601,10 +674,12 @@ export class NativeUploadWorker { controller.abort(new UploadOwnershipLostError()) throw new UploadOwnershipLostError() } + confirmedAt = Math.max(confirmedAt ?? requestedAt, requestedAt) } + const assertOwnership = (): Promise => confirm(false) const heartbeat = setInterval(() => { if (heartbeatRenewal || controller.signal.aborted) return - heartbeatRenewal = assertOwnership().catch((error) => { + heartbeatRenewal = confirm(true).catch((error) => { leaseLost = true controller.abort(error) }).finally(() => { heartbeatRenewal = undefined }) @@ -646,7 +721,7 @@ export class NativeUploadWorker { } /** Returns true when this call published the upload. */ - async #processClaim(claim: InlineUploadProcessingClaim): Promise { + async #processClaim(claim: InlineUploadProcessingClaim, stored?: Promise): Promise { if (!this.#started || this.#abort.signal.aborted) { await this.repository.releaseProcessingClaim({ uploadDbId: claim.upload.id, @@ -671,7 +746,7 @@ export class NativeUploadWorker { let publication const singleGroupFrames = claim.upload.storageFormat - ? await this.#putSingleGroup(claim, controller.signal, assertOwnership) + ? await this.#singleGroupFrames(claim, controller.signal) : undefined if (!claim.upload.storageFormat) { publication = await this.finalizer.preparePublication({ @@ -682,15 +757,19 @@ export class NativeUploadWorker { signal: controller.signal, }) } else if (singleGroupFrames) { - // Verified and stored above; the digest and frames are already proven. + // Verified above; the digest and frames are already proven. The object write and the media + // work need only those bytes, so they run together; both finish before anything else. this.#digests.delete(claim.upload.id) - publication = await this.finalizer.prepareBufferedPublication({ - upload: claim.upload, - frames: bufferedPublicationNeedsBytes(claim.upload.kind) ? singleGroupFrames : undefined, - thumbnailPhotoId, - assertOwnership, - signal: controller.signal, - }) + ;[, publication] = await settleBoth( + this.#storeSingleGroup(claim, singleGroupFrames, controller.signal, assertOwnership, stored), + this.finalizer.prepareBufferedPublication({ + upload: claim.upload, + frames: bufferedPublicationNeedsBytes(claim.upload.kind) ? singleGroupFrames.frames : undefined, + thumbnailPhotoId, + assertOwnership, + signal: controller.signal, + }), + ) } else { let work: InlineUploadStorageWork = claim let resetCount = 0 @@ -749,6 +828,9 @@ export class NativeUploadWorker { ) return true } catch (error) { + // An early write still running would land after the cleanup below. Shutdown only releases + // the claim, so it does not wait (the request stops the write when it ends). + if (!this.#abort.signal.aborted) await stored // Cancellation may have happened on another process or just before // shutdown. Clean a late object write before taking the shutdown path. if (await this.#discardCanceledWork(claim.upload.id)) return false @@ -982,14 +1064,13 @@ export class NativeUploadWorker { * session (create, upload part, complete and two HEAD checks, plus their manifest statements) * proves the same thing with five object-store calls, which dominated small-photo finish time. * Every frame is checked against its manifest digest, the whole body against the declared - * file digest, and the PUT's MD5 ETag proves what was stored. Returns the verified frames, or - * undefined to use multipart. + * file digest, and the PUT's MD5 ETag proves what was stored. Returns the verified frames and + * body, or undefined to use multipart. */ - async #putSingleGroup( + async #singleGroupFrames( work: InlineUploadStorageWork, signal: AbortSignal, - assertOwnership: () => Promise, - ): Promise { + ): Promise<{ frames: Uint8Array[]; bytes: Uint8Array } | undefined> { const upload = work.upload if (!this.multipartStore.put || upload.storageFormat !== IDENTITY_STORAGE_FORMAT || upload.partCount > STORAGE_FRAMES_PER_PART || upload.storageUploadId || @@ -1001,14 +1082,27 @@ export class NativeUploadWorker { !sameBytes(createHash("sha256").update(bytes).digest(), upload.sha256)) { throw new UploadIntegrityError() } + return { frames, bytes } + } + + /** Writes a verified single-group body, unless `stored` reports that `storeEarly` wrote it. */ + async #storeSingleGroup( + work: InlineUploadStorageWork, + verified: { bytes: Uint8Array }, + signal: AbortSignal, + assertOwnership: () => Promise, + stored: Promise | undefined, + ): Promise { + // `storeEarly` wrote these bytes: it checked them against the same declared digest. + if (stored && await stored) return + if (!this.multipartStore.put) throw new UploadIntegrityError() await assertOwnership() await this.multipartStore.put({ - key: storageKeyFor(upload), - bytes, - contentType: upload.mimeType, + key: storageKeyFor(work.upload), + bytes: verified.bytes, + contentType: work.upload.mimeType, signal, }) - return frames } /**