Skip to content

Commit fc34c74

Browse files
authored
refactor(flags): move channel db flag to runtime flags (anomalyco#27615)
1 parent cb4f5cd commit fc34c74

8 files changed

Lines changed: 96 additions & 55 deletions

File tree

‎packages/core/src/flag/flag.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,6 @@ export const Flag = {
6262
OPENCODE_MODELS_URL: process.env["OPENCODE_MODELS_URL"],
6363
OPENCODE_MODELS_PATH: process.env["OPENCODE_MODELS_PATH"],
6464
OPENCODE_DB: process.env["OPENCODE_DB"],
65-
OPENCODE_DISABLE_CHANNEL_DB: truthy("OPENCODE_DISABLE_CHANNEL_DB"),
6665
OPENCODE_SKIP_MIGRATIONS: truthy("OPENCODE_SKIP_MIGRATIONS"),
6766
OPENCODE_STRICT_CONFIG_DEPS: truthy("OPENCODE_STRICT_CONFIG_DEPS"),
6867

‎packages/desktop/src/main/env.d.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ declare module "virtual:opencode-server" {
1919
export const init: typeof import("../../../opencode/dist/types/src/node").Log.init
2020
}
2121
export namespace Database {
22-
export const Path: typeof import("../../../opencode/dist/types/src/node").Database.Path
22+
export const getPath: typeof import("../../../opencode/dist/types/src/node").Database.getPath
2323
export const Client: typeof import("../../../opencode/dist/types/src/node").Database.Client
2424
}
2525
export namespace JsonMigration {

‎packages/opencode/src/cli/cmd/db.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const QueryCommand = cmd({
2828
handler: async (args: { query?: string; format: string }) => {
2929
const query = args.query as string | undefined
3030
if (query) {
31-
const db = new BunDatabase(Database.Path, { readonly: true })
31+
const db = new BunDatabase(Database.getPath(), { readonly: true })
3232
try {
3333
const result = db.query(query).all() as Record<string, unknown>[]
3434
if (args.format === "json") {
@@ -47,7 +47,7 @@ const QueryCommand = cmd({
4747
db.close()
4848
return
4949
}
50-
const child = spawn("sqlite3", [Database.Path], {
50+
const child = spawn("sqlite3", [Database.getPath()], {
5151
stdio: "inherit",
5252
})
5353
await new Promise((resolve) => child.on("close", resolve))
@@ -58,15 +58,15 @@ const PathCommand = cmd({
5858
command: "path",
5959
describe: "print the database path",
6060
handler: () => {
61-
console.log(Database.Path)
61+
console.log(Database.getPath())
6262
},
6363
})
6464

6565
const MigrateCommand = cmd({
6666
command: "migrate",
6767
describe: "migrate JSON data to SQLite (merges with existing data)",
6868
handler: async () => {
69-
const sqlite = new BunDatabase(Database.Path)
69+
const sqlite = new BunDatabase(Database.getPath())
7070
const tty = process.stderr.isTTY
7171
const width = 36
7272
const orange = "\x1b[38;5;214m"

‎packages/opencode/src/effect/runtime-flags.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export class Service extends ConfigService.Service<Service>()("@opencode/Runtime
1515
autoShare: bool("OPENCODE_AUTO_SHARE"),
1616
pure: bool("OPENCODE_PURE"),
1717
disableDefaultPlugins: bool("OPENCODE_DISABLE_DEFAULT_PLUGINS"),
18+
disableChannelDb: bool("OPENCODE_DISABLE_CHANNEL_DB"),
1819
disableEmbeddedWebUi: bool("OPENCODE_DISABLE_EMBEDDED_WEB_UI"),
1920
disableClaudeCodeSkills: Config.all({
2021
broad: bool("OPENCODE_DISABLE_CLAUDE_CODE"),

‎packages/opencode/src/storage/db.ts‎

Lines changed: 59 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ import { type SQLiteBunDatabase } from "drizzle-orm/bun-sqlite"
22
import { migrate } from "drizzle-orm/bun-sqlite/migrator"
33
import { type SQLiteTransaction } from "drizzle-orm/sqlite-core"
44
export * from "drizzle-orm"
5+
import { RuntimeFlags } from "@/effect/runtime-flags"
56
import { LocalContext } from "@/util/local-context"
6-
import { lazy } from "../util/lazy"
77
import { Global } from "@opencode-ai/core/global"
88
import * as Log from "@opencode-ai/core/util/log"
99
import { NamedError } from "@opencode-ai/core/util/error"
@@ -12,9 +12,8 @@ import { readFileSync, readdirSync, existsSync } from "fs"
1212
import { Flag } from "@opencode-ai/core/flag/flag"
1313
import { InstallationChannel } from "@opencode-ai/core/installation/version"
1414
import { InstanceState } from "@/effect/instance-state"
15-
import { iife } from "@/util/iife"
1615
import { init } from "#db"
17-
import { Schema } from "effect"
16+
import { Effect, Schema } from "effect"
1817

1918
declare const OPENCODE_MIGRATIONS: { sql: string; timestamp: number; name: string }[] | undefined
2019

@@ -24,24 +23,29 @@ export const NotFoundError = NamedError.create("NotFoundError", {
2423

2524
const log = Log.create({ service: "db" })
2625

27-
export function getChannelPath() {
28-
if (["latest", "beta", "prod"].includes(InstallationChannel) || Flag.OPENCODE_DISABLE_CHANNEL_DB)
26+
type ChannelDbFlags = Pick<RuntimeFlags.Info, "disableChannelDb">
27+
28+
const readRuntimeFlags = () =>
29+
Effect.runSync(RuntimeFlags.Service.useSync((flags) => flags).pipe(Effect.provide(RuntimeFlags.defaultLayer)))
30+
31+
export function getChannelPath(flags: ChannelDbFlags = readRuntimeFlags()) {
32+
if (["latest", "beta", "prod"].includes(InstallationChannel) || flags.disableChannelDb)
2933
return path.join(Global.Path.data, "opencode.db")
3034
const safe = InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-")
3135
return path.join(Global.Path.data, `opencode-${safe}.db`)
3236
}
3337

34-
export const Path = iife(() => {
38+
export const getPath = (flags?: ChannelDbFlags) => {
3539
if (Flag.OPENCODE_DB) {
3640
if (Flag.OPENCODE_DB === ":memory:" || path.isAbsolute(Flag.OPENCODE_DB)) return Flag.OPENCODE_DB
3741
return path.join(Global.Path.data, Flag.OPENCODE_DB)
3842
}
39-
return getChannelPath()
40-
})
43+
return getChannelPath(flags)
44+
}
4145

4246
export type Transaction = SQLiteTransaction<"sync", void>
4347

44-
type Client = SQLiteBunDatabase
48+
type Client = ReturnType<typeof init>
4549

4650
type Journal = { sql: string; timestamp: number; name: string }[]
4751

@@ -85,38 +89,55 @@ function migrations(dir: string): Journal {
8589
return sql.sort((a, b) => a.timestamp - b.timestamp)
8690
}
8791

88-
export const Client = lazy(() => {
89-
log.info("opening database", { path: Path })
90-
91-
const db = init(Path)
92-
93-
db.run("PRAGMA journal_mode = WAL")
94-
db.run("PRAGMA synchronous = NORMAL")
95-
db.run("PRAGMA busy_timeout = 5000")
96-
db.run("PRAGMA cache_size = -64000")
97-
db.run("PRAGMA foreign_keys = ON")
98-
db.run("PRAGMA wal_checkpoint(PASSIVE)")
99-
100-
// Apply schema migrations
101-
const entries =
102-
typeof OPENCODE_MIGRATIONS !== "undefined"
103-
? OPENCODE_MIGRATIONS
104-
: migrations(path.join(import.meta.dirname, "../../migration"))
105-
if (entries.length > 0) {
106-
log.info("applying migrations", {
107-
count: entries.length,
108-
mode: typeof OPENCODE_MIGRATIONS !== "undefined" ? "bundled" : "dev",
109-
})
110-
if (Flag.OPENCODE_SKIP_MIGRATIONS) {
111-
for (const item of entries) {
112-
item.sql = "select 1;"
92+
let client: Client | undefined
93+
let loaded = false
94+
95+
export const Client = Object.assign(
96+
(flags?: ChannelDbFlags): Client => {
97+
if (loaded) return client as Client
98+
99+
const dbPath = getPath(flags)
100+
log.info("opening database", { path: dbPath })
101+
102+
const db = init(dbPath)
103+
104+
db.run("PRAGMA journal_mode = WAL")
105+
db.run("PRAGMA synchronous = NORMAL")
106+
db.run("PRAGMA busy_timeout = 5000")
107+
db.run("PRAGMA cache_size = -64000")
108+
db.run("PRAGMA foreign_keys = ON")
109+
db.run("PRAGMA wal_checkpoint(PASSIVE)")
110+
111+
// Apply schema migrations
112+
const entries =
113+
typeof OPENCODE_MIGRATIONS !== "undefined"
114+
? OPENCODE_MIGRATIONS
115+
: migrations(path.join(import.meta.dirname, "../../migration"))
116+
if (entries.length > 0) {
117+
log.info("applying migrations", {
118+
count: entries.length,
119+
mode: typeof OPENCODE_MIGRATIONS !== "undefined" ? "bundled" : "dev",
120+
})
121+
if (Flag.OPENCODE_SKIP_MIGRATIONS) {
122+
for (const item of entries) {
123+
item.sql = "select 1;"
124+
}
113125
}
126+
applyMigrations(db, entries)
114127
}
115-
applyMigrations(db, entries)
116-
}
117128

118-
return db
119-
})
129+
client = db
130+
loaded = true
131+
return db
132+
},
133+
{
134+
reset: () => {
135+
loaded = false
136+
client = undefined
137+
},
138+
loaded: () => loaded,
139+
},
140+
)
120141

121142
export function close() {
122143
if (!Client.loaded()) return

‎packages/opencode/test/effect/runtime-flags.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ describe("RuntimeFlags", () => {
2424
fromConfig({
2525
OPENCODE_PURE: "true",
2626
OPENCODE_DISABLE_DEFAULT_PLUGINS: "true",
27+
OPENCODE_DISABLE_CHANNEL_DB: "true",
2728
OPENCODE_AUTO_SHARE: "true",
2829
OPENCODE_DISABLE_EMBEDDED_WEB_UI: "true",
2930
OPENCODE_EXPERIMENTAL: "true",
@@ -39,6 +40,7 @@ describe("RuntimeFlags", () => {
3940
expect(flags.pure).toBe(true)
4041
expect(flags.autoShare).toBe(true)
4142
expect(flags.disableDefaultPlugins).toBe(true)
43+
expect(flags.disableChannelDb).toBe(true)
4244
expect(flags.disableEmbeddedWebUi).toBe(true)
4345
expect(flags.enableExa).toBe(true)
4446
expect(flags.enableParallel).toBe(true)
@@ -80,6 +82,7 @@ describe("RuntimeFlags", () => {
8082
expect(flags.pure).toBe(false)
8183
expect(flags.autoShare).toBe(false)
8284
expect(flags.disableDefaultPlugins).toBe(true)
85+
expect(flags.disableChannelDb).toBe(false)
8386
expect(flags.disableEmbeddedWebUi).toBe(false)
8487
expect(flags.disableClaudeCodeSkills).toBe(false)
8588
expect(flags.enableExa).toBe(false)
@@ -200,6 +203,7 @@ describe("RuntimeFlags", () => {
200203

201204
expect(flags.pure).toBe(false)
202205
expect(flags.disableDefaultPlugins).toBe(false)
206+
expect(flags.disableChannelDb).toBe(false)
203207
expect(flags.disableEmbeddedWebUi).toBe(false)
204208
expect(flags.disableClaudeCodeSkills).toBe(false)
205209
expect(flags.enableExa).toBe(false)

‎packages/opencode/test/fixture/db.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import { disposeAllInstances } from "./fixture"
55
export async function resetDatabase() {
66
await disposeAllInstances().catch(() => undefined)
77
Database.close()
8-
await rm(Database.Path, { force: true }).catch(() => undefined)
9-
await rm(`${Database.Path}-wal`, { force: true }).catch(() => undefined)
10-
await rm(`${Database.Path}-shm`, { force: true }).catch(() => undefined)
8+
const dbPath = Database.getPath()
9+
await rm(dbPath, { force: true }).catch(() => undefined)
10+
await rm(`${dbPath}-wal`, { force: true }).catch(() => undefined)
11+
await rm(`${dbPath}-shm`, { force: true }).catch(() => undefined)
1112
}
Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,29 @@
1-
import { describe, expect, test } from "bun:test"
1+
import { describe, expect } from "bun:test"
22
import path from "path"
3+
import { Effect } from "effect"
34
import { Global } from "@opencode-ai/core/global"
45
import { InstallationChannel } from "@opencode-ai/core/installation/version"
6+
import { RuntimeFlags } from "@/effect/runtime-flags"
57
import { Database } from "@/storage/db"
8+
import { it } from "../lib/effect"
69

7-
describe("Database.Path", () => {
8-
test("returns database path for the current channel", () => {
9-
const expected = ["latest", "beta"].includes(InstallationChannel)
10-
? path.join(Global.Path.data, "opencode.db")
11-
: path.join(Global.Path.data, `opencode-${InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-")}.db`)
12-
expect(Database.getChannelPath()).toBe(expected)
13-
})
10+
describe("Database.getChannelPath", () => {
11+
it.effect("returns database path for the current channel", () =>
12+
Effect.gen(function* () {
13+
const flags = yield* RuntimeFlags.Service
14+
const expected = ["latest", "beta", "prod"].includes(InstallationChannel)
15+
? path.join(Global.Path.data, "opencode.db")
16+
: path.join(Global.Path.data, `opencode-${InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-")}.db`)
17+
18+
expect(Database.getChannelPath(flags)).toBe(expected)
19+
}).pipe(Effect.provide(RuntimeFlags.layer())),
20+
)
21+
22+
it.effect("uses the shared database path when channel databases are disabled", () =>
23+
Effect.gen(function* () {
24+
const flags = yield* RuntimeFlags.Service
25+
26+
expect(Database.getChannelPath(flags)).toBe(path.join(Global.Path.data, "opencode.db"))
27+
}).pipe(Effect.provide(RuntimeFlags.layer({ disableChannelDb: true }))),
28+
)
1429
})

0 commit comments

Comments
 (0)