@drlock/core 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dmitrii Golovin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,226 @@
1
- # Temporary Holding Version
1
+ # @drlock/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Distributed, reentrant lock manager for Node.js. The lock **context** is a
4
+ shareable logical id (AsyncLocalStorage), so reentrancy works across processes,
5
+ not just within one call stack. Storage is pluggable: `MemoryStore` and
6
+ `FileStore` ship here; `@drlock/redis` and `@drlock/postgres` add cross-machine
7
+ backends.
8
+
9
+ ## Install
10
+
11
+ Not published to npm yet. The commands below are the planned release layout.
12
+
13
+ ```sh
14
+ npm i @drlock/core
15
+ # distributed stores:
16
+ npm i @drlock/redis ioredis
17
+ npm i @drlock/postgres pg
18
+ ```
19
+
20
+ The repository sources run directly on Node 22.6+. Published packages cannot rely
21
+ on that alone: Node refuses to type-strip `.ts` files under `node_modules`, so npm
22
+ packaging still needs JS output or a TypeScript loader.
23
+
24
+ ## Quick start
25
+
26
+ ```ts
27
+ import { FileStore, LockManager } from '@drlock/core';
28
+
29
+ const locks = new LockManager(new FileStore({ dir: '/var/locks' }), {
30
+ ttlMs: 10_000, // lease duration (never renewed)
31
+ acquireTimeoutMs: 5_000,
32
+ });
33
+
34
+ await locks.runLocked('invoice:42', async () => {
35
+ // critical section; reentrant for the same context id
36
+ });
37
+
38
+ await locks.close();
39
+ ```
40
+
41
+ `FileStore` is tested across processes on one host (workers sharing a local
42
+ filesystem). NFS and mounted object stores are untested: semantics for atomic
43
+ rename, exclusive create, mtime, and watchers vary, so some may work and some
44
+ will not.
45
+ For other machines use `new RedisStore(...)` / `new PostgresStore(...)` from the
46
+ driver packages.
47
+
48
+ ## Choosing a store
49
+
50
+ | Store | Use when |
51
+ |---|---|
52
+ | `MemoryStore` | Tests and local dev only. State is process-local; it does not coordinate other processes. |
53
+ | `FileStore` | Multiple processes sharing a **local filesystem on one host** (node cluster, PM2, containers with a shared volume). NFS/object-store mounts are untested and not guaranteed. |
54
+ | `@drlock/redis` | Distributed/multi-host environment — the preferred production option (fast, Pub/Sub wakeup, Lua atomicity). |
55
+ | `@drlock/postgres` | Distributed environment where Postgres is already in the stack and you do not want to add Redis. Same guarantees via row locks + LISTEN/NOTIFY. |
56
+
57
+ Details:
58
+
59
+ - `FileStore({ dir, keyTransformer?, keyUntransformer?, mutexStaleMs?, logger? })`
60
+ — portable reference implementation with atomic lockfiles and a sidecar mutex;
61
+ `sweep()` removes stale mutex/expired lock files. Kernel `flock` or an object
62
+ store are valid custom `LockStore` implementations if you need them. A custom `keyTransformer` must be
63
+ paired with `keyUntransformer` (used by `list()`); `list()` skips expired
64
+ lockfiles.
65
+ - `@drlock/redis` — Lua scripts, Pub/Sub wakeup, worker-set holders.
66
+ - `@drlock/postgres` — table + row locks, LISTEN/NOTIFY, worker-set holders.
67
+ `acquire`/`release` require **READ COMMITTED**; PostgreSQL treats **READ
68
+ UNCOMMITTED** as READ COMMITTED and accepts it too. Stricter levels raise
69
+ SQLSTATE `0A000`. `isolationLevel: null` keeps the pool/role default (which must be
70
+ READ COMMITTED or READ UNCOMMITTED); set `isolationLevel: 'read committed'` to
71
+ override a stricter default — this adds `BEGIN`/`COMMIT` around store queries.
72
+
73
+ All stores follow the same contract: atomic per call, results in input order,
74
+ release removes the caller's worker (notOwner/notFound otherwise), delete on release,
75
+ `getState()` returns `null` when free. `subscribe(key, signal)` requires an
76
+ `AbortSignal` (it is also the unsubscribe) and returns a `LockSubscription`:
77
+ await it to know the wakeup registration is active, then observe
78
+ `awakePromise` (release/reconnect/abort). It remains only a hint; re-check state.
79
+ Redis/Postgres retry transient driver errors (at-least-once).
80
+
81
+
82
+ ## Contexts and reentrancy
83
+
84
+ - `runLocked(keys, fn)` / `runLocked(keys, opts, fn)` acquires, runs `fn` inside a
85
+ lock context, and releases in `finally`. `fn` receives the lease's
86
+ `expirySignal`, which aborts if the lease expires before release. It establishes
87
+ a lock context (reusing the active one if present); wrap it in
88
+ `runInContext(id, ...)` only when you need to join a specific shared context id.
89
+ - `runInContext(id, fn)` runs `fn` as that context (or `runInContext(fn)` for the
90
+ current/fresh context). Reuse an `id` in another process
91
+ to **join** the same logical holder (same context, different worker).
92
+ - `runInNewContext(fn, onError?)` starts a fire-and-forget task in a fresh
93
+ context; it does not join the caller's locks.
94
+ - Prefer acquiring the complete key set in one `runLocked(keys)` /
95
+ `acquire(keys)` call. Sequential acquisitions reintroduce hold-and-wait and
96
+ can deadlock; all-or-nothing releases partial results and retries.
97
+ - Nested `acquire`/`runLocked` for the same key and context reenter via an
98
+ in-memory counter — the store is only touched at the 0↔1 hold boundary.
99
+ - One process = one `LockManager`; each manager owns a unique auto-generated
100
+ `workerId` used for store-level holder ids. Do not share a manager or its id.
101
+
102
+ Manual leases **must be acquired inside a lock context**: use `runInContext` or
103
+ a request middleware that wraps handling in `runInContext`. Without one, every
104
+ `acquire()` mints a fresh context id, so calls contend instead of reentering and
105
+ are not treated as one logical holder (the manager warns). `runLocked` reuses the
106
+ active context when there is one and creates one otherwise; wrap it explicitly
107
+ only to set a shared context id.
108
+
109
+ ```ts
110
+ await locks.runInContext(`request:${requestId}`, async () => {
111
+ const lease = await locks.acquire('k'); // same context -> reentrant
112
+ try {
113
+ // ...
114
+ } finally {
115
+ await lease.release(); // or await using lease = await locks.acquire('k')
116
+ }
117
+ }); // pass this id to another process to join
118
+ ```
119
+
120
+ `tryAcquire()` is the non-blocking variant: it resolves `undefined` when the
121
+ lock is busy. Same context requirement applies.
122
+
123
+ ## API
124
+
125
+ | Member | Purpose |
126
+ |---|---|
127
+ | `runLocked(keys, fn)` / `runLocked(keys, opts, fn)` | Acquire + run + release. |
128
+ | `acquire(keys, opts?)` | Returns a `Lease`; throws on timeout/abort. |
129
+ | `tryAcquire(keys, opts?)` | `Lease` or `undefined` when busy, without waiting for availability. Store errors/timeouts can still throw. |
130
+ | `runInContext(id, fn)` / `runInContext(fn)` | Run as a given/current context. |
131
+ | `runInNewContext(fn, onError?)` | Fire-and-forget fresh context. |
132
+ | `getLockInfo(key)` | Live `LockInfo` or `null` when free. |
133
+ | `getLockInfoAll()` | `Record<key, LockInfo>` of acquired locks. |
134
+ | `waitAllReleased(timeoutMs?)` | Resolves when this process holds nothing; optional timeout warns and returns. |
135
+ | `close(timeoutMs?)` | Force-releases local locks (best effort), clears state/timers, closes the store; optional bounded shutdown. |
136
+
137
+ `Lease`: `release(onNotOwner?)`, `remainingMs`, `expiresAt`, `expirySignal`,
138
+ `[Symbol.asyncDispose]()`.
139
+
140
+ `getLockInfoAll()` is `list()` plus a state read per key (N+1); use it for
141
+ introspection, not hot paths.
142
+
143
+ `expirySignal` aborts when the lease expires before release. It is cooperative:
144
+ the watchdog still best-effort releases the store record, and code must observe
145
+ the signal (pass it to fetch/queues or check it at await points).
146
+
147
+ `LockInfo`: `contextId`, `workers`, `expiresAt`, `remainingMs`,
148
+ `acquiredInThisContext`.
149
+
150
+ `release(onNotOwner?)` controls a non-owner/double release:
151
+ `'throw'` (throw `LockReleaseError`), `'ignore'` (silent), or `'warn'` (default
152
+ log). `runLocked` always releases with `'warn'`.
153
+
154
+ ## Options
155
+
156
+ | Option | Default | Meaning |
157
+ |---|---|---|
158
+ | `ttlMs` | `10_000` | Lease duration; never auto-renewed. Positive integer. |
159
+ | `acquireTimeoutMs` | `60_000` | Max wait for acquisition. Non-negative integer. |
160
+ | `pollIntervalMs` | `5_000` | Polling safety net when wakeups are missed. Positive integer. |
161
+ | `idGenerator` | `randomUUID` | Context ids for `runInNewContext`/implicit contexts. |
162
+ | `captureTrace` | stack + call site | Trace captured at acquire and reused on release. |
163
+ | `logger` | console logger | `Logger<ManagerLogFields>` (`warn`/`error`). |
164
+ | `reporter` | none | Optional `MetricsReporter`. |
165
+
166
+ Per-call `AcquireOptions`: `ttlMs`, `acquireTimeoutMs`, `abortSignal`, `trace`.
167
+ Timing values are validated in the constructor and per call; empty key lists are rejected.
168
+
169
+ ## Abort, TTL, shutdown
170
+
171
+ - `abortSignal` cancels a waiting `acquire`/`runLocked` with `LockAbortError`.
172
+ If the lock was already obtained when the abort lands, it is released before
173
+ the error is thrown. A store call already in flight is not interrupted (it
174
+ must settle so an applied acquire is not abandoned).
175
+ - `acquireTimeoutMs` bounds the whole acquire, including an in-flight store call
176
+ (client-side race with `LockAcquireTimeoutError`). A store success that lands
177
+ after the deadline is best-effort released. This cannot cancel the server
178
+ operation, so **always configure driver timeouts** (Redis command/connect
179
+ timeout; Postgres `statement_timeout`/`query_timeout`) as the primary bound.
180
+ - TTL is never prolonged, including by a join: a task must have a definite maximum
181
+ duration. Set a lease long enough for the critical section. A watchdog
182
+ always runs per acquired lock: if the lease deadline passes before
183
+ release, it logs an abnormal warning, best-effort releases the store record,
184
+ and drops the local entry. A later `lease.release()` from the stale lease warns
185
+ and does nothing by default (`'ignore'` is silent, `'throw'` raises
186
+ `LockReleaseError`).
187
+ - TTL locks are best-effort against a paused/slow holder: the watchdog can only
188
+ detect the overrun after the deadline. It aborts `expirySignal`, but only
189
+ cooperative code observes it and it cannot stop synchronous work already
190
+ running. If the resource must reject stale writers, add resource-side fencing/version
191
+ checks (conditional update/CAS) — without them, a holder that overran its lease
192
+ may still write.
193
+ - Graceful shutdown: `await locks.waitAllReleased(timeoutMs?)` then `await locks.close()`.
194
+ With a timeout, a still-held lock logs a warning and the call returns instead
195
+ of hanging shutdown.
196
+ `close(timeoutMs?)` force-releases all locks still held by this manager (best
197
+ effort, ownership-checked), stops watchdogs, clears local state, and
198
+ closes the store. Failed releases (`notOwner`) are logged and their
199
+ records expire by TTL. With a timeout, it logs a warning and returns if
200
+ shutdown stalls. `acquire()`/`tryAcquire()` after `close()` (or while an
201
+ in-flight acquire is finishing) throw `LockManagerClosedError`. Calling
202
+ `waitAllReleased()` after `close()` logs a warning and returns immediately.
203
+
204
+ ## Errors
205
+
206
+ - `LockAcquireTimeoutError` — acquire deadline exceeded.
207
+ - `LockAbortError` — aborted via `abortSignal`.
208
+ - `LockReleaseError` — release with `onNotOwner: 'throw'` and not owned;
209
+ also double or stale release with `'throw'`.
210
+ - `LockManagerClosedError` — `acquire`/`tryAcquire` after `close()` (or an acquire
211
+ that was in flight when close started).
212
+ - `LockSubscribeUnavailableError` — the store has no wakeup backend; `LockManager`
213
+ swallows it and uses polling.
214
+
215
+ ## Tracing and metrics
216
+
217
+ `captureTrace` defaults to the call stack plus the API call site; per-call
218
+ `trace` is merged over it **once at acquisition** and reused for the matching
219
+ release (release does not recapture the stack). `MetricsReporter` receives
220
+ `acquired` / `released` / `acquireFailed` events with `key`, `contextId`,
221
+ `workerId`, and the trace. Acquire/release events include timing; `released`
222
+ includes `ttlMs` so you can derive `durationTTL`. The logger is generic over
223
+ field types (`Logger<ManagerLogFields>`, drivers add their own fields).
224
+
225
+ See [`AGENTS.md`](AGENTS.md) for internals and
226
+ [`../../docs/architecture.md`](../../docs/architecture.md) for the design.
@@ -0,0 +1,11 @@
1
+ import type { CallSite } from './types.ts';
2
+ /**
3
+ * User call site. Call synchronously at the API entry; after an async boundary
4
+ * the user frame is gone.
5
+ */
6
+ export declare function captureCallSite(): CallSite;
7
+ /** User stack frames (library internals skipped). */
8
+ export declare function captureStack(): CallSite[];
9
+ /** Default trace: stack plus its top frame. */
10
+ export declare function defaultCaptureTrace(): Record<string, unknown>;
11
+ //# sourceMappingURL=call-site.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"call-site.d.ts","sourceRoot":"","sources":["../src/call-site.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAK3C;;;GAGG;AACH,wBAAgB,eAAe,IAAI,QAAQ,CAE1C;AAED,qDAAqD;AACrD,wBAAgB,YAAY,IAAI,QAAQ,EAAE,CAUzC;AAED,+CAA+C;AAC/C,wBAAgB,mBAAmB,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAG7D"}
@@ -0,0 +1,45 @@
1
+ import { dirname } from 'node:path';
2
+ // Skip library-internal frames.
3
+ const SRC_DIR = dirname(import.meta.filename);
4
+ /**
5
+ * User call site. Call synchronously at the API entry; after an async boundary
6
+ * the user frame is gone.
7
+ */
8
+ export function captureCallSite() {
9
+ return captureStack()[0] ?? { file: '<unknown>', line: 0, column: 0 };
10
+ }
11
+ /** User stack frames (library internals skipped). */
12
+ export function captureStack() {
13
+ const stack = new Error().stack ?? '';
14
+ const frames = [];
15
+ for (const line of stack.split('\n')) {
16
+ const parsed = parseLine(line);
17
+ if (!parsed)
18
+ continue;
19
+ if (parsed.file.startsWith(SRC_DIR))
20
+ continue;
21
+ frames.push(parsed);
22
+ }
23
+ return frames;
24
+ }
25
+ /** Default trace: stack plus its top frame. */
26
+ export function defaultCaptureTrace() {
27
+ const stack = captureStack();
28
+ return { callSite: stack[0] ?? { file: '<unknown>', line: 0, column: 0 }, stack };
29
+ }
30
+ function parseLine(line) {
31
+ const trimmed = line.trim();
32
+ // at fnName (/path/file.ts:12:34)
33
+ let m = /^at (.+) \((.+):(\d+):(\d+)\)$/.exec(trimmed);
34
+ if (m)
35
+ return { functionName: m[1], file: stripScheme(m[2]), line: Number(m[3]), column: Number(m[4]) };
36
+ // at /path/file.ts:12:34
37
+ m = /^at (.+):(\d+):(\d+)$/.exec(trimmed);
38
+ if (m)
39
+ return { file: stripScheme(m[1]), line: Number(m[2]), column: Number(m[3]) };
40
+ return undefined;
41
+ }
42
+ function stripScheme(file) {
43
+ return file.startsWith('file://') ? file.slice('file://'.length) : file;
44
+ }
45
+ //# sourceMappingURL=call-site.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"call-site.js","sourceRoot":"","sources":["../src/call-site.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,gCAAgC;AAChC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,CAAC,QAAQ,CAAC,CAAC;AAE9C;;;GAGG;AACH,MAAM,UAAU,eAAe;IAC7B,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;AACxE,CAAC;AAED,qDAAqD;AACrD,MAAM,UAAU,YAAY;IAC1B,MAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC;IACtC,MAAM,MAAM,GAAe,EAAE,CAAC;IAC9B,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACrC,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;QAC/B,IAAI,CAAC,MAA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AC,IAAY;IAC/B,OAAO,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1E,CAAC","sourcesContent":["import { dirname } from 'node:path';\nimport type { CallSite } from './types.ts';\n\n// Skip library-internal frames.\nconst SRC_DIR = dirname(import.meta.filename);\n\n/**\n * User call site. Call synchronously at the API entry; after an async boundary\n * the user frame is gone.\n */\nexport function captureCallSite(): CallSite {\n return captureStack()[0] ?? { file: '<unknown>', line: 0, column: 0 };\n}\n\n/** User stack frames (library internals skipped). */\nexport function captureStack(): CallSite[] {\n const stack = new Error().stack ?? '';\n const frames: CallSite[] = [];\n for (const line of stack.split('\\n')) {\n const parsed = parseLine(line);\n if (!parsed) continue;\n if (parsed.file.startsWith(SRC_DIR)) continue;\n frames.push(parsed);\n }\n return frames;\n}\n\n/** Default trace: stack plus its top frame. */\nexport function defaultCaptureTrace(): Record<string, unknown> {\n const stack = captureStack();\n return { callSite: stack[0] ?? { file: '<unknown>', line: 0, column: 0 }, stack };\n}\n\nfunction parseLine(line: string): CallSite | undefined {\n const trimmed = line.trim();\n // at fnName (/path/file.ts:12:34)\n let m = /^at (.+) \\((.+):(\\d+):(\\d+)\\)$/.exec(trimmed);\n if (m) return { functionName: m[1], file: stripScheme(m[2]!), line: Number(m[3]), column: Number(m[4]) };\n // at /path/file.ts:12:34\n m = /^at (.+):(\\d+):(\\d+)$/.exec(trimmed);\n if (m) return { file: stripScheme(m[1]!), line: Number(m[2]), column: Number(m[3]) };\n return undefined;\n}\n\nfunction stripScheme(file: string): string {\n return file.startsWith('file://') ? file.slice('file://'.length) : file;\n}\n"]}
package/dist/file.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import type { AcquireResult, FileStoreLogFields, LockState, LockStore, LockSubscription, Logger, ReleaseResult, StoreAcquireOptions, StoreReleaseOptions } from './types.ts';
2
+ export interface FileStoreOptions {
3
+ dir: string;
4
+ /** Filesystem-safe key encoder; pair with `keyUntransformer`. */
5
+ keyTransformer?: (key: string) => string;
6
+ /** Decoder used by `list()`; required with a custom `keyTransformer`. */
7
+ keyUntransformer?: (stored: string) => string;
8
+ /** Logger for background errors; defaults to console. */
9
+ logger?: Logger<FileStoreLogFields>;
10
+ /** Stale `.mutex` age; default 10000 ms. */
11
+ mutexStaleMs?: number;
12
+ }
13
+ /**
14
+ * Filesystem store for processes on one host. Reentrancy is local; join (a
15
+ * shared context id) adds worker ids to the lockfile. Mutations are serialized
16
+ * by `<lockfile>.mutex`; writes are atomic. A holder unlinks only its own mutex
17
+ * on exit, while contenders may clear stale mutexes by age.
18
+ *
19
+ * Call `sweep()` periodically to remove leftovers from crashed writers.
20
+ */
21
+ export declare class FileStore implements LockStore {
22
+ private readonly dir;
23
+ private readonly transform;
24
+ private readonly untransform;
25
+ private readonly local;
26
+ private readonly listeners;
27
+ private readonly logger;
28
+ private readonly mutexStaleMs;
29
+ private watcher;
30
+ constructor(options: FileStoreOptions);
31
+ acquire(opts: StoreAcquireOptions): Promise<(AcquireResult | null)[]>;
32
+ private acquireOne;
33
+ release(opts: StoreReleaseOptions): Promise<ReleaseResult[]>;
34
+ private releaseOne;
35
+ subscribe(key: string, signal: AbortSignal): Promise<LockSubscription>;
36
+ getState(key: string): Promise<LockState | null>;
37
+ list(): Promise<string[]>;
38
+ /** Removes stale mutexes and expired/unreadable lockfiles; optional cleanup. */
39
+ sweep(): Promise<void>;
40
+ close(): Promise<void>;
41
+ private fileFor;
42
+ private read;
43
+ private notify;
44
+ /** Atomic write via temp + rename. */
45
+ private writeAtomic;
46
+ /**
47
+ * Runs `fn` under an exclusive sidecar mutex (`open(..., 'wx')`). Retries on
48
+ * contention, clears stale mutexes, and unlinks only the mutex it owns
49
+ * (same dev/ino).
50
+ */
51
+ private withMutex;
52
+ private withFileLock;
53
+ private unlinkIfSame;
54
+ private clearStale;
55
+ private ensureWatcher;
56
+ }
57
+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