| 115 | * thread, and every read below is synchronous. |
| 116 | */ |
| 117 | export class GraphSession { |
| 118 | readonly projectRoot: string; |
| 119 | private readonly dbPath: string; |
| 120 | private cg: CodeGraph | null = null; |
| 121 | private identity: FileIdentity | null = null; |
| 122 | |
| 123 | constructor(projectRoot: string) { |
| 124 | this.projectRoot = projectRoot; |
| 125 | this.dbPath = getDatabasePath(projectRoot); |
| 126 | } |
| 127 | |
| 128 | /** |
| 129 | * The open graph, opening (or reopening) it if needed. |
| 130 | * |
| 131 | * @throws {ApiError} `no-index` when the project has no index, |
| 132 | * `index-unusable` when it has one that will not open. |
| 133 | */ |
| 134 | acquire(): CodeGraph { |
| 135 | const current = identify(this.dbPath); |
| 136 | |
| 137 | if (this.cg !== null) { |
| 138 | if (sameFile(this.identity, current)) { |
| 139 | // Same file, but somebody wrote to it. SQLite itself is fine — a WAL |
| 140 | // reader sees the new commits — but our in-memory node cache is not, |
| 141 | // so it goes. One `stat` already paid for; clearing a bounded Map is |
| 142 | // the whole cost. |
| 143 | if (!sameContent(this.identity, current)) { |
| 144 | this.identity = current; |
| 145 | this.cg.dropReadCaches(); |
| 146 | } |
| 147 | return this.cg; |
| 148 | } |
| 149 | // The database was replaced (a re-index) or removed. Drop the stale |
| 150 | // handle; falling through re-opens against whatever is there now. |
| 151 | this.closeQuietly(); |
| 152 | } |
| 153 | |
| 154 | if (!isInitialized(this.projectRoot)) throw noIndexError(this.projectRoot); |
| 155 | |
| 156 | try { |
| 157 | this.cg = CodeGraph.openSync(this.projectRoot); |
| 158 | } catch (err) { |
| 159 | this.cg = null; |
| 160 | this.identity = null; |
| 161 | throw new ApiError( |
| 162 | 'index-unusable', |
| 163 | `The CodeGraph index for ${this.projectRoot} could not be opened: ` + |
| 164 | (err instanceof Error ? err.message : String(err)), |
| 165 | 'If another CodeGraph process is rebuilding it, wait for that to finish. ' + |
| 166 | 'If the index is damaged, rebuild it with "codegraph init".' |
| 167 | ); |
| 168 | } |
| 169 | this.identity = current ?? identify(this.dbPath); |
| 170 | return this.cg; |
| 171 | } |
| 172 | |
| 173 | /** Release the handle. Idempotent — the CLI calls it on Ctrl-C. */ |
| 174 | close(): void { |
nothing calls this directly
no outgoing calls
no test coverage detected