From 024bb08b1d0de2e90c69f0a1e2a83833515449ac Mon Sep 17 00:00:00 2001 From: Ivan Husev Date: Thu, 3 Dec 2026 23:20:55 +0200 Subject: [PATCH] fix: /health answers 503 while database writes fail, the database size from goleveldb's level sizes DevFo-OSS/17 --- CLAUDE.md | 2 +- docs/deployment.md | 2 +- internal/storage/database/store.go | 7 +++- internal/storage/database/store_test.go | 47 +++++++++++++++++++++ internal/storage/kv/db.go | 23 +++++++++++ internal/storage/kv/leveldb/leveldb.go | 54 +++++-------------------- 6 files changed, 88 insertions(+), 47 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6e18018..72f3564 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -81,7 +81,7 @@ Where to look first: - Logs and events are read newest first through their indexes; time marks (`marks.go`) turn date ranges into sequence ranges. Text search of logs compares each line (`textutil.ContainsFold`), first on the stored bytes when the text has no character JSON escapes (`rawSearchable`), so most lines are never decoded; a count that the index walks answer exactly counts keys (`countByKeys`); log counts (the pager) stop at `store.LogCountLimit` (10000; `CountLogs` returns `more`, the pager shows "of 10000+"). A walk over the logs (`scanLogs`; not a count by keys) stops at `config.LogSearchTime` (20 s, every request alike, by the store's clock, `searchBudget`) and reports a `store.LogScan`: `Rest` (logs below it not searched; `merged` steps every walk key by key, so one bound holds for all) and `SearchedTo` (every log received since was searched, from the time marks); a count gives `FromID`, the oldest match or where it stopped, which bounds its list (`LogFilter.FromID`). - API lists fetch `limit+1` rows; `store.Page` trims them and says whether a next page exists (cursor pagination). The web app's lists use pages (`Offset`/`Limit` of `IssueFilter`/`LogFilter`, the API's offset cursor); issues and logs by walking indexes newest first. - `store` never imports `sentry`: callers map to `NewEvent`/`NewLog`. -- `internal/server`: `net/http` ServeMux with method patterns (`"GET /health"`), wrapped in a request-logging middleware (its `statusRecorder` unwraps, so `http.ResponseController`, the read deadline of ingest bodies, reaches the connection) and `recoverPanics` inside it: a handler's panic is logged with method, path, route and stack and answered as a JSON 500 "internal error" (the connection is dropped if the answer had begun). Built from `server.Options`; depends on small interfaces (`Pinger`, `http.Handler` for ingest, `Routes` for the API and the web app), so tests use fakes. Mounts ingest (open), `/health` (open; 503 when `Store.Ping`, a read of the store, fails), the links that stop emails (`Unsubscribe`, open, signed), the API wrapped in `protectAPI` (IP allowlist first, then API token); MCP, OAuth, the web app (`Web`, every address no other route takes) and its API (`UIAPI`, a `UIRoutes`: routes plus the handler of every other address under `UIAPIPrefix`) use the IP allowlist plus their own authentication. `RESTPrefix` (`/api/v1/`) and `UIAPIPrefix` (`/api/ui/`) are defined here; the one `"/api/"` fallback (`unknownAPI`) sends `/api/ui/...` to the web app's API (a login, then a JSON 404) and anything else to a JSON 404 behind the token. `headers.go`: `ContentSecurityPolicy` (the one builder: script sources such as the page's inline hashes), `SecurityHeaders` (policy, nosniff, `Referrer-Policy: same-origin` (no-referrer would make browsers send `Origin: null` on same-origin POSTs), `X-Frame-Options`), `SameOrigin` (Origin's host is the request's, and https when the request is (`IsHTTPS` with the trusted proxies); oauth compares with PUBLIC_URL on purpose), used by `web` and `api/ui.go`. +- `internal/server`: `net/http` ServeMux with method patterns (`"GET /health"`), wrapped in a request-logging middleware (its `statusRecorder` unwraps, so `http.ResponseController`, the read deadline of ingest bodies, reaches the connection) and `recoverPanics` inside it: a handler's panic is logged with method, path, route and stack and answered as a JSON 500 "internal error" (the connection is dropped if the answer had begun). Built from `server.Options`; depends on small interfaces (`Pinger`, `http.Handler` for ingest, `Routes` for the API and the web app), so tests use fakes. Mounts ingest (open), `/health` (open; 503 when `Store.Ping` fails: a read of the store, or its last write failed, `kv.DB.WriteError`, as on a full disk), the links that stop emails (`Unsubscribe`, open, signed), the API wrapped in `protectAPI` (IP allowlist first, then API token); MCP, OAuth, the web app (`Web`, every address no other route takes) and its API (`UIAPI`, a `UIRoutes`: routes plus the handler of every other address under `UIAPIPrefix`) use the IP allowlist plus their own authentication. `RESTPrefix` (`/api/v1/`) and `UIAPIPrefix` (`/api/ui/`) are defined here; the one `"/api/"` fallback (`unknownAPI`) sends `/api/ui/...` to the web app's API (a login, then a JSON 404) and anything else to a JSON 404 behind the token. `headers.go`: `ContentSecurityPolicy` (the one builder: script sources such as the page's inline hashes), `SecurityHeaders` (policy, nosniff, `Referrer-Policy: same-origin` (no-referrer would make browsers send `Origin: null` on same-origin POSTs), `X-Frame-Options`), `SameOrigin` (Origin's host is the request's, and https when the request is (`IsHTTPS` with the trusted proxies); oauth compares with PUBLIC_URL on purpose), used by `web` and `api/ui.go`. - `internal/server` (`access.go`): `ClientIP` (uses `X-Forwarded-For` only when the direct peer is in `TRUSTED_PROXIES`, read right to left; entries may carry a port; addresses are compared unmapped and without an IPv6 zone, `comparable`, and IPv4-mapped networks in the settings are stored as IPv4), `FromTrustedProxy`, `RequireAllowedIP` (403, a debug log line with the address seen), `RequireToken` (constant-time; empty `API_TOKEN` closes the REST API). - `internal/server` (`json.go`): `WriteJSON`/`JSONError` for JSON responses (`{"error": ...}`). Ingest keeps its own `writeError` because Sentry SDKs expect `{"detail": ...}` plus `X-Sentry-Error`. - `internal/api` (the catalog): the one catalog of requests, served as the REST API, as MCP tools and to the web app. `Endpoints(projects, services.All)` lists them in order; handlers reach data only through `services.All` (no store), so tools and pages apply the same rules (with nil arguments it only serves to read the definitions); each is `Define(Endpoint{Name, Description, ReadOnly, Idempotent, Destructive, Confirm, Admin, Transports, OpenWithTemporaryPassword}, handler)` with `handler(ctx, Call, In) (Out, error)`: the input schema comes from `In` (`json` + `jsonschema` tags, `jsonschema.For`) with the enums of `Choices` and the bounds of every `limit` (`DefaultLimit`, `MaxLimit`), `Run` validates the input map against it and decodes it. A new tool or API route = one entry + its handler; nothing else to register. `Call.Access()` is the projects the call sees (all for the REST token, the viewer's otherwise; handlers find projects by name or id through `services.Projects.Find` (`params.go`: `projectIDs` for filters, a missing one 404, a hidden one 403; `projectsField` for a form's field: unknown 400, hidden 403 at the field) and pass the access to services). `Call` has the `Transport` (`TransportREST`, `TransportMCP`, `TransportUI`; a `Call` without one runs nothing), the `Viewer` (the user of the agent or the web app; empty for the REST token), the `Actor` (recorded in the history) and the server `Address` (DSNs); `ForAgent()` is true unless the transport is REST or the web app (fail closed), and then `call.Text` redacts free text with `agentprompt.Redact`. Output is JSON, or `api.Text` written as is (the agent prompt of `get_issue`/`get_event`). Errors are sorted in one place (`OutcomeOf`: the HTTP status, the kind an MCP tool error starts with (`Outcome.ToolText`: `invalid: …`, `forbidden: …`, `not found: …`, `conflict: …`, `unavailable: …`, `internal error`) and the body), which `fail` (REST, the web app, the plain requests) and MCP's `failed` use: `InputError` with its status (`Invalid` 400, `notFound` 404, `conflict` 409, 413, 429 with `Retry-After`, 502 for a destination that refused a test message); `services.Reason` of `services.ErrForbidden` (the role or a rule of who may change whom; `services.Forbidden(reason)`), `services.ErrHidden` (a record of a project outside the viewer's; `services.Hidden(what, ids...)`, which names only what the caller gave, never the record's data) both 403, `store.ErrNotFound` (`services.Missing`) 404, `services.ErrConflict` 409; `services.Refusal` (a form refused as 403 or 409 with its fields, `formError` renames them; a taken project name 409, "This name cannot be used." for a hidden one); `ErrNotFound` 404; anything else logged and reported as "internal error". MCP adds the viewer's project names to a hidden record's refusal (`forbidden: issue k3x9q2mf is not in your projects (frontend, test2)`), which `list_projects` shows them anyway, so an agent tells a deleted issue from a hidden one; a 403 confirms only that an id or name exists. A refused form is `problemsError` (the problem of each field, renamed to the input's names) or `duplicateError` (409, the connection that already sends there, unnamed when hidden): over HTTP the body is `ErrorBody` `{error, fields?, duplicate?}` whatever the status, so a page shows each problem at its field, MCP gets the joined message (`TestInputErrorBody`, `errors_test.go`). Lists: `Page{items, next_cursor}`, 20 rows by default, at most 100, plain-number cursors (offset for issues/projects/deliveries, at most `store.MaxOffset` (`parseOffset`; `ListIssues` clamps too, since offset+limit must not overflow), last id for events/logs; `list_users` and `list_connections` return every row in one page). Every endpoint names its `Transports` (`Define` panics without; `AllTransports`, `ActsAsUser` = MCP and the web app, or one): `Run` refuses what `Refused(call)` names (`AllowedFor` is it being nil): an endpoint its transport does not serve (`ErrNotFound`), for a user without `CanAdminister` an `Admin` one (`services.ErrForbidden`, "your role may not do this"), and in the web app, while the user has a temporary password, anything without `OpenWithTemporaryPassword` (403 "change your password first"); the token runs every REST endpoint. REST only: `get_event_payload` (raw payload), `list_trace` (log attributes), their output must not reach a model provider (the web app reads the payload, indented, inside `get_issue_details`). `ActsAsUser` (`manage.go`, `notifications.go`): account, agents, projects, users, notification connections and email confirmation, acting as the user (`Users` and `Agents` refuse by role with `services.Forbidden` (403: "your role may not change this user" for a user changing an admin, `services.TakeOverProblem` for a user with projects the admin lacks; nobody changes themselves there: "change your own account on /account"); `Projects`, `Connections`, `Verification` and `Deliveries` check no role, only the access (`Projects.Save` keeps the disk share an admin's; `delete_project` is `Admin`)); form rules are shared because tools pass the form's fields as `url.Values` to `services.Projects.Save`/`Connections.Save`, starting from `FormValues` of the stored record so fields not given keep their values. `get_storage` (`session.go`, the web app only): the data the database holds against `MAX_DATABASE_SIZE` (`services.Projects.Storage`, `store.ProjectUsage.Live`, the cleanup's own measure) with the parts of the projects the viewer sees (`ProjectUsage.OnDisk`), other (live minus those projects), the files apart (`files`, `ProjectUsage.Files`), the start and stop percents, `last_received`, `dropped` (per project, `ingest.DropCounter` through `services.Dependencies.Dropped`), for the Projects page. `get_session` (`session.go`, the web app only, `OpenWithTemporaryPassword`): the viewer (`user`, with `display_name`), `can_administer`, `app_name` (`services.All.AppName`), the unresolved count, `project_colors` (the shown color of every project the viewer sees, by name, `services.Projects.ColorsByName`; badges set it with the `style:` directive), `all_projects` (the viewer sees every project, future ones included), `assignable_roles` (`store.User.AssignableRoles`, empty for a user) and `theme` (the user's, `store.User.Theme`, empty until the app records one). `set_theme` (the web app only, `OpenWithTemporaryPassword`, `store.Themes` as `Choices`; `services.Users.SetTheme`, `Store.UpdateUserTheme`) saves the user's theme. The web app's own endpoints (never MCP, mostly because their output is unredacted): `count_issues`, `list_issue_levels`, `list_issue_projects` (the count, level choices and project choices of the issue list (the projects some issue is in, from the tallies, `IssueProjects`: no issue read), from the filters `list_issues` takes, `issueFiltersInput`; `issueOutput.mcp_reference`, `agentprompt.MCPReference`, is filled only for the web app); `list_log_levels` (the level choices of the logs list: the levels some stored log in the viewer's projects has, highest first; no filters); `list_issue_projects` and `list_log_projects` (the project choices: from the issue tallies, `Store.IssueProjects`; one seek per visible project in the logs' project index, `Store.LogProjects`); `get_issue_details` (`issue_details.go`: an issue with its history, its 20 newest events (`next_cursor` for `list_issue_events`, whose items carry `received_at`) and one event (`?event=`, the latest by default) read by `services.Issues.Details`: `event_state` shown, unreadable, missing (not stored, or another issue's) or none (`services.EventState`, generated as a union through `outputSchemas`), the facts, exceptions outermost first with frames newest first, maps as name-sorted pairs, JSON indented by Go, related logs, the stored payload and the agent prompt); `apply_issue_action` (resolve, ignore, reopen or delete 1 to `services.MaxActionIssues` issues, `services.IssueActions` as choices; `ignore_for`/`ignore_until_events` (`ignoreBoundInput`, also on `update_issue_status`) only with ignore, else 400 (`services.ErrBoundWithoutIgnore`); invalid ids 400; deleted ones skipped; delete needs `CanAdminister`, checked by `services.Issues.ApplyAction`, else 403; missing and hidden issues skipped); `delete_logs` (`Admin`, `Destructive`, not for agents, whose logs are for reading: `log_ids`, 1 to `services.MaxActionLogs`, missing ones skipped; `{deleted}`; `list_logs` rows carry their `id`; `count_logs` and `list_logs` say `stopped` and `searched_to` when the search ran out of time, `count_logs` gives `from_id` for `list_logs`, and a stopped `list_logs` has a `next_cursor` that goes on below where it stopped); `list_cleanups` (`services.Projects.Cleanups` → `ShownRun`: `VisibleRun`, the projects outside access as one Other row, sizes from `ShownRun.Left`), `get_project_setup` (every role; `connected`/`connected_at` from the first contact (`services.Projects.Contact`, `store.ProjectUsage.FirstContact`), `received` once something is stored), `get_project_defaults`; `get_user` (`{user, can_manage, can_take_over, access_editable}` with reasons); `get_mcp_setup` (`agents.go`: how to connect an agent); `get_connection` (saved tokens masked by `textutil.MaskSecret`, never whole), `get_connection_defaults`, `test_chat`, `count_deliveries`. `set_connection_active` (also MCP) changes only `active`: a whole-form save would refuse a connection whose tokens cannot be read. `list_users` rows are `get_user`'s; `userOutput` has `display_name` and `created_at`; `list_agents` returns `user_id`, `owners` (whose agents the caller may list, only when more than one) and `connected` per agent; `get_project` gives `shown_color`, and an unknown project is `services.Missing` (404, naming it and pointing to `list_projects`). `create_user`/`update_user` take the roles of `store.AssignableRoles` as `Choices`. `list_projects` gives every role the recorded log levels as an explicit list, highest first (`config.Recording.RecordedLogLevels`, also behind `services.Projects.FormValues`). `typescript_test.go` (`TestTypeScriptCatalog`) generates `web/src/lib/api/catalog.gen.ts` from the endpoints the web app may call: inputs from `InputSchema`, outputs from the handler's output type (`Define` keeps it; `time.Time` → `IsoTime`, `json.RawMessage` → `unknown`), the method and admin/destructive/confirm flags (an endpoint of the web app that answers `Text` fails it: the app reads JSON only), the plain requests (`PlainRequests`, `plainRequests`), `ErrorBody`, `choices`, `levels` (highest first), `shownLevel` (the aliases of `config.EventLevelAliases` too), `apiPrefix`, `maxLimit`, and the values of the server's rules: `limits` (`config.Limits`), `issueStatuses` (with `store.StatusMeanings`), `maxActionIssues` (`services.MaxActionIssues`), `projectPalette` (`config.ProjectPalette`), `personalTokenKind` (`store.GrantToken`), `cleanupSteps` and `cleanupRules` (the cleanup by size), `diskShare` (`store.MinDiskShare`, `MaxDiskShare`, `DiskShareStep`), `roleSummaries`, `help` (`docs.Fields`, and of `docs.Settings` only `shownSettings`: a field or variable the app names that is not generated fails its type check); an unsupported schema keyword fails it, a stale file fails `make test`, `make api-types` rewrites it (excluded from Prettier). Never requests of the catalog, in any transport: logins, changing your own password (the account page asks for the current one, through `session.Auth` and its login limit) and generating personal tokens (`TestCatalogNeverChangesCredentials`, which allows them only in `plain*.go`): they are the plain requests of the web app (`plain.go`, `PlainRequests`: `login_state`, `login`, `setup_admin`, `logout`, `change_password`, `personal_token`, `authorization_request`, `authorization_decision`, each with its method and the Go types of its JSON input and output, `NoContent` for a 204), whose handlers (`LoginRequests` in `plain.go`, `AgentRequests` in `plain_agents.go`, joined in `app.New`) `NewUI` takes by name and mounts on their method inside the same guard; no endpoint takes their names (`TestEndpointNames`). The mount checks no session: each handler reads it itself (`sessionViewer`, the one session check of the catalog's calls and the plain requests) and applies the temporary-password rule where it matters, since `login` and `login_state` must work without one: `login_state` `{app_name, redirect?}` (redirect = `server.SafeNext(next)` only with a valid session); `login` 429 `session.TooManyAttempts` with `Retry-After` (the login window), 401 "Wrong email or password." for a wrong password and an unknown user alike, 200 `{next}`, or `{next, setup: true}` for the env credentials while there is no admin (no session; see Users and roles); `logout` 204 even without a session; `change_password` open with a temporary password, problems as 400 `{error, fields}`, the login limit 429 at `current_password` (`session.ErrTooManyAttempts`); `personal_token` and the consent requests 403 with a temporary password; a body over 64 KiB 413. The description (`ToolDescription`) of a `Destructive` tool, or a `Confirm` one (it changes who may access the server, where errors are sent or what it records), tells the agent to get an explicit confirmation in chat. diff --git a/docs/deployment.md b/docs/deployment.md index f9cfeca..08f084c 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -26,7 +26,7 @@ Image tags: `latest` (newest release), `X.Y` (newest patch of a minor version), The container runs as an unprivileged user (uid 65534). A bind-mounted data folder must be writable by it: `sudo chown 65534:65534 ./data`. A named volume, as in the example, needs nothing. -`GET /health` answers 200 while the server works; Docker uses it too (`docker ps` shows `healthy`). +`GET /health` answers 200 while the server works, and 503 once the database cannot be read or its writes fail (a full disk); Docker uses it too (`docker ps` shows `healthy`). ## HTTPS and a reverse proxy diff --git a/internal/storage/database/store.go b/internal/storage/database/store.go index 7d937a5..616b8c1 100644 --- a/internal/storage/database/store.go +++ b/internal/storage/database/store.go @@ -252,8 +252,13 @@ func (database *Store) syncToDisk() error { }) } -// Ping reads the format key, so a closed store or a failing disk answers with an error. +// Ping reads the format key, so a closed store or a failing disk answers +// with an error, as does a store whose last write failed. func (database *Store) Ping(context.Context) error { + if err := database.db.WriteError(); err != nil { + return fmt.Errorf("writes fail: %w", err) + } + _, err := database.db.Get(database.formatKey) return err diff --git a/internal/storage/database/store_test.go b/internal/storage/database/store_test.go index 4b701b4..68b9825 100644 --- a/internal/storage/database/store_test.go +++ b/internal/storage/database/store_test.go @@ -1373,3 +1373,50 @@ func TestEventsPerIssueCapPerMinuteInABatch(t *testing.T) { t.Fatalf("stored %d, not stored %d: want 2 of each minute", issue.Stored, issue.NotStored) } } + +// failingEngine refuses every write while failing, as a full disk does. +type failingEngine struct { + kv.Engine + + failing atomic.Bool +} + +func (engine *failingEngine) Write(batch *kv.Batch, sync bool) error { + if engine.failing.Load() { + return errors.New("no space left on device") + } + + return engine.Engine.Write(batch, sync) +} + +// A store whose writes fail is not healthy though it still reads, until a write passes again. +func TestPingFailsWhileWritesFail(t *testing.T) { + engine := &failingEngine{Engine: openMemoryEngine()} + database, err := open(engine) + + if err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = database.Close() }) + + engine.failing.Store(true) + + if err := database.SaveLogs(context.Background(), []store.NewLog{{ProjectID: 1, Timestamp: time.Now(), Level: "info", Body: "disk"}}, 0); err == nil { + t.Fatal("the write passed") + } + + if err := database.Ping(context.Background()); err == nil { + t.Error("the ping answers healthy while writes fail") + } + + engine.failing.Store(false) + + if err := database.SaveLogs(context.Background(), []store.NewLog{{ProjectID: 1, Timestamp: time.Now(), Level: "info", Body: "disk"}}, 0); err != nil { + t.Fatal(err) + } + + if err := database.Ping(context.Background()); err != nil { + t.Errorf("after a write passed: %v", err) + } +} diff --git a/internal/storage/kv/db.go b/internal/storage/kv/db.go index 549c0c0..933bd2e 100644 --- a/internal/storage/kv/db.go +++ b/internal/storage/kv/db.go @@ -40,6 +40,8 @@ type DB struct { schema *Schema written atomic.Int64 + // writeFailure is the error of the last write when it failed (WriteError). + writeFailure atomic.Pointer[error] sequenceMutex sync.Mutex next uint64 // the next sequence number @@ -151,6 +153,27 @@ func (db *DB) Peek() uint64 { return db.next } +// Write writes batch to the engine and remembers whether it failed, for WriteError. +func (db *DB) Write(batch *Batch, sync bool) error { + err := db.Engine.Write(batch, sync) + + if batch.Len() > 0 { + db.writeFailure.Store(&err) + } + + return err +} + +// WriteError is the error of the last write when it failed: the engine still +// reads, but refuses writes (a full disk, a corrupted table). +func (db *DB) WriteError() error { + if err := db.writeFailure.Load(); err != nil { + return *err + } + + return nil +} + // Update runs change on a new batch and writes it with its counters, one at a time. // Nothing is written when change fails. func (db *DB) Update(sync bool, change func(batch *Batch) error) error { diff --git a/internal/storage/kv/leveldb/leveldb.go b/internal/storage/kv/leveldb/leveldb.go index 6b6fd7c..a467e22 100644 --- a/internal/storage/kv/leveldb/leveldb.go +++ b/internal/storage/kv/leveldb/leveldb.go @@ -8,8 +8,6 @@ import ( "os" "path/filepath" "slices" - "strconv" - "strings" "syscall" "github.com/syndtr/goleveldb/leveldb" @@ -202,22 +200,22 @@ func liveBytes(iterator kv.Iterator) (int64, error) { // not data, and their size rises and falls as they rotate. var infoLogs = []string{"LOG", "LOG.old"} -// Size sums the database files in use (tables, the journal, the manifest); -// in memory, the keys and values. +// Size sums the files in use: the current version's tables (not those a compaction replaced +// and goleveldb has not deleted yet) and the journal and manifest; in memory, the keys and values. func (engine *levelEngine) Size() (int64, error) { if engine.dir == "" { return liveBytes(engine.Iterate(nil, nil)) } - live, err := engine.liveTables() + var stats leveldb.DBStats - if err != nil { + if err := engine.db.Stats(&stats); err != nil { return 0, err } - var total int64 + total := stats.LevelSizes.Sum() - err = filepath.WalkDir(engine.dir, func(_ string, entry fs.DirEntry, err error) error { + err := filepath.WalkDir(engine.dir, func(_ string, entry fs.DirEntry, err error) error { if err != nil { // A compaction may delete a file while walking. if errors.Is(err, fs.ErrNotExist) { @@ -227,12 +225,7 @@ func (engine *levelEngine) Size() (int64, error) { return err } - if entry.IsDir() || slices.Contains(infoLogs, entry.Name()) { - return nil - } - - // A table a compaction replaced stays on disk until goleveldb's next version change. - if number, ok := tableNumber(entry.Name()); ok && !live[number] { + if entry.IsDir() || slices.Contains(infoLogs, entry.Name()) || isTable(entry.Name()) { return nil } @@ -250,38 +243,11 @@ func (engine *levelEngine) Size() (int64, error) { return total, err } -// liveTables lists the numbers of the tables in use, from "N:size[...]" lines. -func (engine *levelEngine) liveTables() (map[int64]bool, error) { - tables, err := engine.db.GetProperty("leveldb.sstables") - - if err != nil { - return nil, err - } - - live := map[int64]bool{} - - for line := range strings.Lines(tables) { - var number, size int64 - - if count, _ := fmt.Sscanf(line, "%d:%d", &number, &size); count == 2 { - live[number] = true - } - } - - return live, nil -} - -// tableNumber reads "000123.ldb" (or the older ".sst"). -func tableNumber(name string) (int64, bool) { +// isTable tells a table ("000123.ldb", or the older ".sst") by its extension. +func isTable(name string) bool { extension := filepath.Ext(name) - if extension != ".ldb" && extension != ".sst" { - return 0, false - } - - number, err := strconv.ParseInt(strings.TrimSuffix(name, extension), 10, 64) - - return number, err == nil + return extension == ".ldb" || extension == ".sst" } func (engine *levelEngine) Close() error { return engine.db.Close() }