forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.ts
More file actions
227 lines (200 loc) · 6.01 KB
/
storage.ts
File metadata and controls
227 lines (200 loc) · 6.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/**
* Storage Adapter for R2 Bucket
* Typeclass-based abstraction for R2 storage operations
*/
// R2 Types are available globally from worker-configuration.d.ts (generated by Wrangler)
/**
* Storage Adapter Interface - Typeclass for storage operations
* This defines the contract that any storage implementation must satisfy
*/
export interface StorageAdapter<T> {
/**
* Put an object into storage
* @param key - The key/path where to store the object
* @param value - The value to store (will be serialized to JSON)
* @param options - Optional storage options
*/
put(key: string, value: T, options?: R2PutOptions): Promise<void>
/**
* Get an object from storage
* @param key - The key/path of the object to retrieve
* @returns The retrieved object or null if not found
*/
get(key: string): Promise<T | null>
/**
* Delete an object from storage
* @param key - The key/path of the object to delete
*/
delete(key: string): Promise<void>
/**
* List objects in storage with optional prefix
* @param options - List options including prefix
* @returns List of objects with their keys
*/
list(options?: R2ListOptions): Promise<R2Object[]>
/**
* Check if an object exists in storage
* @param key - The key/path to check
* @returns True if the object exists, false otherwise
*/
exists(key: string): Promise<boolean>
}
/**
* R2 Storage Adapter Implementation
* Concrete implementation of StorageAdapter for Cloudflare R2
*/
export class R2StorageAdapter<T> implements StorageAdapter<T> {
constructor(private readonly bucket: R2Bucket) {}
async put(key: string, value: T, options?: R2PutOptions): Promise<void> {
const serializedValue = JSON.stringify(value)
await this.bucket.put(key, serializedValue, options)
}
async get(key: string): Promise<T | null> {
const obj = await this.bucket.get(key)
if (!obj) {
return null
}
return JSON.parse(await obj.text()) as T
}
async delete(key: string): Promise<void> {
await this.bucket.delete(key)
}
async list(options?: R2ListOptions): Promise<R2Object[]> {
const result = await this.bucket.list(options)
return result.objects
}
async exists(key: string): Promise<boolean> {
// head() fetches only object metadata — no body download
const obj = await this.bucket.head(key)
return !!obj
}
/**
* Get the underlying R2 bucket for advanced operations
* This allows access to the raw R2 API when needed
*/
getBucket(): R2Bucket {
return this.bucket
}
}
/**
* Storage Adapter Constructor Function
* Functional-style constructor for creating storage adapters
* @param bucket - The R2 bucket to wrap
* @returns A new StorageAdapter instance
*/
export function createStorageAdapter<T>(bucket: R2Bucket): StorageAdapter<T> {
return new R2StorageAdapter<T>(bucket)
}
/**
* Mock Storage Adapter for Testing
* In-memory implementation for testing purposes
*/
export class MockStorageAdapter<T> implements StorageAdapter<T> {
private store: Map<string, T> = new Map()
async put(key: string, value: T, _options?: R2PutOptions): Promise<void> {
this.store.set(key, value)
}
async get(key: string): Promise<T | null> {
const value = this.store.get(key)
return value ?? null
}
async delete(key: string): Promise<void> {
this.store.delete(key)
}
async list(options?: R2ListOptions): Promise<R2Object[]> {
const prefix = options?.prefix || ""
const result: R2Object[] = []
for (const [key, _value] of this.store.entries()) {
if (key.startsWith(prefix)) {
result.push({
key,
version: "mock-version",
size: JSON.stringify(_value).length,
etag: `"mock-etag-${key}"`,
httpMetadata: { contentType: "application/json" } as R2HTTPMetadata,
customMetadata: {},
uploaded: new Date(),
range: undefined,
} as unknown as R2Object)
}
}
return result
}
async exists(key: string): Promise<boolean> {
return this.store.has(key)
}
/**
* Clear all data in the mock store (for testing)
*/
clear(): void {
this.store.clear()
}
/**
* Get all keys in the mock store (for testing)
*/
getAllKeys(): string[] {
return Array.from(this.store.keys())
}
}
/**
* Storage Adapter Typeclass Utilities
* Higher-order functions for working with storage adapters
*/
export namespace Storage {
/**
* Apply a function to a value retrieved from storage
* @param adapter - The storage adapter
* @param key - The key to retrieve
* @param fn - The function to apply
*/
export async function withValue<T, R>(
adapter: StorageAdapter<T>,
key: string,
fn: (value: T) => R,
): Promise<R | null> {
const value = await adapter.get(key)
return value ? fn(value) : null
}
/**
* Update a value in storage using a transformation function
* @param adapter - The storage adapter
* @param key - The key to update
* @param fn - The transformation function
*/
export async function update<T>(
adapter: StorageAdapter<T>,
key: string,
fn: (current: T | null) => T,
): Promise<void> {
const current = await adapter.get(key)
const updated = fn(current)
await adapter.put(key, updated)
}
/**
* Check if a value exists and meets a condition
* @param adapter - The storage adapter
* @param key - The key to check
* @param predicate - The condition function
*/
export async function existsWhere<T>(
adapter: StorageAdapter<T>,
key: string,
predicate: (value: T) => boolean,
): Promise<boolean> {
const value = await adapter.get(key)
return !!value && predicate(value)
}
/**
* Transaction-like operation for multiple storage operations
* @param adapter - The storage adapter
* @param operations - Array of operations to perform
*/
export async function transaction<T>(
adapter: StorageAdapter<T>,
operations: Array<() => Promise<void>>,
): Promise<void> {
for (const op of operations) {
await op()
}
}
}