Skip to content
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
31 changes: 7 additions & 24 deletions apps/mobile/src/lib/attachmentUpload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ vi.mock("expo-file-system", () => ({
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import { uploadError } from "./composerAttachmentUploadQueue";
import {
prepareTurnAttachments as prepareWithUploads,
releasePendingAttachmentUploads,
Expand All @@ -109,30 +108,14 @@ function prepare(
) {
return prepareWithUploads({
...input,
// An interrupted send waits for its transfer to settle, as the shared registry does.
uploadAttachment: (attachment) =>
Effect.suspend(() => {
const controller = new AbortController();
const upload = uploadComposerAttachment(
input.environmentId,
attachment,
controller.signal,
input.onUploadProgress
? (progress) => input.onUploadProgress?.(attachment.id, progress)
: undefined,
);
return Effect.tryPromise({ try: () => upload, catch: uploadError }).pipe(
Effect.onInterrupt(() =>
Effect.promise(() => {
controller.abort();
return upload.then(
() => undefined,
() => undefined,
);
}),
),
);
}),
uploadComposerAttachment(
input.environmentId,
attachment,
input.onUploadProgress
? (progress) => input.onUploadProgress?.(attachment.id, progress)
: undefined,
),
});
}
import type { DraftComposerAttachment } from "./composerImages";
Expand Down
81 changes: 49 additions & 32 deletions apps/mobile/src/lib/attachmentUpload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ import {
} from "./composerImages";
import { imageMimeType } from "@t3tools/shared/image";
import { uuidv4 } from "./uuid";
import { type ComposerAttachmentUploadError, uploadError } from "./composerAttachmentUploadQueue";
import {
attachmentUploadError,
type AttachmentUploadError,
} from "@t3tools/client-runtime/state/attachment-uploads";

export type UploadedMobileAttachment =
| UploadChatImageAttachment
Expand Down Expand Up @@ -257,71 +260,82 @@ function requireUploadAccess(environmentId: EnvironmentId): void {
}

/**
* Uploads one attachment and resolves to its uploaded id, reusing an earlier upload the server
* still has. An abort deletes the pending upload it created.
* Uploads one attachment and returns its uploaded id, reusing an earlier upload the server
* still has. Interrupting it aborts the native transfer and deletes the pending upload it minted;
* a failed transfer deletes it too.
*/
export async function uploadComposerAttachment(
export const uploadComposerAttachment = Effect.fn("uploadComposerAttachment")(function* (
environmentId: EnvironmentId,
attachment: DraftComposerAttachment,
signal: AbortSignal,
onProgress?: (progress: number) => void,
): Promise<string> {
requireUploadAccess(environmentId);
) {
yield* Effect.try({
try: () => requireUploadAccess(environmentId),
catch: attachmentUploadError,
});
if (
attachment.uploadEnvironmentId === environmentId &&
attachment.uploadedAttachmentId !== undefined
) {
const verification = await verifyPersistedAttachmentUpload({
const verification = yield* verifyPersistedAttachmentUpload({
registry: appAtomRegistry,
createAssetUrl: assetEnvironment.createUrl,
environmentId,
attachmentId: attachment.uploadedAttachmentId,
});
if (verification.status === "failed") throw verification.error;
if (verification.status === "failed") {
return yield* attachmentUploadError(verification.error);
}
if (verification.status === "verified") return attachment.uploadedAttachmentId;
}
if (signal.aborted) throw new Error("Upload cancelled.");
requireUploadAccess(environmentId);
yield* Effect.try({
try: () => requireUploadAccess(environmentId),
catch: attachmentUploadError,
});
if (
Option.isNone(
appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(environmentId)),
)
) {
throw new Error("The environment is not connected.");
return yield* attachmentUploadError(new Error("The environment is not connected."));
}
let minted: string | null = null;
const result = await runAttachmentUploadCycle({
const result = yield* runAttachmentUploadCycle({
registry: appAtomRegistry,
createUploadUrl: attachmentEnvironment.createUploadUrl,
remove: attachmentEnvironment.remove,
environmentId,
upload: attachmentUploadInput(attachment),
// Resolve at transfer time; reconnects may change the base URL.
resolveUploadUrl: (relativeUrl) => {
requireUploadAccess(environmentId);
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return null;
const connection = appAtomRegistry.get(
environmentSession.preparedConnectionValueAtom(environmentId),
);
return Option.isNone(connection)
? null
: resolveAssetUrl(connection.value.httpBaseUrl, relativeUrl);
},
transport: (url) => ({
done: uploadFileBytes(environmentId, attachment, url, signal, onProgress),
abort: () => {},
}),
onMinted: (attachmentId) => {
if (signal.aborted) return "cancel";
minted = attachmentId;
return "continue";
},
transport: (url) =>
Effect.tryPromise({
try: (signal) => uploadFileBytes(environmentId, attachment, url, signal, onProgress),
catch: attachmentUploadError,
}),
});
if (result.status === "uploaded") return result.attachmentId;
if (minted !== null) await releaseCreatedUploadsQuietly(environmentId, [minted]);
throw result.status === "failed" && result.error !== undefined
? result.error
: new Error(`Upload failed for '${attachment.name}'.`);
}
if (result.attachmentId !== null) {
yield* Effect.promise(() =>
releaseCreatedUploadsQuietly(environmentId, [result.attachmentId!]),
);
}
return yield* attachmentUploadError(
result.step === "resolve-url" &&
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
? new Error("This connection cannot upload attachments.")
: result.error instanceof Error
? result.error
: new Error(`Upload failed for '${attachment.name}'.`),
);
});

/**
* Turns a message's attachments into wire references. `uploadAttachment` is the shared upload
Expand All @@ -335,7 +349,7 @@ export const prepareTurnAttachments = Effect.fn("prepareTurnAttachments")(functi
readonly supportsImageUploads?: boolean;
readonly uploadAttachment: (
attachment: DraftComposerAttachment,
) => Effect.Effect<string, ComposerAttachmentUploadError>;
) => Effect.Effect<string, AttachmentUploadError>;
readonly persistUploadedReferences?: (
draftAttachments: ReadonlyArray<DraftComposerAttachment>,
) => Effect.Effect<"persisted" | "abandon">;
Expand All @@ -349,7 +363,7 @@ export const prepareTurnAttachments = Effect.fn("prepareTurnAttachments")(functi
(attachment): attachment is DraftComposerImageAttachment => attachment.type === "image",
),
),
catch: uploadError,
catch: attachmentUploadError,
});
const files = input.attachments.filter((attachment) => attachment.type === "file");
if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
Expand All @@ -362,7 +376,10 @@ export const prepareTurnAttachments = Effect.fn("prepareTurnAttachments")(functi
} satisfies PreparedTurnAttachments as PrepareTurnAttachmentsResult;
}

yield* Effect.try({ try: () => requireUploadAccess(environmentId), catch: uploadError });
yield* Effect.try({
try: () => requireUploadAccess(environmentId),
catch: attachmentUploadError,
});
const uploadedAttachments: UploadedMobileAttachment[] = [];
const pendingAttachmentIds: string[] = [];
for (const attachment of input.attachments) {
Expand Down
Loading
Loading