-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
1898 lines (1725 loc) · 65.6 KB
/
Copy pathapp.go
File metadata and controls
1898 lines (1725 loc) · 65.6 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 main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"path"
"path/filepath"
"sort"
"strings"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
"github.com/yanbo92/topicconsole/internal/apperr"
"github.com/yanbo92/topicconsole/internal/broker"
"github.com/yanbo92/topicconsole/internal/config"
"github.com/yanbo92/topicconsole/internal/discovery"
"github.com/yanbo92/topicconsole/internal/profile"
"github.com/yanbo92/topicconsole/internal/pulsaradmin"
"github.com/yanbo92/topicconsole/internal/pulsarauth"
"github.com/yanbo92/topicconsole/internal/pulsarconn"
"github.com/yanbo92/topicconsole/internal/pulsarmeta"
"github.com/yanbo92/topicconsole/internal/pulsarproduce"
"github.com/yanbo92/topicconsole/internal/pulsartopic"
"github.com/yanbo92/topicconsole/internal/schema"
"github.com/yanbo92/topicconsole/internal/search"
"github.com/yanbo92/topicconsole/internal/settingsbackup"
"github.com/yanbo92/topicconsole/internal/stream"
"github.com/yanbo92/topicconsole/internal/updater"
)
// App is the Wails-bound struct. All public methods become frontend RPCs.
// Keep methods thin — delegate to internal/ packages.
type App struct {
ctx context.Context
version string
profileStore *profile.Store
streamMgr *stream.Manager
searchMgr *search.Manager
metaScanMgr *pulsarmeta.ScanManager
metaCache *broker.MetaCache
avroCodec *schema.Codec
emitEvent func(name string, data any)
discoveryMgr *discovery.Manager
}
type resolvedProfileAuth struct {
profile profile.Profile
clientToken string
adminToken string
}
func NewApp(version string) *App {
return &App{version: version}
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
store, err := profile.NewStore()
if err != nil {
slog.Error("failed to init profile store", "err", err)
return
}
a.profileStore = store
emit := func(name string, data any) {
runtime.EventsEmit(ctx, name, data)
}
a.emitEvent = emit
a.streamMgr = stream.NewManager(ctx, emit)
a.searchMgr = search.NewManager(ctx, emit)
a.metaScanMgr = pulsarmeta.NewScanManager(ctx, emit)
a.metaCache = broker.NewMetaCache()
a.avroCodec = schema.NewCodec()
discoveryMgr, err := discovery.NewManager(store, a.avroCodec, emit)
if err != nil {
slog.Warn("failed to init discovery manager", "err", err)
} else {
a.discoveryMgr = discoveryMgr
}
go func() {
time.Sleep(3 * time.Second)
rel, err := updater.CheckLatest(a.version)
if err != nil {
slog.Warn("update check failed", "err", err)
return
}
if rel != nil {
runtime.EventsEmit(ctx, "app:update-available", rel)
}
}()
}
func (a *App) shutdown(_ context.Context) {
a.searchMgr.StopAll()
a.metaScanMgr.StopAll()
}
// ── App info & updates ────────────────────────────────────────────────────────
// GetAppVersion returns the current application version.
func (a *App) GetAppVersion() string {
return a.version
}
// CheckForUpdates checks GitHub for a newer release.
// Returns the release info if an update is available, nil otherwise.
func (a *App) CheckForUpdates() (*updater.Release, error) {
return updater.CheckLatest(a.version)
}
// OpenURL opens the given URL in the user's default browser.
func (a *App) OpenURL(url string) {
runtime.BrowserOpenURL(a.ctx, url)
}
// ── Profile management ────────────────────────────────────────────────────────
func (a *App) ListProfiles() ([]profile.Profile, error) {
return a.profileStore.List(), nil
}
func (a *App) GetActiveProfile() (*profile.Profile, error) {
return a.profileStore.ActiveProfile()
}
func (a *App) CreateProfile(p profile.Profile) (profile.Profile, error) {
if err := copyProfileCerts(&p); err != nil {
return profile.Profile{}, fmt.Errorf("copy certs: %w", err)
}
return a.profileStore.Create(p)
}
func (a *App) DeleteProfile(id string) error {
return a.profileStore.Delete(id)
}
func (a *App) ReorderProfiles(ids []string) error {
return a.profileStore.Reorder(ids)
}
// ListDiscoveryConnectors returns locally available discovery connectors.
func (a *App) ListDiscoveryConnectors() ([]discovery.ConnectorInfo, error) {
if a.discoveryMgr == nil {
return nil, apperr.Validation("discovery", "discovery manager is not available")
}
return a.discoveryMgr.ListConnectors(), nil
}
// ListDiscoveryConnectorSources returns all editable on-disk HCL sources,
// including malformed files that are not part of the active connector set.
func (a *App) ListDiscoveryConnectorSources() ([]discovery.ConnectorSourceInfo, error) {
if a.discoveryMgr == nil {
return nil, apperr.Validation("discovery", "discovery manager is not available")
}
return a.discoveryMgr.ListConnectorSources()
}
// ReadDiscoveryConnectorSource reads one safely confined connector source.
func (a *App) ReadDiscoveryConnectorSource(filename string) (discovery.ConnectorSource, error) {
if a.discoveryMgr == nil {
return discovery.ConnectorSource{}, apperr.Validation("discovery", "discovery manager is not available")
}
return a.discoveryMgr.ReadConnectorSource(filename)
}
// ValidateDiscoveryConnectorSource validates editor text without mutating disk
// or the manager's active connector set.
func (a *App) ValidateDiscoveryConnectorSource(req discovery.ValidateConnectorSourceRequest) discovery.ConnectorValidation {
if a.discoveryMgr == nil {
return discovery.ConnectorValidation{Diagnostics: []discovery.ConnectorDiagnostic{{
Severity: "error",
Summary: "Discovery unavailable",
Detail: "Discovery manager is not available.",
}}}
}
return a.discoveryMgr.ValidateConnectorSource(req)
}
// SaveDiscoveryConnectorSource atomically saves a valid source and hot reloads
// the active connector set.
func (a *App) SaveDiscoveryConnectorSource(req discovery.SaveConnectorSourceRequest) (discovery.ConnectorSourceInfo, error) {
if a.discoveryMgr == nil {
return discovery.ConnectorSourceInfo{}, apperr.Validation("discovery", "discovery manager is not available")
}
return a.discoveryMgr.SaveConnectorSource(req)
}
// RestoreDiscoveryConnectorSource restores an embedded connector source and
// hot reloads the active connector set.
func (a *App) RestoreDiscoveryConnectorSource(filename string) (discovery.ConnectorSourceInfo, error) {
if a.discoveryMgr == nil {
return discovery.ConnectorSourceInfo{}, apperr.Validation("discovery", "discovery manager is not available")
}
return a.discoveryMgr.RestoreConnectorSource(filename)
}
// RunDiscoveryConnector runs a discovery connector and returns a redacted preview.
func (a *App) RunDiscoveryConnector(req discovery.RunConnectorRequest) (discovery.Preview, error) {
if a.discoveryMgr == nil {
return discovery.Preview{}, apperr.Validation("discovery", "discovery manager is not available")
}
return a.discoveryMgr.Run(req)
}
// SaveDiscoveryPreview persists a previously generated discovery preview.
func (a *App) SaveDiscoveryPreview(previewID string) (profile.Profile, error) {
if a.discoveryMgr == nil {
return profile.Profile{}, apperr.Validation("discovery", "discovery manager is not available")
}
return a.discoveryMgr.Save(previewID)
}
// RunDiscoveryRefresh reruns a profile's source connector and returns a redacted diff.
func (a *App) RunDiscoveryRefresh(req discovery.RefreshRequest) (discovery.RefreshPreview, error) {
if a.discoveryMgr == nil {
return discovery.RefreshPreview{}, apperr.Validation("discovery", "discovery manager is not available")
}
return a.discoveryMgr.RunRefresh(req)
}
// ApplyDiscoveryRefresh applies a previously generated discovery refresh diff.
func (a *App) ApplyDiscoveryRefresh(refreshID string) (profile.Profile, error) {
if a.discoveryMgr == nil {
return profile.Profile{}, apperr.Validation("discovery", "discovery manager is not available")
}
return a.discoveryMgr.ApplyRefresh(refreshID)
}
// ── Export/Import structures ──────────────────────────────────────────────────
type settingsExportDocument struct {
Connections []exportProfile `json:"connections"`
}
type ExportSettingsResult struct {
Cancelled bool `json:"cancelled"`
}
type ImportSettingsResult struct {
Cancelled bool `json:"cancelled"`
Imported int `json:"imported"`
Skipped int `json:"skipped"`
}
type exportProfile struct {
ID string `json:"id"`
Name string `json:"name"`
Pulsar profile.PulsarConfig `json:"pulsar"`
Auth profile.AuthConfig `json:"auth"`
TLS profile.TLSConfig `json:"tls"`
ActiveCredentialID string `json:"activeCredentialID,omitempty"`
Token string `json:"token,omitempty"`
Credentials []exportCredential `json:"credentials,omitempty"`
TopicGroups []profile.TopicGroup `json:"topicGroups,omitempty"`
PinnedTopics []string `json:"pinnedTopics,omitempty"`
PinnedTenants []string `json:"pinnedTenants,omitempty"`
CustomTenants []string `json:"customTenants,omitempty"`
CustomNamespaces []string `json:"customNamespaces,omitempty"`
AvroSchemas []profile.AvroSchemaMapping `json:"avroSchemas,omitempty"`
Discovery *profile.DiscoveryMetadata `json:"discovery,omitempty"`
CACertPEM string `json:"caCertPEM,omitempty"`
ClientCertPEM string `json:"clientCertPEM,omitempty"`
ClientKeyPEM string `json:"clientKeyPEM,omitempty"`
}
type exportCredential struct {
ID string `json:"id"`
Name string `json:"name"`
Auth profile.AuthConfig `json:"auth"`
AdminAuthMode string `json:"adminAuthMode,omitempty"`
AdminAuth profile.AuthConfig `json:"adminAuth,omitempty"`
Token string `json:"token,omitempty"`
AdminToken string `json:"adminToken,omitempty"`
}
type avroSchemaResolvedEvent struct {
Action string `json:"action"`
Topic string `json:"topic"`
SchemaPath string `json:"schemaPath"`
}
// ExportSettings saves all profiles to a user-chosen JSON file.
// When includeSecrets is false, tokens and saved discovery SSH auth are omitted.
func (a *App) ExportSettings(includeSecrets bool) (ExportSettingsResult, error) {
return a.exportSettings(includeSecrets, runtime.SaveFileDialog, os.WriteFile)
}
func (a *App) exportSettings(
includeSecrets bool,
choosePath saveFileDialogFunc,
writeFile writeFileFunc,
) (ExportSettingsResult, error) {
path, err := choosePath(a.ctx, runtime.SaveDialogOptions{
DefaultFilename: "topicconsole-backup.json",
Filters: []runtime.FileFilter{
{DisplayName: "JSON Files", Pattern: "*.json"},
},
})
if err != nil {
return ExportSettingsResult{}, err
}
if path == "" {
return ExportSettingsResult{Cancelled: true}, nil
}
profiles := a.profileStore.List()
export := settingsExportDocument{Connections: make([]exportProfile, 0, len(profiles))}
for _, p := range profiles {
ep := exportProfile{
ID: p.ID,
Name: p.Name,
Pulsar: p.Pulsar,
Auth: p.Auth,
TLS: p.TLS,
ActiveCredentialID: p.ActiveCredentialID,
TopicGroups: p.TopicGroups,
PinnedTopics: p.PinnedTopics,
PinnedTenants: p.PinnedTenants,
CustomTenants: p.CustomTenants,
CustomNamespaces: p.CustomNamespaces,
AvroSchemas: p.AvroSchemas,
Discovery: discoveryMetadataForExport(p.Discovery, includeSecrets),
}
ep.TLS.CACertPath = ""
ep.TLS.ClientCertPath = ""
ep.TLS.ClientKeyPath = ""
if includeSecrets {
ep.Token = p.Token
if p.TLS.CACertPath != "" {
if pem, err := os.ReadFile(p.TLS.CACertPath); err == nil {
ep.CACertPEM = string(pem)
} else {
slog.Warn("export: read CA cert", "path", p.TLS.CACertPath, "err", err)
}
}
if p.TLS.ClientCertPath != "" {
if pem, err := os.ReadFile(p.TLS.ClientCertPath); err == nil {
ep.ClientCertPEM = string(pem)
} else {
slog.Warn("export: read client cert", "path", p.TLS.ClientCertPath, "err", err)
}
}
if p.TLS.ClientKeyPath != "" {
if pem, err := os.ReadFile(p.TLS.ClientKeyPath); err == nil {
ep.ClientKeyPEM = string(pem)
} else {
slog.Warn("export: read client key", "path", p.TLS.ClientKeyPath, "err", err)
}
}
}
for _, cred := range p.Credentials {
ec := exportCredential{
ID: cred.ID,
Name: cred.Name,
Auth: cred.Auth,
AdminAuthMode: cred.AdminAuthMode,
AdminAuth: cred.AdminAuth,
}
if includeSecrets {
ec.Token = cred.Token
ec.AdminToken = cred.AdminToken
}
ep.Credentials = append(ep.Credentials, ec)
}
export.Connections = append(export.Connections, ep)
}
data, err := json.MarshalIndent(export, "", " ")
if err != nil {
return ExportSettingsResult{}, fmt.Errorf("marshal: %w", err)
}
if err := writeFile(path, data, 0o600); err != nil {
return ExportSettingsResult{}, err
}
return ExportSettingsResult{}, nil
}
type saveFileDialogFunc func(context.Context, runtime.SaveDialogOptions) (string, error)
type openDirectoryDialogFunc func(context.Context, runtime.OpenDialogOptions) (string, error)
type writeFileFunc func(string, []byte, os.FileMode) error
type MessageExportFile struct {
Filename string `json:"filename"`
Content string `json:"content"`
}
// SaveMessageExport writes serialized message data to a user-chosen file.
// A false result without an error means the user cancelled the dialog.
func (a *App) SaveMessageExport(topic, format, content string) (bool, error) {
return saveMessageExport(a.ctx, topic, format, content, runtime.SaveFileDialog, writeMessageExportAtomic)
}
// SaveMessageExportFiles writes one serialized message per JSON file under a
// newly created export directory. A false result means the user cancelled.
func (a *App) SaveMessageExportFiles(topic string, files []MessageExportFile) (bool, error) {
return saveMessageExportFiles(a.ctx, topic, files, runtime.OpenDirectoryDialog, os.WriteFile)
}
func saveMessageExport(
ctx context.Context,
topic string,
format string,
content string,
choosePath saveFileDialogFunc,
writeFile writeFileFunc,
) (bool, error) {
filter, err := messageExportFilter(format)
if err != nil {
return false, err
}
selectedPath, err := choosePath(ctx, runtime.SaveDialogOptions{
DefaultFilename: fmt.Sprintf("%s-%d.%s", messageExportBaseName(topic), time.Now().UnixMilli(), format),
Title: "Save Message Export",
Filters: []runtime.FileFilter{filter},
})
if err != nil {
return false, fmt.Errorf("open message export dialog: %w", err)
}
if selectedPath == "" {
return false, nil
}
if err := writeFile(selectedPath, []byte(content), 0o600); err != nil {
return false, fmt.Errorf("write message export: %w", err)
}
return true, nil
}
func messageExportFilter(format string) (runtime.FileFilter, error) {
switch format {
case "jsonl":
return runtime.FileFilter{DisplayName: "JSONL Files", Pattern: "*.jsonl"}, nil
case "csv":
return runtime.FileFilter{DisplayName: "CSV Files", Pattern: "*.csv"}, nil
default:
return runtime.FileFilter{}, fmt.Errorf("unsupported message export format %q", format)
}
}
func saveMessageExportFiles(
ctx context.Context,
topic string,
files []MessageExportFile,
chooseDirectory openDirectoryDialogFunc,
writeFile writeFileFunc,
) (bool, error) {
if err := validateMessageExportFiles(files); err != nil {
return false, err
}
parentDirectory, err := chooseDirectory(ctx, runtime.OpenDialogOptions{
Title: "Select Message Export Folder",
CanCreateDirectories: true,
})
if err != nil {
return false, fmt.Errorf("open message export directory dialog: %w", err)
}
if parentDirectory == "" {
return false, nil
}
exportDirectory, err := createMessageExportDirectory(
parentDirectory,
messageExportBaseName(topic),
time.Now().UnixMilli(),
)
if err != nil {
return false, fmt.Errorf("create message export directory: %w", err)
}
for _, file := range files {
filename := filepath.Join(exportDirectory, file.Filename)
if err := writeFile(filename, []byte(file.Content), 0o600); err != nil {
if cleanupErr := os.RemoveAll(exportDirectory); cleanupErr != nil {
return false, fmt.Errorf("write message export file %q: %w; cleanup: %v", file.Filename, err, cleanupErr)
}
return false, fmt.Errorf("write message export file %q: %w", file.Filename, err)
}
}
return true, nil
}
func validateMessageExportFiles(files []MessageExportFile) error {
if len(files) == 0 {
return fmt.Errorf("message export files must not be empty")
}
seen := make(map[string]struct{}, len(files))
for _, file := range files {
filename := file.Filename
if filename == "" || filename != filepath.Base(filename) || strings.ContainsAny(filename, `/\`) {
return fmt.Errorf("invalid message export filename %q", filename)
}
if filepath.Ext(filename) != ".json" {
return fmt.Errorf("message export filename must end in .json: %q", filename)
}
for _, char := range filename {
if char < 32 || strings.ContainsRune(`<>:"|?*`, char) {
return fmt.Errorf("invalid message export filename %q", filename)
}
}
key := strings.ToLower(filename)
if _, exists := seen[key]; exists {
return fmt.Errorf("duplicate message export filename %q", filename)
}
seen[key] = struct{}{}
}
return nil
}
func createMessageExportDirectory(parentDirectory, topicBase string, timestamp int64) (string, error) {
base := fmt.Sprintf("%s-%d", topicBase, timestamp)
for suffix := 1; ; suffix++ {
name := base
if suffix > 1 {
name = fmt.Sprintf("%s-%d", base, suffix)
}
directory := filepath.Join(parentDirectory, name)
if err := os.Mkdir(directory, 0o700); err == nil {
return directory, nil
} else if !os.IsExist(err) {
return "", err
}
}
}
func messageExportBaseName(topic string) string {
base := path.Base(strings.TrimSpace(topic))
if base == "." || base == "/" || base == "" {
return "messages"
}
base = strings.NewReplacer(
"<", "-",
">", "-",
":", "-",
`"`, "-",
"/", "-",
`\`, "-",
"|", "-",
"?", "-",
"*", "-",
).Replace(base)
base = strings.Trim(base, " .")
if base == "" {
return "messages"
}
return base
}
func discoveryMetadataForExport(in *profile.DiscoveryMetadata, includeSecrets bool) *profile.DiscoveryMetadata {
if in == nil {
return nil
}
out := *in
if in.Inputs != nil {
out.Inputs = make(map[string]string, len(in.Inputs))
for k, v := range in.Inputs {
out.Inputs[k] = v
}
}
if !includeSecrets {
out.SSH = nil
}
return &out
}
// ImportSettings reads profiles from a user-chosen JSON file and merges them
// (adds profiles not already present by ID), restoring exported secrets.
// SelectCertificateFile opens a native file dialog for selecting certificate/key files.
func (a *App) SelectCertificateFile() (string, error) {
return runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select Certificate File",
Filters: []runtime.FileFilter{
{DisplayName: "Certificates (*.pem, *.crt, *.cert, *.key)", Pattern: "*.pem;*.crt;*.cert;*.key"},
{DisplayName: "All Files", Pattern: "*"},
},
})
}
// PickAvroSchemaFile opens a native file dialog for selecting local Avro schemas.
func (a *App) PickAvroSchemaFile() (string, error) {
selectedPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select Avro Schema",
Filters: []runtime.FileFilter{
{DisplayName: "Avro Schemas (*.avsc, *.avro)", Pattern: "*.avsc;*.avro"},
{DisplayName: "All Files", Pattern: "*"},
},
})
if err != nil || strings.TrimSpace(selectedPath) == "" {
return selectedPath, err
}
configPath, _ := a.profileConfigPath()
executablePath, _ := os.Executable()
return relativeAvroSchemaPickerPath(selectedPath, configPath, executablePath), nil
}
// ValidateAvroSchemaMapping validates one local Avro schema mapping before it is saved.
func (a *App) ValidateAvroSchemaMapping(profileID string, topicPattern string, schemaPath string) error {
profileID = strings.TrimSpace(profileID)
if a.profileStore != nil && profileID != "" {
if _, err := a.profileStore.Get(profileID); err != nil {
return err
}
}
if err := validateAvroSchemaTopicPattern(topicPattern); err != nil {
return apperr.Validation("topic pattern", err.Error())
}
schemaPath = strings.TrimSpace(schemaPath)
if schemaPath == "" {
return apperr.Required("schema path")
}
resolvedPath, err := a.resolveLocalAvroSchemaPath(schemaPath)
if err != nil {
return apperr.Validation("avro schema", err.Error())
}
codec := a.avroCodec
if codec == nil {
codec = schema.NewCodec()
}
if err := codec.Validate(resolvedPath); err != nil {
return apperr.Validation("avro schema", err.Error())
}
return nil
}
// Emits "profiles:imported" when at least one profile is imported.
func (a *App) ImportSettings() (ImportSettingsResult, error) {
return a.importSettings(runtime.OpenFileDialog, func(name string, data any) {
runtime.EventsEmit(a.ctx, name, data)
})
}
func (a *App) importSettings(
openFileDialog func(context.Context, runtime.OpenDialogOptions) (string, error),
emitEvent func(string, any),
) (ImportSettingsResult, error) {
path, err := openFileDialog(a.ctx, runtime.OpenDialogOptions{
Filters: []runtime.FileFilter{
{DisplayName: "JSON Files", Pattern: "*.json"},
},
})
if err != nil {
return ImportSettingsResult{}, err
}
if path == "" {
return ImportSettingsResult{Cancelled: true}, nil
}
data, err := os.ReadFile(path)
if err != nil {
return ImportSettingsResult{}, fmt.Errorf("read file: %w", err)
}
document, err := settingsbackup.DecodeLegacy(data)
if err != nil {
return ImportSettingsResult{}, fmt.Errorf("parse settings: %w", err)
}
plan := settingsbackup.PlanImport(document, a.profileStore.List())
certificateRoot := ""
if settingsbackup.HasEmbeddedCertificates(plan.Connections) {
configDirectory, err := config.Dir()
if err != nil {
return ImportSettingsResult{}, fmt.Errorf("restore certificates: %w", err)
}
certificateRoot = filepath.Join(configDirectory, "certs")
}
restored, err := settingsbackup.RestoreCertificates(certificateRoot, plan.Connections)
if err != nil {
return ImportSettingsResult{}, fmt.Errorf("restore certificates: %w", err)
}
if err := a.profileStore.ImportBatch(restored.Profiles); err != nil {
if cleanupErr := restored.Cleanup(); cleanupErr != nil {
return ImportSettingsResult{}, fmt.Errorf("import profiles: %w; cleanup certificates: %v", err, cleanupErr)
}
return ImportSettingsResult{}, fmt.Errorf("import profiles: %w", err)
}
result := ImportSettingsResult{Imported: len(restored.Profiles), Skipped: plan.Skipped}
if result.Imported > 0 {
emitEvent("profiles:imported", nil)
}
return result, nil
}
// RenameProfile updates only the name of a profile.
func (a *App) RenameProfile(id, name string) error {
if strings.TrimSpace(name) == "" {
return apperr.Required("name")
}
p, err := a.profileStore.Get(id)
if err != nil {
return err
}
p.Name = strings.TrimSpace(name)
return a.profileStore.Update(*p)
}
// SwitchProfile stops all active sessions and clears caches,
// then switches the active profile.
func (a *App) SwitchProfile(id string) error {
a.streamMgr.StopAll()
a.searchMgr.StopAll()
a.metaCache.InvalidateAll()
if err := a.profileStore.SetActive(id); err != nil {
return err
}
runtime.EventsEmit(a.ctx, "profile:switched", id)
return nil
}
// ── Profile connection management ─────────────────────────────────────────────
// copyCertToAppData copies a certificate file into the app config directory.
// Returns the new path, or empty string if srcPath is empty.
func copyCertToAppData(profileID, filename, srcPath string) (string, error) {
if srcPath == "" {
return "", nil
}
dir, err := config.Dir()
if err != nil {
return srcPath, fmt.Errorf("config dir: %w", err)
}
if strings.HasPrefix(srcPath, dir) {
return srcPath, nil // already inside app data
}
certsDir := filepath.Join(dir, "certs", profileID)
if err := os.MkdirAll(certsDir, 0o755); err != nil {
return srcPath, fmt.Errorf("create certs dir: %w", err)
}
data, err := os.ReadFile(srcPath)
if err != nil {
return srcPath, fmt.Errorf("read cert %s: %w", srcPath, err)
}
dst := filepath.Join(certsDir, filename)
if err := os.WriteFile(dst, data, 0o600); err != nil {
return srcPath, fmt.Errorf("write cert %s: %w", dst, err)
}
return dst, nil
}
// copyProfileCerts copies TLS certificate files into app data if they are external.
func copyProfileCerts(p *profile.Profile) error {
var err error
if p.TLS.CACertPath, err = copyCertToAppData(p.ID, "ca.pem", p.TLS.CACertPath); err != nil {
return err
}
if p.TLS.ClientCertPath, err = copyCertToAppData(p.ID, "client-cert.pem", p.TLS.ClientCertPath); err != nil {
return err
}
if p.TLS.ClientKeyPath, err = copyCertToAppData(p.ID, "client-key.pem", p.TLS.ClientKeyPath); err != nil {
return err
}
return nil
}
func (a *App) UpdateProfile(p profile.Profile) error {
if err := copyProfileCerts(&p); err != nil {
return fmt.Errorf("copy certs: %w", err)
}
return a.profileStore.Update(p)
}
// AddProfileCredential adds a named credential to a profile.
func (a *App) AddProfileCredential(profileID string, cred profile.NamedCredential) (profile.NamedCredential, error) {
return a.profileStore.AddCredential(profileID, cred)
}
// SetNamedCredentialPassword stores a named credential token in .topicconsole.json.
func (a *App) SetNamedCredentialPassword(profileID, credentialID, password string) error {
return a.profileStore.SetCredentialToken(profileID, credentialID, password)
}
// SetNamedCredentialAdminPassword stores a named credential admin token in .topicconsole.json.
func (a *App) SetNamedCredentialAdminPassword(profileID, credentialID, password string) error {
return a.profileStore.SetCredentialAdminToken(profileID, credentialID, password)
}
// DeleteProfileCredential removes a named credential from a profile.
func (a *App) DeleteProfileCredential(profileID, credentialID string) error {
return a.profileStore.DeleteCredential(profileID, credentialID)
}
// SwitchProfileCredential stops all sessions for a profile, clears caches,
// sets the active credential, and emits an event.
func (a *App) SwitchProfileCredential(profileID, credentialID string) error {
a.streamMgr.StopProfile(profileID)
a.searchMgr.StopProfile(profileID)
a.metaCache.InvalidateBroker(profileID)
if err := a.profileStore.SetActiveCredential(profileID, credentialID); err != nil {
return err
}
runtime.EventsEmit(a.ctx, "profile:credential-switched", map[string]string{
"profileID": profileID,
"credentialID": credentialID,
})
return nil
}
// ClearActiveProfileCredential resets the profile to use its default auth settings.
func (a *App) ClearActiveProfileCredential(profileID string) error {
a.streamMgr.StopProfile(profileID)
a.searchMgr.StopProfile(profileID)
a.metaCache.InvalidateBroker(profileID)
return a.profileStore.ClearActiveCredential(profileID)
}
// adminReachable verifies the admin endpoint responds. Any HTTP response —
// including 401/403, e.g. a non-super-user token — counts as reachable: the
// service is up and the auth pipeline is wired. Only a transport-level
// failure (timeout/refused) is reported as an error.
func adminReachable(ctx context.Context, adminURL, adminToken string) error {
_, err := pulsaradmin.NewClientWithToken(adminURL, adminToken).ListTenants(ctx)
if err == nil || pulsaradmin.IsHTTPError(err) {
return nil
}
return fmt.Errorf("reach Pulsar admin endpoint: %w", err)
}
// TestConnectionDirect tests a Pulsar connection using inline parameters,
// without requiring a saved broker. Useful for testing credentials before saving.
func (a *App) TestConnectionDirect(
serviceURL string,
adminURL string,
tls profile.TLSConfig,
auth profile.AuthConfig,
token string,
adminAuthMode string,
adminAuth profile.AuthConfig,
adminTokenSecret string,
) error {
p := profile.Profile{
Pulsar: profile.PulsarConfig{
ServiceURL: serviceURL,
AdminURL: adminURL,
},
Auth: auth,
TLS: tls,
}
cfg := p.EffectivePulsarConfig()
clientToken, adminToken, err := credentialAuthTokens(profile.NamedCredential{
Auth: auth,
AdminAuthMode: adminAuthMode,
AdminAuth: adminAuth,
}, token, adminTokenSecret)
if err != nil {
return err
}
if err := pulsarconn.TestConnection(a.ctx, pulsarconn.Config{ServiceURL: cfg.ServiceURL, AuthToken: clientToken}); err != nil {
return err
}
ctx, cancel := context.WithTimeout(a.ctx, 10*time.Second)
defer cancel()
return adminReachable(ctx, cfg.AdminURL, adminToken)
}
// TestProfileConnection verifies the saved Pulsar service and admin URLs are reachable.
func (a *App) TestProfileConnection(profileID string) error {
resolved, err := a.resolveProfileAuth(profileID)
if err != nil {
return err
}
cfg := resolved.profile.EffectivePulsarConfig()
if err := pulsarconn.TestConnection(a.ctx, pulsarconn.Config{ServiceURL: cfg.ServiceURL, AuthToken: resolved.clientToken}); err != nil {
return err
}
ctx, cancel := context.WithTimeout(a.ctx, 10*time.Second)
defer cancel()
return adminReachable(ctx, cfg.AdminURL, resolved.adminToken)
}
// TestProfileConnectionWithOverrides verifies connectivity using the profile's
// saved active credential, but with the connection fields (service/admin URLs
// and TLS) replaced by the values currently entered in the edit dialog. This
// lets the user test unsaved edits before saving.
func (a *App) TestProfileConnectionWithOverrides(
profileID string,
serviceURL string,
adminURL string,
tls profile.TLSConfig,
) error {
resolved, err := a.resolveProfileAuth(profileID)
if err != nil {
return err
}
p := profile.Profile{
Pulsar: profile.PulsarConfig{
ServiceURL: serviceURL,
AdminURL: adminURL,
},
TLS: tls,
}
cfg := p.EffectivePulsarConfig()
if err := pulsarconn.TestConnection(a.ctx, pulsarconn.Config{ServiceURL: cfg.ServiceURL, AuthToken: resolved.clientToken}); err != nil {
return err
}
ctx, cancel := context.WithTimeout(a.ctx, 10*time.Second)
defer cancel()
return adminReachable(ctx, cfg.AdminURL, resolved.adminToken)
}
// ── Pinned topics ─────────────────────────────────────────────────────────────
// PinTopic adds a topic to the profile's pinned list.
func (a *App) PinTopic(profileID, topic string) error {
return a.profileStore.PinTopic(profileID, topic)
}
// UnpinTopic removes a topic from the profile's pinned list.
func (a *App) UnpinTopic(profileID, topic string) error {
return a.profileStore.UnpinTopic(profileID, topic)
}
// PinTenant adds a tenant to the profile's pinned list so it sorts to the top.
func (a *App) PinTenant(profileID, tenant string) error {
return a.profileStore.PinTenant(profileID, tenant)
}
// UnpinTenant removes a tenant from the profile's pinned list.
func (a *App) UnpinTenant(profileID, tenant string) error {
return a.profileStore.UnpinTenant(profileID, tenant)
}
// ── Topic groups ──────────────────────────────────────────────────────────────
// SaveTopicGroup creates or updates a topic group for a profile.
func (a *App) SaveTopicGroup(profileID string, g profile.TopicGroup) error {
return a.profileStore.SaveTopicGroup(profileID, g)
}
// DeleteTopicGroup removes a topic group from a profile.
func (a *App) DeleteTopicGroup(profileID, groupID string) error {
return a.profileStore.DeleteTopicGroup(profileID, groupID)
}
// ── Broker metadata ───────────────────────────────────────────────────────────
type TenantListResult struct {
Tenants []string `json:"tenants"`
Warning string `json:"warning,omitempty"`
}
type NamespaceListResult struct {
Namespaces []broker.Namespace `json:"namespaces"`
Warning string `json:"warning,omitempty"`
}
// ListTenants fetches live tenant names from Pulsar Admin, merged with any
// tenants the user added manually. When the admin API rejects the call for
// this token (e.g. a non-super-user token can't list all tenants), the
// manually-added tenants are returned alone so the tree is still usable.
func (a *App) ListTenants(profileID string) (TenantListResult, error) {
resolved, err := a.resolveProfileAuth(profileID)
if err != nil {
return TenantListResult{}, err
}
cfg := resolved.profile.EffectivePulsarConfig()
ctx, cancel := context.WithTimeout(a.ctx, 10*time.Second)
defer cancel()
tenants, err := pulsaradmin.NewClientWithToken(cfg.AdminURL, resolved.adminToken).ListTenants(ctx)
return buildTenantListResult(tenants, err, resolved.profile.CustomTenants, pinnedTenantSet(resolved.profile.PinnedTenants))
}
func buildTenantListResult(apiResult []string, apiErr error, custom []string, pinned map[string]bool) (TenantListResult, error) {
tenants, err := mergeTenantList(apiResult, apiErr, custom, pinned)
if apiErr != nil {
if err != nil {
tenants = []string{}
}
return TenantListResult{Tenants: tenants, Warning: apiErr.Error()}, nil
}
return TenantListResult{Tenants: tenants}, err
}
// mergeTenantList merges live tenants with a profile's manually-added custom
// tenants. When the admin API is unavailable to this token (apiErr != nil),
// custom tenants are served alone so a non-super-user can still browse the
// tenants they added by hand. The API error is returned only when there are no
// custom tenants to fall back on. Pinned tenants sort to the top.
func mergeTenantList(apiResult []string, apiErr error, custom []string, pinned map[string]bool) ([]string, error) {
if apiErr != nil {
if len(custom) > 0 {
return dedupSortTenants(custom, pinned), nil
}
return nil, apiErr
}