@fedify/fedify
Version:
An ActivityPub server framework
79 lines (76 loc) • 2.57 kB
JavaScript
import { Temporal } from "@js-temporal/polyfill";
import { URLPattern } from "urlpattern-polyfill";
//#region x/cfworkers.ts
/**
* Implementation of the {@link KvStore} interface for Cloudflare Workers KV
* binding. This class provides a wrapper around Cloudflare's KV namespace to
* store and retrieve JSON-serializable values using structured keys.
* @since 1.6.0
*/
var WorkersKvStore = class {
#namespace;
constructor(namespace) {
this.#namespace = namespace;
}
#encodeKey(key) {
return JSON.stringify(key);
}
async get(key) {
const encodedKey = this.#encodeKey(key);
const { value, metadata } = await this.#namespace.getWithMetadata(encodedKey, "json");
return metadata == null || metadata.expires < Date.now() ? void 0 : value;
}
async set(key, value, options) {
const encodedKey = this.#encodeKey(key);
const metadata = options?.ttl == null ? {} : { expires: Date.now() + options.ttl.total("milliseconds") };
await this.#namespace.put(encodedKey, JSON.stringify(value), options?.ttl == null ? { metadata } : {
expirationTtl: Math.max(options.ttl.total("seconds"), 60),
metadata
});
}
delete(key) {
return this.#namespace.delete(this.#encodeKey(key));
}
};
/**
* Implementation of the {@link MessageQueue} interface for Cloudflare
* Workers Queues binding. This class provides a wrapper around Cloudflare's
* Queues to send messages to a queue.
*
* Note that this implementation does not support the `listen()` method,
* as Cloudflare Workers Queues do not support message consumption in the same
* way as other message queue systems. Instead, you should use
* the {@link Federation.processQueuedTask} method to process messages
* passed to the queue.
* @since 1.6.0
*/
var WorkersMessageQueue = class {
#queue;
/**
* Cloudflare Queues provide automatic retry with exponential backoff
* and Dead Letter Queues.
* @since 1.7.0
*/
nativeRetrial = true;
constructor(queue) {
this.#queue = queue;
}
enqueue(message, options) {
return this.#queue.send(message, {
contentType: "json",
delaySeconds: options?.delay?.total("seconds") ?? 0
});
}
enqueueMany(messages, options) {
const requests = messages.map((msg) => ({
body: msg,
contentType: "json"
}));
return this.#queue.sendBatch(requests, { delaySeconds: options?.delay?.total("seconds") ?? 0 });
}
listen(_handler, _options) {
throw new TypeError("WorkersMessageQueue does not support listen(). Use Federation.processQueuedTask() method instead.");
}
};
//#endregion
export { WorkersKvStore, WorkersMessageQueue };