-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmount.go
More file actions
2454 lines (2199 loc) · 81.9 KB
/
mount.go
File metadata and controls
2454 lines (2199 loc) · 81.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package livetemplate
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/url"
"os"
"path"
"reflect"
"strings"
"sync"
"sync/atomic"
"time"
lvtcontext "github.com/livetemplate/livetemplate/internal/context"
"github.com/livetemplate/livetemplate/internal/observe"
"github.com/livetemplate/livetemplate/internal/send"
"github.com/livetemplate/livetemplate/internal/session"
"github.com/livetemplate/livetemplate/internal/upload"
"github.com/livetemplate/livetemplate/internal/uploadtypes"
"github.com/livetemplate/livetemplate/pubsub"
"golang.org/x/time/rate"
)
// Session allows controllers to trigger server-initiated actions for
// connected clients. Actions triggered via Session affect every connection
// in the same session group (all tabs sharing one browser session, plus
// any additional devices that the configured Authenticator places in the
// same group).
//
// This is the recommended way to implement:
// - Timers and ticks
// - Background job completion notifications
// - Webhook-triggered updates
// - Cross-tab synchronization
//
// Scope: Session is scoped to a session group (groupID), not to a user
// identity (userID). For the typical anonymous flow where each browser
// session maps to one group via cookie, this is equivalent to "all tabs
// of this browser". For authenticated flows the mapping depends on how
// the Authenticator assigns groupIDs — a user with multiple devices may
// share a group across devices (by returning a stable groupID keyed on
// userID) or may have per-device groups (by returning a per-session
// groupID). Session.TriggerAction always targets the group of the
// Context it was obtained from, never other groups.
type Session interface {
// TriggerAction dispatches the action to the matching controller
// method on every connection in the session group, then sends the
// updated template to each of those connections.
//
// This behaves identically to client-initiated actions: the action
// runs through the controller's action method, errors are captured,
// and diffs are sent over WebSocket to each connection.
//
// Example:
// session.TriggerAction("tick", nil)
// session.TriggerAction("new_notification", map[string]interface{}{"id": 123})
TriggerAction(action string, data map[string]interface{}) error
}
// LiveHandler is the interface returned by Template.Handle()
// It provides HTTP handling and lifecycle management for live template connections.
//
// For server-initiated actions, implement an OnConnect(state, ctx) lifecycle
// method on your controller and call ctx.Session() to obtain a Session handle
// that can be used to trigger actions from background goroutines. See the
// Session interface above and docs/references/server-actions.md for details.
type LiveHandler interface {
http.Handler
// Shutdown gracefully shuts down the handler, draining connections.
//
// It performs the following steps:
// 1. Stops accepting new WebSocket connections
// 2. Sends close frames to all active WebSocket connections
// 3. Waits for in-flight requests to complete (respecting context timeout)
//
// The context timeout controls how long to wait for connections to close.
// After the timeout, remaining connections are forcefully closed.
//
// Example usage with http.Server:
// ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
// defer cancel()
// handler.Shutdown(ctx)
// server.Shutdown(ctx)
Shutdown(ctx context.Context) error
// MetricsHandler returns an http.Handler that exports Prometheus metrics.
//
// The handler responds to GET requests with metrics in Prometheus text format.
// Typically mounted at /metrics for scraping by Prometheus.
//
// Example with standard library http mux:
// mux := http.NewServeMux()
// handler := template.Handle(store)
// mux.Handle("/live", handler)
// mux.Handle("/metrics", handler.MetricsHandler())
// http.ListenAndServe(":8080", mux)
//
// Example with gorilla/mux:
// r := mux.NewRouter()
// handler := template.Handle(store)
// r.Handle("/live", handler)
// r.Handle("/metrics", handler.MetricsHandler())
MetricsHandler() http.Handler
}
const syncMethodName = "Sync"
// ephemeralSweepTTL is how long idle HTTP template cache entries survive in ephemeral
// mode before being evicted by the sweep loop. 30 minutes balances memory reclamation
// for abandoned sessions vs keeping diff baselines alive for active users between
// interactions (e.g., reading a page before submitting a form).
const ephemeralSweepTTL = 30 * time.Minute
// mountConfig configures the mount handler (internal only)
type mountConfig struct {
Template *Template
Controller interface{} // Singleton controller with dependencies
State State // Initial state template (cloned per session)
Upgrader WSUpgrader
SessionStore SessionStore
Authenticator Authenticator
PubSubBroadcaster pubsub.Broadcaster // Optional: for distributed broadcasting across instances
AllowedOrigins []string
WebSocketDisabled bool
MaxConnections int64 // Maximum total connections (0 = unlimited)
MaxConnectionsPerGroup int64 // Maximum connections per group (0 = unlimited)
CookieMaxAge time.Duration // Session cookie max age (default: 1 year)
UploadConfigs map[string]uploadtypes.UploadConfig // Upload field configurations
wsBufferSize int // WebSocket send buffer size per connection (default: 50)
ProgressiveEnhancement bool // Enable non-JS form submission support with PRG pattern (default: true)
HasSync bool // Controller implements Sync() lifecycle method (detected once at Handle() time via reflection, not per-request)
Capabilities []string // Controller capabilities detected at setup (e.g., ["change"])
}
// liveHandler handles both WebSocket and HTTP requests
type liveHandler struct {
config mountConfig
persistable persistableState // non-nil if state has lvt:"persist" fields
registry *session.ConnectionRegistry
limits *session.ConnectionLimits
metricsExporter *observe.PrometheusExporter
tempFileManager uploadTempFileManager
httpTemplates sync.Map // groupID → *httpTemplateCacheEntry (cached for HTTP POST diff optimization)
httpLastPaths sync.Map // groupID → string (last served request path, for detecting URL changes)
// Graceful shutdown state
shutdownOnce sync.Once
shutdownChan chan struct{}
shutdownWg sync.WaitGroup
isShutdown atomic.Bool
}
// httpTemplateCacheEntry wraps a cached Template with a mutex.
// Concurrent HTTP requests for the same groupID (e.g., multiple tabs)
// must serialize template operations to avoid data races on lastTree/lastData.
type httpTemplateCacheEntry struct {
mu sync.Mutex
tmpl *Template
lastAccessed atomic.Int64 // unix timestamp, for time-based eviction in ephemeral mode
}
// wsReadMessage carries data from the readPump goroutine to the event loop.
type wsReadMessage struct {
data []byte
err error
}
type connState struct {
state interface{} // Typed state (cloned per session)
messages map[string]string // Unified map: field errors + flash (prefixed with "_flash:")
messagesMu sync.RWMutex // Mutex for thread-safe message access
groupID string // Session/group ID for this connection
}
func (c *connState) setError(field, message string) {
c.messagesMu.Lock()
defer c.messagesMu.Unlock()
c.messages[field] = message
}
func (c *connState) clearErrors() {
c.messagesMu.Lock()
defer c.messagesMu.Unlock()
// Clear field errors but preserve flash messages for the upcoming render.
// Flash messages are cleared separately after the response is sent.
newMessages := make(map[string]string)
for k, v := range c.messages {
if strings.HasPrefix(k, lvtcontext.FlashPrefix) {
newMessages[k] = v
}
}
c.messages = newMessages
}
func (c *connState) getMessages() map[string]string {
c.messagesMu.RLock()
defer c.messagesMu.RUnlock()
// Return copy to avoid race conditions
result := make(map[string]string, len(c.messages))
for k, v := range c.messages {
result[k] = v
}
return result
}
func (c *connState) setFlash(key, message string) {
// Validate key: reject keys with ":" or starting with "_"
if strings.Contains(key, ":") || strings.HasPrefix(key, "_") {
slog.Warn("Invalid flash key ignored",
slog.String("component", "live_handler"),
slog.String("key", key),
slog.String("reason", "keys must not contain ':' or start with '_'"))
return
}
c.messagesMu.Lock()
defer c.messagesMu.Unlock()
c.messages[lvtcontext.FlashPrefix+key] = message
}
func (c *connState) clearFlash() {
c.messagesMu.Lock()
defer c.messagesMu.Unlock()
// Only clear flash messages (preserve errors)
newMessages := make(map[string]string)
for k, v := range c.messages {
if !strings.HasPrefix(k, lvtcontext.FlashPrefix) {
newMessages[k] = v
}
}
c.messages = newMessages
}
// getFlashValues returns all flash messages as url.Values for cookie encoding.
func (c *connState) getFlashValues() url.Values {
c.messagesMu.RLock()
defer c.messagesMu.RUnlock()
vals := url.Values{}
for k, v := range c.messages {
if strings.HasPrefix(k, lvtcontext.FlashPrefix) {
vals.Set(strings.TrimPrefix(k, lvtcontext.FlashPrefix), v)
}
}
return vals
}
// hasErrors returns true if there are any field errors (non-flash messages)
func (c *connState) hasErrors() bool {
c.messagesMu.RLock()
defer c.messagesMu.RUnlock()
for k := range c.messages {
if !strings.HasPrefix(k, lvtcontext.FlashPrefix) {
return true
}
}
return false
}
// getErrorsOnly returns only field errors (excludes flash messages)
func (c *connState) getErrorsOnly() map[string]string {
c.messagesMu.RLock()
defer c.messagesMu.RUnlock()
result := make(map[string]string)
for k, v := range c.messages {
if !strings.HasPrefix(k, lvtcontext.FlashPrefix) {
result[k] = v
}
}
return result
}
func (h *liveHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Add header to indicate WebSocket availability
if h.config.WebSocketDisabled {
w.Header().Set("X-LiveTemplate-WebSocket", "disabled")
} else {
w.Header().Set("X-LiveTemplate-WebSocket", "enabled")
}
if WSIsUpgrade(r) {
if h.config.WebSocketDisabled {
http.Error(w, "WebSocket is disabled on this endpoint", http.StatusBadRequest)
return
}
h.handleWebSocket(w, r)
} else {
h.handleHTTP(w, r)
}
}
func (h *liveHandler) handleWebSocket(w http.ResponseWriter, r *http.Request) {
// Check if shutting down - reject new connections
if h.isShutdown.Load() {
http.Error(w, "Service is shutting down", http.StatusServiceUnavailable)
return
}
// Track this connection goroutine for graceful shutdown
h.shutdownWg.Add(1)
defer h.shutdownWg.Done()
// Authenticate user and get session group
userID, err := h.config.Authenticator.Identify(r)
if err != nil {
slog.Error("Authentication failed",
slog.String("component", "live_handler"),
slog.Any("error", err))
h.writeUnauthorized(w)
return
}
groupID, err := h.config.Authenticator.GetSessionGroup(r, userID)
if err != nil {
slog.Error("Failed to get session group",
slog.String("component", "live_handler"),
slog.Any("error", err))
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
// Check connection limits before upgrading
if !h.limits.CanAccept(groupID) {
stats := h.limits.Stats()
slog.Warn("Connection rejected (at capacity)",
slog.String("component", "live_handler"),
slog.Int64("active", stats.ActiveConnections),
slog.Int64("max", stats.MaxConnections),
slog.String("group_id", groupID),
slog.Int64("group_count", h.limits.GroupConnectionCount(groupID)),
slog.Int64("max_per_group", stats.MaxPerGroup))
http.Error(w, "Service at capacity, please try again later", http.StatusServiceUnavailable)
return
}
// Set session cookie if this is a new session (cookie doesn't exist)
setCookieIfNew(w, r, groupID, h.config.CookieMaxAge)
// Upgrade to WebSocket after authentication and limit check succeeds
conn, err := h.config.Upgrader.Upgrade(w, r, nil)
if err != nil {
slog.Error("WebSocket upgrade failed",
slog.String("component", "live_handler"),
slog.Any("error", err))
return
}
defer func() {
if err := conn.Close(); err != nil {
slog.Warn("WebSocket close error",
slog.String("component", "live_handler"),
slog.Any("error", err))
}
}()
// Acquire connection slot (increment counters)
if err := h.limits.Acquire(groupID); err != nil {
slog.Error("Failed to acquire connection slot",
slog.String("component", "live_handler"),
slog.Any("error", err))
if writeErr := conn.WriteMessage(WSCloseMessage, WSFormatCloseMessage(WSCloseServiceRestart, "Service at capacity")); writeErr != nil {
slog.Warn("Failed to send close message",
slog.String("component", "live_handler"),
slog.Any("error", writeErr))
}
return
}
defer h.limits.Release(groupID)
slog.Info("Client connected",
slog.String("component", "live_handler"),
slog.String("user_id", userID),
slog.String("group_id", groupID),
slog.String("remote_addr", r.RemoteAddr),
slog.Int64("active_connections", h.limits.ActiveConnections()))
// Clone template for this connection to avoid state conflicts
// Each WebSocket connection needs its own template instance because
// ExecuteUpdates() tracks state (lastTree, lastData, etc.)
connTmpl, err := h.config.Template.Clone()
if err != nil {
slog.Error("Failed to clone template",
slog.String("component", "live_handler"),
slog.Any("error", err))
return
}
// Get or create state for this session group.
// If persist fields exist, try to restore them from SessionStore.
// Otherwise, always start with a fresh clone (ephemeral).
ctx := r.Context()
var typedState interface{}
if restored, ok := h.restorePersistedState(ctx, groupID); ok {
typedState = restored
} else {
typedState, err = h.cloneStateTyped()
if err != nil {
slog.Error("Failed to clone state",
slog.String("component", "live_handler"),
slog.Any("error", err))
return
}
if h.persistable == nil {
slog.Debug("Using fresh state (no persist fields)",
slog.String("component", "live_handler"),
slog.String("group_id", groupID))
} else {
slog.Info("Created new session group",
slog.String("component", "live_handler"),
slog.String("group_id", groupID))
}
}
// Initialize upload registry for this connection
uploadRegistry := h.newUploadRegistry()
for name, config := range h.config.UploadConfigs {
if err := uploadRegistry.CreateUpload(name, config); err != nil {
slog.Warn("Failed to create upload",
slog.String("component", "live_handler"),
slog.String("upload_name", name),
slog.Any("error", err))
}
}
connTmpl.SetUploadRegistry(uploadRegistry)
// Create Connection and register in registry
connection := &session.Connection{
Conn: conn,
GroupID: groupID,
UserID: userID,
Template: connTmpl,
Stores: typedState, // Store typed state for broadcasting
Uploads: uploadRegistry,
}
h.registry.Register(connection, h.config.wsBufferSize)
defer h.registry.Unregister(connection)
defer func() {
if h.tempFileManager == nil {
return
}
if err := h.tempFileManager.RemoveSession(groupID); err != nil {
slog.Warn("Failed to clean up temp files",
slog.String("component", "live_handler"),
slog.String("group_id", groupID),
slog.Any("error", err))
}
}()
slog.Debug("Registered connection",
slog.String("component", "live_handler"),
slog.Int("total_connections", h.registry.Count()),
slog.Int("total_groups", h.registry.GroupCount()))
// Subscribe to scoped pub/sub channels for cross-instance broadcasting
if ds, ok := h.config.PubSubBroadcaster.(pubsub.DynamicSubscriber); ok {
if err := ds.SubscribeToGroup(groupID); err != nil {
slog.Warn("Failed to subscribe to group channel",
slog.String("component", "live_handler"),
slog.String("group_id", groupID),
slog.Any("error", err))
}
if gas, ok := h.config.PubSubBroadcaster.(pubsub.GroupActionSubscriber); ok {
if err := gas.SubscribeToGroupAction(groupID); err != nil {
slog.Warn("Failed to subscribe to group action channel",
slog.String("component", "live_handler"),
slog.String("group_id", groupID),
slog.Any("error", err))
}
}
if userID != "" {
if err := ds.SubscribeToUser(userID); err != nil {
slog.Warn("Failed to subscribe to user channel",
slog.String("component", "live_handler"),
slog.String("user_id", userID),
slog.Any("error", err))
}
if err := ds.SubscribeToServerAction(userID); err != nil {
slog.Warn("Failed to subscribe to server action channel",
slog.String("component", "live_handler"),
slog.String("user_id", userID),
slog.Any("error", err))
}
}
}
// Create connection state (messages are per-connection, not shared)
connSt := &connState{
state: typedState,
messages: make(map[string]string),
groupID: groupID,
}
// Create context for lifecycle methods with query params from initial connection
wsQueryData := send.QueryParamsToData(r)
lifecycleCtx := NewContext(context.Background(), "", wsQueryData)
lifecycleCtx = lifecycleCtx.WithUserID(userID)
lifecycleCtx = lifecycleCtx.WithFlashSetter(connSt)
lifecycleCtx = lifecycleCtx.WithSession(newLocalSession(h, groupID))
// Call Mount on every WebSocket connect (new session AND reconnect).
// Mount() refreshes state from the database, ensuring actions always
// work with fresh data. Keep Mount cheap — it runs on every connect.
newState, err := callMount(h.config.Controller, connSt.state, lifecycleCtx)
if err != nil {
slog.Error("Mount failed",
slog.String("component", "live_handler"),
slog.Any("error", err))
return
}
connSt.state = newState
h.persistState(ctx, groupID, connSt.state)
// Call OnConnect lifecycle method
newState, err = callOnConnect(h.config.Controller, connSt.state, lifecycleCtx)
if err != nil {
slog.Warn("OnConnect failed",
slog.String("component", "live_handler"),
slog.Any("error", err))
// Continue anyway - OnConnect errors are non-fatal
} else {
connSt.state = newState
}
// Schedule OnDisconnect call when WebSocket closes
defer callOnDisconnect(h.config.Controller)
// Send initial tree
var buf bytes.Buffer
err = connTmpl.ExecuteUpdates(&buf, connSt.state, connSt.getMessages())
if err != nil {
slog.Error("Failed to generate initial tree",
slog.String("component", "live_handler"),
slog.Any("error", err))
return
}
var tree map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &tree); err != nil {
slog.Error("Failed to parse initial tree",
slog.String("component", "live_handler"),
slog.Any("error", err))
return
}
response := UpdateResponse{
Tree: tree,
Meta: &ResponseMetadata{
Success: !connSt.hasErrors(),
Errors: connSt.getErrorsOnly(),
Capabilities: h.config.Capabilities,
},
}
responseBytes, err := json.Marshal(response)
if err != nil {
slog.Error("Failed to marshal initial response",
slog.String("component", "live_handler"),
slog.Any("error", err))
return
}
if err = writeUpdateWebSocket(connection, responseBytes); err != nil {
slog.Error("Failed to send initial tree",
slog.String("component", "live_handler"),
slog.Any("error", err))
return
}
// Create rate limiter for this connection (prevents DoS attacks)
var limiter *rate.Limiter
if h.config.Template.config.MessageRateLimit > 0 {
burst := h.config.Template.config.MessageRateBurst
if burst < 1 {
burst = 1
}
limiter = rate.NewLimiter(rate.Limit(h.config.Template.config.MessageRateLimit), burst)
}
// Start readPump goroutine: reads from WebSocket and sends to readChan.
// This decouples WebSocket reads from state mutations, allowing the event
// loop to also process broadcast dispatches via DispatchChan.
// Buffer of 1: deliberately serializes client messages with dispatch processing.
// During dispatch handling, the readPump blocks after buffering one message.
// This bounds memory and ensures state mutations are strictly sequential.
// Tradeoff: slow dispatched actions (e.g., DB calls) pause client message processing.
// Increasing the buffer would NOT help — state mutations must still be sequential.
readChan := make(chan wsReadMessage, 1)
go func() {
defer close(readChan)
for {
_, data, err := conn.ReadMessage()
// If both readChan and Done are ready, Go's select may pick Done,
// discarding the error. The event loop still exits via readChan close.
select {
case readChan <- wsReadMessage{data: data, err: err}:
case <-connection.Done():
return
}
if err != nil {
return
}
}
}()
// Event loop: processes both client messages (readChan) and
// broadcast action dispatches (DispatchChan) serially.
// All state mutations happen in this single goroutine — no mutex needed.
eventLoop:
for {
select {
case rm, ok := <-readChan:
if !ok {
break eventLoop
}
if rm.err != nil {
if WSIsUnexpectedCloseError(rm.err, WSCloseGoingAway, WSCloseAbnormalClosure) {
slog.Warn("WebSocket error",
slog.String("component", "live_handler"),
slog.Any("error", rm.err))
}
break eventLoop
}
// Rate limiting check
if limiter != nil && !limiter.Allow() {
errorResp := UpdateResponse{
Tree: nil,
Meta: &ResponseMetadata{
Success: false,
Errors: map[string]string{"_rate_limit": "Too many requests. Please slow down."},
},
}
if respBytes, err := json.Marshal(errorResp); err == nil {
_ = writeUpdateWebSocket(connection, respBytes)
}
continue
}
// Parse message
msg, err := parseActionFromWebSocket(rm.data)
if err != nil {
slog.Warn("Failed to parse message",
slog.String("component", "live_handler"),
slog.Any("error", err))
continue
}
// Check if this is an upload-related action
uploadHandled, err := h.handleUploadAction(r.Context(), conn, rm.data, msg, connSt, uploadRegistry, connection)
if err != nil {
slog.Warn("Upload action error",
slog.String("component", "live_handler"),
slog.Any("error", err))
continue
}
if uploadHandled {
continue
}
// Route forms without explicit action to the conventional Submit() method.
applyDefaultAction(&msg)
// Clear previous errors
connSt.clearErrors()
// Create Context for action dispatch.
// Note: Query params from initial WS connection are NOT included here.
// They're already available in Mount/OnConnect via wsQueryData.
// WebSocket actions use only msg.Data from the client message.
actionCtx := NewContext(r.Context(), msg.Action, msg.Data)
actionCtx = actionCtx.WithUserID(userID)
actionCtx = actionCtx.WithUploads(uploadRegistry)
actionCtx = actionCtx.WithFlashSetter(connSt)
actionCtx = actionCtx.WithSession(newLocalSession(h, groupID))
// Dispatch action using Controller+State pattern
newState, actionErr := DispatchWithState(h.config.Controller, connSt.state, actionCtx)
if actionErr != nil {
// Handle errors
switch e := actionErr.(type) {
case FieldError:
connSt.setError(e.Field, e.Message)
case MultiError:
for _, fieldErr := range e {
connSt.setError(fieldErr.Field, fieldErr.Message)
}
default:
if !errors.Is(actionErr, ErrMethodNotFound) {
connSt.setError("_general", actionErr.Error())
}
}
} else {
connSt.state = newState
}
if actionErr == nil {
h.persistState(r.Context(), groupID, connSt.state)
connection.Stores = connSt.state
h.processBroadcastsAndSync(groupID, connection, actionCtx.pendingBroadcasts())
}
// Generate tree update
buf.Reset()
if err = connTmpl.ExecuteUpdates(&buf, connSt.state, connSt.getMessages()); err != nil {
slog.Error("Template update execution failed",
slog.String("component", "live_handler"),
slog.Any("error", err))
continue
}
var tree map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &tree); err != nil {
slog.Error("Failed to parse tree",
slog.String("component", "live_handler"),
slog.Any("error", err))
continue
}
response := UpdateResponse{
Tree: tree,
Meta: &ResponseMetadata{
Success: !connSt.hasErrors(),
Errors: connSt.getErrorsOnly(),
Action: msg.Action,
},
}
responseBytes, err := json.Marshal(response)
if err != nil {
slog.Error("Failed to marshal response",
slog.String("component", "live_handler"),
slog.Any("error", err))
continue
}
if err = writeUpdateWebSocket(connection, responseBytes); err != nil {
slog.Error("WebSocket write failed",
slog.String("component", "live_handler"),
slog.Any("error", err))
break eventLoop
}
// Clear flash messages after successful render (flash shows once per action)
connSt.clearFlash()
case req := <-connection.DispatchChan:
h.handleDispatchedAction(connSt, connection, req, userID)
}
}
slog.Info("Client disconnected",
slog.String("component", "live_handler"),
slog.String("user_id", userID),
slog.String("group_id", groupID),
slog.Int("remaining_connections", h.registry.Count()))
}
// wantsJSON returns true if the client expects a JSON response.
// JS clients (fetch/XHR) send Accept: application/json, while browsers send text/html.
// This is used for progressive enhancement to detect whether to return HTML or JSON.
//
// The function parses the Accept header and checks if the first meaningful media type
// is application/json (or a +json subtype). This avoids treating browsers that include
// application/json as a secondary option as JSON clients.
// knownAssetExts lists file extensions that browsers request automatically
// (favicon, manifest, etc.) and should not trigger pathChanged navigation logic.
var knownAssetExts = map[string]bool{
".ico": true, ".png": true, ".jpg": true, ".jpeg": true, ".gif": true, ".svg": true, ".webp": true,
".css": true, ".js": true, ".mjs": true, ".map": true, ".woff": true, ".woff2": true, ".ttf": true,
".json": true, ".xml": true, ".txt": true, ".webmanifest": true,
}
// isKnownAssetExt checks if the extension (from path.Ext, includes leading dot)
// matches a known static asset type. Uses ToLower for case-insensitive matching.
func isKnownAssetExt(ext string) bool {
return knownAssetExts[strings.ToLower(ext)]
}
func wantsJSON(r *http.Request) bool {
accept := r.Header.Get("Accept")
if accept == "" {
return false
}
// Parse the Accept header and consider only the first meaningful media range.
// This avoids treating browsers that primarily prefer text/html as JSON clients
// when they include application/json as a secondary option.
for _, part := range strings.Split(accept, ",") {
mt := strings.TrimSpace(part)
if mt == "" {
continue
}
// Strip any parameters (e.g. ";q=0.9").
if semi := strings.Index(mt, ";"); semi != -1 {
mt = strings.TrimSpace(mt[:semi])
}
// Ignore wildcard entries like "*/*".
if mt == "*/*" {
continue
}
// Treat explicit JSON types (including +json subtypes) as JSON.
return mt == "application/json" || strings.HasSuffix(mt, "+json")
}
return false
}
// setCookieIfNew sets the livetemplate-id cookie if it doesn't already exist
func setCookieIfNew(w http.ResponseWriter, r *http.Request, groupID string, cookieMaxAge time.Duration) {
// Check if cookie already exists
if cookie, err := r.Cookie("livetemplate-id"); err == nil && cookie.Value == groupID {
// Cookie exists and matches - no need to set again
return
}
// Set session cookie
http.SetCookie(w, &http.Cookie{
Name: "livetemplate-id",
Value: groupID,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
MaxAge: int(cookieMaxAge.Seconds()),
})
}
func (h *liveHandler) handleHTTP(w http.ResponseWriter, r *http.Request) {
// Handle HEAD request for capability check
if r.Method == http.MethodHead {
return
}
// Authenticate user and get session group
userID, err := h.config.Authenticator.Identify(r)
if err != nil {
slog.Error("HTTP authentication failed",
slog.String("component", "live_handler"),
slog.Any("error", err))
h.writeUnauthorized(w)
return
}
groupID, err := h.config.Authenticator.GetSessionGroup(r, userID)
if err != nil {
slog.Error("Failed to get session group for HTTP",
slog.String("component", "live_handler"),
slog.Any("error", err))
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
// Set session cookie if this is a new session
setCookieIfNew(w, r, groupID, h.config.CookieMaxAge)
// Get or create state for this session group
ctx := r.Context()
isNewSession := false
var typedState interface{}
// Detect URL path change on GET requests to reset stale cached state
// (e.g., page-mode navigation from /posts/alpha to /posts/beta).
// POST requests are excluded — they target actions, not page navigations.
// Paths are normalized via path.Clean to treat /a/ and /a as identical.
currentPath := path.Clean(r.URL.Path)
if currentPath == "." {
currentPath = "/"
}
// Asset requests (favicon.ico, manifest.json, etc.) that hit catch-all
// handlers are not page navigations and must not trigger pathChanged.
isAssetRequest := isKnownAssetExt(path.Ext(currentPath))
pathChanged := false
if h.persistable != nil && r.Method == http.MethodGet && !isAssetRequest {
if prev, loaded := h.httpLastPaths.Load(groupID); loaded {
pathChanged = prev.(string) != currentPath
}
}
if pathChanged {
// Path changed — use fresh state for the new URL (persist fields reset).
typedState, err = h.cloneStateTyped()
if err != nil {
slog.Error("Failed to clone per-request state",
slog.String("component", "live_handler"),
slog.Any("error", err))
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
isNewSession = true
h.httpTemplates.Delete(groupID)
slog.Debug("Refreshing session for new URL path",
slog.String("component", "live_handler"),
slog.String("group_id", groupID),
slog.String("path", currentPath))
} else if restored, ok := h.restorePersistedState(ctx, groupID); ok {
typedState = restored
slog.Debug("Using existing session group",
slog.String("component", "live_handler"),
slog.String("group_id", groupID))
} else {
// No stored state or no persist fields — start fresh
typedState, err = h.cloneStateTyped()
if err != nil {
slog.Error("Failed to clone state",
slog.String("component", "live_handler"),
slog.Any("error", err))
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if h.persistable == nil {
// No persist fields — ephemeral mode.
// On GET, delete cached template so first render sends full statics.
// On POST, keep cache so responses are incremental diffs.
if r.Method == http.MethodGet {
h.httpTemplates.Delete(groupID)
}
} else {
isNewSession = true
h.httpTemplates.Delete(groupID)
slog.Info("Created new session group",
slog.String("component", "live_handler"),
slog.String("group_id", groupID))
}
}
// Create connection state (messages are per-request)
connSt := &connState{
state: typedState,
messages: make(map[string]string),
groupID: groupID,
}
// Create lifecycle context with query params
queryData := send.QueryParamsToData(r)
lifecycleCtx := NewContext(ctx, "", queryData)
lifecycleCtx = lifecycleCtx.WithUserID(userID)
lifecycleCtx = lifecycleCtx.WithFlashSetter(connSt)
lifecycleCtx = lifecycleCtx.WithSession(newLocalSession(h, groupID))
// Read flash messages from cookie (set by POST redirect)
if flashCookie, err := r.Cookie("lvt-flash"); err == nil && flashCookie.Value != "" {
if flashValues, err := url.ParseQuery(flashCookie.Value); err == nil {
for key, values := range flashValues {
if len(values) > 0 {
connSt.setFlash(key, values[0])
}
}
}
// Clear cookie immediately (one-time read)
http.SetCookie(w, &http.Cookie{
Name: "lvt-flash",
Value: "",
Path: "/",
MaxAge: -1,
})
}
isHTTPGet := r.Method == http.MethodGet && !isAssetRequest
isPageRequest := !isAssetRequest
if isNewSession || isPageRequest {
newState, err := callMount(h.config.Controller, connSt.state, lifecycleCtx)
if err != nil {
// httpLastPaths still holds the previous path (Store is deferred
// until after success), so retries naturally re-detect the change.
slog.Error("Mount failed",
slog.String("component", "live_handler"),
slog.Any("error", err))
http.Error(w, "Failed to initialize application state", http.StatusInternalServerError)
return
}
connSt.state = newState
// Persist after Mount on GET/new-session only. On POST the action handler
// will persist after the action succeeds, avoiding a redundant Set.
if isNewSession || isHTTPGet {
h.persistState(ctx, groupID, connSt.state)
}
// Commit path after successful Mount (not before, to allow retries).
// Skip when no persist fields — pathChanged is never checked.
if isHTTPGet && h.persistable != nil {
h.httpLastPaths.Store(groupID, currentPath)
}
}
// Handle GET request
if r.Method == http.MethodGet {
if wantsJSON(r) {
// JS client in HTTP mode: return initial tree as JSON
httpTmpl, cloneErr := h.config.Template.Clone()
if cloneErr != nil {
http.Error(w, "Failed to clone template", http.StatusInternalServerError)