-
Notifications
You must be signed in to change notification settings - Fork 58
[kernel-1116] browser events: add external events #227
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 62 commits
Commits
Show all changes
76 commits
Select commit
Hold shift + click to select a range
76d837f
feat: add CDP pipeline, cdpmonitor, and wire into API service
archandatta 5c0f7ae
refactor: rename Pipeline to CaptureSession and delete pipeline.go
archandatta ad2dd63
review: fix request context leak in StartCapture, add missing categor…
archandatta 365787c
review: clean up syntax
archandatta d086571
review: move CategoryFor to cdpmonitor package
archandatta 3339cac
review: internalize ring buffer and file writer in CaptureSession con…
archandatta 64e67b1
review: write logs under /var/log/kernel and ensure dir exists
archandatta 048f9c6
review: add capture config to /events/start and OpenAPI spec
archandatta e57e58a
review: fix lifecycle context, stop-before-reset ordering, seq reset,…
archandatta 886b893
fix: oapi version
archandatta 06d2470
fix: Shutdown cancels context outside lock, racing with StartCapture
archandatta 6bb5402
review: validate DetailLevel with generated Valid
archandatta cb45a55
fix: reset ring buffer on session restart to unstrand existing readers
archandatta 02ee74e
chore: remove dead categoryFor function
archandatta 3523994
review: guard zero-capacity ring buffer and fix reader reset after bu…
archandatta cb1a1a7
review: use t.TempDir in test helper, map-based ValidCategory, avoid …
archandatta c9e78a3
review: add captureConfigFrom and StartCapture/StopCapture handler tests
archandatta 1cddf53
feat: refactor events API to resource-style capture sessions
archandatta c6dd362
review: update file writer to be internal to the package
archandatta ff8bddf
review: tighten to `Write(filename string, data []byte) error`
archandatta a8bdeaf
review: update panic -> error
archandatta 8f88ed0
review: update oapi and remove detail level
archandatta 3eaacb3
review: remove url
archandatta 214858a
chore: restore server/api on branch
archandatta b06132a
review: harden captureConfigFromOAPI and clarify stop comment
archandatta 8ebb5e3
review: unexport ringBuffer and drop AllCategories wrapper
archandatta 4bcba48
review: replace event producers with cdp monitor in stop description
archandatta 1295232
remove test line
archandatta a4fd0d6
review: update uuid to cuid2
archandatta d6b348b
Merge branch 'main' into archand/kernel-1116/cdp-pipeline
archandatta 3da65c3
Merge branch 'main' into archand/kernel-1116/cdp-pipeline
archandatta a7b2e54
fix naming
archandatta 85d570a
feat: add cdpmonitor foundation — types, util, computed state machine…
archandatta bed53f8
self review
archandatta d73793c
review: cursor feedback
archandatta 348243a
[kernel-1116] CDP monitor core (#214)
archandatta a62c403
review: update types and sensitive interaction data
archandatta 0605227
feat: add two-layer CDP decode, protocol-faithful types, then monitor…
archandatta 33c07d3
Merge branch 'main' into archand/kernel-1116/cdp-pipeline
archandatta 9c6e066
review: clean up monitor health and types
archandatta 5dd9273
review: add chromium version
archandatta 7550bc1
review: remove dead code
archandatta f3d3166
Merge branch 'archand/kernel-1116/cdp-pipeline' into archand/kernel-1…
archandatta 1cfbc5e
fix injection script
archandatta 2e0c4a0
review: remove sensitive data from inject
archandatta bf4b04c
review
archandatta 90a3ae1
review: sensitive data audit interaction.js
archandatta 4feef7e
review: reconnect failure leaks goroutines and deadlocks Stop
archandatta 8e94162
Merge branch 'main' into archand/kernel-1116/cdp-foundation
archandatta 5465e59
review: create cdpMonitorController
archandatta 7c4c654
review: add ctx to monitor and update comment
archandatta bca495b
review: lift lifeMu to dispatch level to make ctx handling explicit
archandatta fd4d4d3
review: add readme for cdp monitor
archandatta ad28202
feat: capturesession: add Active(), publishLocked helper, session_end…
archandatta 1f45379
feat: openapi: add /events/publish and /events/stream paths + Cache-C…
archandatta ff2a221
chore: regenerate oapi.go with publishEvent + streamEvents endpoints
archandatta 83d118f
feat: add PublishEvent and StreamEvents handlers
archandatta 0a89c58
review: address feedback
archandatta f97e3a9
review: update comment
archandatta 4cb8f0e
review: add events lifecycle test
archandatta 55abde4
Merge branch 'main' into archand/kernel-1116/external-events
archandatta 232eb37
review: add documentation
archandatta 093d8cc
review: introduce PublishEventRequest, honor caller source.kind
archandatta 059f929
review: return assigned envelope from publishEvent
archandatta 7bc3050
review: make seqs process-monotonic across capture sessions
archandatta 56782c0
review: update SSE type
archandatta 5362a27
review: extract EventStream from CaptureSession for process-lifetime …
archandatta 2a4219a
review: remove file writer from EventStream
archandatta 678df70
review: move kernel_api reservation note to EventSource.kind, clean u…
archandatta bc984ab
refactor: move capture_session_id from Envelope into Event.Data, extr…
archandatta 47ce172
refactor: decouple publish/subscribe API from capture session
archandatta e8657e5
review: rename TypeSessionEnded → CaptureSessionEnded, TypeEventsDrop…
archandatta 1762276
review: serialize Envelope directly in PublishEvent response
archandatta f54ba6c
review: move capture_session_id from event data to source.metadata
archandatta 808f9db
refactor: remove events_dropped and capture_session_ended synthetic s…
archandatta bb38112
review: document gap-detection contract for dropped events on SSE stream
archandatta File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) { | ||
| 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 | ||
| } | ||
|
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 | ||
|
cursor[bot] marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| // 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) | ||
|
archandatta marked this conversation as resolved.
Outdated
|
||
|
|
||
| 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 | ||
|
cursor[bot] marked this conversation as resolved.
|
||
| } | ||
|
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 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 fromStreamEvents, then stop and verify the stream receivessession_ended.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
4cb8f0e