Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: introduce client for CDN #104

Closed
wants to merge 2 commits into from
Closed
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
155 changes: 155 additions & 0 deletions libs/client/src/cdn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import { getRestApiUrl, RequiredConfig } from "./config";
import { dispatchRequest } from "./request";
import { StorageClient } from "./storage";
import { isPlainObject } from "./utils";

type AuthTokenRequest = object;

/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
type AuthTokenResponse = {
token: string;
created_at: string;
expires_at: string;
token_type?: string;
base_url?: string;
};

/**
* Auth Token
* @returns AuthTokenResponse Successful Response
* @throws ApiError
*/
async function authToken(
storage_type: string,
config: RequiredConfig,
): Promise<AuthTokenResponse> {
return await dispatchRequest<AuthTokenRequest, AuthTokenResponse>({
method: "POST",
targetUrl: `${getRestApiUrl()}/storage/auth/token?storage_type=${storage_type}`,
input: {},
config,
});
}

type CDNUploadResponse = {
access_url: string;
uploaded: boolean;
};

/**
* CDN Direct Upload
* @returns CDNUploadResponse Successful Response
*/
async function cdnDirectUpload(
token: CDNToken,
file: Blob,
config: RequiredConfig,
): Promise<CDNUploadResponse> {
const { fetch, responseHandler } = config;
const response = await fetch(`${token.baseUploadUrl}/files/upload`, {
method: "POST",
body: file,
headers: {
Authorization: `${token.tokenType} ${token.token}`,
},
});

return await responseHandler(response);
}

class CDNToken {
public token: string;
public tokenType: string;
public baseUploadUrl: string;
public expiresAt: Date;

constructor(tokenResponse: AuthTokenResponse) {
this.token = tokenResponse.token;
this.tokenType = tokenResponse.token_type ?? "Bearer";

if (tokenResponse.base_url === undefined) {
throw new Error("base_url is required");
}

this.baseUploadUrl = tokenResponse.base_url ?? "";
this.expiresAt = new Date(tokenResponse.expires_at);
}

isExpired(): boolean {
return new Date().getTime() >= this.expiresAt.getTime();
}
}

class CDNTokenManager {
private token?: CDNToken;
private storageType: string = "fal-cdn-v3";

constructor(private config: RequiredConfig) {}

async get(): Promise<CDNToken> {
if (!this.token) {
this.token = await this.fetch();
} else if (this.token.isExpired()) {
this.token = await this.fetch();
}

return this.token;
}

private async fetch(): Promise<CDNToken> {
const response = await authToken(this.storageType, this.config);
return new CDNToken(response);
}
}

class CDNStorageCLient implements StorageClient {
private tokenManager: CDNTokenManager;

constructor(private config: RequiredConfig) {
this.tokenManager = new CDNTokenManager(config);
}

async upload(file: Blob): Promise<string> {
const token = await this.tokenManager.get();
const upload = await cdnDirectUpload(token, file, this.config);

return upload.access_url;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
// NOTE: Copy from the storage client
async transformInput(input: any): Promise<any> {
if (Array.isArray(input)) {
return Promise.all(input.map((item) => this.transformInput(item)));
} else if (input instanceof Blob) {
return await this.upload(input);
} else if (isPlainObject(input)) {
const inputObject = input as Record<string, any>;
const promises = Object.entries(inputObject).map(
async ([key, value]): Promise<KeyValuePair> => {
return [key, await this.transformInput(value)];
},
);
const results = await Promise.all(promises);
return Object.fromEntries(results);
}
// Return the input as is if it's neither an object nor a file/blob/data URI
return input;
}
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type KeyValuePair = [string, any];

type StorageClientDependencies = {
config: RequiredConfig;
};

export function createCDNClient({
config,
}: StorageClientDependencies): StorageClient {
return new CDNStorageCLient(config);
}
10 changes: 8 additions & 2 deletions libs/client/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createCDNClient } from "./cdn";
import { Config, createConfig } from "./config";
import { createQueueClient, QueueClient, QueueSubscribeOptions } from "./queue";
import { createRealtimeClient, RealtimeClient } from "./realtime";
Expand Down Expand Up @@ -79,9 +80,14 @@ export interface FalClient {
* @param userConfig Optional configuration to override the default settings.
* @returns a new instance of the `FalClient`.
*/
export function createFalClient(userConfig: Config = {}): FalClient {
export function createFalClient(
userConfig: Config = {},
useCDN = false,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added this as the CDN flag. let me know if you prefer something else @drochetti

): FalClient {
const config = createConfig(userConfig);
const storage = createStorageClient({ config });
const storage = useCDN
? createCDNClient({ config })
: createStorageClient({ config });
const queue = createQueueClient({ config, storage });
const streaming = createStreamingClient({ config, storage });
const realtime = createRealtimeClient({ config });
Expand Down
Loading