@nanobpm/urban 0.64.0 → 0.65.0

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.
@@ -0,0 +1,176 @@
1
+ // Slice S1 (binding) — the resolver: bind → validate → identity → resolved
2
+ // handle, with private-per-app / shared-on-same-name semantics enforced two
3
+ // ways:
4
+ //
5
+ // 1. In-process: a ContextResolver memoises by identity key, so two resolves of
6
+ // the same name return the SAME handle (and never double-clone), while
7
+ // distinct names get distinct handles.
8
+ // 2. Across processes/instances: the on-disk location is derived
9
+ // deterministically from the identity slug under a shared cache root, so two
10
+ // Nano instances naming the same context share one working copy on disk.
11
+ // Known first-use limitation (deferred past slice S1): the single-flight in
12
+ // (1) is in-process only, so concurrent *first* resolves of the same context
13
+ // across instances can race materialisation (clone/pin). Sharing is reliable
14
+ // once the substrate exists; a follow-up slice adds an inter-process lock to
15
+ // make concurrent first-use safe too — see GitSubstrateBackend.materialise.
16
+
17
+ import { homedir, tmpdir } from "node:os";
18
+ import { join, resolve as resolvePath } from "node:path";
19
+ import { parseContextBinding } from "./descriptor.ts";
20
+ import { resolveContextIdentity } from "./identity.ts";
21
+ import { GitSubstrateBackend } from "./git-backend.ts";
22
+ import type { ResolvedContextHandle, SubstrateBackend } from "./backend.ts";
23
+
24
+ /** Options for a {@link ContextResolver}. */
25
+ export interface ContextResolverOptions {
26
+ /**
27
+ * Root directory under which per-context working copies are cloned. Two
28
+ * resolvers sharing a `cacheRoot` share substrates on disk. Defaults to
29
+ * {@link defaultContextCacheRoot}.
30
+ */
31
+ readonly cacheRoot?: string;
32
+ /**
33
+ * The substrate backend. Defaults to a git backend ({@link GitSubstrateBackend}).
34
+ * Injecting a different backend is the seam for a future PII/mutable or
35
+ * self-hosted substrate.
36
+ */
37
+ readonly backend?: SubstrateBackend;
38
+ }
39
+
40
+ /** Per-resolution overrides. */
41
+ export interface ResolveOptions {
42
+ /**
43
+ * Controls whether a re-resolution re-fetches the substrate. Note the
44
+ * {@link ContextResolver} memoises per identity: once an identity has resolved,
45
+ * repeat resolves return the cached handle and do **not** re-fetch unless you
46
+ * explicitly pass `refresh: true`, which forces a fresh materialisation (a
47
+ * fetch + re-pin on the backend). While a materialisation is still in flight,
48
+ * concurrent resolves — including `refresh: true` — coalesce onto it rather
49
+ * than starting a second one. The backend's own default (fetch on an existing
50
+ * clone) therefore only applies the first time an identity is materialised or
51
+ * when `refresh: true` is passed. Defaults to `undefined` (reuse the memoised
52
+ * handle).
53
+ */
54
+ readonly refresh?: boolean;
55
+ }
56
+
57
+ /**
58
+ * The default cache root for context working copies. Honours
59
+ * `URBAN_CONTEXT_CACHE_DIR`, then `XDG_CACHE_HOME`, then `~/.cache`, falling
60
+ * back to the OS temp dir when no home directory is available.
61
+ */
62
+ export function defaultContextCacheRoot(
63
+ env: Record<string, string | undefined> = process.env,
64
+ ): string {
65
+ if (env.URBAN_CONTEXT_CACHE_DIR) return env.URBAN_CONTEXT_CACHE_DIR;
66
+ if (env.XDG_CACHE_HOME) return join(env.XDG_CACHE_HOME, "urban", "context");
67
+ const home = safeHomedir();
68
+ if (home) return join(home, ".cache", "urban", "context");
69
+ return join(tmpdir(), "urban", "context");
70
+ }
71
+
72
+ /** `os.homedir()`, but tolerant: returns `undefined` if the home dir can't be
73
+ * determined (Node can throw here) so callers fall back to the temp dir. */
74
+ function safeHomedir(): string | undefined {
75
+ try {
76
+ return homedir() || undefined;
77
+ } catch {
78
+ return undefined;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Resolves context bindings to concrete local working copies. A single resolver
84
+ * instance enforces shared-on-same-name in-process by memoising per identity
85
+ * key; distinct names stay private.
86
+ */
87
+ export class ContextResolver {
88
+ readonly #cacheRoot: string;
89
+ readonly #backend: SubstrateBackend;
90
+ // Per-identity resolution record. Despite serving the single-flight guarantee,
91
+ // this map is NOT purged once a resolution settles: the settled record is
92
+ // retained as the long-lived memoisation cache backing shared-on-same-name, so
93
+ // repeat resolves return the identical handle. Entries are removed only on
94
+ // rejection (so a failed materialise can be retried); a fulfilled entry lives
95
+ // for the resolver's lifetime. Do not add "drop settled entries" cleanup here
96
+ // without also giving up memoisation.
97
+ readonly #resolutions = new Map<string, { promise: Promise<ResolvedContextHandle>; settled: boolean }>();
98
+
99
+ constructor(options: ContextResolverOptions = {}) {
100
+ // Normalise to an absolute path so a relative `cacheRoot` (or a relative
101
+ // `URBAN_CONTEXT_CACHE_DIR`) still yields an absolute `localPath`, honouring
102
+ // `SubstrateResolveOptions.localPath` ("Absolute path…"). Note this resolves
103
+ // a relative `cacheRoot` against *this* process's CWD, so the cross-process
104
+ // sharing promised in the module header only holds for an ABSOLUTE
105
+ // `cacheRoot`; a relative one is shared only among instances that happen to
106
+ // share a working directory.
107
+ this.#cacheRoot = resolvePath(options.cacheRoot ?? defaultContextCacheRoot());
108
+ this.#backend = options.backend ?? new GitSubstrateBackend();
109
+ }
110
+
111
+ /** The cache root this resolver clones into. */
112
+ get cacheRoot(): string {
113
+ return this.#cacheRoot;
114
+ }
115
+
116
+ /**
117
+ * Resolve a binding (validated first) to a {@link ResolvedContextHandle}. Two
118
+ * bindings that name the same context return the identical handle from this
119
+ * resolver; distinct names return distinct handles.
120
+ */
121
+ async resolve(
122
+ binding: unknown,
123
+ options: ResolveOptions = {},
124
+ ): Promise<ResolvedContextHandle> {
125
+ const parsed = parseContextBinding(binding);
126
+ const identity = resolveContextIdentity(parsed);
127
+ const localPath = join(this.#cacheRoot, identity.slug);
128
+
129
+ // Shared-on-same-name: concurrent or repeated resolves of one identity share
130
+ // a single materialisation. Coalesce onto an in-flight one regardless of
131
+ // `refresh` — it is already producing a fresh working copy, so starting a
132
+ // second `materialise()` would double-clone into the same `localPath` and
133
+ // break the single-in-flight guarantee. Only re-materialise once the prior
134
+ // resolution has settled AND the caller explicitly asked to `refresh`.
135
+ const existing = this.#resolutions.get(identity.key);
136
+ if (existing && (!existing.settled || options.refresh !== true)) {
137
+ return existing.promise;
138
+ }
139
+
140
+ const record: { promise: Promise<ResolvedContextHandle>; settled: boolean } = {
141
+ promise: this.#backend
142
+ .materialise(identity, { localPath, refresh: options.refresh })
143
+ .catch((error) => {
144
+ if (this.#resolutions.get(identity.key) === record) {
145
+ this.#resolutions.delete(identity.key);
146
+ }
147
+ throw error;
148
+ }),
149
+ settled: false,
150
+ };
151
+ this.#resolutions.set(identity.key, record);
152
+ record.promise.then(
153
+ () => {
154
+ record.settled = true;
155
+ },
156
+ () => {
157
+ // Rejection is surfaced to the caller via the returned promise; the map
158
+ // entry is already removed in the catch above.
159
+ },
160
+ );
161
+ return record.promise;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * One-shot convenience: resolve a single binding with a fresh resolver. Prefer a
167
+ * long-lived {@link ContextResolver} when resolving many bindings so sharing is
168
+ * memoised across calls.
169
+ */
170
+ export function resolveContextBinding(
171
+ binding: unknown,
172
+ options: ContextResolverOptions & ResolveOptions = {},
173
+ ): Promise<ResolvedContextHandle> {
174
+ const { cacheRoot, backend, ...resolveOptions } = options;
175
+ return new ContextResolver({ cacheRoot, backend }).resolve(binding, resolveOptions);
176
+ }