Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
62 commits
Select commit Hold shift + click to select a range
76d837f
feat: add CDP pipeline, cdpmonitor, and wire into API service
archandatta Apr 2, 2026
5c0f7ae
refactor: rename Pipeline to CaptureSession and delete pipeline.go
archandatta Apr 2, 2026
ad2dd63
review: fix request context leak in StartCapture, add missing categor…
archandatta Apr 2, 2026
365787c
review: clean up syntax
archandatta Apr 6, 2026
d086571
review: move CategoryFor to cdpmonitor package
archandatta Apr 7, 2026
3339cac
review: internalize ring buffer and file writer in CaptureSession con…
archandatta Apr 7, 2026
64e67b1
review: write logs under /var/log/kernel and ensure dir exists
archandatta Apr 7, 2026
048f9c6
review: add capture config to /events/start and OpenAPI spec
archandatta Apr 7, 2026
e57e58a
review: fix lifecycle context, stop-before-reset ordering, seq reset,…
archandatta Apr 7, 2026
886b893
fix: oapi version
archandatta Apr 7, 2026
06d2470
fix: Shutdown cancels context outside lock, racing with StartCapture
archandatta Apr 7, 2026
6bb5402
review: validate DetailLevel with generated Valid
archandatta Apr 7, 2026
cb45a55
fix: reset ring buffer on session restart to unstrand existing readers
archandatta Apr 7, 2026
02ee74e
chore: remove dead categoryFor function
archandatta Apr 7, 2026
3523994
review: guard zero-capacity ring buffer and fix reader reset after bu…
archandatta Apr 7, 2026
cb1a1a7
review: use t.TempDir in test helper, map-based ValidCategory, avoid …
archandatta Apr 7, 2026
c9e78a3
review: add captureConfigFrom and StartCapture/StopCapture handler tests
archandatta Apr 7, 2026
1cddf53
feat: refactor events API to resource-style capture sessions
archandatta Apr 8, 2026
c6dd362
review: update file writer to be internal to the package
archandatta Apr 9, 2026
ff8bddf
review: tighten to `Write(filename string, data []byte) error`
archandatta Apr 9, 2026
a8bdeaf
review: update panic -> error
archandatta Apr 9, 2026
8f88ed0
review: update oapi and remove detail level
archandatta Apr 9, 2026
3eaacb3
review: remove url
archandatta Apr 9, 2026
214858a
chore: restore server/api on branch
archandatta Apr 9, 2026
b06132a
review: harden captureConfigFromOAPI and clarify stop comment
archandatta Apr 9, 2026
8ebb5e3
review: unexport ringBuffer and drop AllCategories wrapper
archandatta Apr 9, 2026
4bcba48
review: replace event producers with cdp monitor in stop description
archandatta Apr 9, 2026
1295232
remove test line
archandatta Apr 9, 2026
a4fd0d6
review: update uuid to cuid2
archandatta Apr 10, 2026
d6b348b
Merge branch 'main' into archand/kernel-1116/cdp-pipeline
archandatta Apr 10, 2026
3da65c3
Merge branch 'main' into archand/kernel-1116/cdp-pipeline
archandatta Apr 10, 2026
a7b2e54
fix naming
archandatta Apr 10, 2026
85d570a
feat: add cdpmonitor foundation — types, util, computed state machine…
archandatta Apr 13, 2026
bed53f8
self review
archandatta Apr 13, 2026
d73793c
review: cursor feedback
archandatta Apr 13, 2026
348243a
[kernel-1116] CDP monitor core (#214)
archandatta Apr 13, 2026
a62c403
review: update types and sensitive interaction data
archandatta Apr 14, 2026
0605227
feat: add two-layer CDP decode, protocol-faithful types, then monitor…
archandatta Apr 14, 2026
33c07d3
Merge branch 'main' into archand/kernel-1116/cdp-pipeline
archandatta Apr 21, 2026
9c6e066
review: clean up monitor health and types
archandatta Apr 22, 2026
5dd9273
review: add chromium version
archandatta Apr 22, 2026
7550bc1
review: remove dead code
archandatta Apr 22, 2026
f3d3166
Merge branch 'archand/kernel-1116/cdp-pipeline' into archand/kernel-1…
archandatta Apr 22, 2026
1cfbc5e
fix injection script
archandatta Apr 22, 2026
2e0c4a0
review: remove sensitive data from inject
archandatta Apr 22, 2026
bf4b04c
review
archandatta Apr 22, 2026
90a3ae1
review: sensitive data audit interaction.js
archandatta Apr 22, 2026
4feef7e
review: reconnect failure leaks goroutines and deadlocks Stop
archandatta Apr 22, 2026
8e94162
Merge branch 'main' into archand/kernel-1116/cdp-foundation
archandatta Apr 22, 2026
5465e59
review: create cdpMonitorController
archandatta Apr 22, 2026
7c4c654
review: add ctx to monitor and update comment
archandatta Apr 23, 2026
bca495b
review: lift lifeMu to dispatch level to make ctx handling explicit
archandatta Apr 23, 2026
fd4d4d3
review: add readme for cdp monitor
archandatta Apr 23, 2026
ad28202
feat: capturesession: add Active(), publishLocked helper, session_end…
archandatta Apr 23, 2026
1f45379
feat: openapi: add /events/publish and /events/stream paths + Cache-C…
archandatta Apr 23, 2026
ff2a221
chore: regenerate oapi.go with publishEvent + streamEvents endpoints
archandatta Apr 23, 2026
83d118f
feat: add PublishEvent and StreamEvents handlers
archandatta Apr 23, 2026
0a89c58
review: address feedback
archandatta Apr 24, 2026
f97e3a9
review: update comment
archandatta Apr 24, 2026
4cb8f0e
review: add events lifecycle test
archandatta May 1, 2026
55abde4
Merge branch 'main' into archand/kernel-1116/external-events
archandatta May 6, 2026
232eb37
review: add documentation
archandatta May 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ oapi-generate:
openapi-down-convert --input openapi.yaml --output openapi-3.0.yaml
go tool oapi-codegen -config ./oapi-codegen.yaml ./openapi-3.0.yaml
@echo "Fixing oapi-codegen issue https://github.com/oapi-codegen/oapi-codegen/issues/1764..."
go run ./scripts/oapi/patch_sse_methods -file ./lib/oapi/oapi.go -expected-replacements 3
go run ./scripts/oapi/patch_sse_methods -file ./lib/oapi/oapi.go -expected-replacements 4
go fmt ./lib/oapi/oapi.go
go mod tidy

Expand Down
8 changes: 4 additions & 4 deletions server/cmd/api/api/capture_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestCaptureConfigFrom(t *testing.T) {
})

