GithubHelp home page GithubHelp logo

citilinkru / camunda-client-go Goto Github PK

View Code? Open in Web Editor NEW
132.0 15.0 55.0 95 KB

Camunda REST API client for golang

License: MIT License

Go 100.00%
camunda camunda-bpm-platform camunda-bpm camunda-external-task camunda-framework api-client rest-client golang-library bpmn bpms

camunda-client-go's Introduction

Camunda REST API client for golang

Go Report Card codecov Go Reference Release

Installation

go get github.com/citilinkru/camunda-client-go/v3

Usage

Create client:

client := camunda_client_go.NewClient(camunda_client_go.ClientOptions{
	EndpointUrl: "http://localhost:8080/engine-rest",
    ApiUser: "demo",
    ApiPassword: "demo",
    Timeout: time.Second * 10,
})

Create deployment:

file, err := os.Open("demo.bpmn")
if err != nil {
    fmt.Printf("Error read file: %s\n", err)
    return
}
result, err := client.Deployment.Create(camunda_client_go.ReqDeploymentCreate{
    DeploymentName: "DemoProcess",
    Resources: map[string]interface{}{
        "demo.bpmn": file,
    },
})
if err != nil {
    fmt.Printf("Error deploy process: %s\n", err)
    return
}

fmt.Printf("Result: %#+v\n", result)

Start instance:

processKey := "demo-process"
result, err := client.ProcessDefinition.StartInstance(
	camunda_client_go.QueryProcessDefinitionBy{Key: &processKey},
	camunda_client_go.ReqStartInstance{},
)
if err != nil {
    fmt.Printf("Error start process: %s\n", err)
    return
}

fmt.Printf("Result: %#+v\n", result)

More examples

Examples documentation

Usage for External task

Create external task processor:

logger := func(err error) {
	fmt.Println(err.Error())
}
asyncResponseTimeout := 5000
proc := processor.NewProcessor(client, &processor.Options{
    WorkerId: "demo-worker",
    LockDuration: time.Second * 5,
    MaxTasks: 10,
    MaxParallelTaskPerHandler: 100,
    AsyncResponseTimeout: &asyncResponseTimeout,
}, logger)

Add and subscribe external task handler:

proc.AddHandler(
    []*camunda_client_go.QueryFetchAndLockTopic{
        {TopicName: "HelloWorldSetter"},
    },
    func(ctx *processor.Context) error {
        fmt.Printf("Running task %s. WorkerId: %s. TopicName: %s\n", ctx.Task.Id, ctx.Task.WorkerId, ctx.Task.TopicName)

        err := ctx.Complete(processor.QueryComplete{
            Variables: &map[string]camunda_client_go.Variable {
                "result": {Value: "Hello world!", Type: "string"},
            },
        })
        if err != nil {
            fmt.Printf("Error set complete task %s: %s\n", ctx.Task.Id, err)
            
            return ctx.HandleFailure(processor.QueryHandleFailure{
                ErrorMessage: &errTxt,
                Retries: &retries,
                RetryTimeout: &retryTimeout,
            })
        }
        
        fmt.Printf("Task %s completed\n", ctx.Task.Id)
        return nil
    },
)

Features

  • Support api version 7.11
  • Full support API External Task
  • Full support API Process Definition
  • Full support API Process Instance
  • Full support API Deployment
  • Partial support API History
  • Partial support API Tenant
  • Without external dependencies

Road map

  • Full coverage by tests
  • Full support references api

Testing

Unit-tests:

go test -v -race ./...

Run linter:

docker run --rm -v $(pwd):/app -w /app golangci/golangci-lint:v1.45.2 golangci-lint run -v

Integration tests:

docker run --rm --name camunda -p 8080:8080 camunda/camunda-bpm-platform
go test -tags=integration -failfast ./...

Examples:

Go to examples directory and follow the instructions to run the examples.

CONTRIBUTE

  • write code
  • run go fmt ./...
  • run all linters and tests (see above)
  • run all examples (see above)
  • create a PR describing the changes

LICENSE

MIT

AUTHOR

Konstantin Osipov [email protected]

camunda-client-go's People

Contributors

ace-codemaker avatar cezarytarnowski-tomtom avatar grcwolf avatar imix avatar liderman avatar manu88 avatar mlaflamm avatar qs-wang avatar sasswart avatar sgadisetti avatar sinhashubham95 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

camunda-client-go's Issues

startPuller

func (p *Processor) startPuller(query camundaclientgo.QueryFetchAndLock, handler Handler) {
	var tasksChan = make(chan *camundaclientgo.ResLockedExternalTask)

	maxParallelTaskPerHandler := p.options.MaxParallelTaskPerHandler
	if maxParallelTaskPerHandler < 1 {
		maxParallelTaskPerHandler = 1
	}

	// create worker pool
	for i := 0; i < maxParallelTaskPerHandler; i++ {
		p.workerGroup.Add(1)
		go p.runWorker(handler, tasksChan)
	}

	go func() {
		retries := 0
		for {
			select {
			case <-p.ctx.Done():
				close(tasksChan)
				return
			default:
				tasks, err := p.client.ExternalTask.FetchAndLock(query)
				if err != nil {
					if retries < 60 {
						retries += 1
					}
					p.logger(fmt.Errorf("failed pull: %w, sleeping: %d seconds", err, retries))
					time.Sleep(time.Duration(retries) * time.Second)
					continue
				}
				retries = 0

				for _, task := range tasks {
					tasksChan <- task
				}
			}
		}
	}()
}

