MCPcopy
hub / github.com/jvilk/BrowserFS / SimpleSyncRWTransaction

Class SimpleSyncRWTransaction

src/generic/key_value_filesystem.ts:147–217  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

145 * A simple RW transaction for simple synchronous key-value stores.
146 */
147export class SimpleSyncRWTransaction implements SyncKeyValueRWTransaction {
148 /**
149 * Stores data in the keys we modify prior to modifying them.
150 * Allows us to roll back commits.
151 */
152 private originalData: { [key: string]: Buffer | undefined } = {};
153 /**
154 * List of keys modified in this transaction, if any.
155 */
156 private modifiedKeys: string[] = [];
157
158 constructor(private store: SimpleSyncStore) { }
159
160 public get(key: string): Buffer | undefined {
161 const val = this.store.get(key);
162 this.stashOldValue(key, val);
163 return val;
164 }
165
166 public put(key: string, data: Buffer, overwrite: boolean): boolean {
167 this.markModified(key);
168 return this.store.put(key, data, overwrite);
169 }
170
171 public del(key: string): void {
172 this.markModified(key);
173 this.store.del(key);
174 }
175
176 public commit(): void {/* NOP */}
177
178 public abort(): void {
179 // Rollback old values.
180 for (const key of this.modifiedKeys) {
181 const value = this.originalData[key];
182 if (!value) {
183 // Key didn't exist.
184 this.store.del(key);
185 } else {
186 // Key existed. Store old value.
187 this.store.put(key, value, true);
188 }
189 }
190 }
191
192 /**
193 * Stashes given key value pair into `originalData` if it doesn't already
194 * exist. Allows us to stash values the program is requesting anyway to
195 * prevent needless `get` requests if the program modifies the data later
196 * on during the transaction.
197 */
198 private stashOldValue(key: string, value: Buffer | undefined) {
199 // Keep only the earliest value in the transaction.
200 if (!this.originalData.hasOwnProperty(key)) {
201 this.originalData[key] = value;
202 }
203 }
204

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected