github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/model/job/trigger_webhook.go (about)

     1  package job
     2  
     3  import "sync"
     4  
     5  type firer interface {
     6  	fire(trigger Trigger, request *JobRequest)
     7  }
     8  
     9  // WebhookTrigger implements the @webhook triggers. It schedules a job when an
    10  // HTTP request is made at this webhook.
    11  type WebhookTrigger struct {
    12  	*TriggerInfos
    13  	mu sync.Mutex
    14  	ch chan *JobRequest
    15  	cb firer
    16  }
    17  
    18  // NewWebhookTrigger returns a new instance of WebhookTrigger.
    19  func NewWebhookTrigger(infos *TriggerInfos) (*WebhookTrigger, error) {
    20  	return &WebhookTrigger{TriggerInfos: infos}, nil
    21  }
    22  
    23  // Type implements the Type method of the Trigger interface.
    24  func (w *WebhookTrigger) Type() string {
    25  	return w.TriggerInfos.Type
    26  }
    27  
    28  // Schedule implements the Schedule method of the Trigger interface.
    29  func (w *WebhookTrigger) Schedule() <-chan *JobRequest {
    30  	w.mu.Lock()
    31  	defer w.mu.Unlock()
    32  	w.ch = make(chan *JobRequest)
    33  	return w.ch
    34  }
    35  
    36  // Unschedule implements the Unschedule method of the Trigger interface.
    37  func (w *WebhookTrigger) Unschedule() {
    38  	// Note: it is called only for the in-memory scheduler
    39  	w.mu.Lock()
    40  	defer w.mu.Unlock()
    41  	close(w.ch)
    42  	w.ch = nil
    43  }
    44  
    45  // Infos implements the Infos method of the Trigger interface.
    46  func (w *WebhookTrigger) Infos() *TriggerInfos {
    47  	return w.TriggerInfos
    48  }
    49  
    50  // CombineRequest implements the CombineRequest method of the Trigger interface.
    51  func (w *WebhookTrigger) CombineRequest() string {
    52  	return appendPayload
    53  }
    54  
    55  // SetCallback registers a struct to be called when the webhook is fired.
    56  func (w *WebhookTrigger) SetCallback(cb firer) {
    57  	w.mu.Lock()
    58  	defer w.mu.Unlock()
    59  	w.cb = cb
    60  }
    61  
    62  // Fire is called with a payload when the webhook has been requested.
    63  func (w *WebhookTrigger) Fire(payload Payload, manual bool) {
    64  	w.mu.Lock()
    65  	defer w.mu.Unlock()
    66  	req := w.JobRequest()
    67  	req.Payload = payload
    68  	req.Manual = manual
    69  	if w.ch != nil {
    70  		w.ch <- req
    71  	}
    72  	if w.cb != nil {
    73  		w.cb.fire(w, req)
    74  	}
    75  }