t.Run("valid categories", func(t *testing.T) {
cats := []oapi.CaptureConfigCategories{oapi.Console, oapi.Network}
cats := []oapi.CaptureConfigCategories{oapi.CaptureConfigCategoriesConsole, oapi.CaptureConfigCategoriesNetwork}
body := &oapi.StartCaptureSessionRequest{
Config: &oapi.CaptureConfig{Categories: &cats},
}
Expand Down Expand Up @@ -64,7 +64,7 @@ func TestStartCaptureSession(t *testing.T) {

t.Run("success with config", func(t *testing.T) {
svc := newTestService(t, newMockRecordManager())
cats := []oapi.CaptureConfigCategories{oapi.Console}
cats := []oapi.CaptureConfigCategories{oapi.CaptureConfigCategoriesConsole}
resp, err := svc.StartCaptureSession(ctx, oapi.StartCaptureSessionRequestObject{
Body: &oapi.StartCaptureSessionRequest{
Config: &oapi.CaptureConfig{Categories: &cats},
Expand Down Expand Up @@ -141,7 +141,7 @@ func TestUpdateCaptureSession(t *testing.T) {
_, err := svc.StartCaptureSession(ctx, oapi.StartCaptureSessionRequestObject{})
require.NoError(t, err)

cats := []oapi.CaptureConfigCategories{oapi.Console}
cats := []oapi.CaptureConfigCategories{oapi.CaptureConfigCategoriesConsole}
resp, err := svc.UpdateCaptureSession(ctx, oapi.UpdateCaptureSessionRequestObject{
Body: &oapi.UpdateCaptureSessionRequest{
Config: &oapi.CaptureConfig{Categories: &cats},
Expand All @@ -152,7 +152,7 @@ func TestUpdateCaptureSession(t *testing.T) {
require.True(t, ok)
require.NotNil(t, r200.Config.Categories)
assert.Len(t, *r200.Config.Categories, 1)
assert.Equal(t, oapi.Console, (*r200.Config.Categories)[0])
assert.Equal(t, oapi.CaptureConfigCategoriesConsole, (*r200.Config.Categories)[0])
})

t.Run("empty body is no-op", func(t *testing.T) {
Expand Down
166 changes: 166 additions & 0 deletions server/cmd/api/api/events.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package api

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"time"

"github.com/kernel/kernel-images/server/lib/events"
oapi "github.com/kernel/kernel-images/server/lib/oapi"
)

// PublishEvent handles POST /events/publish.
// Injects a caller-supplied event into the active capture session. Returns 400
// if no session is active or the event fails validation.
func (s *ApiService) PublishEvent(_ context.Context, req oapi.PublishEventRequestObject) (oapi.PublishEventResponseObject, error) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we add one lifecycle test for the new event flow? Something like start capture session, publish an event through PublishEvent, read it from StreamEvents, then stop and verify the stream receives session_ended.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if !s.captureSession.Active() {
return oapi.PublishEvent400JSONResponse{BadRequestErrorJSONResponse: oapi.BadRequestErrorJSONResponse{Message: "no active capture session"}}, nil
}

body := req.Body
if body == nil || body.Type == "" {
return oapi.PublishEvent400JSONResponse{BadRequestErrorJSONResponse: oapi.BadRequestErrorJSONResponse{Message: "type is required"}}, nil
}
if body.Type == events.TypeSessionEnded || body.Type == events.TypeEventsDropped {
return oapi.PublishEvent400JSONResponse{BadRequestErrorJSONResponse: oapi.BadRequestErrorJSONResponse{Message: "type is reserved"}}, nil
}

ev := events.Event{Type: body.Type}

if body.Ts != nil {
ev.Ts = *body.Ts
}
if body.Category != nil {
cat := events.EventCategory(*body.Category)
if !events.ValidCategory(cat) {
return oapi.PublishEvent400JSONResponse{BadRequestErrorJSONResponse: oapi.BadRequestErrorJSONResponse{Message: "invalid category"}}, nil
}
ev.Category = cat
} else {
ev.Category = events.CategorySystem
}
Comment thread
archandatta marked this conversation as resolved.

// Enforce source.kind = KindKernelAPI so callers can't spoof the origin.
ev.Source.Kind = events.KindKernelAPI
if body.Source != nil {
if body.Source.Event != nil {
ev.Source.Event = *body.Source.Event
}
if body.Source.Metadata != nil {
ev.Source.Metadata = *body.Source.Metadata
}
}

if body.Data != nil {
// re-marshal body.Data to normalize it into a canonical RawMessage byte slice.
data, err := json.Marshal(body.Data)
if err != nil {
return oapi.PublishEvent400JSONResponse{BadRequestErrorJSONResponse: oapi.BadRequestErrorJSONResponse{Message: "invalid data"}}, nil
}
ev.Data = json.RawMessage(data)
}

s.captureSession.PublishUnfiltered(ev)
return oapi.PublishEvent200Response{}, nil
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PublishEvent returns 200 when event silently dropped

Low Severity

PublishEvent checks Active() then later calls PublishUnfiltered, but these are separate mutex acquisitions. If the session stops between them, PublishUnfiltered silently drops the event (it returns nothing), yet the handler still returns a 200 "Event accepted" response. The caller has no indication the event was lost. Having PublishUnfiltered return a boolean indicating whether the event was actually published would let the handler respond accurately.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 55abde4. Configure here.

}

// StreamEvents handles GET /events/stream.
// Opens an SSE stream of envelopes from the active capture session's ring buffer.
// Supports reconnection via the Last-Event-ID header. Emits a keepalive comment
// frame every 15 s when no event arrives, and exits cleanly on session_ended.
func (s *ApiService) StreamEvents(ctx context.Context, req oapi.StreamEventsRequestObject) (oapi.StreamEventsResponseObject, error) {
if !s.captureSession.Active() {
return oapi.StreamEvents400JSONResponse{BadRequestErrorJSONResponse: oapi.BadRequestErrorJSONResponse{Message: "no active capture session"}}, nil
}

afterSeq := uint64(0)
if id := req.Params.LastEventID; id != nil && *id != "" {
// Invalid/non-numeric values fall back to 0, replaying all events from the start.
// Note: seq is per capture session and resets on each Start(). A Last-Event-ID
// from a previous session may silently overlap with the current session's seqs.
if n, err := strconv.ParseUint(*id, 10, 64); err == nil {
afterSeq = n
}
}

sessionID := s.captureSession.ID()
reader := s.captureSession.NewReader(afterSeq)
Comment thread
archandatta marked this conversation as resolved.

pr, pw := io.Pipe()
go func() {
defer pw.Close()
for {
readCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
result, err := reader.Read(readCtx)
cancel()
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
select {
case <-ctx.Done():
return
default:
// No event in 15 s and client still connected, send keepalive.
if _, err := pw.Write([]byte(":\n\n")); err != nil {
return
}
continue
}
}
return
}

if result.Dropped > 0 {
env := events.Envelope{
CaptureSessionID: sessionID,
Seq: 0,
Event: events.Event{
Ts: time.Now().UnixMicro(),
Type: events.TypeEventsDropped,
Category: events.CategorySystem,
Source: events.Source{Kind: events.KindKernelAPI},
Data: json.RawMessage(fmt.Sprintf(`{"dropped":%d}`, result.Dropped)),
},
}
// Omit the id: field so the client's Last-Event-ID is not overwritten.
if err := writeEnvelopeFrame(pw, nil, env); err != nil {
return
}
continue
Comment thread
cursor[bot] marked this conversation as resolved.
}

env := result.Envelope
if err := writeEnvelopeFrame(pw, &env.Seq, *env); err != nil {
return
}
if env.Event.Type == events.TypeSessionEnded {
return
}
}
}()

headers := oapi.StreamEvents200ResponseHeaders{XSSEContentType: "application/json"}
return oapi.StreamEvents200TexteventStreamResponse{Body: pr, Headers: headers}, nil
}

// writeEnvelopeFrame writes a single SSE frame. If seq is non-nil it is
// emitted as the id: field, updating the client's Last-Event-ID.
func writeEnvelopeFrame(w io.Writer, seq *uint64, env events.Envelope) error {
data, err := json.Marshal(env)
if err != nil {
return err
}
var buf bytes.Buffer
if seq != nil {
fmt.Fprintf(&buf, "id: %d\n", *seq)
}
buf.WriteString("data: ")
buf.Write(data)
buf.WriteString("\n\n")
_, err = w.Write(buf.Bytes())
return err
}
92 changes: 92 additions & 0 deletions server/cmd/api/api/events_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package api

import (
"bufio"
"context"
"encoding/json"
"strings"
"testing"
"time"

"github.com/kernel/kernel-images/server/lib/events"
oapi "github.com/kernel/kernel-images/server/lib/oapi"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestEventLifecycle(t *testing.T) {
t.Parallel()
ctx := context.Background()
svc := newTestService(t, newMockRecordManager())

// Start a capture session.
startResp, err := svc.StartCaptureSession(ctx, oapi.StartCaptureSessionRequestObject{})
require.NoError(t, err)
require.IsType(t, oapi.StartCaptureSession201JSONResponse{}, startResp)

// Open an SSE stream (5s budget covers the three 2s selects below).
streamCtx, streamCancel := context.WithTimeout(ctx, 5*time.Second)
defer streamCancel()
streamResp, err := svc.StreamEvents(streamCtx, oapi.StreamEventsRequestObject{})
require.NoError(t, err)
r200, ok := streamResp.(oapi.StreamEvents200TexteventStreamResponse)
require.True(t, ok)

// Drain SSE frames into a channel.
received := make(chan events.Envelope, 4)
go func() {
defer close(received)
rd := bufio.NewReader(r200.Body)
for {
line, err := rd.ReadString('\n')
if err != nil {
return
}
if !strings.HasPrefix(line, "data: ") {
continue
}
payload := strings.TrimSpace(strings.TrimPrefix(line, "data: "))
var env events.Envelope
if err := json.Unmarshal([]byte(payload), &env); err != nil {
continue
}
received <- env
}
}()

// Publish an event.
resp, err := svc.PublishEvent(ctx, oapi.PublishEventRequestObject{
Body: &oapi.Event{Type: "test.event"},
})
require.NoError(t, err)
assert.IsType(t, oapi.PublishEvent200Response{}, resp)

// Verify the published event arrives on the stream.
select {
case env := <-received:
assert.Equal(t, "test.event", env.Event.Type)
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for test.event")
}

// Stop the session.
stopResp, err := svc.StopCaptureSession(ctx, oapi.StopCaptureSessionRequestObject{})
require.NoError(t, err)
assert.IsType(t, oapi.StopCaptureSession200JSONResponse{}, stopResp)

// Verify session_ended arrives on the stream.
select {
case env := <-received:
assert.Equal(t, events.TypeSessionEnded, env.Event.Type)
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for session_ended")
}

// Verify the stream closes after session_ended.
select {
case _, open := <-received:
assert.False(t, open, "stream should be closed after session_ended")
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for stream to close")
}
}
Loading
Loading