В рутине в бесконечном цикле нет возможности проставить паузу между запросами. С увеличением кол-ва экстернал тасков - увеличивается сетевой трафик и забивается пул конекций

external task handling by process def keys

bpmnClient.QueryFetchAndLockTopic.ProcessDefinitionKeyIn
Sorry my pure english
We have error when start handling external tasks, I thing this need slice not pointer string

when modify processinstance, the datatype is wrong on ReqModifyProcessInstance.Instructions.Variables

When I call the Modify method of ProcessInstance, a parameter of type ReqModifyProcessInstance is required, which contains an slice of type ReqModifyProcessInstanceInstruction struct, and its "Variables" property should be an object of type map[string]ReqProcessVariable, not a slice of type ReqProcessVariable.
The official documentation description is: A JSON object containing variable key-value pairs. Each key is a variable name and each value a JSON variable value object.

type ReqModifyProcessInstanceInstruction struct {
	// ...
	// A JSON object containing variable key-value pairs.
	// Each key is a variable name and each value a JSON variable value object.
	Variables []ReqProcessVariable `json:"variables"`
}

What is the official status of v2?

I am wondering if v2 is a recommended version or is it experimental? Against which version should someone submit a new PR?

At the time I am writing this, the most recent commit in master (5b9b9ff) removed all reference to v2. This is confusing to know that there is a v2 out there but there is no mention of it in the README when landing on the main github page of the project.

Thank you.

Invalid QueryFetchAndLockTopic.TenantIdIn type

There is a problem with the type of "QueryFetchAndLockTopic.TenantIdIn". I get an error with type *string but It works If I change it to *[]string.

Current: QueryFetchAndLockTopic.TenantIdIn *string json:"tenantIdIn,omitempty"

TenantIdIn := "test"
proc.AddHandler(
            &[]camundaclientgo.QueryFetchAndLockTopic{
                  {TopicName: "testTopic", TenantIdIn: &TenantIdIn},
      },

error:

{"level":"debug","error":"failed pull: request error: response error with status code 400: Cannot construct instance of java.lang.String[]: no String-argument constructor/factory method to deserialize from String value ('test')\n
at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 193] (through reference chain: org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksExtendedDto["topic
s"]->java.util.ArrayList[1]->org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksDto$FetchExternalTaskTopicDto["tenantIdIn"]), sleeping: 2 seconds","time":"2021-11-17T12:02:25Z","message":"Camunda"}

Suggested: QueryFetchAndLockTopic.TenantIdIn *[]string json:"tenantIdIn,omitempty"

proc.AddHandler(
	&[]camundaclientgo.QueryFetchAndLockTopic{
		{TopicName: "testTopic", TenantIdIn: &[]string{"test"}},
	},

No way to stop long polling on a Processor

There is currently no way to programmatically stop long polling on a Processor. Once started, long polling stops only when the process exits. This makes it very hard to have multiple separate integration tests on a single package without interference.

I’ve prepared a PR, #39, that add the ability to stop long polling

start process Not found

Use rest deploy bpmn file not start with client.ProcessDefinition.StartInstance, only be used in user interface. My username and password are correct . Why?

Prometheus metrics on client side

Hi,I am a software developer currently working with your Go client for the Camunda BPM platform, and I must commend you for your excellent work.

However, as I continue to integrate the Go client into my projects, I noticed that the current version lacks Prometheus metrics in the client. Utilizing Prometheus metrics has been an essential part of my workflow, enabling effective monitoring and performance tracking.

I am aware that Camunda provides its own API for metrics, but for my specific use-case, I require these metrics on the client-side.

I understand that adding this feature might require substantial efforts and architectural considerations. But I believe that including Prometheus metrics would significantly improve the utility of the client and benefit other developers who also rely on comprehensive monitoring tools.

Given this, I would like to propose contributing to your project by adding Prometheus metrics on the client-side. I would appreciate your feedback and guidance on this.

Could you kindly inform me if there are plans to integrate Prometheus metrics into the client in the foreseeable future, or if my contribution in this regard would be welcome?

Invalid QueryFetchAndLock.ProcessVariables type

When calling QueryFetchAndLock (POST /external-task/fetchAndLock) with the QueryFetchAndLockTopic.ProcessVariables set, the camuda api returns the err Object values cannot be used to query. It seems that the ProcessVariables for the QueryFetchAndLockTopic should be a map[string]interface{}, where the value should be a string, number, or other camunda supported primitive, instead of map[string]Variable. (For Reference: Camunda Fetch & Lock External Task API Doc).

Current request payload:

{
    "workerId": "worker-x",
    "maxTasks": 1,
    "topics": [
	    {
	        "topicName": "topic-y",
	        "lockDuration": 100,
	        "businessKey": "8e539d03-...",
	        "processVariables": {
	            "resourceVersion": {
			"type": "String",
		        "value": "44",
			"valueInfo": {}
		    }
	        }
	    }
    ]
}

Suggested request payload:

{
    "workerId": "worker-x",
    "maxTasks": 1,
    "topics": [
	    {
	        "topicName": "topic-y",
	        "lockDuration": 100,
	        "businessKey": "8e539d03-...",
	        "processVariables": {
	            "resourceVersion": "44"
	        }
	    }
    ]
}

SendMessage throws MismatchingMessageCorrelationException

Camunda throws an org.camunda.bpm.engine.MismatchingMessageCorrelationException exception when businessKey field in POST /message is an empty string.

BusinessKey field in ReqMessage struct in message.go should have omitempty for it work properly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.