code: func (s *State) Flush(ctx context.Context, mon monitor.Monitor) error {
  	if mon == nil {
  		mon = s.Monitor()
  	}
  
  	if mon == nil {
  		return errors.New("no tsmon Monitor is configured")
  	}
  
  	// Run any callbacks that have been registered to populate values in callback
  	// metrics.
  	s.runCallbacks(ctx)
  	if s.invokeGlobalCallbacksOnFlush {
  		s.RunGlobalCallbacks(ctx)
  	}
  
  	cells := s.store.GetAll(ctx)
  	if len(cells) == 0 {
  		return nil
  	}
  
  	logging.Debugf(ctx, "Starting tsmon flush: %d cells", len(cells))
  	defer logging.Debugf(ctx, "Finished tsmon flush")
  
  	// Split up the payload into chunks if there are too many cells.
  	chunkSize := mon.ChunkSize()
  	if chunkSize == 0 {
  		chunkSize = len(cells)
  	}
  
  	var failedSends int
  	var lastErr error
  
  	for len(cells) > 0 {
  		count := minInt(chunkSize, len(cells))
  		if err := mon.Send(ctx, cells[:count]); err != nil {
  			logging.Errorf(ctx, "Failed to send %d cells: %v", count, err)
  			failedSends += count
  			lastErr = err
  			// Continue anyway.
  		}
  		cells = cells[count:]
  	}
  
  	logging.Debugf(ctx, "Sent %d/%d cells", len(cells)-failedSends, len(cells))
  
  	s.resetGlobalCallbackMetrics(ctx)
  
  	return lastErr
  }
docs: // Flush sends all the metrics that are registered in the application.
  //
  // Uses given monitor if not nil, otherwise the State's current monitor.