Skip to content

Commit

Permalink
Supposedly better messaging
Browse files Browse the repository at this point in the history
  • Loading branch information
Dokotela committed Nov 22, 2024
1 parent 105c390 commit 438af1f
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 26 deletions.
16 changes: 10 additions & 6 deletions pocketfhir/caddy.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (
_ "github.com/caddyserver/caddy/v2/modules/standard"
)

// CaddyConfig is a struct that contains the configuration parameters for starting the Caddy server.
type CaddyConfig struct {
// caddyConfig is a struct that contains the configuration parameters for starting the Caddy server.
type caddyConfig struct {
PbPort string
HttpPort string
HttpsPort string
Expand All @@ -21,10 +21,11 @@ type CaddyConfig struct {
}

// startCaddyInstance initializes and starts the Caddy server instance.
func startCaddyInstance(config CaddyConfig) {
func startCaddyInstance(config caddyConfig) error {
// Change working directory
if err := os.Chdir(config.StoragePath); err != nil {
log.Fatalf("Failed to change working directory to %s: %v", config.StoragePath, err)
return err
}

// Log consolidated configuration details
Expand All @@ -37,6 +38,7 @@ func startCaddyInstance(config CaddyConfig) {
configJSON, err := json.MarshalIndent(caddyCfg, "", " ")
if err != nil {
log.Fatalf("Failed to serialize Caddy config: %v", err)
return err
}
log.Printf("Generated Caddy config: %s", string(configJSON))

Expand All @@ -45,12 +47,14 @@ func startCaddyInstance(config CaddyConfig) {
err = caddy.Load(configJSON, true)
if err != nil {
log.Fatalf("[ERROR] Failed to load Caddy configuration: %v", err)
return err
}
log.Println("Caddy server started successfully.")
return nil
}

// createConfig generates a basic Caddy configuration to run a reverse proxy with HTTP and a static file server.
func createConfig(config CaddyConfig) *caddy.Config {
func createConfig(config caddyConfig) *caddy.Config {
// Define paths for certs and proxy logs
pbProxyPath := fmt.Sprintf("%s/proxy_access.log", config.StoragePath)

Expand Down Expand Up @@ -108,7 +112,7 @@ func generateStorageConfig(storagePath string) string {
}

// Generates the HTTP application configuration section
func generateHttpAppConfig(config CaddyConfig) string {
func generateHttpAppConfig(config caddyConfig) string {
httpsServerConfig := generateHttpsServerConfig(config)
return fmt.Sprintf(`"http": {
"http_port": %s,
Expand All @@ -119,7 +123,7 @@ func generateHttpAppConfig(config CaddyConfig) string {
}

// Generates the HTTP server configuration for reverse proxy with health checks
func generateHttpsServerConfig(config CaddyConfig) string {
func generateHttpsServerConfig(config caddyConfig) string {
return fmt.Sprintf(`"srv_https": {
"listen": [":%s"],
"routes": [
Expand Down
22 changes: 13 additions & 9 deletions pocketfhir/create_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,22 +285,26 @@ func validateFHIRResource(resourceData []byte) error {
}

// Extract meta from resource JSON
func getMetaFromResource(resourceData []byte) *Meta {
func getMetaFromResource(resourceData []byte) *meta {
var resourceJson map[string]interface{}
if err := json.Unmarshal(resourceData, &resourceJson); err != nil {
log.Printf("Failed to unmarshal resource data: %v", err)
return &Meta{}
return &meta{}
}

meta, ok := resourceJson["meta"].(map[string]interface{})
metaData, ok := resourceJson["meta"].(map[string]interface{})
if !ok {
log.Println("Meta field not found in resource")
return &Meta{}
return &meta{}
}

return &Meta{
LastUpdated: meta["lastUpdated"].(string),
VersionId: meta["versionId"].(string),
// Use safe type assertions to avoid panics
lastUpdated, _ := metaData["lastUpdated"].(string)
versionId, _ := metaData["versionId"].(string)

return &meta{
LastUpdated: lastUpdated,
VersionId: versionId,
}
}

Expand Down Expand Up @@ -341,8 +345,8 @@ func moveResourceToHistory(app *pocketbase.PocketBase, collectionName string, re
return nil
}

// Meta struct to hold meta data fields
type Meta struct {
// meta struct to hold meta data fields
type meta struct {
LastUpdated string
VersionId string
}
50 changes: 44 additions & 6 deletions pocketfhir/native_bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,66 @@ import (
"log"
)

// Java Callbacks, make sure to register them before starting pocketbase
// to expose any method to java, add that with FirstLetterCapital
// Java Callbacks, make sure to register them before starting PocketBase
// to expose any method to Java, add that with FirstLetterCapital
var nativeBridge NativeBridge

// RegisterNativeBridgeCallback allows setting the NativeBridge interface for callbacks
func RegisterNativeBridgeCallback(c NativeBridge) {
nativeBridge = c
}

// Helper methods

// NativeBridge interface to define the methods used for native callbacks
type NativeBridge interface {
handleCallback(string, string) string
HandleCallback(command string, data string) string
}

// sendCommand sends command to native and returns the response
func sendCommand(command string, data string) string {
if nativeBridge != nil {
log.Printf("[DEBUG] Sending command '%s' with data: %s", command, data)
return nativeBridge.handleCallback(command, data)
return nativeBridge.HandleCallback(command, data)
}
log.Printf("[DEBUG] No NativeBridge defined. Command '%s' not sent.", command)
return ""
}

// sendHealthUpdate sends an update to the native layer regarding the health of servers (PocketBase/Caddy).
func sendHealthUpdate(healthStatus string) {
if nativeBridge != nil {
log.Printf("[DEBUG] Sending health update: %s", healthStatus)
nativeBridge.HandleCallback("HealthUpdate", healthStatus)
} else {
log.Printf("[DEBUG] No NativeBridge defined. Health update '%s' not sent.", healthStatus)
}
}

// This function will be triggered when starting PocketBase
func onPocketBaseStart() {
sendHealthUpdate("PocketBase server started successfully.")
}

// This function will be triggered when stopping PocketBase
func onPocketBaseStop() {
sendHealthUpdate("PocketBase server stopped successfully.")
}

// This function will be triggered when starting Caddy
func onCaddyStart() {
sendHealthUpdate("Caddy server started successfully.")
}

// This function will be triggered when stopping Caddy
func onCaddyStop() {
sendHealthUpdate("Caddy server stopped successfully.")
}

// This function will be triggered if there's an error with PocketBase
func onPocketBaseError(err error) {
sendHealthUpdate("PocketBase server encountered an error: " + err.Error())
}

// This function will be triggered if there's an error with Caddy
func onCaddyError(err error) {
sendHealthUpdate("Caddy server encountered an error: " + err.Error())
}
6 changes: 4 additions & 2 deletions pocketfhir/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

// runServerInstance handles the setup and running of the PocketBase server instance.
func runServerInstance(app *pocketbase.PocketBase, ipAddress, pbPort string, enableApiLogs bool) {
func runServerInstance(app *pocketbase.PocketBase, ipAddress, pbPort string, enableApiLogs bool) error {
// Set CLI-like arguments for PocketBase to specify server address and port
log.Printf("[DEBUG] Setting CLI arguments for server address and port: %s:%s\n", ipAddress, pbPort)
os.Args = []string{os.Args[0], "serve", "--http", fmt.Sprintf("%s:%s", ipAddress, pbPort)}
Expand All @@ -33,14 +33,16 @@ func runServerInstance(app *pocketbase.PocketBase, ipAddress, pbPort string, ena
// Initialize collections if necessary
if err := initializeCollections(app); err != nil {
log.Printf("[ERROR] Failed to initialize collections: %v", err)
return
return err
}

// Start the server
log.Println("[DEBUG] Starting PocketBase server instance...")
if err := app.Start(); err != nil {
log.Fatalf("[ERROR] Failed to start PocketBase server: %v", err)
return err
}
return nil
}

// setupPocketbaseCallbacks sets up additional callbacks and native routes for PocketBase
Expand Down
22 changes: 19 additions & 3 deletions pocketfhir/start_stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func StartPocketFHIR(
// Set environment variables for PocketBase configuration
log.Println("[DEBUG] Setting environment variables...")
if err := os.Setenv("POCKETBASE_DATA_DIR", dataDir); err != nil {
onPocketBaseError(err)
log.Fatalf("Failed to set data directory: %v", err)
}

Expand All @@ -45,7 +46,13 @@ func StartPocketFHIR(
DefaultDev: enableApiLogs,
HideStartBanner: false,
})
runServerInstance(pocketBaseApp, pbUrl, pbPort, enableApiLogs)

if err := runServerInstance(pocketBaseApp, pbUrl, pbPort, enableApiLogs); err != nil {
log.Printf("[ERROR] PocketBase failed to start: %v", err)
onPocketBaseError(err)
return
}
onPocketBaseStart()
}()

// Start the Caddy server in a separate goroutine
Expand All @@ -54,7 +61,7 @@ func StartPocketFHIR(
log.Println("[DEBUG] Starting Caddy server with HTTPS...")

// Create the Caddy configuration
caddyConfig := CaddyConfig{
caddyConfig := caddyConfig{
PbPort: pbPort,
HttpPort: httpPort,
HttpsPort: httpsPort,
Expand All @@ -63,7 +70,12 @@ func StartPocketFHIR(
IpAddress: ipAddress,
}

startCaddyInstance(caddyConfig)
if err := startCaddyInstance(caddyConfig); err != nil {
log.Printf("[ERROR] Caddy failed to start: %v", err)
onCaddyError(err)
return
}
onCaddyStart()
}()

// Wait for interrupt signal to gracefully shut down the servers
Expand Down Expand Up @@ -99,8 +111,10 @@ func StopPocketFHIR() {
})
if err != nil {
log.Printf("[ERROR] Failed to terminate PocketBase: %v", err)
onPocketBaseError(err)
} else {
log.Println("[DEBUG] PocketBase server terminated successfully.")
onPocketBaseStop()
}
}
}()
Expand All @@ -112,8 +126,10 @@ func StopPocketFHIR() {

if err := caddy.Stop(); err != nil {
log.Printf("[ERROR] Failed to stop Caddy server: %v", err)
onCaddyError(err)
} else {
log.Println("[DEBUG] Caddy server stopped successfully.")
onCaddyStop()
}
}()

Expand Down

0 comments on commit 438af1f

Please sign in to comment.