func mongoOnEnter()

in pkg/rules/mongo/client_setup.go [44:105]


func mongoOnEnter(call api.CallContext, opts ...*options.ClientOptions) {
	if !mongoEnabler.Enable() {
		return
	}
	syncMap := sync.Map{}
	for _, opt := range opts {
		hosts := opt.Hosts
		hostLength := len(hosts)
		if hostLength == 0 {
			continue
		}
		configuredMonitor := opt.Monitor
		var host string
		opt.Monitor = &event.CommandMonitor{
			Started: func(ctx context.Context, startedEvent *event.CommandStartedEvent) {
				if configuredMonitor != nil {
					configuredMonitor.Started(ctx, startedEvent)
				}
				host = hosts[0]
				if hostLength > 1 {
					if infoSplit := strings.Index(startedEvent.ConnectionID, "["); infoSplit > 0 && strings.HasSuffix(startedEvent.ConnectionID, "]") {
						host = startedEvent.ConnectionID[0:infoSplit]
					}
				}
				mongoRequest := mongoRequest{
					CommandName: startedEvent.CommandName,
					Host:        host,
				}
				newCtx := mongoInstrumenter.Start(ctx, mongoRequest)
				syncMap.Store(fmt.Sprintf("%d", startedEvent.RequestID), newCtx)
			},
			Succeeded: func(ctx context.Context, succeededEvent *event.CommandSucceededEvent) {
				if configuredMonitor != nil {
					configuredMonitor.Succeeded(ctx, succeededEvent)
				}
				if newCtx, ok := syncMap.LoadAndDelete(fmt.Sprintf("%d", succeededEvent.RequestID)); ok && newCtx != nil {
					newContext, ok := newCtx.(context.Context)
					if ok {
						mongoInstrumenter.End(newContext, mongoRequest{
							CommandName: succeededEvent.CommandName,
							Host:        host,
						}, nil, nil)
					}
				}
			},
			Failed: func(ctx context.Context, failedEvent *event.CommandFailedEvent) {
				if configuredMonitor != nil {
					configuredMonitor.Failed(ctx, failedEvent)
				}
				if newCtx, ok := syncMap.LoadAndDelete(fmt.Sprintf("%d", failedEvent.RequestID)); ok && newCtx != nil {
					newContext, ok := newCtx.(context.Context)
					if ok {
						mongoInstrumenter.End(newContext, mongoRequest{
							CommandName: failedEvent.CommandName,
							Host:        host,
						}, nil, errors.New(failedEvent.Failure))
					}
				}
			},
		}
	}
}