github.com/safing/portbase@v0.19.5/runtime/modules_integration.go (about)

     1  package runtime
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  
     7  	"github.com/safing/portbase/database"
     8  	"github.com/safing/portbase/database/record"
     9  	"github.com/safing/portbase/log"
    10  	"github.com/safing/portbase/modules"
    11  )
    12  
    13  var modulesIntegrationUpdatePusher func(...record.Record)
    14  
    15  func startModulesIntegration() (err error) {
    16  	modulesIntegrationUpdatePusher, err = Register("modules/", &ModulesIntegration{})
    17  	if err != nil {
    18  		return err
    19  	}
    20  
    21  	if !modules.SetEventSubscriptionFunc(pushModuleEvent) {
    22  		log.Warningf("runtime: failed to register the modules event subscription function")
    23  	}
    24  
    25  	return nil
    26  }
    27  
    28  // ModulesIntegration provides integration with the modules system.
    29  type ModulesIntegration struct{}
    30  
    31  // Set is called when the value is set from outside.
    32  // If the runtime value is considered read-only ErrReadOnly
    33  // should be returned. It is guaranteed that the key of
    34  // the record passed to Set is prefixed with the key used
    35  // to register the value provider.
    36  func (mi *ModulesIntegration) Set(record.Record) (record.Record, error) {
    37  	return nil, ErrReadOnly
    38  }
    39  
    40  // Get should return one or more records that match keyOrPrefix.
    41  // keyOrPrefix is guaranteed to be at least the prefix used to
    42  // register the ValueProvider.
    43  func (mi *ModulesIntegration) Get(keyOrPrefix string) ([]record.Record, error) {
    44  	return nil, database.ErrNotFound
    45  }
    46  
    47  type eventData struct {
    48  	record.Base
    49  	sync.Mutex
    50  	Data interface{}
    51  }
    52  
    53  func pushModuleEvent(moduleName, eventName string, internal bool, data interface{}) {
    54  	// Create event record and set key.
    55  	eventRecord := &eventData{
    56  		Data: data,
    57  	}
    58  	eventRecord.SetKey(fmt.Sprintf(
    59  		"runtime:modules/%s/event/%s",
    60  		moduleName,
    61  		eventName,
    62  	))
    63  	eventRecord.UpdateMeta()
    64  	if internal {
    65  		eventRecord.Meta().MakeSecret()
    66  		eventRecord.Meta().MakeCrownJewel()
    67  	}
    68  
    69  	// Push event to database subscriptions.
    70  	modulesIntegrationUpdatePusher(eventRecord)
    71  }