-
Notifications
You must be signed in to change notification settings - Fork 311
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fbfd38b
commit addcfe5
Showing
14 changed files
with
1,429 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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 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 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 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 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,135 @@ | ||
// Copyright © 2023 The Things Network Foundation, The Things Industries B.V. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
// Package events contains the internal events APi for the Console. | ||
package events | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
"sync" | ||
|
||
"github.com/gorilla/mux" | ||
"go.thethings.network/lorawan-stack/v3/pkg/auth/rights" | ||
"go.thethings.network/lorawan-stack/v3/pkg/config" | ||
"go.thethings.network/lorawan-stack/v3/pkg/console/internal/events/eventsmux" | ||
"go.thethings.network/lorawan-stack/v3/pkg/console/internal/events/subscriptions" | ||
"go.thethings.network/lorawan-stack/v3/pkg/events" | ||
"go.thethings.network/lorawan-stack/v3/pkg/log" | ||
"go.thethings.network/lorawan-stack/v3/pkg/ratelimit" | ||
"go.thethings.network/lorawan-stack/v3/pkg/task" | ||
"go.thethings.network/lorawan-stack/v3/pkg/ttnpb" | ||
"go.thethings.network/lorawan-stack/v3/pkg/web" | ||
"go.thethings.network/lorawan-stack/v3/pkg/webhandlers" | ||
"go.thethings.network/lorawan-stack/v3/pkg/webmiddleware" | ||
"nhooyr.io/websocket" | ||
) | ||
|
||
// Component is the interface of the component to the events API handler. | ||
type Component interface { | ||
task.Starter | ||
Context() context.Context | ||
RateLimiter() ratelimit.Interface | ||
GetBaseConfig(context.Context) config.ServiceBase | ||
} | ||
|
||
type eventsHandler struct { | ||
component Component | ||
subscriber events.Subscriber | ||
definedNames map[string]struct{} | ||
} | ||
|
||
var _ web.Registerer = (*eventsHandler)(nil) | ||
|
||
func (h *eventsHandler) RegisterRoutes(server *web.Server) { | ||
router := server.APIRouter().PathPrefix(ttnpb.HTTPAPIPrefix + "/console/internal/events/").Subrouter() | ||
router.Use( | ||
mux.MiddlewareFunc(webmiddleware.Namespace("console/internal/events")), | ||
ratelimit.HTTPMiddleware(h.component.RateLimiter(), "http:console:internal:events"), | ||
mux.MiddlewareFunc(webmiddleware.Metadata("Authorization")), | ||
) | ||
router.Path("/").HandlerFunc(h.handleEvents).Methods(http.MethodGet) | ||
} | ||
|
||
func (h *eventsHandler) handleEvents(w http.ResponseWriter, r *http.Request) { | ||
ctx := r.Context() | ||
logger := log.FromContext(ctx) | ||
|
||
if err := rights.RequireAuthenticated(ctx); err != nil { | ||
webhandlers.Error(w, r, err) | ||
return | ||
} | ||
|
||
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{ | ||
InsecureSkipVerify: true, // CORS is not enabled for APIs. | ||
CompressionMode: websocket.CompressionContextTakeover, | ||
}) | ||
if err != nil { | ||
logger.WithError(err).Debug("Failed to accept WebSocket") | ||
return | ||
} | ||
defer conn.Close(websocket.StatusNormalClosure, "main task closed") | ||
|
||
ctx, cancel := context.WithCancelCause(ctx) | ||
defer cancel(nil) | ||
|
||
var wg sync.WaitGroup | ||
defer wg.Wait() | ||
|
||
m := eventsmux.New(func(ctx context.Context, cancel func(error)) subscriptions.Interface { | ||
return subscriptions.New(ctx, cancel, h.subscriber, h.definedNames, h.component) | ||
}) | ||
for name, f := range map[string]func(context.Context) error{ | ||
"console_events_mux": makeMuxTask(m, cancel), | ||
"console_events_read": makeReadTask(conn, m, cancel), | ||
"console_events_write": makeWriteTask(conn, m, cancel), | ||
} { | ||
wg.Add(1) | ||
h.component.StartTask(&task.Config{ | ||
Context: ctx, | ||
ID: name, | ||
Func: f, | ||
Done: wg.Done, | ||
Restart: task.RestartNever, | ||
Backoff: task.DefaultBackoffConfig, | ||
}) | ||
} | ||
} | ||
|
||
// Option configures the events API handler. | ||
type Option func(*eventsHandler) | ||
|
||
// WithSubscriber configures the Subscriber to use for events. | ||
func WithSubscriber(subscriber events.Subscriber) Option { | ||
return func(h *eventsHandler) { | ||
h.subscriber = subscriber | ||
} | ||
} | ||
|
||
// New returns an events API handler for the Console. | ||
func New(c Component, opts ...Option) web.Registerer { | ||
definedNames := make(map[string]struct{}) | ||
for _, def := range events.All().Definitions() { | ||
definedNames[def.Name()] = struct{}{} | ||
} | ||
h := &eventsHandler{ | ||
component: c, | ||
subscriber: events.DefaultPubSub(), | ||
definedNames: definedNames, | ||
} | ||
for _, opt := range opts { | ||
opt(h) | ||
} | ||
return h | ||
} |
This file contains 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,106 @@ | ||
// Copyright © 2023 The Things Network Foundation, The Things Industries B.V. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
// Package eventsmux implements the events mux. | ||
package eventsmux | ||
|
||
import ( | ||
"context" | ||
|
||
"go.thethings.network/lorawan-stack/v3/pkg/console/internal/events/protocol" | ||
"go.thethings.network/lorawan-stack/v3/pkg/console/internal/events/subscriptions" | ||
"go.thethings.network/lorawan-stack/v3/pkg/events" | ||
"go.thethings.network/lorawan-stack/v3/pkg/log" | ||
) | ||
|
||
// Interface is the interface for the events mux. | ||
type Interface interface { | ||
// Requests returns the channel for requests. | ||
Requests() chan<- protocol.Request | ||
// Responses returns the channel for responses. | ||
Responses() <-chan protocol.Response | ||
|
||
// Run runs the events mux. | ||
Run(context.Context) error | ||
} | ||
|
||
type mux struct { | ||
createSubs func(context.Context, func(error)) subscriptions.Interface | ||
|
||
requestCh chan protocol.Request | ||
responseCh chan protocol.Response | ||
} | ||
|
||
// Requests implements Interface. | ||
func (m *mux) Requests() chan<- protocol.Request { | ||
return m.requestCh | ||
} | ||
|
||
// Responses implements Interface. | ||
func (m *mux) Responses() <-chan protocol.Response { | ||
return m.responseCh | ||
} | ||
|
||
// Run implements Interface. | ||
func (m *mux) Run(ctx context.Context) (err error) { | ||
ctx, cancel := context.WithCancelCause(ctx) | ||
defer func() { cancel(err) }() | ||
subs := m.createSubs(ctx, cancel) | ||
defer subs.Close() | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
return ctx.Err() | ||
case req := <-m.requestCh: | ||
var resp protocol.Response | ||
switch req := req.(type) { | ||
case *protocol.SubscribeRequest: | ||
resp = req.Response(subs.Subscribe(req.ID, req.Identifiers, req.After, req.Tail, req.Names)) | ||
case *protocol.UnsubscribeRequest: | ||
resp = req.Response(subs.Unsubscribe(req.ID)) | ||
default: | ||
panic("unreachable") | ||
} | ||
select { | ||
case <-ctx.Done(): | ||
return ctx.Err() | ||
case m.responseCh <- resp: | ||
} | ||
case subEvt := <-subs.SubscriptionEvents(): | ||
evtPB, err := events.Proto(subEvt.Event) | ||
if err != nil { | ||
log.FromContext(ctx).WithError(err).Warn("Failed to convert event to proto") | ||
continue | ||
} | ||
select { | ||
case <-ctx.Done(): | ||
return ctx.Err() | ||
case m.responseCh <- &protocol.PublishResponse{ | ||
ID: subEvt.ID, | ||
Event: evtPB, | ||
}: | ||
} | ||
} | ||
} | ||
} | ||
|
||
// New returns a new Interface. | ||
func New(createSubs func(context.Context, func(error)) subscriptions.Interface) Interface { | ||
return &mux{ | ||
createSubs: createSubs, | ||
|
||
requestCh: make(chan protocol.Request, 1), | ||
responseCh: make(chan protocol.Response, 1), | ||
} | ||
} |
Oops, something went wrong.