From 91f1bb64a0368dca5f88be4f0f62c57418e9f824 Mon Sep 17 00:00:00 2001 From: Yethe Samartaka Date: Mon, 30 Nov 2026 22:33:43 +0100 Subject: [PATCH 1/2] Upgrade Go to 1.27 --- AGENTS.md | 1 + README.md | 2 +- docs/streaming-architecture.md | 24 +- docs/testkit.md | 8 +- go.mod | 2 +- internal/conversion/worker_test.go | 60 +--- internal/ingestion/coverage_extra_test.go | 10 - internal/ingestion/export_v1_from_v2.go | 332 ++++++++++++++++++ internal/ingestion/export_v1_from_v2_test.go | 328 +++++++++++++++++ internal/ingestion/extra_events.go | 2 +- internal/ingestion/session.go | 15 +- internal/ingestion/writer_v2.go | 68 +--- internal/ingestion/writer_v2_test.go | 19 +- internal/maptool/jobmanager_test.go | 37 +- internal/server/coverage_extra_test.go | 7 +- internal/server/handler.go | 3 + internal/server/handler_stream.go | 22 +- internal/server/handler_stream_resume_test.go | 31 +- internal/server/handler_stream_test.go | 93 +++-- internal/server/operation.go | 13 + internal/server/operation_indexes_test.go | 106 ++++++ internal/server/operation_test.go | 6 +- internal/server/recording_download.go | 80 +++++ internal/server/recording_download_test.go | 39 ++ internal/server/route_access_test.go | 74 ++++ internal/storage/json.go | 3 +- internal/storage/json_test.go | 8 + internal/storage/parser.go | 17 +- internal/storage/parser_test.go | 53 +++ internal/storage/parser_v1.go | 19 +- internal/storage/precompress.go | 2 +- internal/storage/precompress_test.go | 3 + internal/storage/streaming_converter.go | 10 +- internal/storage/streaming_json_reader.go | 2 +- .../storage/streaming_json_reader_test.go | 7 + internal/testkit/cases.go | 6 +- 36 files changed, 1290 insertions(+), 222 deletions(-) create mode 100644 internal/ingestion/export_v1_from_v2.go create mode 100644 internal/ingestion/export_v1_from_v2_test.go create mode 100644 internal/server/operation_indexes_test.go create mode 100644 internal/server/recording_download.go create mode 100644 internal/server/recording_download_test.go diff --git a/AGENTS.md b/AGENTS.md index da7c92415..fad3ada42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,6 +3,7 @@ Start with [Contributing](CONTRIBUTING.md). Use [Maintainer context](docs/maintainer-context.md) to trace a contract, failure path, or guard and [Comment hygiene](docs/comment-hygiene.md) for comment changes. - Verify [HTTP authorization](internal/server/handler.go) through the registered mux under a non-root prefix. Viewer, admin, and producer routes use different credentials. Use the [streaming contract](docs/streaming-architecture.md) for ingestion, recording formats, and playback. Follow the [schema generation instructions](CONTRIBUTING.md#protobuf-schema-changes) for protobuf changes. +- Store native v2 recordings as protobuf and convert them to v1 JSON on demand for downloads. Keep existing v1 JSON and schema-v1 protobuf recordings readable. - Keep the UI's SolidJS, CSS module, and i18n conventions. Use the [operational runbook](docs/operational-verification.md) for startup, native map tooling, and Arsenal imports. - Inspect the working tree before editing. Preserve local changes and use synthetic recordings, paths, identities, secrets, and provider responses for local checks. The [testkit](docs/testkit.md) is available without an application startup. - Match [CI](.github/workflows) for Go tests and UI typecheck, lint, tests, and build when those surfaces change. Build the SPA before packaging the embedded binary. Keep tests close to the code they exercise. diff --git a/README.md b/README.md index 8d55450a3..8602f8a62 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Each archive contains the binary and required assets (markers, ammo icons). ### Build from source -Requires [Go 1.26+](https://golang.org/dl/) and [Node.js 24+](https://nodejs.org/). +Requires [Go 1.27.4+](https://golang.org/dl/) and [Node.js 24+](https://nodejs.org/). ```bash # Build the frontend diff --git a/docs/streaming-architecture.md b/docs/streaming-architecture.md index d9176d750..2dd6d6a57 100644 --- a/docs/streaming-architecture.md +++ b/docs/streaming-architecture.md @@ -43,8 +43,8 @@ timeline. Older clients that omit the declaration keep their zero-based frames, legacy marker end sentinel and projectile trajectory field name. Unknown future message types are logged and skipped. -Each accepted mission gets one unique storage key, used for its database row, -v2 directory and legacy `.json.gz` backup. At mission end the web writes: +Each accepted mission gets one unique storage key for its database row and +protobuf directory. At mission end the web writes: - Native **v2 protobuf** metadata and chunks, retaining the richer entity states, telemetry, mission metadata, radio/ACE events, placed objects and focus ranges. @@ -54,15 +54,19 @@ v2 directory and legacy `.json.gz` backup. At mission end the web writes: - Player snapshot sidecars using the existing `snapshots/.pb` format and endpoint, keeping large inventories out of the startup manifest. Older v2 files with inline snapshots remain readable. -- A **v1 JSON.gz backup** for legacy playback, downloads and fallback conversion. - Existing uploads, v1 conversion, schema-v1 protobuf and JSON playback retain - their existing paths. Legacy conversion never overwrites a native v2 recording. + +The existing viewer download URL serves a previously stored **v1 JSON.gz** +when available. For native v2 recordings without that file, it converts the +protobuf recording to v1 JSON on request. Each conversion holds the whole +mission in memory, so the server runs one at a time and queues the rest. +Existing uploads, v1 conversion, schema-v1 protobuf and JSON playback retain +their existing paths. An end-mission acknowledgement is sent only after the recording and operation are saved. Direct v2 output is already finalized and needs no conversion job. -If v2 writing fails, a successful legacy backup becomes the operation's source -and follows the existing conversion setting. A failed save is reported by closing -the connection without a success acknowledgement, and the row is marked failed. +If v2 writing fails, the server closes the connection without a success +acknowledgement and marks the row failed. A resumable producer can replay the +mission. ### Resume after a network failure @@ -211,9 +215,9 @@ received data and appends `partial` to the mission's existing tags. Repeated starts cannot silently discard an active mission. Their reconnect starts a new recording segment. -The session retains history in web memory for its legacy backup. A web process +The session retains history in web memory for protobuf finalization. A web process crash is not the same as a producer disconnect and does not guarantee a finalized -backup; this protocol does not yet include a durable ingestion journal. +recording. This protocol does not yet include a durable ingestion journal. ### Verification diff --git a/docs/testkit.md b/docs/testkit.md index 4cf480c3d..0b52a42cc 100644 --- a/docs/testkit.md +++ b/docs/testkit.md @@ -27,17 +27,19 @@ go run ./cmd/ocap-testkit run -race stream-recovery Put `-race` immediately after `run`. It instruments Go steps in the selected cases and records the exact command in the report. UI steps run normally. Use a [supported compiler and platform](https://go.dev/doc/articles/race_detector#Requirements). Coverage and race detection measure different things. The detector reports races on paths exercised by the selected tests. [Go race detector](https://go.dev/doc/articles/race_detector#How_To_Use) +For a diagnostic goroutine-leak profile after three synthetic reconnect-and-discard cycles, run the focused integration test with `OCAP_STREAM_LEAK_PROFILE=1 go test ./internal/server -run '^TestStreamRecoveryLeakProfile$' -count=1`. The profile is written to stderr for inspection and does not impose a process-wide leak threshold. Go's reachability-based profile may miss blockers reachable from globals or runnable goroutines. + ## Cases | Case | Evidence | | --- | --- | -| `filename-migration` | Repair and rerun, collisions, and no disk or database changes after an incomplete row scan | +| `filename-migration` | Legacy filename repair, collisions, interrupted scans, and additive SQLite indexes | | `legacy-upload` | Repeated filename replacement, failed reload leaves the prior recording available, and legacy raw JSON playback | -| `route-access` | Prefixed viewer route and admin mutation authorization through the mux, plus producer credential rejection | +| `route-access` | Prefixed viewer access to stored JSON and v2-generated downloads, protected admin mutations, and producer credential rejection | | `steam-boundary` | Fake OpenID verifier and loopback profile API, denied allowlist access and provider errors | | `stream-recovery` | Loopback reconnect, repeated starts, partial replacement, durable end, repeated discard, and fake-clock tests for reservation timeouts and a failed keepalive write | | `conversion-recovery` | Temporary conversion artifacts, status failures and admin retry | -| `playback-delivery` | Synthetic artifact serving and decoding, lazy sidecar replay and Gear exports, event-time factions, and bounded chunk traversal | +| `playback-delivery` | Synthetic artifact serving and decoding, v2 to v1 export, lazy sidecar replay and Gear exports, event-time factions, and bounded chunk traversal | | `map-boundary` | Synthetic ZIP and job lifecycle, authenticated SSE, stubbed CDN fallback | | `startup` | Fake dependencies for startup, failure and shutdown wiring | diff --git a/go.mod b/go.mod index 6de35ebb4..5682d4708 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/OCAP2/web -go 1.27.2 +go 1.27.4 require ( github.com/OCAP2/extension/v5 v5.0.2-0.20261027093953-0a7ce6a9b9a7 diff --git a/internal/conversion/worker_test.go b/internal/conversion/worker_test.go index 286c5a404..249247e0f 100644 --- a/internal/conversion/worker_test.go +++ b/internal/conversion/worker_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "testing" + "testing/synctest" "time" "github.com/OCAP2/web/internal/server" @@ -323,26 +324,12 @@ func TestTriggerConversion(t *testing.T) { ChunkSize: 10, }) - // TriggerConversion is async, so we need to wait for it - worker.TriggerConversion(1, "trigger_mission") - - // Wait for async conversion to complete - timeout := time.After(5 * time.Second) - ticker := time.NewTicker(50 * time.Millisecond) - defer ticker.Stop() - - for { - select { - case <-timeout: - t.Fatal("Timeout waiting for async conversion") - case <-ticker.C: - if status, ok := repo.status[1]; ok && status == "completed" { - // Conversion completed - assert.Equal(t, "protobuf", repo.format[1]) - return - } - } - } + synctest.Test(t, func(t *testing.T) { + worker.TriggerConversion(1, "trigger_mission") + synctest.Wait() + assert.Equal(t, server.ConversionStatusCompleted, repo.status[1]) + assert.Equal(t, "protobuf", repo.format[1]) + }) } func TestTriggerConversion_Failure(t *testing.T) { @@ -353,25 +340,11 @@ func TestTriggerConversion_Failure(t *testing.T) { DataDir: dir, }) - // Trigger conversion for non-existent file - worker.TriggerConversion(99, "nonexistent_file") - - // Wait for async conversion to fail - timeout := time.After(2 * time.Second) - ticker := time.NewTicker(50 * time.Millisecond) - defer ticker.Stop() - - for { - select { - case <-timeout: - t.Fatal("Timeout waiting for async conversion failure") - case <-ticker.C: - if status, ok := repo.status[99]; ok && status == "failed" { - // Conversion failed as expected - return - } - } - } + synctest.Test(t, func(t *testing.T) { + worker.TriggerConversion(99, "nonexistent_file") + synctest.Wait() + assert.Equal(t, server.ConversionStatusFailed, repo.status[99]) + }) } func TestWorker_ContextCancellation(t *testing.T) { @@ -722,11 +695,10 @@ func TestTriggerConversion_FailedStatusUpdateError(t *testing.T) { DataDir: dir, }) - // TriggerConversion is async, just verify it doesn't panic - worker.TriggerConversion(1, "nonexistent") - - // Give the goroutine time to run - time.Sleep(100 * time.Millisecond) + synctest.Test(t, func(t *testing.T) { + worker.TriggerConversion(1, "nonexistent") + synctest.Wait() + }) } func TestComputeStats_DeduplicatesPlayersByName(t *testing.T) { diff --git a/internal/ingestion/coverage_extra_test.go b/internal/ingestion/coverage_extra_test.go index 1dc1e7ee5..ed0151875 100644 --- a/internal/ingestion/coverage_extra_test.go +++ b/internal/ingestion/coverage_extra_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "io" - "math" "os" "path/filepath" "testing" @@ -208,10 +207,6 @@ func TestWriterV2_ExtraBranches(t *testing.T) { require.NoError(t, os.MkdirAll(filepath.Join(dirPB, "manifest.pb", "sub"), 0755)) assert.ErrorContains(t, WriteV2Manifest(s, dirPB, 1), "write manifest.pb") - // WriteV2Manifest write manifest.json error (manifest.json is a directory) - dirJSON := t.TempDir() - require.NoError(t, os.MkdirAll(filepath.Join(dirJSON, "manifest.json"), 0755)) - assert.ErrorContains(t, WriteV2Manifest(s, dirJSON, 1), "write manifest.json") } type fakeTempWriteCloser struct { @@ -315,11 +310,6 @@ func TestIngestion_100PercentCoverage(t *testing.T) { require.NoError(t, os.MkdirAll(p1, 0755)) assert.Error(t, sFin.Finalize(finDir)) - // writer_v2.go:39 (manifestToJSON marshal fails with NaN World Latitude) - sNaN := NewSession() - sNaN.SetMission(nil, &core.World{WorldName: "altis", Latitude: float32(math.NaN())}) - assert.ErrorContains(t, WriteV2Manifest(sNaN, t.TempDir(), 1), "marshal JSON archive") - // writer_v2.go:185, 186 (multiple soldiers & vehicles trigger sort comparators) sSort := NewSession() sSort.HandleAddSoldier(core.Soldier{ID: 10, UnitName: "B"}) diff --git a/internal/ingestion/export_v1_from_v2.go b/internal/ingestion/export_v1_from_v2.go new file mode 100644 index 000000000..65199a8a6 --- /dev/null +++ b/internal/ingestion/export_v1_from_v2.go @@ -0,0 +1,332 @@ +package ingestion + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/OCAP2/extension/v5/pkg/core" + pbv1 "github.com/OCAP2/web/pkg/schemas/protobuf/v1" + pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" + "google.golang.org/protobuf/proto" +) + +// ExportV2AsV1JSON reconstructs the legacy recording document from the native +// protobuf manifest and frame chunks. Context cancellation is checked before +// each chunk read so large mission exports can be abandoned promptly. +func ExportV2AsV1JSON(ctx context.Context, recordingDir string) (map[string]any, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + manifestData, err := os.ReadFile(filepath.Join(recordingDir, "manifest.pb")) + if err != nil { + return nil, fmt.Errorf("read v2 manifest: %w", err) + } + manifest := new(pbv2.Manifest) + if err := proto.Unmarshal(manifestData, manifest); err != nil { + return nil, fmt.Errorf("decode v2 manifest: %w", err) + } + if manifest.Version != 2 { + return nil, fmt.Errorf("unsupported v2 manifest version %d", manifest.Version) + } + for _, d := range manifest.Soldiers { + if d.Id > 65535 { + return nil, fmt.Errorf("soldier id %d exceeds legacy entity id range", d.Id) + } + } + for _, d := range manifest.Vehicles { + if d.Id > 65535 { + return nil, fmt.Errorf("vehicle id %d exceeds legacy entity id range", d.Id) + } + } + session := sessionFromV2Manifest(manifest) + if err := appendV2Snapshots(ctx, session, recordingDir, manifest.SnapshotUnitIds); err != nil { + return nil, err + } + for i := uint32(0); i < manifest.ChunkCount; i++ { + if err := ctx.Err(); err != nil { + return nil, err + } + chunkPath := filepath.Join(recordingDir, "chunks", fmt.Sprintf("%04d.pb", i)) + data, err := os.ReadFile(chunkPath) + if err != nil { + return nil, fmt.Errorf("read v2 chunk %d: %w", i, err) + } + chunk := new(pbv2.Chunk) + if err := proto.Unmarshal(data, chunk); err != nil { + return nil, fmt.Errorf("decode v2 chunk %d: %w", i, err) + } + for _, frame := range chunk.Frames { + for _, state := range frame.Soldiers { + if state.Id > 65535 { + return nil, fmt.Errorf("soldier state id %d exceeds legacy entity id range", state.Id) + } + } + for _, state := range frame.Vehicles { + if state.Id > 65535 { + return nil, fmt.Errorf("vehicle state id %d exceeds legacy entity id range", state.Id) + } + } + } + appendV2Chunk(session, chunk) + } + return session.ToV1JSON(), nil +} + +func sessionFromV2Manifest(m *pbv2.Manifest) *Session { + s := NewSession() + s.frameCount = core.Frame(m.FrameCount) + if len(m.MetadataJson) > 0 { + var metadata struct { + Mission *core.Mission + World *core.World + } + if json.Unmarshal(m.MetadataJson, &metadata) == nil { + s.mission, s.world = metadata.Mission, metadata.World + } + } + if s.world == nil && m.World != nil { + s.world = &core.World{WorldName: m.World.WorldName, WorldSize: m.World.WorldSize, Latitude: m.World.Latitude, Longitude: m.World.Longitude, Author: m.World.Author, DisplayName: m.World.DisplayName} + } + if s.mission == nil && m.Mission != nil { + s.mission = &core.Mission{MissionName: m.Mission.MissionName, BriefingName: m.Mission.BriefingName, Author: m.Mission.Author, ServerName: m.Mission.ServerName, ExtensionVersion: m.Mission.ExtensionVersion, AddonVersion: m.Mission.AddonVersion, ExtensionBuild: m.Mission.ExtensionBuild, Tag: m.Mission.Tag, CaptureDelay: float32(m.CaptureDelayMs) / 1000} + } + for _, d := range m.Soldiers { + deleted := core.Frame(d.EndFrame) < lastFrame(s.frameCount) + deleteFrame := core.Frame(0) + if deleted { + deleteFrame = core.Frame(d.EndFrame) + } + soldier := core.Soldier{ID: uint16(d.Id), UnitName: d.Name, Side: protoSideName(d.Side), GroupID: d.GroupName, RoleDescription: d.Role, JoinFrame: core.Frame(d.StartFrame), DeleteFrame: deleteFrame, IsPlayer: d.IsPlayer, ClassName: d.ClassName, PlayerUID: d.PlayerUid} + rec := &soldierRecord{Soldier: soldier, deleted: deleted} + for _, f := range d.FramesFired { + rec.FiredEvents = append(rec.FiredEvents, core.FiredEvent{SoldierID: soldier.ID, CaptureFrame: core.Frame(f.FrameNum), StartPos: v2Position(f.StartPos), EndPos: v2Position(f.EndPos), Weapon: f.Weapon, Magazine: f.Magazine, FiringMode: f.FiringMode}) + } + s.soldiers[soldier.ID] = rec + } + for _, d := range m.Vehicles { + deleted := core.Frame(d.EndFrame) < lastFrame(s.frameCount) + deleteFrame := core.Frame(0) + if deleted { + deleteFrame = core.Frame(d.EndFrame) + } + vehicle := core.Vehicle{ID: uint16(d.Id), DisplayName: d.Name, OcapType: d.VehicleClass, ClassName: d.ClassName, JoinFrame: core.Frame(d.StartFrame), DeleteFrame: deleteFrame, Customization: d.Customization} + s.vehicles[vehicle.ID] = &vehicleRecord{Vehicle: vehicle, deleted: deleted} + } + for _, f := range m.FocusRanges { + s.focusRanges = append(s.focusRanges, core.FocusRange{Start: core.Frame(f.Start), End: core.Frame(f.End)}) + } + for _, t := range m.Times { + s.times = append(s.times, core.TimeState{CaptureFrame: core.Frame(t.FrameNum), SystemTimeUTC: t.SystemTimeUtc, MissionDate: t.Date, TimeMultiplier: t.TimeMultiplier, MissionTime: t.Time}) + } + for _, marker := range m.Markers { + // Zero-padded keys keep the manifest's marker order after markersToV1 sorts by name. + s.markers[fmt.Sprintf("v2-%08d", len(s.markers))] = markerRecordFromProto(marker) + } + for _, event := range m.Events { + appendV2Event(s, event) + } + // The native manifest stores artifacts after the writer's derivation pass: + // generated projectile lines, hit events, and placed-object markers are + // already present. Re-deriving them would duplicate those legacy outputs. + s.projectilesDerived = true + return s +} + +func appendV2Snapshots(ctx context.Context, s *Session, dir string, ids []uint32) error { + for _, id := range ids { + if err := ctx.Err(); err != nil { + return err + } + path := filepath.Join(dir, "snapshots", fmt.Sprintf("%d.pb", id)) + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + continue + } + return fmt.Errorf("read v2 player snapshot %d: %w", id, err) + } + series := new(pbv1.PlayerSnapshotSeries) + if err := proto.Unmarshal(data, series); err != nil { + return fmt.Errorf("decode v2 player snapshot %d: %w", id, err) + } + for _, e := range series.Events { + s.events = append(s.events, eventRecord{eventType: e.Type, frame: core.Frame(e.FrameNum), general: &core.GeneralEvent{CaptureFrame: core.Frame(e.FrameNum), Name: e.Type, Message: e.Message}}) + } + } + return nil +} + +func appendV2Chunk(s *Session, chunk *pbv2.Chunk) { + for _, frame := range chunk.Frames { + f := core.Frame(frame.FrameNum) + for _, state := range frame.Soldiers { + id := uint16(state.Id) + rec := s.soldiers[id] + if rec == nil { + rec = &soldierRecord{Soldier: core.Soldier{ID: id, JoinFrame: f}} + s.soldiers[id] = rec + } + // The extension reports occupancy through the vehicle id alone and + // leaves InVehicle unset, so either field marks a mounted unit, as + // in the v2 playback decoder. + var vehicleID *uint16 + if state.InVehicle || state.VehicleId != 0 { + v := uint16(state.VehicleId) + vehicleID = &v + } + rec.States = append(rec.States, core.SoldierState{SoldierID: id, CaptureFrame: f, Position: v2Position(state.Position), Bearing: uint16(state.Bearing), Lifestate: uint8(state.Lifestate), InVehicle: state.InVehicle, InVehicleObjectID: vehicleID, UnitName: state.Name, IsPlayer: state.IsPlayer, GroupID: state.GroupName, Side: state.Side, CurrentRole: state.Role}) + } + for _, state := range frame.Vehicles { + id := uint16(state.Id) + rec := s.vehicles[id] + if rec == nil { + rec = &vehicleRecord{Vehicle: core.Vehicle{ID: id, JoinFrame: f}} + s.vehicles[id] = rec + } + crew, _ := json.Marshal(state.CrewIds) + if len(state.CrewIds) == 0 { + crew = []byte("[]") + } + rec.States = append(rec.States, core.VehicleState{VehicleID: id, CaptureFrame: f, Position: v2Position(state.Position), Bearing: uint16(state.Bearing), IsAlive: state.Alive, Crew: string(crew), Side: state.Side}) + } + } +} + +func appendV2Event(s *Session, e *pbv2.Event) { + frame := core.Frame(e.FrameNum) + switch ev := e.Event.(type) { + case *pbv2.Event_Kill: + k := ev.Kill + victim, killer := uint(k.VictimSoldierId), uint(k.KillerSoldierId) + if k.VictimIsVehicle { + victim = uint(k.VictimVehicleId) + } + if k.KillerIsVehicle { + killer = uint(k.KillerVehicleId) + } + s.events = append(s.events, eventRecord{eventType: "killed", frame: frame, kill: &core.KillEvent{CaptureFrame: frame, VictimSoldierID: ptrUnlessVehicle(victim, k.VictimIsVehicle), VictimVehicleID: ptrIfVehicle(victim, k.VictimIsVehicle), KillerSoldierID: ptrUnlessVehicle(killer, k.KillerIsVehicle), KillerVehicleID: ptrIfVehicle(killer, k.KillerIsVehicle), WeaponName: k.WeaponName, WeaponMagazine: k.WeaponMagazine, EventText: k.EventText, Distance: k.Distance}}) + case *pbv2.Event_Hit: + h := ev.Hit + victim, source := uint(h.VictimSoldierId), uint(h.ShooterSoldierId) + if h.VictimIsVehicle { + victim = uint(h.VictimVehicleId) + } + if h.ShooterIsVehicle { + source = uint(h.ShooterVehicleId) + } + s.events = append(s.events, eventRecord{eventType: "hit", frame: frame, hit: &core.HitEvent{CaptureFrame: frame, VictimSoldierID: ptrUnlessVehicle(victim, h.VictimIsVehicle), VictimVehicleID: ptrIfVehicle(victim, h.VictimIsVehicle), ShooterSoldierID: ptrUnlessVehicle(source, h.ShooterIsVehicle), ShooterVehicleID: ptrIfVehicle(source, h.ShooterIsVehicle), WeaponName: h.WeaponName, WeaponMagazine: h.WeaponMagazine, EventText: h.EventText, Distance: h.Distance}}) + case *pbv2.Event_Chat: + c := ev.Chat + id := uint(c.SoldierId) + s.events = append(s.events, eventRecord{eventType: "chat", frame: frame, chat: &core.ChatEvent{CaptureFrame: frame, SoldierID: &id, Channel: c.Channel, FromName: c.FromName, Message: c.Message, PlayerUID: c.PlayerUid}}) + case *pbv2.Event_General: + g := ev.General + var extra map[string]any + _ = json.Unmarshal(g.ExtraDataJson, &extra) + if extra == nil { + extra = map[string]any{} + } + s.events = append(s.events, eventRecord{eventType: g.Name, frame: frame, general: &core.GeneralEvent{CaptureFrame: frame, Name: g.Name, Message: g.Message, ExtraData: extra}}) + case *pbv2.Event_Radio: + r := ev.Radio + id := uint(r.SoldierId) + s.radio = append(s.radio, core.RadioEvent{CaptureFrame: frame, SoldierID: &id, Radio: r.Radio, RadioType: r.RadioType, StartEnd: r.StartEnd, Channel: int8(r.Channel), IsAdditional: r.IsAdditional, Frequency: r.Frequency, Code: r.Code}) + case *pbv2.Event_Ace3Death: + d := ev.Ace3Death + var source *uint + if d.HasDamageSource { + v := uint(d.LastDamageSourceId) + source = &v + } + s.aceDeaths = append(s.aceDeaths, core.Ace3DeathEvent{CaptureFrame: frame, SoldierID: uint(d.SoldierId), Reason: d.Reason, LastDamageSourceID: source}) + case *pbv2.Event_Ace3Unconscious: + u := ev.Ace3Unconscious + s.aceUnconscious = append(s.aceUnconscious, core.Ace3UnconsciousEvent{CaptureFrame: frame, SoldierID: uint(u.SoldierId), IsUnconscious: u.IsUnconscious}) + case *pbv2.Event_EndMission: + v := ev.EndMission + s.events = append(s.events, eventRecord{eventType: "endMission", frame: frame, general: &core.GeneralEvent{CaptureFrame: frame, Name: "endMission", Message: v.Message, ExtraData: map[string]any{"side": v.Side}}}) + case *pbv2.Event_Connect: + v := ev.Connect + name := "disconnected" + if v.IsConnect { + name = "connected" + } + s.events = append(s.events, eventRecord{eventType: name, frame: frame, general: &core.GeneralEvent{CaptureFrame: frame, Name: name, Message: v.UnitName}}) + case *pbv2.Event_Telemetry: + t := ev.Telemetry + te := core.TelemetryEvent{CaptureFrame: frame, FpsAverage: t.FpsAverage, FpsMin: t.FpsMin} + if t.Weather != nil { + w := t.Weather + te.Weather = core.WeatherData{Fog: w.Fog, Overcast: w.Overcast, Rain: w.Rain, Humidity: w.Humidity, Waves: w.Waves, WindDir: w.WindDir, WindStr: w.WindStr, Gusts: w.Gusts, Lightnings: w.Lightnings, MoonIntensity: w.MoonIntensity, MoonPhase: w.MoonPhase, SunOrMoon: w.SunOrMoon} + } + s.telemetry = append(s.telemetry, te) + } +} + +func markerRecordFromProto(m *pbv2.MarkerDef) *markerRecord { + marker := core.Marker{MarkerType: m.Type, Text: m.Text, CaptureFrame: core.Frame(m.StartFrame), EndFrame: core.Frame(m.EndFrame), OwnerID: int(m.PlayerId), Color: strings.TrimPrefix(m.Color, "#"), Side: protoSideName(m.Side), Shape: m.Shape, Brush: m.Brush, Size: "[1,1]"} + if len(m.Size) == 2 { + b, _ := json.Marshal(m.Size) + marker.Size = string(b) + } + if m.DeletedFrame != nil { + marker.EndFrame = core.Frame(*m.DeletedFrame) + marker.IsDeleted = true + } + rec := &markerRecord{Marker: marker} + for i, p := range m.Positions { + if i == 0 { + marker.Position, marker.Direction, marker.Alpha = v2Position(p.Position), p.Direction, p.Alpha + if len(p.LineCoords) >= 2 { + for j := 0; j+1 < len(p.LineCoords); j += 2 { + marker.Polyline = append(marker.Polyline, core.Position2D{X: float64(p.LineCoords[j]), Y: float64(p.LineCoords[j+1])}) + } + } + continue + } + rec.States = append(rec.States, core.MarkerState{MarkerID: uint(marker.ID), CaptureFrame: core.Frame(p.FrameNum), Position: v2Position(p.Position), Direction: p.Direction, Alpha: p.Alpha, Text: p.Text, Color: p.Color, MarkerType: p.Type, Brush: p.Brush, Shape: p.Shape}) + } + rec.Marker = marker + return rec +} + +func v2Position(p *pbv2.Position3D) core.Position3D { + if p == nil { + return core.Position3D{} + } + return core.Position3D{X: float64(p.X), Y: float64(p.Y), Z: float64(p.Z)} +} + +func protoSideName(side pbv2.Side) string { + switch side { + case pbv2.Side_SIDE_WEST: + return "WEST" + case pbv2.Side_SIDE_EAST: + return "EAST" + case pbv2.Side_SIDE_GUER: + return "GUER" + case pbv2.Side_SIDE_CIV: + return "CIV" + case pbv2.Side_SIDE_GLOBAL: + return "GLOBAL" + default: + return "UNKNOWN" + } +} + +func ptrIfVehicle(id uint, vehicle bool) *uint { + if !vehicle { + return nil + } + return &id +} +func ptrUnlessVehicle(id uint, vehicle bool) *uint { + if vehicle { + return nil + } + return &id +} diff --git a/internal/ingestion/export_v1_from_v2_test.go b/internal/ingestion/export_v1_from_v2_test.go new file mode 100644 index 000000000..fe07ba894 --- /dev/null +++ b/internal/ingestion/export_v1_from_v2_test.go @@ -0,0 +1,328 @@ +package ingestion + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "testing" + + "github.com/OCAP2/extension/v5/pkg/core" + pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +func TestExportV2AsV1JSONMatchesSessionConversion(t *testing.T) { + dir := t.TempDir() + s := NewSession() + s.mission = &core.Mission{MissionName: "Export test", CaptureDelay: .25, ExtensionVersion: "1", AddonVersion: "2", ExtensionBuild: "build", Author: "author", Tag: "tags"} + s.world = &core.World{WorldName: "Altis"} + s.frameCount = 3 + s.focusRanges = []core.FocusRange{{Start: 1, End: 2}} + s.HandleAddSoldier(core.Soldier{ID: 1, JoinFrame: 0, UnitName: "Player", Side: "WEST", GroupID: "Alpha", RoleDescription: "Rifleman", IsPlayer: true}) + s.HandleSoldierState(core.SoldierState{SoldierID: 1, CaptureFrame: 0, Position: core.Position3D{X: 1, Y: 2, Z: 3}, Bearing: 90, Lifestate: 1, UnitName: "Player", IsPlayer: true, GroupID: "Alpha", Side: "WEST", CurrentRole: "Rifleman"}) + s.HandleSoldierState(core.SoldierState{SoldierID: 1, CaptureFrame: 2, Position: core.Position3D{X: 4, Y: 5, Z: 6}, Bearing: 180, Lifestate: 1, InVehicleObjectID: uint16Ptr(3), UnitName: "Player", IsPlayer: true, GroupID: "Alpha", Side: "WEST", CurrentRole: "Rifleman"}) + s.HandleFiredEvent(core.FiredEvent{SoldierID: 1, CaptureFrame: 2, Weapon: "rifle", EndPos: core.Position3D{X: 10}}) + s.HandleAddVehicle(core.Vehicle{ID: 3, JoinFrame: 0, DisplayName: "Truck", OcapType: "car", ClassName: "Truck_F", DeleteFrame: 2}) + s.HandleVehicleState(core.VehicleState{VehicleID: 3, CaptureFrame: 0, Position: core.Position3D{X: 7, Y: 8, Z: 9}, Bearing: 270, IsAlive: true, Crew: "[1]"}) + s.HandleKillEvent(core.KillEvent{CaptureFrame: 2, VictimSoldierID: uintPtr(1), EventText: "rifle", Distance: 10}) + s.HandleChatEvent(core.ChatEvent{CaptureFrame: 1, SoldierID: uintPtr(1), Channel: "side", FromName: "Player", Message: "hello"}) + s.HandleGeneralEvent(core.GeneralEvent{CaptureFrame: 1, Name: "custom", Message: `{"ok":true}`}) + s.HandleGeneralEvent(core.GeneralEvent{CaptureFrame: 1, Name: "inventorySnapshot", Message: `{"unitId":1,"items":[]}`}) + s.HandleAddMarker(core.Marker{ID: 1, MarkerName: "HQ", CaptureFrame: 0, MarkerType: "mil_dot", Text: "HQ", Position: core.Position3D{X: 10, Y: 20}, Color: "#FF0000", Side: "WEST", Shape: "ICON", Brush: "Solid", Size: "[1,1]", Alpha: 1}) + s.HandleMarkerState(core.MarkerState{MarkerID: 1, CaptureFrame: 2, Position: core.Position3D{X: 11, Y: 21}, Alpha: 1}) + s.HandleTimeState(core.TimeState{CaptureFrame: 1, SystemTimeUTC: "2026-01-02T03:04:05Z", MissionDate: "2035-06-07", TimeMultiplier: 1, MissionTime: 123}) + s.placed[7] = core.PlacedObject{ID: 7, JoinFrame: 1, ClassName: "Mine_APERS", DisplayName: "Mine", Position: core.Position3D{X: 20, Y: 30}, OwnerID: 1, Side: "WEST", MarkerIcon: "mine"} + s.placedEvents = append(s.placedEvents, core.PlacedObjectEvent{CaptureFrame: 2, PlacedID: 7, EventType: "detonated"}) + s.HandleTelemetry(core.TelemetryEvent{CaptureFrame: 1, FpsAverage: 45, Weather: core.WeatherData{Fog: .2, Overcast: .3}}) + cf, err := NewChunkFlusher(dir, 10) + require.NoError(t, err) + s.SetChunkFlusher(cf) + for frame := uint32(0); frame < 3; frame++ { + if frame == 0 { + require.NoError(t, cf.AddSoldierState(frame, SoldierStateToProto(s.soldiers[1].States[0]))) + require.NoError(t, cf.AddVehicleState(frame, VehicleStateToProto(s.vehicles[3].States[0]))) + } else if frame == 2 { + require.NoError(t, cf.AddSoldierState(frame, SoldierStateToProto(s.soldiers[1].States[1]))) + } + } + require.NoError(t, cf.FlushThrough(3)) + s.deriveProjectileData() + expected := s.ToV1JSON() + require.NoError(t, WriteV2Manifest(s, dir, cf.ChunkCount())) + got, err := ExportV2AsV1JSON(context.Background(), dir) + require.NoError(t, err) + sortMarkers := func(document map[string]any) { + markers := document["Markers"].([]any) + sort.Slice(markers, func(i, j int) bool { return mustJSON(t, markers[i]) < mustJSON(t, markers[j]) }) + } + sortMarkers(expected) + sortMarkers(got) + require.JSONEq(t, mustJSON(t, expected), mustJSON(t, got)) +} + +type cancelAfterManifestCheck struct { + context.Context + checked bool +} + +func (c *cancelAfterManifestCheck) Err() error { + if c.checked { + return context.Canceled + } + c.checked = true + return nil +} + +func TestExportV2AsV1JSONErrorsAndCancellation(t *testing.T) { + t.Run("missing manifest", func(t *testing.T) { + _, err := ExportV2AsV1JSON(context.Background(), t.TempDir()) + require.Error(t, err) + }) + t.Run("invalid manifest", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "manifest.pb"), []byte("bad"), 0600)) + _, err := ExportV2AsV1JSON(context.Background(), dir) + require.Error(t, err) + }) + t.Run("missing chunk", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, ChunkCount: 1}) + _, err := ExportV2AsV1JSON(context.Background(), dir) + require.Error(t, err) + }) + t.Run("invalid chunk", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, ChunkCount: 1}) + chunkDir := filepath.Join(dir, "chunks") + require.NoError(t, os.MkdirAll(chunkDir, 0700)) + require.NoError(t, os.WriteFile(filepath.Join(chunkDir, "0000.pb"), []byte("bad"), 0600)) + _, err := ExportV2AsV1JSON(context.Background(), dir) + require.Error(t, err) + }) + t.Run("cancel before reading manifest", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, ChunkCount: 1}) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := ExportV2AsV1JSON(ctx, dir) + require.ErrorIs(t, err, context.Canceled) + }) + t.Run("cancel before reading first chunk", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, ChunkCount: 1}) + ctx := &cancelAfterManifestCheck{Context: t.Context()} + _, err := ExportV2AsV1JSON(ctx, dir) + require.ErrorIs(t, err, context.Canceled) + }) + t.Run("decode manifest metadata fallback", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, FrameCount: 2, CaptureDelayMs: 125, World: &pbv2.WorldMeta{WorldName: "Altis"}, Mission: &pbv2.MissionMeta{MissionName: "Fallback"}}) + got, err := ExportV2AsV1JSON(t.Context(), dir) + require.NoError(t, err) + require.Equal(t, "Altis", got["worldName"]) + require.Equal(t, "Fallback", got["missionName"]) + require.Equal(t, float32(.125), got["captureDelay"]) + }) + t.Run("empty metadata falls back to empty defaults", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, FrameCount: 1, MetadataJson: []byte("{}")}) + got, err := ExportV2AsV1JSON(context.Background(), dir) + require.NoError(t, err) + require.Equal(t, "", got["missionName"]) + require.Equal(t, "", got["worldName"]) + }) + t.Run("unsupported version and out of range ids", func(t *testing.T) { + for name, manifest := range map[string]*pbv2.Manifest{ + "version": {Version: 1}, + "soldier": {Version: 2, Soldiers: []*pbv2.SoldierDef{{Id: 65536}}}, + "vehicle": {Version: 2, Vehicles: []*pbv2.VehicleDef{{Id: 65536}}}, + } { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, manifest) + _, err := ExportV2AsV1JSON(context.Background(), dir) + require.Error(t, err) + }) + } + }) + t.Run("missing optional snapshot", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, SnapshotUnitIds: []uint32{1}}) + got, err := ExportV2AsV1JSON(context.Background(), dir) + require.NoError(t, err) + require.Empty(t, got["events"]) + }) + t.Run("cancel before snapshot", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, SnapshotUnitIds: []uint32{1}}) + ctx := &cancelAfterManifestCheck{Context: t.Context()} + _, err := ExportV2AsV1JSON(ctx, dir) + require.ErrorIs(t, err, context.Canceled) + }) + t.Run("corrupt snapshot", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, SnapshotUnitIds: []uint32{1}}) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "snapshots"), 0700)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "snapshots", "1.pb"), []byte("bad"), 0600)) + _, err := ExportV2AsV1JSON(context.Background(), dir) + require.Error(t, err) + }) + t.Run("snapshot path is not a file", func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, SnapshotUnitIds: []uint32{1}}) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "snapshots", "1.pb"), 0700)) + _, err := ExportV2AsV1JSON(context.Background(), dir) + require.Error(t, err) + }) +} + +func TestAppendV2EventTypedVariants(t *testing.T) { + s := NewSession() + frame := uint32(4) + events := []*pbv2.Event{ + {FrameNum: frame, Event: &pbv2.Event_Radio{Radio: &pbv2.RadioEvent{SoldierId: 1, Channel: 2}}}, + {FrameNum: frame, Event: &pbv2.Event_Ace3Death{Ace3Death: &pbv2.Ace3DeathEvent{SoldierId: 1, HasDamageSource: true, LastDamageSourceId: 2}}}, + {FrameNum: frame, Event: &pbv2.Event_Ace3Unconscious{Ace3Unconscious: &pbv2.Ace3UnconsciousEvent{SoldierId: 1}}}, + {FrameNum: frame, Event: &pbv2.Event_EndMission{EndMission: &pbv2.EndMissionEvent{Side: "WEST", Message: "done"}}}, + {FrameNum: frame, Event: &pbv2.Event_Connect{Connect: &pbv2.ConnectEvent{UnitName: "Player", IsConnect: true}}}, + {FrameNum: frame, Event: &pbv2.Event_General{General: &pbv2.GeneralEvent{Name: "disconnected", Message: "123", ExtraDataJson: []byte(`{"playerUid":"synthetic-uid"}`)}}}, + {FrameNum: frame, Event: &pbv2.Event_Projectile{Projectile: &pbv2.ProjectileEvent{FirerId: 1, Trajectory: []*pbv2.TrajectoryPoint{{Position: &pbv2.Position3D{}, FrameNum: frame}}, Hits: []*pbv2.ProjectileHit{{FrameNum: frame, HitSoldier: true, SoldierId: 2}}}}}, + {FrameNum: frame, Event: &pbv2.Event_Telemetry{Telemetry: &pbv2.TelemetryEvent{FpsAverage: 30, Weather: &pbv2.WeatherData{Fog: .1}}}}, + {FrameNum: frame, Event: &pbv2.Event_General{General: &pbv2.GeneralEvent{Name: "raw", ExtraDataJson: []byte(`{"x":1}`)}}}, + {FrameNum: frame, Event: &pbv2.Event_Hit{Hit: &pbv2.HitEvent{VictimIsVehicle: true, ShooterIsVehicle: true}}}, + {FrameNum: frame, Event: &pbv2.Event_Kill{Kill: &pbv2.KillEvent{VictimIsVehicle: true, KillerIsVehicle: true}}}, + {FrameNum: frame, Event: &pbv2.Event_Chat{Chat: &pbv2.ChatEvent{Message: "chat"}}}, + } + for _, event := range events { + appendV2Event(s, event) + } + require.Len(t, s.events, 7) + require.Len(t, s.radio, 1) + require.Len(t, s.aceDeaths, 1) + require.Len(t, s.aceUnconscious, 1) + require.Empty(t, s.projectiles, "raw projectiles are not part of legacy events") + require.Len(t, s.telemetry, 1) + exported := s.ToV1JSON()["events"] + require.Contains(t, exported, []any{core.Frame(frame), "connected", "Player"}) + require.Contains(t, exported, []any{core.Frame(frame), "disconnected", "123", "synthetic-uid"}) +} + +func TestAppendV2ChunkAddsUndeclaredEntitiesAndHandlesNilPositions(t *testing.T) { + s := NewSession() + appendV2Chunk(s, &pbv2.Chunk{Frames: []*pbv2.Frame{{FrameNum: 0, Soldiers: []*pbv2.SoldierState{{Id: 4}}, Vehicles: []*pbv2.VehicleState{{Id: 5}}}}}) + require.Contains(t, s.soldiers, uint16(4)) + require.Contains(t, s.vehicles, uint16(5)) + require.Equal(t, uint16(0), s.soldiers[4].States[0].Bearing) + require.NotNil(t, s.vehicles[5].States[0].Crew) +} + +func TestAppendV2ChunkVehicleOccupancy(t *testing.T) { + s := NewSession() + appendV2Chunk(s, &pbv2.Chunk{Frames: []*pbv2.Frame{{FrameNum: 0, Soldiers: []*pbv2.SoldierState{ + {Id: 1, VehicleId: 3}, + {Id: 2, InVehicle: true, VehicleId: 4}, + {Id: 5}, + }}}}) + require.Equal(t, uint16Ptr(3), s.soldiers[1].States[0].InVehicleObjectID, "the extension sets only the vehicle id") + require.Equal(t, uint16Ptr(4), s.soldiers[2].States[0].InVehicleObjectID) + require.True(t, s.soldiers[2].States[0].InVehicle) + require.Nil(t, s.soldiers[5].States[0].InVehicleObjectID) +} + +func TestExportV2AsV1JSONPreservesManifestMarkerOrder(t *testing.T) { + dir := t.TempDir() + manifest := &pbv2.Manifest{Version: 2, FrameCount: 1} + var want []any + for i := range 12 { + text := fmt.Sprintf("marker %d", i) + manifest.Markers = append(manifest.Markers, &pbv2.MarkerDef{Text: text, Positions: []*pbv2.MarkerPosition{{Position: &pbv2.Position3D{}}}}) + want = append(want, text) + } + writeManifestFixture(t, dir, manifest) + got, err := ExportV2AsV1JSON(context.Background(), dir) + require.NoError(t, err) + var texts []any + for _, marker := range got["Markers"].([]any) { + texts = append(texts, marker.([]any)[1]) + } + require.Equal(t, want, texts) +} + +func TestExportV2AsV1JSONChunkIDValidation(t *testing.T) { + for name, frame := range map[string]*pbv2.Frame{ + "soldier": {Soldiers: []*pbv2.SoldierState{{Id: 65536}}}, + "vehicle": {Vehicles: []*pbv2.VehicleState{{Id: 65536}}}, + } { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, ChunkCount: 1}) + chunkDir := filepath.Join(dir, "chunks") + require.NoError(t, os.MkdirAll(chunkDir, 0700)) + data, err := proto.Marshal(&pbv2.Chunk{Frames: []*pbv2.Frame{frame}}) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(chunkDir, "0000.pb"), data, 0600)) + _, err = ExportV2AsV1JSON(context.Background(), dir) + require.Error(t, err) + }) + } +} + +func TestExportV2AsV1JSONEntityEndFrames(t *testing.T) { + dir := t.TempDir() + writeManifestFixture(t, dir, &pbv2.Manifest{Version: 2, FrameCount: 5, Soldiers: []*pbv2.SoldierDef{ + {Id: 1, Name: "deleted", EndFrame: 2}, + {Id: 2, Name: "active", EndFrame: 4}, + {Id: 3, Name: "deleted on first frame", EndFrame: 0}, + }}) + got, err := ExportV2AsV1JSON(context.Background(), dir) + require.NoError(t, err) + entities := got["entities"].([]any) + require.Equal(t, core.Frame(2), entities[1].(map[string]any)["endFrameNum"]) + _, hasEnd := entities[2].(map[string]any)["endFrameNum"] + require.False(t, hasEnd) + require.Equal(t, core.Frame(0), entities[3].(map[string]any)["endFrameNum"]) + session := sessionFromV2Manifest(&pbv2.Manifest{Version: 2, FrameCount: 5, Vehicles: []*pbv2.VehicleDef{{Id: 3, EndFrame: 2}, {Id: 4, EndFrame: 4}}}) + require.Equal(t, core.Frame(2), session.vehicles[3].Vehicle.DeleteFrame) + require.Zero(t, session.vehicles[4].Vehicle.DeleteFrame) +} + +func TestMarkerRecordProtoVariantsAndSideNames(t *testing.T) { + marker := markerRecordFromProto(&pbv2.MarkerDef{StartFrame: 1, DeletedFrame: proto.Uint32(3), Size: []float32{2, 4}, Positions: []*pbv2.MarkerPosition{{LineCoords: []float32{1, 2, 3, 4}}, {FrameNum: 2, Position: &pbv2.Position3D{X: 5}, Text: "changed"}}}) + require.True(t, marker.Marker.IsDeleted) + require.Len(t, marker.Marker.Polyline, 2) + require.Len(t, marker.States, 1) + for side, name := range map[pbv2.Side]string{ + pbv2.Side_SIDE_WEST: "WEST", pbv2.Side_SIDE_EAST: "EAST", pbv2.Side_SIDE_GUER: "GUER", pbv2.Side_SIDE_CIV: "CIV", pbv2.Side_SIDE_GLOBAL: "GLOBAL", pbv2.Side_SIDE_UNKNOWN: "UNKNOWN", + } { + require.Equal(t, name, protoSideName(side)) + } +} + +func TestPointerIDHelpersPreserveVariants(t *testing.T) { + id := uint(7) + require.Equal(t, &id, ptrIfVehicle(id, true)) + require.Nil(t, ptrIfVehicle(id, false)) + require.Equal(t, &id, ptrUnlessVehicle(id, false)) + require.Nil(t, ptrUnlessVehicle(id, true)) +} + +func writeManifestFixture(t *testing.T, dir string, m *pbv2.Manifest) { + t.Helper() + data, err := proto.Marshal(m) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(dir, "manifest.pb"), data, 0600)) +} + +func uintPtr(v uint) *uint { return &v } +func uint16Ptr(v uint16) *uint16 { return &v } + +func mustJSON(t *testing.T, value any) string { + t.Helper() + data, err := json.Marshal(value) + require.NoError(t, err) + return string(data) +} diff --git a/internal/ingestion/extra_events.go b/internal/ingestion/extra_events.go index a54f80eed..73d108ee3 100644 --- a/internal/ingestion/extra_events.go +++ b/internal/ingestion/extra_events.go @@ -37,7 +37,7 @@ func (s *Session) hasGeneralEvent(name string) bool { func (s *Session) appendExtraV1Events(events []any) []any { // The addon emits native serverFps/weather general events when its tracking // is on. Telemetry-derived samples are only a fallback for when they are - // absent, otherwise the v1 backup reports each reading twice. + // absent, otherwise the v1 export reports each reading twice. hasNativeFps := s.hasGeneralEvent("serverFps") hasNativeWeather := s.hasGeneralEvent("weather") for _, e := range s.radio { diff --git a/internal/ingestion/session.go b/internal/ingestion/session.go index c2184d114..2b89174c2 100644 --- a/internal/ingestion/session.go +++ b/internal/ingestion/session.go @@ -1,5 +1,5 @@ -// Package ingestion accumulates streaming mission data and produces -// v1 JSON recordings for the conversion pipeline. +// Package ingestion accumulates streaming missions for protobuf storage and +// exports legacy v1 JSON. package ingestion import ( @@ -7,10 +7,12 @@ import ( "encoding/json" "fmt" "io" + "maps" "math" "os" "path/filepath" "regexp" + "slices" "sort" "strings" "time" @@ -931,6 +933,12 @@ func (s *Session) eventsToV1() []any { default: if e.general != nil { switch e.eventType { + case "connected", "disconnected": + event := []any{e.general.CaptureFrame, e.eventType, e.general.Message} + if uid := stringFromExtra(e.general.ExtraData, "playerUid"); uid != "" { + event = append(event, uid) + } + events = append(events, event) case "endMission": events = append(events, []any{e.frame, "endMission", []any{stringFromExtra(e.general.ExtraData, "side"), e.general.Message}}) case "captured", "contested": @@ -968,7 +976,8 @@ func (s *Session) eventsToV1() []any { func (s *Session) markersToV1() []any { markers := make([]any, 0, len(s.markers)) - for _, rec := range s.markers { + for _, name := range slices.Sorted(maps.Keys(s.markers)) { + rec := s.markers[name] m := rec.Marker posArray := make([][]any, 0, 1+len(rec.States)) diff --git a/internal/ingestion/writer_v2.go b/internal/ingestion/writer_v2.go index 7e12fe7bb..6ccbbe927 100644 --- a/internal/ingestion/writer_v2.go +++ b/internal/ingestion/writer_v2.go @@ -3,7 +3,6 @@ package ingestion import ( "encoding/json" "fmt" - "os" "path/filepath" "sort" "strings" @@ -11,12 +10,13 @@ import ( "google.golang.org/protobuf/proto" "github.com/OCAP2/extension/v5/pkg/core" + "github.com/OCAP2/web/internal/storage" pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" ) const defaultChunkSize = 300 -// WriteV2Manifest writes the v2 protobuf manifest and a JSON archive from session data. +// WriteV2Manifest writes the v2 protobuf manifest from session data. // Chunks are expected to have been written already by the ChunkFlusher. func WriteV2Manifest(session *Session, outputDir string, chunkCount uint32) error { manifest := buildManifest(session, chunkCount) @@ -33,15 +33,6 @@ func WriteV2Manifest(session *Session, outputDir string, chunkCount uint32) erro return fmt.Errorf("write manifest.pb: %w", err) } - // Write JSON archive for debugging. - jsonData, err := json.MarshalIndent(manifestToJSON(manifest), "", " ") - if err != nil { - return fmt.Errorf("marshal JSON archive: %w", err) - } - if err := os.WriteFile(filepath.Join(outputDir, "manifest.json"), jsonData, 0644); err != nil { - return fmt.Errorf("write manifest.json: %w", err) - } - return nil } @@ -465,7 +456,7 @@ func sideStringToProto(s string) pbv2.Side { func captureDelayMs(session *Session) uint32 { if session.mission != nil && session.mission.CaptureDelay > 0 { - return uint32(session.mission.CaptureDelay * 1000) + return storage.CaptureDelayMillis(float64(session.mission.CaptureDelay)) } return 1000 } @@ -538,59 +529,6 @@ func parseMarkerSizeF32(sizeStr string) []float32 { return f32 } -// manifestToJSON creates a JSON-serializable representation of the manifest for debugging. -func manifestToJSON(m *pbv2.Manifest) map[string]any { - result := map[string]any{ - "version": m.Version, - "frameCount": m.FrameCount, - "chunkSize": m.ChunkSize, - "captureDelayMs": m.CaptureDelayMs, - "chunkCount": m.ChunkCount, - } - - if m.World != nil { - result["world"] = map[string]any{ - "worldName": m.World.WorldName, - "worldSize": m.World.WorldSize, - "latitude": m.World.Latitude, - "longitude": m.World.Longitude, - "author": m.World.Author, - "displayName": m.World.DisplayName, - } - } - - if m.Mission != nil { - mission := map[string]any{ - "missionName": m.Mission.MissionName, - "briefingName": m.Mission.BriefingName, - "author": m.Mission.Author, - "serverName": m.Mission.ServerName, - "extensionVersion": m.Mission.ExtensionVersion, - "addonVersion": m.Mission.AddonVersion, - "extensionBuild": m.Mission.ExtensionBuild, - "tag": m.Mission.Tag, - } - if m.Mission.PlayableSlots != nil { - mission["playableSlots"] = m.Mission.PlayableSlots - } - if m.Mission.SideFriendly != nil { - mission["sideFriendly"] = m.Mission.SideFriendly - } - if len(m.Mission.Addons) > 0 { - mission["addons"] = m.Mission.Addons - } - result["mission"] = mission - } - - result["soldierCount"] = len(m.Soldiers) - result["vehicleCount"] = len(m.Vehicles) - result["eventCount"] = len(m.Events) - result["markerCount"] = len(m.Markers) - result["timeCount"] = len(m.Times) - - return result -} - // telemetryToProtoEvent converts a core.TelemetryEvent to a v2 proto Event. func telemetryToProtoEvent(te core.TelemetryEvent) *pbv2.Event { t := &pbv2.TelemetryEvent{ diff --git a/internal/ingestion/writer_v2_test.go b/internal/ingestion/writer_v2_test.go index 15ebb363a..9d815dac3 100644 --- a/internal/ingestion/writer_v2_test.go +++ b/internal/ingestion/writer_v2_test.go @@ -203,10 +203,21 @@ func TestWriteV2Manifest_Roundtrip(t *testing.T) { require.Len(t, manifest.Times, 1) assert.Equal(t, "2025-01-15T10:30:00Z", manifest.Times[0].SystemTimeUtc) - // Verify JSON archive also exists. - jsonData, err := os.ReadFile(filepath.Join(dir, "manifest.json")) - require.NoError(t, err) - assert.Contains(t, string(jsonData), "Test Mission") + assert.NoFileExists(t, filepath.Join(dir, "manifest.json")) +} + +func TestBuildManifestCaptureDelayMillisRounding(t *testing.T) { + for _, test := range []struct { + seconds float32 + want uint32 + }{ + {seconds: 1.001, want: 1001}, + {seconds: 0.251, want: 251}, + } { + session := NewSession() + session.SetMission(&core.Mission{CaptureDelay: test.seconds}, &core.World{}) + assert.Equal(t, test.want, buildManifest(session, 1).CaptureDelayMs) + } } func TestSoldierStateToProto(t *testing.T) { diff --git a/internal/maptool/jobmanager_test.go b/internal/maptool/jobmanager_test.go index 0f58dc7c7..f72edf722 100644 --- a/internal/maptool/jobmanager_test.go +++ b/internal/maptool/jobmanager_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "testing" + "testing/synctest" "time" "github.com/stretchr/testify/assert" @@ -69,24 +70,26 @@ func TestJobManager_ListJobs_WithItems(t *testing.T) { } func TestJobManager_SubmitFunc(t *testing.T) { - jm := NewJobManager(t.TempDir(), func() *Pipeline { return noopPipeline() }) - go jm.Start(context.Background()) - defer jm.Stop() - - called := false - snap, err := jm.SubmitFunc("test-1", "restyle", func(ctx context.Context, job *Job) error { - called = true - return nil + synctest.Test(t, func(t *testing.T) { + jm := NewJobManager(t.TempDir(), func() *Pipeline { return noopPipeline() }) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + go jm.Start(ctx) + + called := false + snap, err := jm.SubmitFunc("test-1", "restyle", func(ctx context.Context, job *Job) error { + called = true + return nil + }) + require.NoError(t, err) + assert.Equal(t, "restyle", snap.WorldName) + + synctest.Wait() + assert.True(t, called) + got := jm.GetJob("test-1") + require.NotNil(t, got) + assert.Equal(t, StatusDone, got.Status) }) - require.NoError(t, err) - assert.Equal(t, "restyle", snap.WorldName) - - time.Sleep(500 * time.Millisecond) - - assert.True(t, called) - got := jm.GetJob("test-1") - require.NotNil(t, got) - assert.Equal(t, StatusDone, got.Status) } func TestJobManager_SubmitFunc_Error(t *testing.T) { diff --git a/internal/server/coverage_extra_test.go b/internal/server/coverage_extra_test.go index 5223a8dbc..eab777606 100644 --- a/internal/server/coverage_extra_test.go +++ b/internal/server/coverage_extra_test.go @@ -913,7 +913,9 @@ func TestHandlerStream_100PercentCoverage(t *testing.T) { sessDone.SetMission(&core.Mission{MissionName: "EndBad", CaptureDelay: 1}, &core.World{WorldName: "altis"}) ownerC := &streamConn{} ssEnd := &streamSession{session: sessDone, owner: ownerC, outputDir: filepath.Join(dir, "endbad"), counts: map[string]int{"x": 1}} - require.NoError(t, os.MkdirAll(ssEnd.outputDir, 0755)) + flusher, err := ingestion.NewChunkFlusher(ssEnd.outputDir, 300) + require.NoError(t, err) + sessDone.SetChunkFlusher(flusher) assert.Equal(t, endSaved, h.endStream(ssEnd, ownerC, streaming.Envelope{Type: streaming.TypeEndMission, Payload: json.RawMessage(`{bad`)})) // startStream reserve timeout (280) & discardStreamed reserve timeout (693) & discardStreamed retry exhaustion (713) @@ -1000,6 +1002,9 @@ func TestHandlerStream_100PercentCoverage(t *testing.T) { repoOperation: h.repoOperation, conversionTrigger: &mockConvTrigger{}, } + assert.ErrorContains(t, hV1.finalizeSession(sessV1, "", filepath.Join(t.TempDir(), "native"), 0), "has no chunk flusher") + missingData := &Handler{setting: Setting{Data: filepath.Join(t.TempDir(), "missing")}} + assert.ErrorContains(t, missingData.finalizeSession(sessV1, "", "", 0), "write JSON.gz") // v2OutputDir == "" + FocusRanges non-empty + conversionTrigger != nil -> hits 925, 967-970, 1010! assert.NoError(t, hV1.finalizeSession(sessV1, "", "", 0)) diff --git a/internal/server/handler.go b/internal/server/handler.go index c73802d99..1e53f1385 100644 --- a/internal/server/handler.go +++ b/internal/server/handler.go @@ -556,6 +556,9 @@ func (h *Handler) GetData(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(relativePath, ".json.gz") { f, err := os.Open(absolutePath) if err != nil { + if os.IsNotExist(err) && h.serveV2AsV1Download(w, r, relativePath) { + return + } http.NotFound(w, r) return } diff --git a/internal/server/handler_stream.go b/internal/server/handler_stream.go index 8ce19d94f..02e1b0c96 100644 --- a/internal/server/handler_stream.go +++ b/internal/server/handler_stream.go @@ -333,7 +333,7 @@ func (h *Handler) startStream(envelope streaming.Envelope, conn *streamConn) (*s if err := os.MkdirAll(h.setting.Data, 0755); err != nil { return refuse("streaming storage unavailable") } - // Allocate one unique key for the row, v2 directory and legacy backup. + // Allocate one unique key for the operation and its protobuf artifacts. output, err := streamMkdirTemp(h.setting.Data, ingestion.MakeFilename(payload.Mission.MissionName)+"_*") if err != nil { return refuse("streaming storage unavailable") @@ -897,7 +897,7 @@ func withPartialTag(tag string) string { return tag + ",partial" } -// finalizeSession writes v2 protobuf + v1 JSON, stores an Operation, and triggers conversion. +// finalizeSession writes the recording and publishes its completed operation. // If streamingOpID > 0, updates the existing "streaming" row instead of inserting a new one. func (h *Handler) finalizeSession(session *ingestion.Session, tag string, v2OutputDir string, streamingOpID int64) error { if h.setting.Data == "" { @@ -928,20 +928,19 @@ func (h *Handler) finalizeSession(session *ingestion.Session, tag string, v2Outp if v2OutputDir == "" { filename = ingestion.MakeFilename(missionName) } - if err := session.WriteJSONGzNamed(h.setting.Data, filename); err != nil { - return fmt.Errorf("write JSON.gz: %w", err) - } - // Write v2 protobuf (manifest + finalize chunks). var chunkCount int - hasV2 := session.ChunkFlusher() != nil && v2OutputDir != "" + hasV2 := v2OutputDir != "" if hasV2 { + if session.ChunkFlusher() == nil { + return errors.New("native v2 session has no chunk flusher") + } if err := session.Finalize(v2OutputDir); err != nil { - slog.Error("stream: v2 finalization failed, falling back to v1 only", "error", err) - hasV2 = false - } else { - chunkCount = int(session.ChunkFlusher().ChunkCount()) + return fmt.Errorf("finalize v2 recording: %w", err) } + chunkCount = int(session.ChunkFlusher().ChunkCount()) + } else if err := session.WriteJSONGzNamed(h.setting.Data, filename); err != nil { + return fmt.Errorf("write JSON.gz: %w", err) } storageFormat := "json" @@ -949,7 +948,6 @@ func (h *Handler) finalizeSession(session *ingestion.Session, tag string, v2Outp conversionStatus := ConversionStatusPending if hasV2 { - filename = filepath.Base(v2OutputDir) storageFormat = "protobuf" schemaVersion = uint32(storage.SchemaVersionV2) conversionStatus = ConversionStatusCompleted // v2 is already in final format diff --git a/internal/server/handler_stream_resume_test.go b/internal/server/handler_stream_resume_test.go index 7f4b6797e..8b41b4c25 100644 --- a/internal/server/handler_stream_resume_test.go +++ b/internal/server/handler_stream_resume_test.go @@ -3,10 +3,12 @@ package server import ( "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "os" "path/filepath" + "runtime/pprof" "strings" "sync" "testing" @@ -819,10 +821,10 @@ func TestStreamResume_EndNotAcknowledgedBeforeSaveSucceeds(t *testing.T) { last := sendStates(t, c, 2, 1, 3) rh.waitSeq("m-slow", last) - // The save is slow, then fails: a directory blocks the legacy backup. + // The save is slow, then fails: a nonempty directory blocks the protobuf manifest. ops := rh.ops() require.Len(t, ops, 1) - require.NoError(t, os.Mkdir(filepath.Join(rh.dir, ops[0].Filename+".json.gz"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(rh.dir, ops[0].Filename, "manifest.pb", "blocked"), 0o755)) release := make(chan struct{}) var releaseOnce sync.Once unblock := func() { releaseOnce.Do(func() { close(release) }) } @@ -926,6 +928,31 @@ func TestStreamResume_ConcurrentRepeatedStartsShareOneSession(t *testing.T) { readUntil(t, second, isAckFor(streaming.TypeEndMission)) } +func TestStreamRecoveryLeakProfile(t *testing.T) { + if os.Getenv("OCAP_STREAM_LEAK_PROFILE") != "1" { + t.Skip("set OCAP_STREAM_LEAK_PROFILE=1 to print a goroutine leak diagnostic") + } + + rh := newResumeHarness(t, time.Minute) + for i := 0; i < 3; i++ { + missionID := fmt.Sprintf("leak-profile-%d", i) + first := rh.dial() + startResumable(t, first, "Leak Profile", missionID, "profile-producer") + first.Close() + + resumed := rh.dial() + sendEnv(t, resumed, streaming.TypeResume, 0, streaming.ResumePayload{MissionID: missionID, ProducerID: "profile-producer"}) + ack := readUntil(t, resumed, isType(streaming.ServerResumeOK)) + sendEnv(t, resumed, streaming.TypeDiscardMission, ack.Seq+1, nil) + readUntil(t, resumed, isAckFor(streaming.TypeDiscardMission)) + require.Zero(t, rh.h.streamRegistry().activeCount()) + } + + profile := pprof.Lookup("goroutineleak") + require.NotNil(t, profile, "Go 1.27 should expose the goroutine leak profile") + require.NoError(t, profile.WriteTo(os.Stderr, 1)) +} + func TestStreamRegistryReserveWaitsForConcurrentStart(t *testing.T) { synctest.Test(t, func(t *testing.T) { const wait = time.Second diff --git a/internal/server/handler_stream_test.go b/internal/server/handler_stream_test.go index bc8bcb821..c22b07353 100644 --- a/internal/server/handler_stream_test.go +++ b/internal/server/handler_stream_test.go @@ -14,7 +14,6 @@ import ( "testing/synctest" "time" - "github.com/OCAP2/extension/v5/pkg/streaming" "github.com/OCAP2/web/internal/storage" pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" "github.com/go-fuego/fuego" @@ -50,6 +49,45 @@ func TestSendStreamPings_StopsOnWriteError(t *testing.T) { }) } +func TestSendStreamPings_StopsWhenDoneCloses(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + const interval = 30 * time.Second + done := make(chan struct{}) + pings := make(chan struct{}, 4) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + sendStreamPings(done, interval, func() error { + pings <- struct{}{} + return nil + }) + }() + + synctest.Wait() + synctest.Sleep(interval) + select { + case <-pings: + default: + t.Fatal("the loop should send a ping at its first interval") + } + + close(done) + synctest.Wait() + select { + case <-stopped: + default: + t.Fatal("the loop should stop after done closes") + } + + synctest.Sleep(2 * interval) + select { + case <-pings: + t.Fatal("the stopped loop must not send another ping") + default: + } + }) +} + func TestHandleStream_InvalidStartMetadata(t *testing.T) { for _, payload := range []string{`null`, `{}`, `{"mission":null,"world":{}}`, `{"mission":{"MissionName":"Bad","CaptureDelay":0},"world":{"WorldName":"altis"}}`} { t.Run(payload, func(t *testing.T) { @@ -81,8 +119,8 @@ func TestHandleStream_FinalizationFailureIsNotAcknowledged(t *testing.T) { ops, err := h.repoOperation.Select(context.Background(), Filter{}) require.NoError(t, err) require.Len(t, ops, 1) - // A directory blocks atomic publication of the legacy backup. - require.NoError(t, os.Mkdir(filepath.Join(dir, ops[0].Filename+".json.gz"), 0755)) + // A nonempty directory blocks atomic publication of the protobuf manifest. + require.NoError(t, os.MkdirAll(filepath.Join(dir, ops[0].Filename, "manifest.pb", "blocked"), 0755)) require.NoError(t, c.WriteJSON(map[string]string{"type": "end_mission"})) c.SetReadDeadline(time.Now().Add(time.Second)) _, _, err = c.ReadMessage() @@ -92,7 +130,7 @@ func TestHandleStream_FinalizationFailureIsNotAcknowledged(t *testing.T) { require.Equal(t, ConversionStatusFailed, stored.ConversionStatus) } -func TestHandleStream_V2FailurePreservesLegacyFallback(t *testing.T) { +func TestHandleStream_V2FailureLeavesNoLegacyRecording(t *testing.T) { h, mux, dir := newTestStreamHandlerWithRepo(t) srv := httptest.NewServer(mux) defer srv.Close() @@ -107,16 +145,15 @@ func TestHandleStream_V2FailurePreservesLegacyFallback(t *testing.T) { require.NoError(t, os.Rename(chunkDir, chunkDir+".unavailable")) require.NoError(t, os.WriteFile(chunkDir, []byte("blocked"), 0600)) require.NoError(t, c.WriteJSON(map[string]string{"type": "end_mission"})) - var ack streaming.AckMessage - require.NoError(t, c.ReadJSON(&ack)) - require.Equal(t, "end_mission", ack.For) + require.NoError(t, c.SetReadDeadline(time.Now().Add(time.Second))) + _, _, err = c.ReadMessage() + require.True(t, websocket.IsCloseError(err, websocket.CloseInternalServerErr), "%v", err) stored, err := h.repoOperation.GetByFilename(context.Background(), ops[0].Filename) require.NoError(t, err) - require.Equal(t, "json", stored.StorageFormat) - require.Equal(t, uint32(1), stored.SchemaVersion) - require.Equal(t, ConversionStatusCompleted, stored.ConversionStatus) - _, err = storage.NewJSONEngine(dir).GetManifest(context.Background(), stored.Filename) - require.NoError(t, err) + require.Equal(t, "protobuf", stored.StorageFormat) + require.Equal(t, uint32(storage.SchemaVersionV2), stored.SchemaVersion) + require.Equal(t, ConversionStatusFailed, stored.ConversionStatus) + require.NoFileExists(t, filepath.Join(dir, stored.Filename+".json.gz")) } func newTestStreamHandler(enabled bool) (*Handler, *http.ServeMux) { @@ -499,18 +536,6 @@ func TestHandleStream_FullLifecycle(t *testing.T) { conn.ReadJSON(&ack) require.Equal(t, "end_mission", ack["for"]) - // Verify a .json.gz file was written - files, _ := filepath.Glob(filepath.Join(dir, "*.json.gz")) - require.Len(t, files, 1, "expected a legacy JSON backup to be written") - backupName := strings.TrimSuffix(filepath.Base(files[0]), ".json.gz") - legacy, err := storage.NewJSONEngine(dir).GetManifest(context.Background(), backupName) - require.NoError(t, err) - assert.Equal(t, "Lifecycle Test", legacy.MissionName) - // Legacy JSON uses entity IDs as array indexes, including empty slots. - require.Len(t, legacy.Entities, 2) - assert.Equal(t, uint32(1), legacy.Entities[1].ID) - assert.Equal(t, "TestPlayer", legacy.Entities[1].Name) - // Verify operation was stored in DB ops, err := hdlr.repoOperation.Select(context.Background(), Filter{}) require.NoError(t, err) @@ -524,6 +549,8 @@ func TestHandleStream_FullLifecycle(t *testing.T) { assert.Equal(t, 1, op.PlayerCount) assert.Equal(t, 1, op.SideComposition["WEST"].Players) assert.FileExists(t, filepath.Join(dir, op.Filename, "manifest.pb")) + assert.NoFileExists(t, filepath.Join(dir, op.Filename, "manifest.json")) + assert.NoFileExists(t, filepath.Join(dir, op.Filename+".json.gz")) // Upstream's revision-based backfill must not replace freshly finalized stats. backfill, err := hdlr.repoOperation.SelectStatsBackfill(context.Background()) @@ -532,7 +559,7 @@ func TestHandleStream_FullLifecycle(t *testing.T) { } func TestHandleStream_CrashDisconnectFinalizes(t *testing.T) { - _, e, dir := newTestStreamHandlerWithRepo(t) + h, e, dir := newTestStreamHandlerWithRepo(t) srv := httptest.NewServer(e) defer srv.Close() @@ -558,10 +585,14 @@ func TestHandleStream_CrashDisconnectFinalizes(t *testing.T) { // Simulate crash: just close without end_mission conn.Close() - // Give server time to detect close and finalize - time.Sleep(200 * time.Millisecond) - - // Verify a file was written (partial data) - files, _ := filepath.Glob(filepath.Join(dir, "*.json.gz")) - assert.NotEmpty(t, files, "expected partial .json.gz file after crash disconnect") + // A legacy producer disconnect still publishes a partial protobuf recording. + require.Eventually(t, func() bool { + ops, err := h.repoOperation.Select(context.Background(), Filter{}) + return err == nil && len(ops) == 1 && ops[0].ConversionStatus == ConversionStatusCompleted + }, time.Second, time.Millisecond) + ops, err := h.repoOperation.Select(context.Background(), Filter{}) + require.NoError(t, err) + require.Len(t, ops, 1) + require.FileExists(t, filepath.Join(dir, ops[0].Filename, "manifest.pb")) + require.NoFileExists(t, filepath.Join(dir, ops[0].Filename+".json.gz")) } diff --git a/internal/server/operation.go b/internal/server/operation.go index cd5ba36c6..75921cf88 100644 --- a/internal/server/operation.go +++ b/internal/server/operation.go @@ -293,6 +293,15 @@ func (r *RepoOperation) migration() (err error) { } } + if version < 16 { + if err = r.runMigration(16, + `CREATE INDEX IF NOT EXISTS idx_operations_date ON operations(date)`, + `CREATE INDEX IF NOT EXISTS idx_operations_conversion_status_id ON operations(conversion_status, id)`, + ); err != nil { + return err + } + } + return nil } @@ -642,6 +651,7 @@ func (r *RepoOperation) Select(ctx context.Context, filter Filter) ([]Operation, AND date <= $2 AND date >= $3 AND tag LIKE '%' || $4 || '%' + ORDER BY id ASC ` rows, err := r.db.QueryContext( ctx, @@ -691,6 +701,9 @@ func (*RepoOperation) scan(ctx context.Context, rows *sql.Rows) ([]Operation, er o.SideComposition = unmarshalSideComposition(sideRaw) ops = append(ops, o) } + if err := rows.Err(); err != nil { + return nil, err + } return ops, nil } diff --git a/internal/server/operation_indexes_test.go b/internal/server/operation_indexes_test.go new file mode 100644 index 000000000..3945c7d2e --- /dev/null +++ b/internal/server/operation_indexes_test.go @@ -0,0 +1,106 @@ +package server + +import ( + "context" + "database/sql" + "errors" + "path/filepath" + "strconv" + "testing" + + "github.com/mattn/go-sqlite3" + "github.com/stretchr/testify/require" +) + +func TestMigrationV16OperationsIndexes(t *testing.T) { + path := filepath.Join(t.TempDir(), "operations.db") + repo, err := NewRepoOperation(path) + require.NoError(t, err) + _, err = repo.db.Exec(` + DELETE FROM version WHERE db = 16; + DROP INDEX idx_operations_date; + DROP INDEX idx_operations_conversion_status_id; + WITH RECURSIVE ids(id) AS ( + SELECT 1 UNION ALL SELECT id + 1 FROM ids WHERE id < 4096 + ) + INSERT INTO operations (world_name, mission_name, mission_duration, filename, date, tag, conversion_status) + SELECT 'altis', 'Mission ' || id, 100, 'recording-' || id, + date('2010-01-01', '+' || (4096 - id) || ' days'), 'TvT', + CASE WHEN id % 128 = 0 THEN 'pending' ELSE 'completed' END + FROM ids; + CREATE TRIGGER block_v16 BEFORE INSERT ON version WHEN NEW.db = 16 + BEGIN SELECT RAISE(ABORT, 'blocked migration'); END; + `) + require.NoError(t, err) + require.ErrorContains(t, repo.migration(), "blocked migration") + var count int + require.NoError(t, repo.db.QueryRow("SELECT count(*) FROM sqlite_master WHERE name IN ('idx_operations_date', 'idx_operations_conversion_status_id')").Scan(&count)) + require.Zero(t, count) + _, err = repo.db.Exec("DROP TRIGGER block_v16") + require.NoError(t, err) + require.NoError(t, repo.Close()) + + repo, err = NewRepoOperation(path) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, repo.Close()) }) + require.NoError(t, repo.db.QueryRow("SELECT MAX(db) FROM version").Scan(&count)) + require.Equal(t, 16, count) + _, err = repo.db.Exec("ANALYZE") + require.NoError(t, err) + + ctx := context.Background() + date := "2010-01-01" + missions, err := repo.Select(ctx, Filter{Name: "sion 409", Older: date, Newer: date, Tag: "v"}) + require.NoError(t, err) + require.Len(t, missions, 1) + require.EqualValues(t, 4096, missions[0].ID) + all, err := repo.Select(ctx, Filter{}) + require.NoError(t, err) + require.Len(t, all, 4096) + require.Equal(t, "recording-1", all[0].Filename) + require.Equal(t, "recording-4096", all[len(all)-1].Filename) + pending, err := repo.SelectPending(ctx, 3) + require.NoError(t, err) + require.Len(t, pending, 3) + for i, mission := range pending { + require.Equal(t, "recording-"+strconv.Itoa((i+1)*128), mission.Filename) + } + + var id, parent, unused int + var plan string + require.NoError(t, repo.db.QueryRow(`EXPLAIN QUERY PLAN SELECT id FROM operations + WHERE date >= ? AND date <= ? ORDER BY id`, date, date).Scan(&id, &parent, &unused, &plan)) + require.Contains(t, plan, "SEARCH operations USING COVERING INDEX idx_operations_date") + require.NoError(t, repo.db.QueryRow(`EXPLAIN QUERY PLAN SELECT id FROM operations + WHERE conversion_status = 'pending' ORDER BY id LIMIT 3`).Scan(&id, &parent, &unused, &plan)) + require.Contains(t, plan, "SEARCH operations USING COVERING INDEX idx_operations_conversion_status_id") +} + +func TestScanRejectsPartialResultsAfterIterationError(t *testing.T) { + db, err := sql.Open("sqlite3", ":memory:") + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, db.Close()) }) + db.SetMaxOpenConns(1) + ctx := context.Background() + conn, err := db.Conn(ctx) + require.NoError(t, err) + require.NoError(t, conn.Raw(func(driverConn any) error { + return driverConn.(*sqlite3.SQLiteConn).RegisterFunc("read_id", func(id int64) (int64, error) { + if id == 2 { + return 0, errors.New("operation read failed") + } + return id, nil + }, false) + })) + require.NoError(t, conn.Close()) + rows, err := db.QueryContext(ctx, ` + SELECT read_id(1), 'altis', 'first', 10, 'first-file', '2026-01-01', '', '', '', 0, 0, 0, 0, '', 0, NULL, NULL + UNION ALL + SELECT read_id(2), 'altis', 'second', 10, 'second-file', '2026-01-01', '', '', '', 0, 0, 0, 0, '', 0, NULL, NULL + `) + require.NoError(t, err) + defer rows.Close() + missions, err := (&RepoOperation{}).scan(ctx, rows) + require.ErrorContains(t, err, "operation read failed") + require.Nil(t, missions) +} diff --git a/internal/server/operation_test.go b/internal/server/operation_test.go index 5cdec7a47..4ccbc605b 100644 --- a/internal/server/operation_test.go +++ b/internal/server/operation_test.go @@ -522,7 +522,7 @@ func TestMigrationRerun(t *testing.T) { var version int err = repo2.db.QueryRow("SELECT db FROM version ORDER BY db DESC LIMIT 1").Scan(&version) assert.NoError(t, err) - assert.Equal(t, 15, version) + assert.Equal(t, 16, version) } func TestMigrationV10NormalizeWorldName(t *testing.T) { @@ -630,7 +630,7 @@ func TestMigrationV11DecodeFilenames(t *testing.T) { // Version recorded. var version int require.NoError(t, repo2.db.QueryRow(`SELECT MAX(db) FROM version`).Scan(&version)) - assert.Equal(t, 15, version) + assert.Equal(t, 16, version) } func TestDecodeFilename(t *testing.T) { @@ -967,7 +967,7 @@ func TestMigrationV11_DBCollisionSkipped(t *testing.T) { // Version still bumped. var version int require.NoError(t, repo2.db.QueryRow(`SELECT MAX(db) FROM version`).Scan(&version)) - assert.Equal(t, 15, version) + assert.Equal(t, 16, version) } func TestMigrationV11_FilesystemCollisionSkipped(t *testing.T) { diff --git a/internal/server/recording_download.go b/internal/server/recording_download.go new file mode 100644 index 000000000..07ee4c87a --- /dev/null +++ b/internal/server/recording_download.go @@ -0,0 +1,80 @@ +package server + +import ( + "bytes" + "compress/gzip" + "encoding/json" + jsonv2 "encoding/json/v2" + "errors" + "log/slog" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "github.com/OCAP2/web/internal/ingestion" + "github.com/OCAP2/web/internal/storage" +) + +// v2DownloadSlots bounds concurrent v2-to-v1 exports. Each export rebuilds the +// whole legacy document in memory, so parallel downloads of a long mission +// could exhaust the process. The slot is released before the response is sent. +var v2DownloadSlots = make(chan struct{}, 1) + +// v2DownloadTestHooks.beforeWait runs before a download waits for an export slot. +var v2DownloadTestHooks struct{ beforeWait func() } + +func (h *Handler) serveV2AsV1Download(w http.ResponseWriter, r *http.Request, urlPath string) bool { + filename := strings.TrimSuffix(strings.TrimPrefix(urlPath, "/"), ".json.gz") + if h.repoOperation == nil || isInvalidStorageName(filename) { + return false + } + op, err := h.repoOperation.GetByFilename(r.Context(), filename) + if err != nil || op.StorageFormat != "protobuf" || op.SchemaVersion != uint32(storage.SchemaVersionV2) || op.ConversionStatus != ConversionStatusCompleted { + return false + } + + recordingDir := filepath.Join(h.setting.Data, filename) + if _, err := os.Stat(filepath.Join(recordingDir, "manifest.pb")); err != nil { + return false + } + if r.Method == http.MethodHead { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Encoding", "gzip") + w.WriteHeader(http.StatusOK) + return true + } + + if hook := v2DownloadTestHooks.beforeWait; hook != nil { + hook() + } + select { + case v2DownloadSlots <- struct{}{}: + case <-r.Context().Done(): + return true // the client is gone + } + compressed, err := exportV2AsV1Gzip(r, recordingDir) + <-v2DownloadSlots + if err != nil { + slog.Warn("cannot generate recording download", "recording", filename, "error", err) + http.Error(w, "recording download unavailable", http.StatusInternalServerError) + return true + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Encoding", "gzip") + http.ServeContent(w, r, filename+".json.gz", time.Time{}, bytes.NewReader(compressed)) + return true +} + +func exportV2AsV1Gzip(r *http.Request, recordingDir string) ([]byte, error) { + export, err := ingestion.ExportV2AsV1JSON(r.Context(), recordingDir) + if err != nil { + return nil, err + } + var compressed bytes.Buffer + encoder := gzip.NewWriter(&compressed) + encodeErr := jsonv2.MarshalWrite(encoder, export, json.DefaultOptionsV1()) + err = errors.Join(encodeErr, encoder.Close()) // Close flushes the gzip trailer + return compressed.Bytes(), err +} diff --git a/internal/server/recording_download_test.go b/internal/server/recording_download_test.go new file mode 100644 index 000000000..9157550c6 --- /dev/null +++ b/internal/server/recording_download_test.go @@ -0,0 +1,39 @@ +package server + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/OCAP2/web/internal/storage" + "github.com/stretchr/testify/require" +) + +func TestServeV2AsV1DownloadStopsWaitingWhenClientLeaves(t *testing.T) { + h, _, dir := newTestStreamHandlerWithRepo(t) + op := &Operation{ + WorldName: "altis", MissionName: "Queued export", Filename: "queued", Date: "2026-01-02", + StorageFormat: "protobuf", SchemaVersion: uint32(storage.SchemaVersionV2), ConversionStatus: ConversionStatusCompleted, + } + require.NoError(t, h.repoOperation.Store(t.Context(), op)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, op.Filename), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, op.Filename, "manifest.pb"), nil, 0o644)) + + // Another export holds the only slot. + v2DownloadSlots <- struct{}{} + defer func() { <-v2DownloadSlots }() + + // The client leaves once its request is queued, after the recording lookup. + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + v2DownloadTestHooks.beforeWait = cancel + defer func() { v2DownloadTestHooks.beforeWait = nil }() + rec := httptest.NewRecorder() + req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/data/queued.json.gz", nil) + require.True(t, h.serveV2AsV1Download(rec, req, "/queued.json.gz")) + require.Empty(t, rec.Body.Bytes(), "nothing is exported for a client that left") + require.Empty(t, rec.Header().Get("Content-Encoding")) +} diff --git a/internal/server/route_access_test.go b/internal/server/route_access_test.go index 460ae5439..2d1ace004 100644 --- a/internal/server/route_access_test.go +++ b/internal/server/route_access_test.go @@ -1,6 +1,8 @@ package server import ( + "compress/gzip" + "encoding/json" "net/http" "net/http/httptest" "os" @@ -9,6 +11,9 @@ import ( "testing" "time" + "github.com/OCAP2/extension/v5/pkg/core" + "github.com/OCAP2/web/internal/ingestion" + "github.com/OCAP2/web/internal/storage" "github.com/go-fuego/fuego" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -77,4 +82,73 @@ func TestRecordingRouteAccess(t *testing.T) { _, err = repo.GetByID(t.Context(), operationID) assert.NoError(t, err, "viewer request must preserve the recording row") assert.FileExists(t, recordingPath, "viewer request must preserve the recording file") + + t.Run("native v2 download uses the same viewer route", func(t *testing.T) { + native := &Operation{ + WorldName: "altis", MissionName: "Native mission", Filename: "native", + Date: "2026-01-02", StorageFormat: "protobuf", SchemaVersion: uint32(storage.SchemaVersionV2), + ConversionStatus: ConversionStatusCompleted, + } + require.NoError(t, repo.Store(t.Context(), native)) + nativeDir := filepath.Join(dataDir, native.Filename) + flusher, err := ingestion.NewChunkFlusher(nativeDir, 300) + require.NoError(t, err) + session := ingestion.NewSession() + session.SetMission(&core.Mission{MissionName: native.MissionName, CaptureDelay: 1}, &core.World{WorldName: native.WorldName}) + session.SetChunkFlusher(flusher) + session.HandleAddSoldier(core.Soldier{ID: 1, UnitName: "Synthetic player", IsPlayer: true}) + session.HandleSoldierState(core.SoldierState{SoldierID: 1, UnitName: "Synthetic player", IsPlayer: true}) + require.NoError(t, session.Finalize(nativeDir)) + + path := "/ocap/data/native.json.gz" + fakeNetwork := httptest.NewTestServer(t, server.Mux) + client := fakeNetwork.Client() + request := func(method string, token string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, nil) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + rec := httptest.NewRecorder() + server.Mux.ServeHTTP(rec, req) + return rec + } + require.Equal(t, http.StatusUnauthorized, request(http.MethodGet, "").Code) + head := request(http.MethodHead, viewerToken) + require.Equal(t, http.StatusOK, head.Code) + require.Empty(t, head.Body.Bytes()) + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, fakeNetwork.URL+path, nil) + require.NoError(t, err) + req.Header.Set("Authorization", "Bearer "+viewerToken) + req.Header.Set("Accept-Encoding", "gzip") + response, err := client.Do(req) + require.NoError(t, err) + defer response.Body.Close() + require.Equal(t, http.StatusOK, response.StatusCode) + require.Equal(t, "gzip", response.Header.Get("Content-Encoding")) + gz, err := gzip.NewReader(response.Body) + require.NoError(t, err) + defer gz.Close() + var legacy struct { + MissionName string `json:"missionName"` + Entities []struct { + ID int `json:"id"` + Name string `json:"name"` + } `json:"entities"` + } + require.NoError(t, json.NewDecoder(gz).Decode(&legacy)) + require.Equal(t, native.MissionName, legacy.MissionName) + require.Len(t, legacy.Entities, 2) + require.Equal(t, 1, legacy.Entities[1].ID) + require.Equal(t, "Synthetic player", legacy.Entities[1].Name) + require.NoFileExists(t, filepath.Join(dataDir, "native.json.gz")) + require.NoFileExists(t, filepath.Join(nativeDir, "manifest.json")) + require.NoError(t, os.Remove(filepath.Join(nativeDir, "chunks", "0000.pb"))) + require.Equal(t, http.StatusInternalServerError, request(http.MethodGet, viewerToken).Code) + require.NoError(t, os.WriteFile(filepath.Join(nativeDir, "manifest.pb"), []byte{0xff}, 0o644)) + require.Equal(t, http.StatusInternalServerError, request(http.MethodGet, viewerToken).Code) + require.NoError(t, os.Remove(filepath.Join(nativeDir, "manifest.pb"))) + require.Equal(t, http.StatusNotFound, request(http.MethodGet, viewerToken).Code) + require.NoError(t, repo.UpdateConversionStatus(t.Context(), native.ID, ConversionStatusStreaming)) + require.Equal(t, http.StatusNotFound, request(http.MethodGet, viewerToken).Code) + }) } diff --git a/internal/storage/json.go b/internal/storage/json.go index 76c0ee772..3f4dd69af 100644 --- a/internal/storage/json.go +++ b/internal/storage/json.go @@ -32,7 +32,7 @@ func (e *JSONEngine) GetManifest(ctx context.Context, filename string) (*Manifes MissionName: getString(data, "missionName"), EndFrame: getUint32(data, "endFrame"), ChunkSize: 300, - CaptureDelayMs: uint32(getFloat64(data, "captureDelay") * 1000), + CaptureDelayMs: CaptureDelayMillis(getFloat64(data, "captureDelay")), ChunkCount: 1, // JSON is single "chunk" } @@ -143,4 +143,3 @@ func getFloat64(m map[string]interface{}, key string) float64 { func getUint32(m map[string]interface{}, key string) uint32 { return uint32(getFloat64(m, key)) } - diff --git a/internal/storage/json_test.go b/internal/storage/json_test.go index d92964e84..d4eb52147 100644 --- a/internal/storage/json_test.go +++ b/internal/storage/json_test.go @@ -97,6 +97,14 @@ func TestJSONEngineGetManifestGzipped(t *testing.T) { assert.False(t, manifest.Entities[0].IsPlayer) } +func TestJSONEngineGetManifestRoundsCaptureDelayToNearestMillisecond(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "rounded.json"), []byte(`{"captureDelay":0.251}`), 0644)) + manifest, err := NewJSONEngine(dir).GetManifest(context.Background(), "rounded") + require.NoError(t, err) + assert.Equal(t, uint32(251), manifest.CaptureDelayMs) +} + func TestJSONEngineNotFound(t *testing.T) { engine := NewJSONEngine(t.TempDir()) diff --git a/internal/storage/parser.go b/internal/storage/parser.go index 6aa1b1a9c..3f8a87b99 100644 --- a/internal/storage/parser.go +++ b/internal/storage/parser.go @@ -1,6 +1,21 @@ package storage -import "fmt" +import ( + "fmt" + "math" +) + +// CaptureDelayMillis converts a capture interval to the manifest's millisecond precision. +func CaptureDelayMillis(seconds float64) uint32 { + if !(seconds > 0) { + return 0 + } + millis := math.Round(seconds * 1000) + if millis >= math.MaxUint32 { + return math.MaxUint32 + } + return uint32(millis) +} // ParseResult contains parsed data in a schema-agnostic format. // This is the intermediate representation produced by parsing JSON input, diff --git a/internal/storage/parser_test.go b/internal/storage/parser_test.go index 6e6967dd0..301498c5f 100644 --- a/internal/storage/parser_test.go +++ b/internal/storage/parser_test.go @@ -1,6 +1,8 @@ package storage import ( + "errors" + "math" "testing" "github.com/stretchr/testify/assert" @@ -89,6 +91,24 @@ func TestParserV1_Version(t *testing.T) { assert.Equal(t, JSONInputVersionV1, p.Version()) } +func TestCaptureDelayMillis(t *testing.T) { + for _, test := range []struct { + seconds float64 + want uint32 + }{ + {seconds: 1.001, want: 1001}, + {seconds: 0.251, want: 251}, + {seconds: 0.0004, want: 0}, + {seconds: 0.0005, want: 1}, + {seconds: 0, want: 0}, + {seconds: -1, want: 0}, + {seconds: math.NaN(), want: 0}, + {seconds: float64(math.MaxUint32), want: math.MaxUint32}, + } { + assert.Equal(t, test.want, CaptureDelayMillis(test.seconds)) + } +} + func TestParserV1_Parse_MinimalData(t *testing.T) { p := &ParserV1{} data := map[string]interface{}{ @@ -1458,3 +1478,36 @@ func TestParserV1_collectEntityPositions_EdgeCases(t *testing.T) { assert.Empty(t, result.Positions) }) } + +func TestParserV1_visitEntityPositionsMatchesCollector(t *testing.T) { + p := &ParserV1{} + positions := []interface{}{ + []interface{}{[]interface{}{10.0, 20.0, 30.0}, 90.0, 1.0, 0.0, "one", 1.0}, + []interface{}{[]interface{}{11.0, 21.0}, 91.0, 0.0, 7.0, "two", 0.0}, + "malformed", + []interface{}{[]interface{}{12.0, 22.0, 32.0}, 180.0, 1.0, []interface{}{3.0}, []interface{}{5.0, 7.0}}, + } + collected := p.collectEntityPositions(map[string]interface{}{"positions": positions}, 12, 4, "unit") + var visited []EntityPosition + err := p.visitEntityPositions(positions, 4, "unit", func(position EntityPosition) error { + visited = append(visited, position) + return nil + }) + require.NoError(t, err) + require.Equal(t, collected.Positions, visited) + require.Equal(t, []uint32{4, 5, 7}, []uint32{visited[0].FrameNum, visited[1].FrameNum, visited[2].FrameNum}) + + wantErr := errors.New("stop visiting") + count := 0 + err = p.visitEntityPositions(positions, 4, "unit", func(EntityPosition) error { + count++ + return wantErr + }) + require.ErrorIs(t, err, wantErr) + require.Equal(t, 1, count) + + err = p.visitEntityPositions(positions[3:], 4, "vehicle", func(EntityPosition) error { + return wantErr + }) + require.ErrorIs(t, err, wantErr) +} diff --git a/internal/storage/parser_v1.go b/internal/storage/parser_v1.go index 91965da6e..f325bc306 100644 --- a/internal/storage/parser_v1.go +++ b/internal/storage/parser_v1.go @@ -25,7 +25,7 @@ func (p *ParserV1) Parse(data map[string]interface{}, chunkSize uint32) (*ParseR MissionName: getString(data, "missionName"), EndFrame: getUint32(data, "endFrame"), ChunkSize: chunkSize, - CaptureDelayMs: uint32(getFloat64(data, "captureDelay") * 1000), + CaptureDelayMs: CaptureDelayMillis(getFloat64(data, "captureDelay")), ExtensionVersion: getString(data, "extensionVersion"), AddonVersion: getString(data, "addonVersion"), } @@ -511,7 +511,14 @@ func (p *ParserV1) collectEntityPositions(em map[string]interface{}, entityID ui EntityID: entityID, Positions: make([]EntityPosition, 0, len(positions)), } + _ = p.visitEntityPositions(positions, startFrame, entityType, func(pos EntityPosition) error { + data.Positions = append(data.Positions, pos) + return nil + }) + return data +} +func (p *ParserV1) visitEntityPositions(positions []interface{}, startFrame uint32, entityType string, visit func(EntityPosition) error) error { for i, posData := range positions { posArr, ok := posData.([]interface{}) if !ok || len(posArr) < 3 { @@ -588,7 +595,9 @@ func (p *ParserV1) collectEntityPositions(em map[string]interface{}, entityID ui expanded.CrewIDs = make([]uint32, len(pos.CrewIDs)) copy(expanded.CrewIDs, pos.CrewIDs) } - data.Positions = append(data.Positions, expanded) + if err := visit(expanded); err != nil { + return err + } } continue } @@ -596,10 +605,12 @@ func (p *ParserV1) collectEntityPositions(em map[string]interface{}, entityID ui // Dense format: one position per frame pos.FrameNum = startFrame + uint32(i) - data.Positions = append(data.Positions, pos) + if err := visit(pos); err != nil { + return err + } } - return data + return nil } // parseFramesFired extracts fired frame data from an entity diff --git a/internal/storage/precompress.go b/internal/storage/precompress.go index 52b3daed8..147b329b2 100644 --- a/internal/storage/precompress.go +++ b/internal/storage/precompress.go @@ -86,7 +86,7 @@ func compress(encoding string, data []byte) ([]byte, error) { return enc.EncodeAll(data, nil), nil case EncodingGzip: var buf bytes.Buffer - zw, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression) + zw, _ := gzip.NewWriterLevel(&buf, gzip.DefaultCompression) _, _ = zw.Write(data) _ = zw.Close() return buf.Bytes(), nil diff --git a/internal/storage/precompress_test.go b/internal/storage/precompress_test.go index 240f2fed6..78c14739f 100644 --- a/internal/storage/precompress_test.go +++ b/internal/storage/precompress_test.go @@ -57,6 +57,9 @@ func TestWriteArtifact_WritesRawAndSidecars(t *testing.T) { assert.Equal(t, payload, readZstd(t, path+".zst"), "zstd sidecar round-trips") assert.Equal(t, payload, readGzip(t, path+".gz"), "gzip sidecar round-trips") + info, err := os.Stat(path + ".gz") + require.NoError(t, err) + assert.Less(t, info.Size(), int64(len(payload))) zstdInfo, err := os.Stat(path + ".zst") require.NoError(t, err) diff --git a/internal/storage/streaming_converter.go b/internal/storage/streaming_converter.go index 00357b95b..5e2a118f5 100644 --- a/internal/storage/streaming_converter.go +++ b/internal/storage/streaming_converter.go @@ -128,12 +128,11 @@ func (sc *Converter) Convert(ctx context.Context, jsonPath, outputPath string) e entities = append(entities, def) // Collect positions and bucket them to disk - posData := parser.collectEntityPositions(em, def.Id, startFrame, entityType) - if posData != nil { - for _, pos := range posData.Positions { + if positions, ok := em["positions"].([]interface{}); ok { + if err := parser.visitEntityPositions(positions, startFrame, entityType, func(pos EntityPosition) error { chunkIdx := pos.FrameNum / sc.ChunkSize state := &pbv1.EntityState{ - EntityId: posData.EntityID, + EntityId: def.Id, FrameNum: pos.FrameNum, PosX: pos.PosX, PosY: pos.PosY, @@ -151,6 +150,9 @@ func (sc *Converter) Convert(ctx context.Context, jsonPath, outputPath string) e if err := bucket.Write(chunkIdx, state); err != nil { return fmt.Errorf("bucket write: %w", err) } + return nil + }); err != nil { + return err } } diff --git a/internal/storage/streaming_json_reader.go b/internal/storage/streaming_json_reader.go index 37ae8f649..1643badad 100644 --- a/internal/storage/streaming_json_reader.go +++ b/internal/storage/streaming_json_reader.go @@ -149,7 +149,7 @@ func (sr *StreamingJSONReader) Process(callbacks StreamingCallbacks) (StreamingM } case "captureDelay": if f, ok := val.(float64); ok { - meta.CaptureDelayMs = uint32(f * 1000) + meta.CaptureDelayMs = CaptureDelayMillis(f) } case "extensionVersion": if s, ok := val.(string); ok { diff --git a/internal/storage/streaming_json_reader_test.go b/internal/storage/streaming_json_reader_test.go index aad62232a..0d92efd8d 100644 --- a/internal/storage/streaming_json_reader_test.go +++ b/internal/storage/streaming_json_reader_test.go @@ -14,6 +14,13 @@ import ( "github.com/stretchr/testify/require" ) +func TestStreamingJSONReaderRoundsCaptureDelay(t *testing.T) { + reader := NewStreamingJSONReader(bytes.NewBufferString(`{"captureDelay":1.001}`)) + meta, err := reader.Process(StreamingCallbacks{}) + require.NoError(t, err) + assert.EqualValues(t, 1001, meta.CaptureDelayMs) +} + func TestStreamingJSONReader_Metadata(t *testing.T) { data := makeTestJSON(t) reader := NewStreamingJSONReader(bytes.NewReader(data)) diff --git a/internal/testkit/cases.go b/internal/testkit/cases.go index b02ed4374..49cf84f15 100644 --- a/internal/testkit/cases.go +++ b/internal/testkit/cases.go @@ -1,7 +1,7 @@ package testkit // Bump this when case inputs or expected behavior change. -const fixtureVersion = "ocap-local-v4" +const fixtureVersion = "ocap-local-v5" type testStep struct { target string @@ -18,6 +18,7 @@ type testCase struct { var cases = []testCase{ {"filename-migration", "Legacy filename repair, rerun, and a failed candidate scan", []testStep{ {"./internal/server", []string{"TestMigrationRerun", "TestMigrationV11DecodeFilenames", "TestMigrationV11_DBCollisionSkipped", "TestMigrationV11_FilesystemCollisionSkipped", "TestMigrateDecodeFilenames_IterationErrorLeavesVersionUnchanged"}}, + {"./internal/server", []string{"TestMigrationV16OperationsIndexes", "TestScanRejectsPartialResultsAfterIterationError"}}, }}, {"legacy-upload", "Recording replacement, failure without a row, and legacy playback", []testStep{ {"./internal/server", []string{"TestIntegration_UploadSameFilenameReplaces", "TestIntegration_FailedReuploadPreservesExisting", "TestIntegration_UploadWriteFailureLeavesNoRow", "TestIntegration_ServeLegacyRawJSONAsGz"}}, @@ -40,6 +41,8 @@ var cases = []testCase{ "TestStreamDiscard_LostAckResolvedByResume", "TestStreamRegistryReserveWaitsForConcurrentStart", "TestSendStreamPings_StopsOnWriteError", + "TestSendStreamPings_StopsWhenDoneCloses", + "TestHandleStream_V2FailureLeavesNoLegacyRecording", }}, }}, {"conversion-recovery", "Clean interrupted conversions without resetting stream-owned recordings", []testStep{ @@ -49,6 +52,7 @@ var cases = []testCase{ {"playback-delivery", "Negotiated recording artifacts and UI compatibility with stored formats", []testStep{ {"./internal/server", []string{"TestIntegration_ConversionAndStaticServing", "TestIntegration_PrecompressedArtifactServing"}}, {"./internal/storage", []string{"TestWriteArtifact_RemovesStaleSidecarsWhenPayloadShrinks"}}, + {"./internal/ingestion", []string{"TestExportV2AsV1JSONMatchesSessionConversion", "TestExportV2AsV1JSONErrorsAndCancellation"}}, {"ui", []string{ "src/data/decoders/__tests__/streamingV2Compatibility.test.ts", "src/data/decoders/__tests__/protobufDecoder.test.ts", From fb49ee08af38cffb9affb5957bc12f77c1bb3dc6 Mon Sep 17 00:00:00 2001 From: Yethe Samartaka Date: Tue, 1 Dec 2026 09:10:04 +0100 Subject: [PATCH 2/2] Keep the v1 JSON copy and fallback by default Streamed native v2 recordings are saved as before: with a v1 .json.gz copy and the debug manifest.json, and from the v1 JSON when writing v2 fails. Two settings opt out: - streaming.protobufOnly stores them without the copy and manifest.json; downloads convert them to v1 JSON on request. - streaming.disableV1Fallback fails the save instead of falling back and deletes a v1 copy written for it. The producer gets no acknowledgement, and a resumable extension resends the mission. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- README.md | 2 + docs/streaming-architecture.md | 32 ++-- internal/ingestion/coverage_extra_test.go | 10 ++ internal/ingestion/session.go | 14 +- internal/ingestion/writer_v2.go | 69 +++++++- internal/ingestion/writer_v2_test.go | 14 ++ internal/server/coverage_extra_test.go | 1 - internal/server/handler_stream.go | 51 ++++-- internal/server/handler_stream_resume_test.go | 4 +- internal/server/handler_stream_test.go | 155 ++++++++++++++---- internal/server/route_access_test.go | 1 + internal/server/setting.go | 10 ++ internal/testkit/cases.go | 3 +- setting.json.example | 4 +- 15 files changed, 306 insertions(+), 66 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fad3ada42..7adb4c738 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ Start with [Contributing](CONTRIBUTING.md). Use [Maintainer context](docs/maintainer-context.md) to trace a contract, failure path, or guard and [Comment hygiene](docs/comment-hygiene.md) for comment changes. - Verify [HTTP authorization](internal/server/handler.go) through the registered mux under a non-root prefix. Viewer, admin, and producer routes use different credentials. Use the [streaming contract](docs/streaming-architecture.md) for ingestion, recording formats, and playback. Follow the [schema generation instructions](CONTRIBUTING.md#protobuf-schema-changes) for protobuf changes. -- Store native v2 recordings as protobuf and convert them to v1 JSON on demand for downloads. Keep existing v1 JSON and schema-v1 protobuf recordings readable. +- Native v2 recordings get a v1 JSON copy and fall back to it when v2 writing fails; `streaming.protobufOnly` and `streaming.disableV1Fallback` opt out. A download of a v2 recording without the copy converts it on demand. Keep existing v1 JSON and schema-v1 protobuf recordings readable. - Keep the UI's SolidJS, CSS module, and i18n conventions. Use the [operational runbook](docs/operational-verification.md) for startup, native map tooling, and Arsenal imports. - Inspect the working tree before editing. Preserve local changes and use synthetic recordings, paths, identities, secrets, and provider responses for local checks. The [testkit](docs/testkit.md) is available without an application startup. - Match [CI](.github/workflows) for Go tests and UI typecheck, lint, tests, and build when those surfaces change. Build the SPA before packaging the embedded binary. Keep tests close to the code they exercise. diff --git a/README.md b/README.md index 8602f8a62..0b30f2682 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,8 @@ Live mission data can be streamed to the server via WebSocket. | `streaming.resumeGrace` | `OCAP_STREAMING_RESUMEGRACE` | How long a disconnected mission waits for its producer to resume before it is saved as partial | `5m` | | `streaming.ackInterval` | `OCAP_STREAMING_ACKINTERVAL` | How often received messages are acknowledged to a resuming producer | `1s` | | `streaming.maxSessions` | `OCAP_STREAMING_MAXSESSIONS` | Missions ingested at once (each is held in memory until saved); a producer turned away retries. `0` = no limit | `0` | +| `streaming.protobufOnly` | `OCAP_STREAMING_PROTOBUFONLY` | Store streamed recordings only as protobuf, without the v1 `.json.gz` copy and the debug `manifest.json`. Their v1 JSON download is generated on request | `false` | +| `streaming.disableV1Fallback` | `OCAP_STREAMING_DISABLEV1FALLBACK` | When a streamed recording cannot be written as protobuf, fail the save instead of keeping the mission as v1 JSON. The producer gets no acknowledgement, the recording is marked failed, and a resumable extension sends the mission again | `false` | ### CORS diff --git a/docs/streaming-architecture.md b/docs/streaming-architecture.md index 2dd6d6a57..202c0611b 100644 --- a/docs/streaming-architecture.md +++ b/docs/streaming-architecture.md @@ -43,8 +43,8 @@ timeline. Older clients that omit the declaration keep their zero-based frames, legacy marker end sentinel and projectile trajectory field name. Unknown future message types are logged and skipped. -Each accepted mission gets one unique storage key for its database row and -protobuf directory. At mission end the web writes: +Each accepted mission gets one unique storage key, used for its database row, +v2 directory and v1 `.json.gz` copy. At mission end the web writes: - Native **v2 protobuf** metadata and chunks, retaining the richer entity states, telemetry, mission metadata, radio/ACE events, placed objects and focus ranges. @@ -54,19 +54,25 @@ protobuf directory. At mission end the web writes: - Player snapshot sidecars using the existing `snapshots/.pb` format and endpoint, keeping large inventories out of the startup manifest. Older v2 files with inline snapshots remain readable. +- A **v1 JSON.gz copy** for legacy playback, downloads and fallback conversion, + and a readable `manifest.json` next to `manifest.pb` for debugging. + Existing uploads, v1 conversion, schema-v1 protobuf and JSON playback retain + their existing paths. Legacy conversion never overwrites a native v2 recording. -The existing viewer download URL serves a previously stored **v1 JSON.gz** -when available. For native v2 recordings without that file, it converts the -protobuf recording to v1 JSON on request. Each conversion holds the whole -mission in memory, so the server runs one at a time and queues the rest. -Existing uploads, v1 conversion, schema-v1 protobuf and JSON playback retain -their existing paths. +With `streaming.protobufOnly`, the web writes neither the v1 copy nor +`manifest.json`. The viewer download URL serves a stored v1 JSON.gz when there +is one; for a native v2 recording without it, the server converts the protobuf +recording to v1 JSON on request. Each conversion holds the whole mission in +memory, so the server runs one at a time and queues the rest. An end-mission acknowledgement is sent only after the recording and operation are saved. Direct v2 output is already finalized and needs no conversion job. -If v2 writing fails, the server closes the connection without a success -acknowledgement and marks the row failed. A resumable producer can replay the -mission. +If v2 writing fails, the v1 JSON becomes the operation's source and follows the +existing conversion setting; with `protobufOnly` it is written at that point. +With `streaming.disableV1Fallback`, the save fails instead and no v1 JSON is +kept. A failed save is reported by closing the connection without a success +acknowledgement, and the row is marked failed. A resumable producer can replay +the mission. ### Resume after a network failure @@ -116,6 +122,8 @@ the next section. | `streaming.resumeGrace` | `5m` | How long a disconnected mission waits for its producer | | `streaming.ackInterval` | `1s` | How often received envelopes are acknowledged | | `streaming.maxSessions` | `0` | Missions ingested at once; `0` = no limit | +| `streaming.protobufOnly` | `false` | Store native v2 recordings without the v1 copy and `manifest.json` | +| `streaming.disableV1Fallback` | `false` | Fail a save whose v2 recording cannot be written instead of keeping it as v1 JSON | Each session holds its mission in memory until it is saved, so many game servers resending missions in full after a web restart can add up. @@ -215,7 +223,7 @@ received data and appends `partial` to the mission's existing tags. Repeated starts cannot silently discard an active mission. Their reconnect starts a new recording segment. -The session retains history in web memory for protobuf finalization. A web process +The session retains history in web memory until it is saved. A web process crash is not the same as a producer disconnect and does not guarantee a finalized recording. This protocol does not yet include a durable ingestion journal. diff --git a/internal/ingestion/coverage_extra_test.go b/internal/ingestion/coverage_extra_test.go index ed0151875..1dc1e7ee5 100644 --- a/internal/ingestion/coverage_extra_test.go +++ b/internal/ingestion/coverage_extra_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "io" + "math" "os" "path/filepath" "testing" @@ -207,6 +208,10 @@ func TestWriterV2_ExtraBranches(t *testing.T) { require.NoError(t, os.MkdirAll(filepath.Join(dirPB, "manifest.pb", "sub"), 0755)) assert.ErrorContains(t, WriteV2Manifest(s, dirPB, 1), "write manifest.pb") + // WriteV2Manifest write manifest.json error (manifest.json is a directory) + dirJSON := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dirJSON, "manifest.json"), 0755)) + assert.ErrorContains(t, WriteV2Manifest(s, dirJSON, 1), "write manifest.json") } type fakeTempWriteCloser struct { @@ -310,6 +315,11 @@ func TestIngestion_100PercentCoverage(t *testing.T) { require.NoError(t, os.MkdirAll(p1, 0755)) assert.Error(t, sFin.Finalize(finDir)) + // writer_v2.go:39 (manifestToJSON marshal fails with NaN World Latitude) + sNaN := NewSession() + sNaN.SetMission(nil, &core.World{WorldName: "altis", Latitude: float32(math.NaN())}) + assert.ErrorContains(t, WriteV2Manifest(sNaN, t.TempDir(), 1), "marshal JSON archive") + // writer_v2.go:185, 186 (multiple soldiers & vehicles trigger sort comparators) sSort := NewSession() sSort.HandleAddSoldier(core.Soldier{ID: 10, UnitName: "B"}) diff --git a/internal/ingestion/session.go b/internal/ingestion/session.go index 2b89174c2..49acb7968 100644 --- a/internal/ingestion/session.go +++ b/internal/ingestion/session.go @@ -1,5 +1,5 @@ -// Package ingestion accumulates streaming missions for protobuf storage and -// exports legacy v1 JSON. +// Package ingestion accumulates streaming missions, writes them as v2 +// protobuf and v1 JSON, and exports stored v2 recordings as v1 JSON. package ingestion import ( @@ -85,6 +85,9 @@ type Session struct { placedEvents []core.PlacedObjectEvent focusStart *core.Frame focusRanges []core.FocusRange + + // skipManifestJSON leaves out manifest.json; see SetManifestJSON. + skipManifestJSON bool } // NewSession creates an empty ingestion session. @@ -280,6 +283,13 @@ func (s *Session) ChunkFlusher() *ChunkFlusher { return s.chunkFlusher } +// SetManifestJSON sets whether Finalize writes manifest.json, a readable +// summary of the v2 manifest for debugging, next to manifest.pb. It does +// unless set otherwise. +func (s *Session) SetManifestJSON(write bool) { + s.skipManifestJSON = !write +} + // Finalize flushes remaining chunks and writes the v2 manifest. // outputDir is the directory where chunks/ and manifest files are written. func (s *Session) Finalize(outputDir string) error { diff --git a/internal/ingestion/writer_v2.go b/internal/ingestion/writer_v2.go index 6ccbbe927..b6f872c3c 100644 --- a/internal/ingestion/writer_v2.go +++ b/internal/ingestion/writer_v2.go @@ -3,6 +3,7 @@ package ingestion import ( "encoding/json" "fmt" + "os" "path/filepath" "sort" "strings" @@ -16,7 +17,8 @@ import ( const defaultChunkSize = 300 -// WriteV2Manifest writes the v2 protobuf manifest from session data. +// WriteV2Manifest writes the v2 protobuf manifest from session data, and a +// JSON summary for debugging unless the session skips it. // Chunks are expected to have been written already by the ChunkFlusher. func WriteV2Manifest(session *Session, outputDir string, chunkCount uint32) error { manifest := buildManifest(session, chunkCount) @@ -32,6 +34,18 @@ func WriteV2Manifest(session *Session, outputDir string, chunkCount uint32) erro if err := writeAtomic(filepath.Join(outputDir, "manifest.pb"), data); err != nil { return fmt.Errorf("write manifest.pb: %w", err) } + if session.skipManifestJSON { + return nil + } + + // Write JSON archive for debugging. + jsonData, err := json.MarshalIndent(manifestToJSON(manifest), "", " ") + if err != nil { + return fmt.Errorf("marshal JSON archive: %w", err) + } + if err := os.WriteFile(filepath.Join(outputDir, "manifest.json"), jsonData, 0644); err != nil { + return fmt.Errorf("write manifest.json: %w", err) + } return nil } @@ -529,6 +543,59 @@ func parseMarkerSizeF32(sizeStr string) []float32 { return f32 } +// manifestToJSON creates a JSON-serializable representation of the manifest for debugging. +func manifestToJSON(m *pbv2.Manifest) map[string]any { + result := map[string]any{ + "version": m.Version, + "frameCount": m.FrameCount, + "chunkSize": m.ChunkSize, + "captureDelayMs": m.CaptureDelayMs, + "chunkCount": m.ChunkCount, + } + + if m.World != nil { + result["world"] = map[string]any{ + "worldName": m.World.WorldName, + "worldSize": m.World.WorldSize, + "latitude": m.World.Latitude, + "longitude": m.World.Longitude, + "author": m.World.Author, + "displayName": m.World.DisplayName, + } + } + + if m.Mission != nil { + mission := map[string]any{ + "missionName": m.Mission.MissionName, + "briefingName": m.Mission.BriefingName, + "author": m.Mission.Author, + "serverName": m.Mission.ServerName, + "extensionVersion": m.Mission.ExtensionVersion, + "addonVersion": m.Mission.AddonVersion, + "extensionBuild": m.Mission.ExtensionBuild, + "tag": m.Mission.Tag, + } + if m.Mission.PlayableSlots != nil { + mission["playableSlots"] = m.Mission.PlayableSlots + } + if m.Mission.SideFriendly != nil { + mission["sideFriendly"] = m.Mission.SideFriendly + } + if len(m.Mission.Addons) > 0 { + mission["addons"] = m.Mission.Addons + } + result["mission"] = mission + } + + result["soldierCount"] = len(m.Soldiers) + result["vehicleCount"] = len(m.Vehicles) + result["eventCount"] = len(m.Events) + result["markerCount"] = len(m.Markers) + result["timeCount"] = len(m.Times) + + return result +} + // telemetryToProtoEvent converts a core.TelemetryEvent to a v2 proto Event. func telemetryToProtoEvent(te core.TelemetryEvent) *pbv2.Event { t := &pbv2.TelemetryEvent{ diff --git a/internal/ingestion/writer_v2_test.go b/internal/ingestion/writer_v2_test.go index 9d815dac3..36790b152 100644 --- a/internal/ingestion/writer_v2_test.go +++ b/internal/ingestion/writer_v2_test.go @@ -203,6 +203,20 @@ func TestWriteV2Manifest_Roundtrip(t *testing.T) { require.Len(t, manifest.Times, 1) assert.Equal(t, "2025-01-15T10:30:00Z", manifest.Times[0].SystemTimeUtc) + // Verify JSON archive also exists. + jsonData, err := os.ReadFile(filepath.Join(dir, "manifest.json")) + require.NoError(t, err) + assert.Contains(t, string(jsonData), "Test Mission") +} + +func TestWriteV2Manifest_WithoutManifestJSON(t *testing.T) { + session := NewSession() + session.SetMission(&core.Mission{MissionName: "Protobuf Only", CaptureDelay: 1}, &core.World{WorldName: "altis"}) + session.SetManifestJSON(false) + dir := t.TempDir() + + require.NoError(t, WriteV2Manifest(session, dir, 1)) + assert.FileExists(t, filepath.Join(dir, "manifest.pb")) assert.NoFileExists(t, filepath.Join(dir, "manifest.json")) } diff --git a/internal/server/coverage_extra_test.go b/internal/server/coverage_extra_test.go index eab777606..e8ec52c02 100644 --- a/internal/server/coverage_extra_test.go +++ b/internal/server/coverage_extra_test.go @@ -1002,7 +1002,6 @@ func TestHandlerStream_100PercentCoverage(t *testing.T) { repoOperation: h.repoOperation, conversionTrigger: &mockConvTrigger{}, } - assert.ErrorContains(t, hV1.finalizeSession(sessV1, "", filepath.Join(t.TempDir(), "native"), 0), "has no chunk flusher") missingData := &Handler{setting: Setting{Data: filepath.Join(t.TempDir(), "missing")}} assert.ErrorContains(t, missingData.finalizeSession(sessV1, "", "", 0), "write JSON.gz") // v2OutputDir == "" + FocusRanges non-empty + conversionTrigger != nil -> hits 925, 967-970, 1010! diff --git a/internal/server/handler_stream.go b/internal/server/handler_stream.go index 02e1b0c96..dece9ad8a 100644 --- a/internal/server/handler_stream.go +++ b/internal/server/handler_stream.go @@ -333,7 +333,7 @@ func (h *Handler) startStream(envelope streaming.Envelope, conn *streamConn) (*s if err := os.MkdirAll(h.setting.Data, 0755); err != nil { return refuse("streaming storage unavailable") } - // Allocate one unique key for the operation and its protobuf artifacts. + // Allocate one unique key for the row, v2 directory and v1 JSON copy. output, err := streamMkdirTemp(h.setting.Data, ingestion.MakeFilename(payload.Mission.MissionName)+"_*") if err != nil { return refuse("streaming storage unavailable") @@ -897,7 +897,10 @@ func withPartialTag(tag string) string { return tag + ",partial" } -// finalizeSession writes the recording and publishes its completed operation. +// finalizeSession writes the recording and publishes its operation: v2 +// protobuf with a v1 JSON copy, which the save falls back to if v2 fails (see +// Streaming.ProtobufOnly and DisableV1Fallback), or v1 JSON alone, which is +// converted. // If streamingOpID > 0, updates the existing "streaming" row instead of inserting a new one. func (h *Handler) finalizeSession(session *ingestion.Session, tag string, v2OutputDir string, streamingOpID int64) error { if h.setting.Data == "" { @@ -929,18 +932,46 @@ func (h *Handler) finalizeSession(session *ingestion.Session, tag string, v2Outp filename = ingestion.MakeFilename(missionName) } + writeV1 := func() error { + if err := session.WriteJSONGzNamed(h.setting.Data, filename); err != nil { + return fmt.Errorf("write JSON.gz: %w", err) + } + return nil + } + + // A native v2 recording gets its v1 copy first, ready to stand in for it, + // unless streaming.protobufOnly leaves it out. + opts := h.setting.Streaming + hasV2 := session.ChunkFlusher() != nil && v2OutputDir != "" + wroteV1 := !hasV2 || !opts.ProtobufOnly + if wroteV1 { + if err := writeV1(); err != nil { + return err + } + } + + // Write v2 protobuf (manifest + finalize chunks). var chunkCount int - hasV2 := v2OutputDir != "" if hasV2 { - if session.ChunkFlusher() == nil { - return errors.New("native v2 session has no chunk flusher") - } + session.SetManifestJSON(!opts.ProtobufOnly) if err := session.Finalize(v2OutputDir); err != nil { - return fmt.Errorf("finalize v2 recording: %w", err) + if opts.DisableV1Fallback { + if wroteV1 { + // Nothing may be served or converted from a failed save. + _ = os.Remove(filepath.Join(h.setting.Data, filename+".json.gz")) + } + return fmt.Errorf("finalize v2 recording: %w", err) + } + slog.Error("stream: v2 finalization failed, falling back to v1 only", "error", err) + if !wroteV1 { + if err := writeV1(); err != nil { + return err + } + } + hasV2 = false + } else { + chunkCount = int(session.ChunkFlusher().ChunkCount()) } - chunkCount = int(session.ChunkFlusher().ChunkCount()) - } else if err := session.WriteJSONGzNamed(h.setting.Data, filename); err != nil { - return fmt.Errorf("write JSON.gz: %w", err) } storageFormat := "json" diff --git a/internal/server/handler_stream_resume_test.go b/internal/server/handler_stream_resume_test.go index 8b41b4c25..5018c8994 100644 --- a/internal/server/handler_stream_resume_test.go +++ b/internal/server/handler_stream_resume_test.go @@ -821,10 +821,10 @@ func TestStreamResume_EndNotAcknowledgedBeforeSaveSucceeds(t *testing.T) { last := sendStates(t, c, 2, 1, 3) rh.waitSeq("m-slow", last) - // The save is slow, then fails: a nonempty directory blocks the protobuf manifest. + // The save is slow, then fails: a directory blocks the legacy backup. ops := rh.ops() require.Len(t, ops, 1) - require.NoError(t, os.MkdirAll(filepath.Join(rh.dir, ops[0].Filename, "manifest.pb", "blocked"), 0o755)) + require.NoError(t, os.Mkdir(filepath.Join(rh.dir, ops[0].Filename+".json.gz"), 0o755)) release := make(chan struct{}) var releaseOnce sync.Once unblock := func() { releaseOnce.Do(func() { close(release) }) } diff --git a/internal/server/handler_stream_test.go b/internal/server/handler_stream_test.go index c22b07353..4af17cc18 100644 --- a/internal/server/handler_stream_test.go +++ b/internal/server/handler_stream_test.go @@ -14,6 +14,7 @@ import ( "testing/synctest" "time" + "github.com/OCAP2/extension/v5/pkg/streaming" "github.com/OCAP2/web/internal/storage" pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" "github.com/go-fuego/fuego" @@ -29,6 +30,9 @@ func TestStreamingSettingDefaults(t *testing.T) { assert.False(t, s.Streaming.Enabled) assert.Equal(t, time.Duration(0), s.Streaming.PingInterval) assert.Equal(t, time.Duration(0), s.Streaming.PingTimeout) + // Native v2 recordings keep their v1 JSON copy and fallback. + assert.False(t, s.Streaming.ProtobufOnly) + assert.False(t, s.Streaming.DisableV1Fallback) } func TestSendStreamPings_StopsOnWriteError(t *testing.T) { @@ -108,52 +112,116 @@ func TestHandleStream_InvalidStartMetadata(t *testing.T) { } } -func TestHandleStream_FinalizationFailureIsNotAcknowledged(t *testing.T) { - h, mux, dir := newTestStreamHandlerWithRepo(t) +// dialTestStream connects a producer to the stream endpoint served by mux. +func dialTestStream(t *testing.T, mux http.Handler) *websocket.Conn { + t.Helper() srv := httptest.NewServer(mux) - defer srv.Close() + t.Cleanup(srv.Close) c, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http")+"/api/v1/stream?secret=test-secret", nil) require.NoError(t, err) - defer c.Close() + t.Cleanup(func() { c.Close() }) + return c +} + +// blockV2Chunks makes the final flush of a recording's v2 chunks fail. +func blockV2Chunks(t *testing.T, dir, filename string) { + t.Helper() + chunkDir := filepath.Join(dir, filename, "chunks") + require.NoError(t, os.Rename(chunkDir, chunkDir+".unavailable")) + require.NoError(t, os.WriteFile(chunkDir, []byte("blocked"), 0600)) +} + +// requireSaveRefused waits for the server to close the connection without +// acknowledging end_mission, and returns the operation it marked failed. +func requireSaveRefused(t *testing.T, h *Handler, c *websocket.Conn, filename string) *Operation { + t.Helper() + require.NoError(t, c.SetReadDeadline(time.Now().Add(time.Second))) + _, _, err := c.ReadMessage() + require.True(t, websocket.IsCloseError(err, websocket.CloseInternalServerErr), "%v", err) + stored, err := h.repoOperation.GetByFilename(context.Background(), filename) + require.NoError(t, err) + require.Equal(t, ConversionStatusFailed, stored.ConversionStatus) + return stored +} + +func TestHandleStream_FinalizationFailureIsNotAcknowledged(t *testing.T) { + h, mux, dir := newTestStreamHandlerWithRepo(t) + c := dialTestStream(t, mux) sendStartMission(t, c, "Failure", "altis") ops, err := h.repoOperation.Select(context.Background(), Filter{}) require.NoError(t, err) require.Len(t, ops, 1) - // A nonempty directory blocks atomic publication of the protobuf manifest. - require.NoError(t, os.MkdirAll(filepath.Join(dir, ops[0].Filename, "manifest.pb", "blocked"), 0755)) + // A directory blocks atomic publication of the legacy backup. + require.NoError(t, os.Mkdir(filepath.Join(dir, ops[0].Filename+".json.gz"), 0755)) require.NoError(t, c.WriteJSON(map[string]string{"type": "end_mission"})) - c.SetReadDeadline(time.Now().Add(time.Second)) - _, _, err = c.ReadMessage() - require.True(t, websocket.IsCloseError(err, websocket.CloseInternalServerErr), "%v", err) - stored, err := h.repoOperation.GetByFilename(context.Background(), ops[0].Filename) - require.NoError(t, err) - require.Equal(t, ConversionStatusFailed, stored.ConversionStatus) + requireSaveRefused(t, h, c, ops[0].Filename) +} + +func TestHandleStream_V2FailurePreservesLegacyFallback(t *testing.T) { + for _, tc := range []struct { + name string + protobufOnly bool // the v1 JSON is written only once v2 failed + }{{name: "v1 copy"}, {name: "protobuf only", protobufOnly: true}} { + t.Run(tc.name, func(t *testing.T) { + h, mux, dir := newTestStreamHandlerWithRepo(t) + h.setting.Streaming.ProtobufOnly = tc.protobufOnly + c := dialTestStream(t, mux) + sendStartMission(t, c, "Fallback", "altis") + ops, err := h.repoOperation.Select(context.Background(), Filter{}) + require.NoError(t, err) + require.Len(t, ops, 1) + blockV2Chunks(t, dir, ops[0].Filename) + require.NoError(t, c.WriteJSON(map[string]string{"type": "end_mission"})) + var ack streaming.AckMessage + require.NoError(t, c.ReadJSON(&ack)) + require.Equal(t, "end_mission", ack.For) + stored, err := h.repoOperation.GetByFilename(context.Background(), ops[0].Filename) + require.NoError(t, err) + require.Equal(t, "json", stored.StorageFormat) + require.Equal(t, uint32(1), stored.SchemaVersion) + require.Equal(t, ConversionStatusCompleted, stored.ConversionStatus) + _, err = storage.NewJSONEngine(dir).GetManifest(context.Background(), stored.Filename) + require.NoError(t, err) + }) + } } -func TestHandleStream_V2FailureLeavesNoLegacyRecording(t *testing.T) { +func TestHandleStream_V2AndLegacyFallbackFailureIsNotAcknowledged(t *testing.T) { h, mux, dir := newTestStreamHandlerWithRepo(t) - srv := httptest.NewServer(mux) - defer srv.Close() - c, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http")+"/api/v1/stream?secret=test-secret", nil) - require.NoError(t, err) - defer c.Close() - sendStartMission(t, c, "Fallback", "altis") + h.setting.Streaming.ProtobufOnly = true + c := dialTestStream(t, mux) + sendStartMission(t, c, "No Fallback Left", "altis") ops, err := h.repoOperation.Select(context.Background(), Filter{}) require.NoError(t, err) require.Len(t, ops, 1) - chunkDir := filepath.Join(dir, ops[0].Filename, "chunks") - require.NoError(t, os.Rename(chunkDir, chunkDir+".unavailable")) - require.NoError(t, os.WriteFile(chunkDir, []byte("blocked"), 0600)) + blockV2Chunks(t, dir, ops[0].Filename) + require.NoError(t, os.Mkdir(filepath.Join(dir, ops[0].Filename+".json.gz"), 0755)) require.NoError(t, c.WriteJSON(map[string]string{"type": "end_mission"})) - require.NoError(t, c.SetReadDeadline(time.Now().Add(time.Second))) - _, _, err = c.ReadMessage() - require.True(t, websocket.IsCloseError(err, websocket.CloseInternalServerErr), "%v", err) - stored, err := h.repoOperation.GetByFilename(context.Background(), ops[0].Filename) - require.NoError(t, err) - require.Equal(t, "protobuf", stored.StorageFormat) - require.Equal(t, uint32(storage.SchemaVersionV2), stored.SchemaVersion) - require.Equal(t, ConversionStatusFailed, stored.ConversionStatus) - require.NoFileExists(t, filepath.Join(dir, stored.Filename+".json.gz")) + requireSaveRefused(t, h, c, ops[0].Filename) +} + +func TestHandleStream_V2FailureWithoutFallbackLeavesNoLegacyRecording(t *testing.T) { + for _, tc := range []struct { + name string + protobufOnly bool // no v1 copy was written before v2 failed + }{{name: "v1 copy"}, {name: "protobuf only", protobufOnly: true}} { + t.Run(tc.name, func(t *testing.T) { + h, mux, dir := newTestStreamHandlerWithRepo(t) + h.setting.Streaming.ProtobufOnly = tc.protobufOnly + h.setting.Streaming.DisableV1Fallback = true + c := dialTestStream(t, mux) + sendStartMission(t, c, "Fallback", "altis") + ops, err := h.repoOperation.Select(context.Background(), Filter{}) + require.NoError(t, err) + require.Len(t, ops, 1) + blockV2Chunks(t, dir, ops[0].Filename) + require.NoError(t, c.WriteJSON(map[string]string{"type": "end_mission"})) + stored := requireSaveRefused(t, h, c, ops[0].Filename) + require.Equal(t, "protobuf", stored.StorageFormat) + require.Equal(t, uint32(storage.SchemaVersionV2), stored.SchemaVersion) + require.NoFileExists(t, filepath.Join(dir, stored.Filename+".json.gz")) + }) + } } func newTestStreamHandler(enabled bool) (*Handler, *http.ServeMux) { @@ -484,7 +552,13 @@ func TestNewHandler_StreamRouteRegistered(t *testing.T) { } func TestHandleStream_FullLifecycle(t *testing.T) { + t.Run("v1 copy", func(t *testing.T) { testStreamFullLifecycle(t, false) }) + t.Run("protobuf only", func(t *testing.T) { testStreamFullLifecycle(t, true) }) +} + +func testStreamFullLifecycle(t *testing.T, protobufOnly bool) { hdlr, e, dir := newTestStreamHandlerWithRepo(t) + hdlr.setting.Streaming.ProtobufOnly = protobufOnly srv := httptest.NewServer(e) defer srv.Close() @@ -549,8 +623,19 @@ func TestHandleStream_FullLifecycle(t *testing.T) { assert.Equal(t, 1, op.PlayerCount) assert.Equal(t, 1, op.SideComposition["WEST"].Players) assert.FileExists(t, filepath.Join(dir, op.Filename, "manifest.pb")) - assert.NoFileExists(t, filepath.Join(dir, op.Filename, "manifest.json")) - assert.NoFileExists(t, filepath.Join(dir, op.Filename+".json.gz")) + if protobufOnly { + assert.NoFileExists(t, filepath.Join(dir, op.Filename, "manifest.json")) + assert.NoFileExists(t, filepath.Join(dir, op.Filename+".json.gz")) + } else { + assert.FileExists(t, filepath.Join(dir, op.Filename, "manifest.json")) + legacy, err := storage.NewJSONEngine(dir).GetManifest(context.Background(), op.Filename) + require.NoError(t, err, "the v1 JSON copy shares the recording's storage key") + assert.Equal(t, "Lifecycle Test", legacy.MissionName) + // Legacy JSON uses entity IDs as array indexes, including empty slots. + require.Len(t, legacy.Entities, 2) + assert.Equal(t, uint32(1), legacy.Entities[1].ID) + assert.Equal(t, "TestPlayer", legacy.Entities[1].Name) + } // Upstream's revision-based backfill must not replace freshly finalized stats. backfill, err := hdlr.repoOperation.SelectStatsBackfill(context.Background()) @@ -585,7 +670,7 @@ func TestHandleStream_CrashDisconnectFinalizes(t *testing.T) { // Simulate crash: just close without end_mission conn.Close() - // A legacy producer disconnect still publishes a partial protobuf recording. + // A legacy producer disconnect still publishes a partial recording. require.Eventually(t, func() bool { ops, err := h.repoOperation.Select(context.Background(), Filter{}) return err == nil && len(ops) == 1 && ops[0].ConversionStatus == ConversionStatusCompleted @@ -594,5 +679,5 @@ func TestHandleStream_CrashDisconnectFinalizes(t *testing.T) { require.NoError(t, err) require.Len(t, ops, 1) require.FileExists(t, filepath.Join(dir, ops[0].Filename, "manifest.pb")) - require.NoFileExists(t, filepath.Join(dir, ops[0].Filename+".json.gz")) + require.FileExists(t, filepath.Join(dir, ops[0].Filename+".json.gz")) } diff --git a/internal/server/route_access_test.go b/internal/server/route_access_test.go index 2d1ace004..2f9a99825 100644 --- a/internal/server/route_access_test.go +++ b/internal/server/route_access_test.go @@ -98,6 +98,7 @@ func TestRecordingRouteAccess(t *testing.T) { session.SetChunkFlusher(flusher) session.HandleAddSoldier(core.Soldier{ID: 1, UnitName: "Synthetic player", IsPlayer: true}) session.HandleSoldierState(core.SoldierState{SoldierID: 1, UnitName: "Synthetic player", IsPlayer: true}) + session.SetManifestJSON(false) // stored as with streaming.protobufOnly: no v1 copy require.NoError(t, session.Finalize(nativeDir)) path := "/ocap/data/native.json.gz" diff --git a/internal/server/setting.go b/internal/server/setting.go index 09f0e3044..8ff6c784f 100644 --- a/internal/server/setting.go +++ b/internal/server/setting.go @@ -82,6 +82,14 @@ type Streaming struct { // MaxSessions limits missions ingested at once; each holds its history // in memory. A producer turned away retries. 0 means no limit. MaxSessions int `json:"maxSessions" yaml:"maxSessions"` + // ProtobufOnly stores a native v2 recording without its v1 .json.gz copy + // and debug manifest.json. Its v1 JSON download is generated on request. + ProtobufOnly bool `json:"protobufOnly" yaml:"protobufOnly"` + // DisableV1Fallback fails a save whose v2 recording cannot be written, + // instead of keeping the mission as v1 JSON: the producer gets no + // acknowledgement, the operation is marked failed, and a resumable + // producer sends the mission again. + DisableV1Fallback bool `json:"disableV1Fallback" yaml:"disableV1Fallback"` } type CORSConfig struct { @@ -147,6 +155,8 @@ func NewSetting() (setting Setting, err error) { viper.SetDefault("streaming.resumeGrace", "5m") viper.SetDefault("streaming.ackInterval", "1s") viper.SetDefault("streaming.maxSessions", 0) + viper.SetDefault("streaming.protobufOnly", false) + viper.SetDefault("streaming.disableV1Fallback", false) viper.SetDefault("auth.sessionTTL", "24h") viper.SetDefault("auth.adminSteamIds", []string{}) viper.SetDefault("auth.steamApiKey", "") diff --git a/internal/testkit/cases.go b/internal/testkit/cases.go index 49cf84f15..69017acf0 100644 --- a/internal/testkit/cases.go +++ b/internal/testkit/cases.go @@ -42,7 +42,8 @@ var cases = []testCase{ "TestStreamRegistryReserveWaitsForConcurrentStart", "TestSendStreamPings_StopsOnWriteError", "TestSendStreamPings_StopsWhenDoneCloses", - "TestHandleStream_V2FailureLeavesNoLegacyRecording", + "TestHandleStream_V2FailurePreservesLegacyFallback", + "TestHandleStream_V2FailureWithoutFallbackLeavesNoLegacyRecording", }}, }}, {"conversion-recovery", "Clean interrupted conversions without resetting stream-owned recordings", []testStep{ diff --git a/setting.json.example b/setting.json.example index cb0c98002..f0c01dd19 100644 --- a/setting.json.example +++ b/setting.json.example @@ -39,7 +39,9 @@ "pingTimeout": "10s", "resumeGrace": "5m", "ackInterval": "1s", - "maxSessions": 0 + "maxSessions": 0, + "protobufOnly": false, + "disableV1Fallback": false }, "auth": { "mode": "public",